From d38df54b23101fb34cbe5088d2ed8571c352dfa2 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Wed, 25 Nov 2026 13:00:53 +0000 Subject: [PATCH 01/23] fix: pin shell and playground worker authentication relays Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/documentdb/ClustersClient.test.ts | 30 ++ src/documentdb/ClustersClient.ts | 23 ++ src/documentdb/auth/WorkerTokenRelay.ts | 231 +++++++++++++ .../playground/PlaygroundEvaluator.test.ts | 154 ++++++++- .../playground/PlaygroundEvaluator.ts | 325 ++++++++---------- .../playground/WorkerSessionManager.test.ts | 26 +- .../playground/WorkerSessionManager.ts | 98 ++++-- .../playground/playgroundWorker.test.ts | 49 ++- src/documentdb/playground/playgroundWorker.ts | 60 +++- src/documentdb/playground/types.ts | 10 + src/documentdb/playground/workerTypes.ts | 61 ++++ .../shell/ShellSessionManager.test.ts | 146 +++++++- src/documentdb/shell/ShellSessionManager.ts | 313 +++++++---------- 13 files changed, 1100 insertions(+), 426 deletions(-) create mode 100644 src/documentdb/auth/WorkerTokenRelay.ts diff --git a/src/documentdb/ClustersClient.test.ts b/src/documentdb/ClustersClient.test.ts index 511803848..1e6218c59 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -298,12 +298,42 @@ describe('regular connection startup diagnostics', () => { await expect(ClustersClient.resolveBoundClient(client.binding)).rejects.toMatchObject({ reason: 'userDisconnected', }); + expect(mockConnect).toHaveBeenCalledTimes(2); } finally { ClustersClient.unlatch(clusterId); } }); + it('compares current credentials with the canonical password-free and auth-qualified fingerprint', (): void => { + const uri = 'mongodb://host.example.com:27017/'; + function setNative(user: string, password: string): void { + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.NativeAuth, uri, { + connectionUser: user, + connectionPassword: password, + }); + } + setNative('first', 'first-password'); + const first = ClustersClient.getExpectedFingerprint(clusterId); + expect(first).toBe( + computeConnectionFingerprint({ connectionString: uri, principal: { kind: 'native', username: 'first' } }), + ); + setNative('first', 'rotated-password'); + expect(ClustersClient.getExpectedFingerprint(clusterId)).toBe(first); + setNative('second', 'rotated-password'); + expect(ClustersClient.getExpectedFingerprint(clusterId)).not.toBe(first); + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.NoAuth, uri); + expect(ClustersClient.getExpectedFingerprint(clusterId)).not.toBe(first); + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.MicrosoftEntraID, uri, undefined, undefined, { + tenantId: verifiedIdentity.tenantId, + }); + expect(ClustersClient.getExpectedFingerprint(clusterId)).toBeUndefined(); + expect(ClustersClient.getExpectedFingerprint(clusterId, verifiedIdentity)).toBe( + computeConnectionFingerprint({ connectionString: uri, principal: verifiedIdentity }), + ); + expect(ClustersClient.getExpectedFingerprint(clusterId, { ...verifiedIdentity, tenantId: 'other' })).toBeUndefined(); + }); + it('does not open a changed connection for an old surface, even with no cached client', async (): Promise => { const client = await ClustersClient.connectInteractive(clusterId); await ClustersClient.deleteClient(clusterId); diff --git a/src/documentdb/ClustersClient.ts b/src/documentdb/ClustersClient.ts index 643b43f66..7faae61a5 100644 --- a/src/documentdb/ClustersClient.ts +++ b/src/documentdb/ClustersClient.ts @@ -314,6 +314,29 @@ export class ClustersClient { return identity?.kind === 'entra' ? identity : undefined; } + /** Compute from current credentials, not from a possibly stale cached client. */ + public static getExpectedFingerprint(clusterId: string, entraFallback?: VerifiedEntraIdentity): string | undefined { + const credentials = CredentialCache.getCredentials(clusterId); + if (!credentials) { + return undefined; + } + const method = credentials.authMechanism ?? AuthMethodId.NativeAuth; + const pin = ClustersClient.getEntraPin(clusterId) ?? entraFallback; + const tenantId = credentials.entraIdConfig?.tenantId; + if (method === AuthMethodId.MicrosoftEntraID && (!pin || pin.tenantId !== tenantId)) { + return undefined; + } + return computeConnectionFingerprint({ + connectionString: credentials.connectionString, + principal: getVerifiedIdentity( + method, + credentials, + credentials.connectionStringWithPassword ?? credentials.connectionString, + pin, + ), + }); + } + public static getEpoch(clusterId: string): number { return ClustersClient._epochs.get(clusterId) ?? 0; } diff --git a/src/documentdb/auth/WorkerTokenRelay.ts b/src/documentdb/auth/WorkerTokenRelay.ts new file mode 100644 index 000000000..f5b2af28c --- /dev/null +++ b/src/documentdb/auth/WorkerTokenRelay.ts @@ -0,0 +1,231 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { traceAuthFlow, traceEntraDestination, type AuthTraceContext } from '../../utils/authTrace'; +import { ClustersClient } from '../ClustersClient'; +import { + getWorkerAuthReason, + type MainToWorkerMessage, + type WorkerAuthReason, + type WorkerToMainMessage, +} from '../playground/workerTypes'; +import { withTokenAcquisitionTiming, type ConnectionStartupTimings } from '../utils/ConnectionStartupTimings'; +import { type VerifiedEntraIdentity } from './AuthHandler'; +import { AuthMethodId } from './AuthMethodId'; +import { + resolveInteractiveTokenResource, + resolveManagedIdentityTokenResource, + TokenResourceResolutionError, + type ResolvedTokenResource, +} from './documentdbTokenResource'; +import { evaluateEntraDestinationFromSettings } from './entraDestinationSettings'; +import { + EntraIdentityMismatchError, + EntraSignInRequiredError, + TokenCallbackError, +} from './entraErrors/entraCallbackErrors'; +import { clearEntraTokenFailure, recordEntraTokenFailure } from './entraErrors/entraTokenFailures'; +import { getEntraSession, readEntraSignInEnvironment } from './entraSession'; +import { EntraDestinationRejectedError } from './oidcAllowedHosts'; + +export function sameEntraIdentity(a: VerifiedEntraIdentity, b: VerifiedEntraIdentity): boolean { + return a.providerId === b.providerId && a.accountId === b.accountId && a.tenantId === b.tenantId; +} + +export function createWorkerAuthError(reason: WorkerAuthReason, method?: AuthMethodId): Error { + switch (reason) { + case 'signInRequired': + return new EntraSignInRequiredError('noSession'); + case 'identityMismatch': + return new EntraIdentityMismatchError(); + case 'destinationRejected': + return new EntraDestinationRejectedError({ hostCount: 0 }); + case 'refreshFailed': + return new TokenCallbackError(undefined, method === AuthMethodId.ManagedIdentity ? method : undefined); + } +} + +/** Host-only token relay for a single worker. The worker cannot select its own identity or destination. */ +export class WorkerTokenRelay { + private resource: ResolvedTokenResource | undefined; + private pending: Promise = Promise.resolve(); + + constructor( + private readonly clusterId: string, + private readonly init: Extract, + readonly epoch: number, + private readonly correlationId: string, + private pin: VerifiedEntraIdentity | undefined, + private readonly onIdentity?: (identity: VerifiedEntraIdentity) => void, + ) {} + + async relay( + { requestId }: Extract, + postResponse: (response: MainToWorkerMessage) => void, + isCurrentWorker: () => boolean, + timings?: ConnectionStartupTimings, + trace?: AuthTraceContext, + ): Promise { + const isCurrent = (): boolean => + isCurrentWorker() && + !ClustersClient.getLatchReason(this.clusterId) && + ClustersClient.getEpoch(this.clusterId) === this.epoch; + const activeTrace = (): AuthTraceContext | undefined => (isCurrent() ? trace : undefined); + const { connectionString, authMechanism, tenantId, managedIdentityClientId } = this.init; + const managed = authMechanism === AuthMethodId.ManagedIdentity; + const assertDestination = (): void => { + const decision = evaluateEntraDestinationFromSettings(connectionString); + traceEntraDestination(decision, requestId, activeTrace()); + if (!decision.allowed) { + throw new EntraDestinationRejectedError(decision); + } + }; + const run = async (): Promise => { + if (!isCurrent()) { + return; + } + let mode: 'managedIdentity' | 'silent' | 'interactive' | undefined; + let acquiring = false; + try { + if (!managed && authMechanism !== AuthMethodId.MicrosoftEntraID) { + throw new Error('Token request from a non-OIDC worker'); + } + assertDestination(); + const pin = this.pin; + const environment = managed ? undefined : readEntraSignInEnvironment(); + const assertEnvironment = (): string => { + const now = readEntraSignInEnvironment(); + if ( + !environment || + (pin && (pin.providerId !== now.providerId || pin.tenantId !== tenantId)) || + environment.providerId !== now.providerId || + environment.cloudName !== now.cloudName || + environment.authority !== now.authority + ) { + throw new EntraSignInRequiredError('providerChanged'); + } + return environment.providerId; + }; + mode = managed ? 'managedIdentity' : pin ? 'silent' : 'interactive'; + const resolved = + this.resource ?? + (managed + ? await resolveManagedIdentityTokenResource(connectionString) + : await resolveInteractiveTokenResource(connectionString)); + if (!isCurrent()) { + return; + } + this.resource = resolved; + const { tokenResource: _resource, ...details } = resolved.details; + traceAuthFlow('entraCloud.resolved', details, requestId, activeTrace()); + let identity: VerifiedEntraIdentity | undefined; + let accessToken: string; + acquiring = true; + if (managed) { + const { getManagedIdentityAccessToken } = await import('./managedIdentityTokenProvider'); + if (!isCurrent()) { + return; + } + assertDestination(); + accessToken = ( + await withTokenAcquisitionTiming(timings, () => + getManagedIdentityAccessToken( + [resolved.scope], + managedIdentityClientId, + tenantId, + this.correlationId, + activeTrace(), + ), + ) + ).accessToken; + } else { + assertDestination(); + const providerId = assertEnvironment(); + const session = await withTokenAcquisitionTiming(timings, () => + getEntraSession({ + providerId, + resource: resolved.scope, + tenantId, + account: pin ? { id: pin.accountId, label: pin.accountLabel } : undefined, + mode: pin ? 'silent' : 'interactive', + }), + ); + if (!isCurrent()) { + return; + } + assertEnvironment(); + if (!session && pin) { + throw new EntraSignInRequiredError('noSession'); + } + if (!session?.account.id) { + throw new TokenCallbackError(undefined); + } + if (pin && session.account.id !== pin.accountId) { + throw new EntraIdentityMismatchError(); + } + identity = { + kind: 'entra', + providerId, + tenantId, + accountId: session.account.id, + accountLabel: session.account.label, + }; + accessToken = session.accessToken; + } + if (!isCurrent()) { + return; + } + assertDestination(); + if (identity) { + // The first interactive lookup may have overlapped a verified tree connection. + const verified = pin ? undefined : ClustersClient.getLastVerifiedIdentity(this.clusterId); + if (verified?.kind === 'entra' && !sameEntraIdentity(identity, verified)) { + throw new EntraIdentityMismatchError(); + } + this.onIdentity?.(identity); + this.pin = identity; + } + clearEntraTokenFailure(this.clusterId); + traceAuthFlow('workerTokenRelay.completed', { mode, outcome: 'returned' }, requestId, activeTrace()); + postResponse({ type: 'tokenResponse', requestId, accessToken }); + } catch (error) { + if (!isCurrent()) { + return; + } + const reason = getWorkerAuthReason(error) ?? 'refreshFailed'; + if (error instanceof TokenResourceResolutionError) { + traceAuthFlow('entraCloud.unresolved', error.details, requestId, activeTrace()); + } + if (reason === 'refreshFailed' && acquiring && this.resource) { + if (trace?.startupProperties) { + trace.startupProperties.entraFailureKind = 'tokenAcquisitionFailed'; + } + recordEntraTokenFailure(this.clusterId, { + cloudCategory: this.resource.cloudCategory, + authMethod: managed ? 'managedIdentity' : 'interactive', + }); + } + traceAuthFlow( + 'workerTokenRelay.completed', + { mode: mode ?? 'none', outcome: reason }, + requestId, + activeTrace(), + ); + postResponse({ + type: 'tokenError', + requestId, + error: createWorkerAuthError(reason, authMechanism as AuthMethodId).message, + reason, + ...(reason === 'destinationRejected' ? { errorName: 'EntraDestinationRejectedError' as const } : {}), + }); + } + }; + + // Serializing relays prevents two first requests from prompting before either has pinned an account. + const next = this.pending.then(run); + this.pending = next.catch(() => undefined); + await next; + } +} diff --git a/src/documentdb/playground/PlaygroundEvaluator.test.ts b/src/documentdb/playground/PlaygroundEvaluator.test.ts index fa24e08b9..0f8c00987 100644 --- a/src/documentdb/playground/PlaygroundEvaluator.test.ts +++ b/src/documentdb/playground/PlaygroundEvaluator.test.ts @@ -22,11 +22,12 @@ import { recordEntraTokenFailure, resetEntraTokenFailuresForTests, } from '../auth/entraErrors/entraTokenFailures'; +import { ClustersClient } from '../ClustersClient'; import { type getManagedIdentityAccessToken } from '../auth/managedIdentityTokenProvider'; import { type CachedClusterCredentials } from '../CredentialCache'; import { PlaygroundEvaluator } from './PlaygroundEvaluator'; import { type WorkerSessionCallbacks } from './WorkerSessionManager'; -import { type MainToWorkerMessage, type WorkerToMainMessage } from './workerTypes'; +import { getWorkerAuthReason, type MainToWorkerMessage, type WorkerToMainMessage } from './workerTypes'; type InitMessage = Extract; type TokenRequest = Extract; @@ -37,17 +38,23 @@ const mocks = vi.hoisted(() => ({ interactiveToken: vi.fn< ( - scopes?: string | string[], - tenantId?: string, + provider: string, + scopes: readonly string[], options?: vscode.AuthenticationGetSessionOptions, ) => Promise >(), + configuredProvider: vi.fn<() => string>(), managedIdentityToken: vi.fn(), resolveInteractive: vi.fn(), resolveManagedIdentity: vi.fn(), callbacks: undefined as WorkerSessionCallbacks | undefined, initMessage: undefined as InitMessage | undefined, clusterId: undefined as string | undefined, + worker: { + isConnectedTo: vi.fn<(clusterId: string) => boolean>(), + sendEval: vi.fn<(message: MainToWorkerMessage) => Promise<{ result: { type: string; printable: string; durationMs: number } }>>(), + killWorker: vi.fn(), + }, })); vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ @@ -83,7 +90,13 @@ vi.mock('../CredentialCache', () => ({ vi.mock('@microsoft/vscode-azext-azureauth', async (importOriginal) => ({ ...(await importOriginal()), - getSessionFromVSCode: mocks.interactiveToken, + getConfiguredAuthProviderId: mocks.configuredProvider, + getConfiguredAzureEnv: () => ({ name: 'AzureCloud' }), +})); + +vi.mock('vscode', async (importOriginal) => ({ + ...(await importOriginal()), + authentication: { getSession: mocks.interactiveToken }, })); vi.mock('../auth/managedIdentityTokenProvider', () => ({ @@ -100,7 +113,7 @@ vi.mock('./WorkerSessionManager', () => ({ WorkerSessionManager: vi.fn().mockImplementation(function (callbacks: WorkerSessionCallbacks) { mocks.callbacks = callbacks; return { - isConnectedTo: vi.fn(() => false), + ...mocks.worker, ensureWorker: vi.fn(async (clusterId: string, initMessage: InitMessage): Promise => { mocks.clusterId = clusterId; mocks.initMessage = initMessage; @@ -108,7 +121,7 @@ vi.mock('./WorkerSessionManager', () => ({ get workerClusterId(): string | undefined { return mocks.clusterId; }, - sendEval: vi.fn().mockResolvedValue({ result: { type: 'number', printable: '1', durationMs: 0 } }), + shutdown: vi.fn(), dispose: vi.fn(), }; }), @@ -139,6 +152,9 @@ describe('PlaygroundEvaluator token relay lifecycle', () => { mocks.callbacks = undefined; mocks.initMessage = undefined; mocks.clusterId = undefined; + mocks.configuredProvider.mockReturnValue('microsoft'); + mocks.worker.isConnectedTo.mockReturnValue(false); + mocks.worker.sendEval.mockResolvedValue({ result: { type: 'number', printable: '1', durationMs: 0 } }); customSuffix = undefined; vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ get: vi.fn((_key: string, defaultValue: unknown): unknown => defaultValue), @@ -179,7 +195,7 @@ describe('PlaygroundEvaluator token relay lifecycle', () => { if (!init) { throw new Error('Expected the evaluator to initialize its worker'); } - expect(mocks.getCredentials).toHaveBeenCalledExactlyOnceWith(clusterId); + expect(mocks.getCredentials).toHaveBeenCalledWith(clusterId); // Token relays must never consult credentials changed since worker initialization. mocks.getCredentials.mockClear().mockImplementation((): never => { throw new Error('Live credential-cache reads are forbidden during token relay'); @@ -210,6 +226,115 @@ describe('PlaygroundEvaluator token relay lifecycle', () => { expect(mocks.managedIdentityToken).not.toHaveBeenCalled(); } + const connection = { clusterId, clusterDisplayName: 'Test Cluster', databaseName: 'test' }; + + it('uses a verified cluster identity silently on the first relay', async (): Promise => { + const verified = vi.spyOn(ClustersClient, 'getLastVerifiedIdentity').mockReturnValue({ + kind: 'entra', + providerId: 'microsoft', + tenantId: 'interactive-tenant', + accountId: 'private-account', + accountLabel, + }); + try { + await initializeSession(AuthMethodId.MicrosoftEntraID); + const response = await requestToken({ type: 'tokenRequest', requestId: 'first-silent' }); + expect(response).toHaveBeenCalledWith(expect.objectContaining({ type: 'tokenResponse' })); + expect(mocks.interactiveToken).toHaveBeenCalledExactlyOnceWith( + 'microsoft', + [resolution.scope, 'VSCODE_TENANT:interactive-tenant'], + { silent: true, account: { id: 'private-account', label: accountLabel } }, + ); + } finally { + verified.mockRestore(); + } + }); + + it('fails closed for a changed account or provider and does not return either token', async (): Promise => { + await initializeSession(AuthMethodId.MicrosoftEntraID); + await requestToken({ type: 'tokenRequest', requestId: 'first' }); + mocks.interactiveToken.mockResolvedValueOnce({ + id: 'other-session', + account: { id: 'other-account', label: 'other-account' }, + scopes: [resolution.scope], + accessToken: 'other-token', + }); + const mismatch = await requestToken({ type: 'tokenRequest', requestId: 'different-account' }); + expect(mismatch).toHaveBeenCalledWith(expect.objectContaining({ type: 'tokenError', reason: 'identityMismatch' })); + mocks.configuredProvider.mockReturnValue('microsoft-sovereign-cloud'); + const changed = await requestToken({ type: 'tokenRequest', requestId: 'different-provider' }); + expect(changed).toHaveBeenCalledWith(expect.objectContaining({ type: 'tokenError', reason: 'signInRequired' })); + expect(mocks.interactiveToken).toHaveBeenCalledTimes(2); + expect(getRecentEntraTokenFailure(clusterId)).toBeUndefined(); + }); + + it('checks a document fingerprint on warm runs without consulting the credentials cache', async (): Promise => { + await initializeSession(AuthMethodId.NoAuth); + mocks.worker.isConnectedTo.mockReturnValue(true); + const capture = vi.fn(); + await evaluator.evaluate(connection, '2', undefined, capture); + const binding = capture.mock.calls[0][0] as { fingerprint: string }; + await evaluator.evaluate({ ...connection, ...binding }, '3'); + await expect(evaluator.evaluate({ ...connection, fingerprint: 'old-binding' }, '4')).rejects.toMatchObject({ + reason: 'credentialsChanged', + }); + expect(mocks.worker.sendEval).toHaveBeenCalledTimes(3); + }); + + it('rejects a latched Run or an old document binding after evaluator recreation', async (): Promise => { + await initializeSession(AuthMethodId.NoAuth); + mocks.worker.isConnectedTo.mockReturnValue(true); + const capture = vi.fn(); + await evaluator.evaluate(connection, '1', undefined, capture); + const binding = capture.mock.calls[0][0] as { fingerprint: string }; + const oldDocument = { ...connection, ...binding }; + evaluator.dispose(); + evaluator = new PlaygroundEvaluator(); + mocks.worker.isConnectedTo.mockReturnValue(false); + ClustersClient.latch(clusterId, 'userDisconnected'); + try { + await expect(evaluator.evaluate(oldDocument, '2')).rejects.toMatchObject({ reason: 'userDisconnected' }); + } finally { + ClustersClient.unlatch(clusterId); + } + mocks.getCredentials.mockReturnValue({ clusterId, connectionString: 'mongodb://other.example.com/', authMechanism: AuthMethodId.NoAuth }); + await evaluator.evaluate(connection, '3'); + mocks.worker.isConnectedTo.mockReturnValue(true); + await expect(evaluator.evaluate(oldDocument, '4')).rejects.toMatchObject({ reason: 'credentialsChanged' }); + mocks.getCredentials.mockClear(); + }); + + it.each([AuthMethodId.MicrosoftEntraID, AuthMethodId.ManagedIdentity])( + 'restarts %s at the next Run after refresh fails, without replaying the failed query', + async (authMechanism): Promise => { + await initializeSession(authMechanism); + await requestToken({ type: 'tokenRequest', requestId: 'first' }); + mocks.worker.isConnectedTo.mockReturnValue(true); + const capture = vi.fn(); + await evaluator.evaluate(connection, '2', undefined, capture); + const binding = capture.mock.calls[0][0] as { fingerprint: string }; + const bound = { ...connection, ...binding }; + const failure = new Error('outer driver error', { cause: Object.assign(new Error('private broker'), { name: 'TokenCallbackError' }) }); + mocks.worker.sendEval.mockRejectedValueOnce(failure); + await expect(evaluator.evaluate(bound, 'failed')).rejects.toSatisfy((error: unknown) => getWorkerAuthReason(error) === 'refreshFailed'); + mocks.worker.isConnectedTo.mockReturnValue(false); + mocks.getCredentials.mockReturnValue({ + clusterId, + connectionString: originalConnection, + authMechanism, + entraIdConfig: { tenantId: 'interactive-tenant' }, + managedIdentityConfig: { tenantId: 'managed-tenant', clientId: 'managed-client' }, + }); + await evaluator.evaluate(bound, 'next'); + mocks.worker.isConnectedTo.mockReturnValue(true); + mocks.getCredentials.mockClear(); + await evaluator.evaluate(bound, 'after'); + expect(mocks.worker.sendEval.mock.calls.map(([message]) => message.type === 'eval' && message.code)).toEqual([ + '1', '2', 'failed', 'next', 'after', + ]); + }, + ); + it.each([AuthMethodId.MicrosoftEntraID, AuthMethodId.ManagedIdentity])( 'uses the captured %s identity and original connection despite forged request fields', async (authMethod): Promise => { @@ -249,9 +374,12 @@ describe('PlaygroundEvaluator token relay lifecycle', () => { expect(mocks.resolveManagedIdentity).not.toHaveBeenCalled(); expect(mocks.managedIdentityToken).not.toHaveBeenCalled(); expect(mocks.interactiveToken).toHaveBeenCalledTimes(2); - for (const call of mocks.interactiveToken.mock.calls) { - expect(call).toEqual([[resolution.scope], init.tenantId, { createIfNone: true }]); - } + const scopes = [resolution.scope, `VSCODE_TENANT:${init.tenantId}`]; + expect(mocks.interactiveToken).toHaveBeenNthCalledWith(1, 'microsoft', scopes, { createIfNone: true }); + expect(mocks.interactiveToken).toHaveBeenNthCalledWith(2, 'microsoft', scopes, { + silent: true, + account: { id: 'private-account', label: accountLabel }, + }); } expect(response).toHaveBeenCalledExactlyOnceWith({ type: 'tokenResponse', @@ -293,6 +421,7 @@ describe('PlaygroundEvaluator token relay lifecycle', () => { requestId: 'refresh', error: "Microsoft Entra ID isn't allowed for this server.", errorName: 'EntraDestinationRejectedError', + reason: 'destinationRejected', }); const output = JSON.stringify([ response.mock.calls, @@ -348,6 +477,7 @@ describe('PlaygroundEvaluator token relay lifecycle', () => { requestId: 'pending', error: "Microsoft Entra ID isn't allowed for this server.", errorName: 'EntraDestinationRejectedError', + reason: 'destinationRejected', }); expect(getRecentEntraTokenFailure(clusterId)).toBe(failure); expect(startupProperties.entraFailureKind).not.toBe('tokenAcquisitionFailed'); @@ -382,7 +512,8 @@ describe('PlaygroundEvaluator token relay lifecycle', () => { expect(response).toHaveBeenCalledExactlyOnceWith({ type: 'tokenError', requestId: 'native', - error: 'No credentials found for the query playground connection.', + error: 'Failed to obtain a Microsoft Entra ID token.', + reason: 'refreshFailed', }); }); @@ -402,6 +533,7 @@ describe('PlaygroundEvaluator token relay lifecycle', () => { requestId: 'rejected', error: "Microsoft Entra ID isn't allowed for this server.", errorName: 'EntraDestinationRejectedError', + reason: 'destinationRejected', }); }, ); diff --git a/src/documentdb/playground/PlaygroundEvaluator.ts b/src/documentdb/playground/PlaygroundEvaluator.ts index 246ab068e..9836c3e7a 100644 --- a/src/documentdb/playground/PlaygroundEvaluator.ts +++ b/src/documentdb/playground/PlaygroundEvaluator.ts @@ -14,24 +14,23 @@ import { randomUUID } from 'crypto'; import type * as vscode from 'vscode'; import { ext } from '../../extensionVariables'; import { meterSilentCatch } from '../../utils/accumulatingTelemetry'; -import { traceAuthFlow, traceAuthOperation, traceEntraDestination, type AuthTraceContext } from '../../utils/authTrace'; import { getBatchSizeSetting, getConnectionTimeoutMs } from '../../utils/workspacUtils'; -import { AuthMethodId } from '../auth/AuthMethod'; -import { - resolveInteractiveTokenResource, - resolveManagedIdentityTokenResource, - TokenResourceResolutionError, - type ResolvedTokenResource, -} from '../auth/documentdbTokenResource'; -import { evaluateEntraDestinationFromSettings } from '../auth/entraDestinationSettings'; -import { clearEntraTokenFailure, recordEntraTokenFailure } from '../auth/entraErrors/entraTokenFailures'; -import { EntraDestinationRejectedError } from '../auth/oidcAllowedHosts'; +import { type VerifiedEntraIdentity } from '../auth/AuthHandler'; +import { AuthMethodId } from '../auth/AuthMethodId'; +import { createWorkerAuthError, sameEntraIdentity, WorkerTokenRelay } from '../auth/WorkerTokenRelay'; +import { ClustersClient } from '../ClustersClient'; +import { computeConnectionFingerprint } from '../connectionFingerprint'; +import { ConnectionUnavailableError } from '../ConnectionUnavailableError'; import { CredentialCache } from '../CredentialCache'; -import { withTokenAcquisitionTiming, type ConnectionStartupTimings } from '../utils/ConnectionStartupTimings'; import { resolveAllowInvalidCertificates } from '../utils/tlsException'; -import { type ExecutionResult, type PlaygroundConnection } from './types'; +import { type ExecutionResult, type PlaygroundConnection, type PlaygroundWorkerBinding } from './types'; import { WorkerSessionManager } from './WorkerSessionManager'; -import { type MainToWorkerMessage, type SerializableMongoClientOptions, type WorkerToMainMessage } from './workerTypes'; +import { + getWorkerAuthReason, + type MainToWorkerMessage, + type SerializableMongoClientOptions, + type WorkerAuthReason, +} from './workerTypes'; /** * Evaluates query playground code in a persistent worker thread. @@ -78,7 +77,12 @@ import { type MainToWorkerMessage, type SerializableMongoClientOptions, type Wor export class PlaygroundEvaluator implements vscode.Disposable { private readonly _workerManager: WorkerSessionManager; private _sessionInitMessage: Extract | undefined; - private _resolvedTokenResource: ResolvedTokenResource | undefined; + private _relay: WorkerTokenRelay | undefined; + /** A worker snapshot, not a document binding. */ + private _workerFingerprint: string | undefined; + private _pinContext: { clusterId: string; identity: VerifiedEntraIdentity } | undefined; + private _authFailure: { clusterId: string; reason: WorkerAuthReason } | undefined; + private _disposed = false; /** * Telemetry session ID — generated on worker spawn, stable across evals within the @@ -162,13 +166,10 @@ export class PlaygroundEvaluator implements vscode.Disposable { break; } }, - onTokenRequest: ( - msg: Extract, - postResponse: (response: MainToWorkerMessage) => void, - isCurrent: () => boolean, - timings?: ConnectionStartupTimings, - traceContext?: AuthTraceContext, - ) => this.handleTokenRequest(msg, postResponse, isCurrent, timings, traceContext), + onTokenRequest: async (request, post, isCurrent, timings, trace) => { + const relay = this._relay; + await relay?.relay(request, post, () => this._relay === relay && isCurrent(), timings, trace); + }, onWorkerExit: (exitCode: number) => { ext.outputChannel.debug(`${logPrefix} Worker exited with code ${String(exitCode)}`); this.resetSession(); @@ -188,28 +189,84 @@ export class PlaygroundEvaluator implements vscode.Disposable { connection: PlaygroundConnection, code: string, onProgress?: (message: string) => void, + onFirstBinding?: (binding: PlaygroundWorkerBinding) => void, ): Promise { - // Ensure worker is alive and connected to the right cluster - const needsSpawn = !this._workerManager.isConnectedTo(connection.clusterId); - if (needsSpawn) { - onProgress?.(l10n.t('Initializing…')); - ext.outputChannel?.trace( - `[PlaygroundEvaluator] Spawning new worker for cluster=${connection.clusterId}, db=${connection.databaseName}`, - ); + const { clusterId, fingerprint } = connection; + this.assertConnectionAvailable(clusterId); + const epoch = ClustersClient.getEpoch(clusterId); + const sameCluster = this._workerManager.isConnectedTo(clusterId); + const pin = this._pinContext?.clusterId === clusterId ? this._pinContext.identity : undefined; + const verified = ClustersClient.getLastVerifiedIdentity(clusterId); + const entraPin = verified?.kind === 'entra' ? verified : undefined; + const reason = + (this._authFailure?.clusterId === clusterId ? this._authFailure.reason : undefined) ?? + (sameCluster ? this._workerManager.authFailure : undefined); + if (sameCluster && this._relay?.epoch === epoch) { + const currentFingerprint = ClustersClient.getBinding(clusterId)?.fingerprint; + if ( + (fingerprint !== undefined && + (fingerprint !== this._workerFingerprint || + (currentFingerprint !== undefined && fingerprint !== currentFingerprint))) || + (pin && entraPin && !sameEntraIdentity(pin, entraPin)) + ) { + throw new ConnectionUnavailableError('credentialsChanged'); + } } + if ((pin || fingerprint) && (reason === 'signInRequired' || reason === 'identityMismatch')) { + throw createWorkerAuthError(reason); + } + const needsSpawn = !sameCluster || !!reason || this._relay?.epoch !== epoch; const initStartTime = Date.now(); - const initMsg = this.buildInitMessage(connection); - - // Start a new telemetry session if we're spawning a new worker - if (needsSpawn) { + let initMsg: Extract; + if (needsSpawn || !this._sessionInitMessage) { + onProgress?.(l10n.t('Initializing…')); + this.assertConnectionAvailable(clusterId); + const pinned = connection.entraIdentity ?? pin; + const expected = ClustersClient.getExpectedFingerprint(clusterId, pinned); + if (fingerprint !== undefined && fingerprint !== expected) { + throw new ConnectionUnavailableError('credentialsChanged'); + } + if (pin && entraPin && !sameEntraIdentity(pin, entraPin) && !fingerprint) { + throw new ConnectionUnavailableError('credentialsChanged'); + } + initMsg = this.buildInitMessage(connection); + if (this._workerManager.isAlive || this._workerManager.workerState === 'spawning') { + this._workerManager.killWorker(); + } + this.resetSession(); + const workerPin = initMsg.authMechanism === AuthMethodId.MicrosoftEntraID ? entraPin ?? pinned : undefined; + this._pinContext = workerPin && { clusterId, identity: workerPin }; this._sessionInitMessage = initMsg; - this._resolvedTokenResource = undefined; + this._workerFingerprint = expected; this._sessionId = randomUUID(); - this._sessionEvalCount = 0; this._sessionAuthMethod = initMsg.authMechanism; + const originalUri = initMsg.connectionString; + this._relay = new WorkerTokenRelay( + clusterId, + initMsg, + epoch, + this._sessionId, + workerPin, + (identity) => { + this._pinContext = { clusterId, identity }; + this._workerFingerprint = computeConnectionFingerprint({ + connectionString: originalUri, + principal: identity, + }); + }, + ); + } else { + initMsg = this._sessionInitMessage; } + const relay = this._relay; + const assertCurrent = (): void => { + this.assertConnectionAvailable(clusterId); + if (relay !== this._relay || epoch !== ClustersClient.getEpoch(clusterId)) { + throw new ConnectionUnavailableError('credentialsChanged'); + } + }; onProgress?.(l10n.t('Authenticating…')); let originalFailure: { error: unknown } | undefined; try { @@ -219,7 +276,8 @@ export class PlaygroundEvaluator implements vscode.Disposable { context.telemetry.properties.authMethod = initMsg.authMechanism; context.telemetry.properties.needsSpawn = needsSpawn ? 'true' : 'false'; try { - await this._workerManager.ensureWorker(connection.clusterId, initMsg, getConnectionTimeoutMs(), { + assertCurrent(); + await this._workerManager.ensureWorker(clusterId, initMsg, getConnectionTimeoutMs(), { sessionId: this._sessionId, }); } catch (error) { @@ -228,12 +286,18 @@ export class PlaygroundEvaluator implements vscode.Disposable { } }); } catch (error) { - throw originalFailure ? originalFailure.error : error; + originalFailure ??= { error }; } // The telemetry wrapper swallows cancellation even when rethrow is enabled. if (originalFailure) { + this.recordWorkerFailure(clusterId, relay, originalFailure.error); throw originalFailure.error; } + assertCurrent(); + this._authFailure = undefined; + if (fingerprint === undefined && this._workerFingerprint !== undefined) { + onFirstBinding?.({ fingerprint: this._workerFingerprint, entraIdentity: this._pinContext?.identity }); + } this._lastInitDurationMs = needsSpawn ? Date.now() - initStartTime : 0; // Reset console output counter for this eval run @@ -241,6 +305,7 @@ export class PlaygroundEvaluator implements vscode.Disposable { // Send eval message and await result onProgress?.(l10n.t('Running query…')); + assertCurrent(); this._sessionEvalCount++; @@ -252,8 +317,13 @@ export class PlaygroundEvaluator implements vscode.Disposable { displayBatchSize: getBatchSizeSetting(), }; - const workerResult = await this._workerManager.sendEval(evalMsg); - return this.deserializeResult(workerResult.result); + try { + const workerResult = await this._workerManager.sendEval(evalMsg); + return this.deserializeResult(workerResult.result); + } catch (error) { + this.recordWorkerFailure(clusterId, relay, error); + throw error; + } } /** @@ -262,8 +332,10 @@ export class PlaygroundEvaluator implements vscode.Disposable { */ async shutdown(): Promise { ext.outputChannel?.trace('[PlaygroundEvaluator] Shutting down worker'); - await this._workerManager.shutdown(); this.resetSession(); + this._pinContext = undefined; + this._authFailure = undefined; + await this._workerManager.shutdown(); } /** @@ -271,13 +343,40 @@ export class PlaygroundEvaluator implements vscode.Disposable { * Used for infinite loop recovery (timeout) and cancellation. */ killWorker(): void { + const clusterId = this._workerManager.workerClusterId; + const reason = this._workerManager.authFailure; + if (clusterId && reason) { + this._authFailure ??= { clusterId, reason }; + } this._workerManager.killWorker(); this.resetSession(); } dispose(): void { + this._disposed = true; this._workerManager.dispose(); this.resetSession(); + this._pinContext = undefined; + this._authFailure = undefined; + } + + private assertConnectionAvailable(clusterId: string): void { + const reason = ClustersClient.getLatchReason(clusterId); + if (reason || this._disposed) { + throw new ConnectionUnavailableError(reason ?? 'connectionRemoved'); + } + } + + private recordWorkerFailure(clusterId: string, relay: WorkerTokenRelay | undefined, error: unknown): void { + const reason = getWorkerAuthReason(error); + if ( + reason && + relay === this._relay && + relay?.epoch === ClustersClient.getEpoch(clusterId) && + !ClustersClient.getLatchReason(clusterId) + ) { + this._authFailure = { clusterId, reason }; + } } // ─── Private: Init message ─────────────────────────────────────────────── @@ -374,149 +473,6 @@ export class PlaygroundEvaluator implements vscode.Disposable { }; } - // ─── Private: Token handling ───────────────────────────────────────────── - - /** - * Handle a token request from the worker (Entra ID OIDC). - * Token acquisition stays on the main thread so there is one credential and one cache per window. - */ - private async handleTokenRequest( - msg: Extract, - postResponse: (response: MainToWorkerMessage) => void, - isCurrent: () => boolean, - timings?: ConnectionStartupTimings, - traceContext?: AuthTraceContext, - ): Promise { - try { - const clusterId = this._workerManager.workerClusterId; - const sessionInit = this._sessionInitMessage; - if ( - !clusterId || - !sessionInit || - (sessionInit.authMechanism !== 'MicrosoftEntraID' && sessionInit.authMechanism !== 'ManagedIdentity') - ) { - throw new Error(l10n.t('No credentials found for the query playground connection.')); - } - if (!isCurrent()) { - return; - } - const connectionString = sessionInit.connectionString; - const decision = evaluateEntraDestinationFromSettings(connectionString); - traceEntraDestination(decision, msg.requestId, traceContext); - if (!decision.allowed) { - throw new EntraDestinationRejectedError(decision); - } - const usesManagedIdentity = sessionInit.authMechanism === 'ManagedIdentity'; - let resolved: ResolvedTokenResource; - try { - resolved = - this._resolvedTokenResource ?? - (usesManagedIdentity - ? await resolveManagedIdentityTokenResource(connectionString) - : await resolveInteractiveTokenResource(connectionString)); - if (isCurrent()) { - this._resolvedTokenResource = resolved; - } - traceAuthFlow('entraCloud.resolved', resolved.details, msg.requestId, traceContext); - } catch (error) { - if (error instanceof TokenResourceResolutionError) { - traceAuthFlow('entraCloud.unresolved', error.details, msg.requestId, traceContext); - } - throw error; - } - let accessToken: string; - - if (usesManagedIdentity) { - const { getManagedIdentityAccessToken } = await import('../auth/managedIdentityTokenProvider'); - this._sessionId ??= randomUUID(); - try { - accessToken = ( - await withTokenAcquisitionTiming(timings, () => - getManagedIdentityAccessToken( - [resolved.scope], - sessionInit.managedIdentityClientId, - sessionInit.tenantId, - this._sessionId, - traceContext, - ), - ) - ).accessToken; - } catch (error) { - if (traceContext?.startupProperties) { - traceContext.startupProperties.entraFailureKind = 'tokenAcquisitionFailed'; - } - if (isCurrent()) { - recordEntraTokenFailure(clusterId, { - cloudCategory: resolved.cloudCategory, - authMethod: 'managedIdentity', - }); - } - throw error; - } - } else { - const { getSessionFromVSCode } = await import('@microsoft/vscode-azext-azureauth'); - let session: vscode.AuthenticationSession | undefined; - try { - session = await traceAuthOperation( - 'interactiveEntra.getSession', - () => - withTokenAcquisitionTiming(timings, () => - getSessionFromVSCode([resolved.scope], sessionInit.tenantId, { createIfNone: true }), - ), - { - tenantSpecified: !!sessionInit.tenantId, - createIfNone: true, - cloudCategory: resolved.cloudCategory, - tokenResourceReason: resolved.reason, - }, - msg.requestId, - traceContext, - ); - - if (!session) { - throw new Error(l10n.t('Failed to obtain Entra ID token.')); - } - } catch (error) { - if (traceContext?.startupProperties) { - traceContext.startupProperties.entraFailureKind = 'tokenAcquisitionFailed'; - } - if (isCurrent()) { - recordEntraTokenFailure(clusterId, { - cloudCategory: resolved.cloudCategory, - authMethod: 'interactive', - }); - } - throw error; - } - - accessToken = session.accessToken; - } - - const currentDecision = evaluateEntraDestinationFromSettings(connectionString); - traceEntraDestination(currentDecision, msg.requestId, traceContext); - if (!currentDecision.allowed) { - throw new EntraDestinationRejectedError(currentDecision); - } - if (isCurrent()) { - clearEntraTokenFailure(clusterId); - } - postResponse({ - type: 'tokenResponse', - requestId: msg.requestId, - accessToken, - }); - } catch (error: unknown) { - const errorMessage = error instanceof Error ? error.message : String(error); - postResponse({ - type: 'tokenError', - requestId: msg.requestId, - error: errorMessage, - ...(error instanceof EntraDestinationRejectedError - ? { errorName: 'EntraDestinationRejectedError' as const } - : {}), - }); - } - } // ─── Private: Session telemetry ────────────────────────────────────────── @@ -533,7 +489,8 @@ export class PlaygroundEvaluator implements vscode.Disposable { } this._sessionInitMessage = undefined; - this._resolvedTokenResource = undefined; + this._relay = undefined; + this._workerFingerprint = undefined; this._sessionId = undefined; this._sessionEvalCount = 0; this._sessionAuthMethod = undefined; diff --git a/src/documentdb/playground/WorkerSessionManager.test.ts b/src/documentdb/playground/WorkerSessionManager.test.ts index d1725634d..d4e437c54 100644 --- a/src/documentdb/playground/WorkerSessionManager.test.ts +++ b/src/documentdb/playground/WorkerSessionManager.test.ts @@ -28,7 +28,7 @@ import { type WorkerSessionCallbacks, type WorkerStartupTelemetryContext, } from './WorkerSessionManager'; -import { type MainToWorkerMessage } from './workerTypes'; +import { getWorkerAuthReason, type MainToWorkerMessage } from './workerTypes'; interface RecordedTelemetry { readonly eventName: string; @@ -800,6 +800,30 @@ describe('WorkerSessionManager', () => { return { manager, initPromise, requestId: initMessage.requestId, worker }; } + it.each(['signInRequired', 'identityMismatch', 'destinationRejected', 'refreshFailed'] as const)( + 'reconstructs %s at both boundaries and marks a warm worker broken', + async (reason): Promise => { + const failed = await startWorker(); + failed.worker._emit('message', { + type: 'initResult', requestId: failed.requestId, success: false, authReason: reason, + }); + await expect(failed.initPromise).rejects.toSatisfy((error: unknown) => getWorkerAuthReason(error) === reason); + + const active = await startWorker(); + active.worker._emit('message', { type: 'initResult', requestId: active.requestId, success: true }); + await active.initPromise; + const evaluating = active.manager.sendEval({ + type: 'eval', requestId: '', code: '1', databaseName: 'test', displayBatchSize: 20, + }); + const worker = vi.mocked(Worker).mock.results.at(-1)?.value as { postMessage: Mock }; + const evaluation = worker.postMessage.mock.calls.at(-1)?.[0] as MainToWorkerMessage; + active.worker._emit('message', { type: 'evalError', requestId: evaluation.requestId, authReason: reason }); + await expect(evaluating).rejects.toSatisfy((error: unknown) => getWorkerAuthReason(error) === reason); + expect(active.manager.authFailure).toBe(reason); + active.manager.dispose(); + }, + ); + it('reports a stalled token request with total and stage timings without connection details', async () => { const { initPromise, requestId, worker } = await startWorker(); vi.advanceTimersByTime(200); diff --git a/src/documentdb/playground/WorkerSessionManager.ts b/src/documentdb/playground/WorkerSessionManager.ts index 53ea35c56..d4db91fc6 100644 --- a/src/documentdb/playground/WorkerSessionManager.ts +++ b/src/documentdb/playground/WorkerSessionManager.ts @@ -16,6 +16,7 @@ import { Worker } from 'worker_threads'; import { ext } from '../../extensionVariables'; import { settingsKeys } from '../../settingsKeys'; import { traceEntraDestination, type AuthTraceContext } from '../../utils/authTrace'; +import { AuthMethodId } from '../auth/AuthMethodId'; import { getEntraCustomHostnameSuffix } from '../auth/entraDestinationSettings'; import { removeConflictingOidcMechanism } from '../auth/nonOidcConnectionString'; import { @@ -24,13 +25,18 @@ import { normalizeCustomHostnameSuffix, } from '../auth/oidcAllowedHosts'; import { createOidcDestinationPolicy } from '../auth/oidcClientOptions'; +import { createWorkerAuthError } from '../auth/WorkerTokenRelay'; +import { ClustersClient } from '../ClustersClient'; +import { ConnectionUnavailableError } from '../ConnectionUnavailableError'; import { SettingsHintError } from '../shell/SettingsHintError'; import { prepareDriverConnectionString } from '../srv/prepareDriverConnectionString'; import { ConnectionStartupTimings } from '../utils/ConnectionStartupTimings'; import { + isWorkerAuthReason, type MainToWorkerMessage, type SerializableExecutionResult, type SerializableOidcDestinationPolicy, + type WorkerAuthReason, type WorkerStartupStage, type WorkerToMainMessage, } from './workerTypes'; @@ -116,6 +122,9 @@ export class WorkerSessionManager implements vscode.Disposable { private _worker: Worker | undefined; private _workerState: WorkerState = 'idle'; private _workerClusterId: string | undefined; + private _workerAuthMethod: AuthMethodId | undefined; + private _authFailure: WorkerAuthReason | undefined; + private _shuttingDownWorker: Worker | undefined; private _startup: WorkerStartup | undefined; private _startupAbortController: AbortController | undefined; private _oidcDestinationPolicy: SerializableOidcDestinationPolicy | undefined; @@ -152,6 +161,10 @@ export class WorkerSessionManager implements vscode.Disposable { return this._workerClusterId; } + get authFailure(): WorkerAuthReason | undefined { + return this._authFailure; + } + /** * Whether the worker is alive and connected to the specified cluster. */ @@ -179,10 +192,7 @@ export class WorkerSessionManager implements vscode.Disposable { telemetryContext: WorkerStartupTelemetryContext = {}, ): Promise { // If worker is alive but connected to a different cluster, shut it down - if (this._worker && this._workerClusterId !== clusterId) { - ext.outputChannel?.trace( - `[WorkerSessionManager] Cluster changed (${String(this._workerClusterId)} → ${clusterId}), terminating old worker`, - ); + if (this._worker && (this._workerClusterId !== clusterId || this._authFailure || this._shuttingDownWorker)) { this.terminateWorker('intentional'); } @@ -198,13 +208,14 @@ export class WorkerSessionManager implements vscode.Disposable { * @returns The serializable execution result from the worker. */ async sendEval(evalMsg: MainToWorkerMessage & { type: 'eval' }): Promise<{ result: SerializableExecutionResult }> { + const worker = this._worker; this._workerState = 'executing'; try { const result = await this.sendRequest<{ result: SerializableExecutionResult }>(evalMsg); return result; } finally { - if (this._workerState === 'executing') { + if (this._worker === worker && this._workerState === 'executing') { this._workerState = 'ready'; } } @@ -221,13 +232,17 @@ export class WorkerSessionManager implements vscode.Disposable { } ext.outputChannel?.trace('[WorkerSessionManager] Graceful shutdown requested'); + const worker = this._worker; + this._shuttingDownWorker = worker; try { await this.sendRequest({ type: 'shutdown', requestId: '' }, 5000); } catch { // Shutdown timed out or failed — force-kill } - this.terminateWorker('intentional'); + if (this._worker === worker) { + this.terminateWorker('intentional'); + } } /** @@ -330,6 +345,17 @@ export class WorkerSessionManager implements vscode.Disposable { telemetryContext: WorkerStartupTelemetryContext, ): Promise { this._workerState = 'spawning'; + const epoch = ClustersClient.getEpoch(clusterId); + const assertAvailable = (): void => { + const reason = ClustersClient.getLatchReason(clusterId); + if (reason) { + throw new ConnectionUnavailableError(reason); + } + if (epoch !== ClustersClient.getEpoch(clusterId) || abortSignal.aborted) { + throw new UserCancelledError('workerStartup'); + } + }; + assertAvailable(); const options = { ...initMsg.clientOptions }; const usesOidc = initMsg.authMechanism === 'MicrosoftEntraID' || initMsg.authMechanism === 'ManagedIdentity'; const customHostnameSuffix = usesOidc @@ -406,12 +432,11 @@ export class WorkerSessionManager implements vscode.Disposable { // extension root, rather than this module's location, keeps the path independent of the // chunk this code is bundled into. const workerPath = path.join(ext.context.extensionPath, 'playgroundWorker.mjs'); - if (abortSignal.aborted) { - throw new UserCancelledError('workerStartup'); - } + assertAvailable(); const worker = new Worker(workerPath); this._worker = worker; this._workerClusterId = clusterId; + this._workerAuthMethod = initMsg.authMechanism as AuthMethodId; // Everything this worker reports stays tied to the startup that created it. const connection: AuthTraceContext = { startupCorrelationId: startup.requestId, @@ -421,7 +446,9 @@ export class WorkerSessionManager implements vscode.Disposable { // Listen for messages from the worker worker.on('message', (msg: WorkerToMainMessage) => { - this.handleWorkerMessage(msg, connection); + if (this._worker === worker) { + this.handleWorkerMessage(msg, connection, worker); + } }); // terminateWorker() detaches a worker before it exits, so only the current worker can exit unexpectedly. @@ -450,6 +477,10 @@ export class WorkerSessionManager implements vscode.Disposable { }); await this.sendRequest(preparedInitMsg, initTimeoutMs, settingsKeys.connectionTimeout); + assertAvailable(); + if (this._worker !== worker || this._shuttingDownWorker === worker) { + throw new UserCancelledError('workerStartup'); + } this.finishStartup('succeeded'); this._workerState = 'ready'; } @@ -586,7 +617,7 @@ export class WorkerSessionManager implements vscode.Disposable { /** * Handle an incoming message from the worker. */ - private handleWorkerMessage(msg: WorkerToMainMessage, connection: AuthTraceContext): void { + private handleWorkerMessage(msg: WorkerToMainMessage, connection: AuthTraceContext, worker: Worker): void { switch (msg.type) { case 'initTiming': { const startup = this._startup; @@ -620,12 +651,16 @@ export class WorkerSessionManager implements vscode.Disposable { const pending = this._pendingRequests.get(msg.requestId); if (pending) { this._pendingRequests.delete(msg.requestId); - if (msg.success) { + const reason = isWorkerAuthReason(msg.authReason) + ? msg.authReason + : (msg.errorName === 'EntraDestinationRejectedError' ? 'destinationRejected' : this._authFailure); + this._authFailure ??= reason; + if (msg.success && !reason) { pending.resolve(undefined); } else { pending.reject( - msg.errorName === 'EntraDestinationRejectedError' - ? new EntraDestinationRejectedError({ hostCount: 0 }) + reason + ? createWorkerAuthError(reason, this._workerAuthMethod) : new Error(msg.error ?? 'Worker init failed'), ); } @@ -637,6 +672,10 @@ export class WorkerSessionManager implements vscode.Disposable { const pending = this._pendingRequests.get(msg.requestId); if (pending) { this._pendingRequests.delete(msg.requestId); + if (isWorkerAuthReason(msg.authReason)) { + this._authFailure ??= msg.authReason; + } + // Never turn a successful (possibly side-effecting) command into a retry. pending.resolve(msg); } break; @@ -646,8 +685,12 @@ export class WorkerSessionManager implements vscode.Disposable { const pending = this._pendingRequests.get(msg.requestId); if (pending) { this._pendingRequests.delete(msg.requestId); - const error: Error & { code?: number } = new Error(msg.error); - if (msg.stack) { + const reason = isWorkerAuthReason(msg.authReason) ? msg.authReason : this._authFailure; + this._authFailure ??= reason; + const error: Error & { code?: number } = reason + ? createWorkerAuthError(reason, this._workerAuthMethod) + : new Error(msg.error); + if (!reason && msg.stack) { error.stack = msg.stack; } if (msg.code !== undefined) { @@ -668,16 +711,23 @@ export class WorkerSessionManager implements vscode.Disposable { } case 'tokenRequest': { - if (this._callbacks.onTokenRequest) { - const worker = this._worker; + const isCurrent = (): boolean => this._worker === worker && this._shuttingDownWorker !== worker; + if (isCurrent() && this._callbacks.onTokenRequest) { void this._callbacks.onTokenRequest( msg, (response) => { - if (this._worker === worker) { - worker?.postMessage(response); + if (isCurrent()) { + if (response.type === 'tokenError') { + this._authFailure ??= isWorkerAuthReason(response.reason) + ? response.reason + : response.errorName === 'EntraDestinationRejectedError' + ? 'destinationRejected' + : 'refreshFailed'; + } + worker.postMessage(response); } }, - () => this._worker === worker, + isCurrent, this._startup?.costTimings, connection, ); @@ -712,6 +762,9 @@ export class WorkerSessionManager implements vscode.Disposable { this._workerState = 'idle'; this._workerClusterId = undefined; + this._workerAuthMethod = undefined; + this._authFailure = undefined; + this._shuttingDownWorker = undefined; // Reject all pending requests for (const [, entry] of this._pendingRequests) { @@ -748,6 +801,9 @@ export class WorkerSessionManager implements vscode.Disposable { this._worker = undefined; this._workerState = 'idle'; this._workerClusterId = undefined; + this._workerAuthMethod = undefined; + this._authFailure = undefined; + this._shuttingDownWorker = undefined; // Reject any still-pending requests for (const [, entry] of this._pendingRequests) { diff --git a/src/documentdb/playground/playgroundWorker.test.ts b/src/documentdb/playground/playgroundWorker.test.ts index e927cb2b5..c70f47710 100644 --- a/src/documentdb/playground/playgroundWorker.test.ts +++ b/src/documentdb/playground/playgroundWorker.test.ts @@ -17,6 +17,7 @@ const transport = vi.hoisted(() => ({ on: vi.fn(), postMessage: vi.fn() })); const driver = vi.hoisted(() => ({ construct: vi.fn<(connectionString: string, options: MongoClientOptions) => void>(), connect: vi.fn(), + evaluate: vi.fn(), })); vi.mock('worker_threads', () => ({ parentPort: transport })); @@ -32,7 +33,7 @@ vi.mock('mongodb', async () => { }); vi.mock('@documentdb-js/shell-runtime', () => ({ DocumentDBShellRuntime: vi.fn().mockImplementation(function () { - return {}; + return { evaluate: driver.evaluate }; }), })); @@ -257,9 +258,54 @@ describe('playground worker OIDC configuration at the driver boundary', () => { success: false, error: "Microsoft Entra ID isn't allowed for this server.", errorName: 'EntraDestinationRejectedError', + authReason: 'destinationRejected', }); }); + it.each(['signInRequired', 'identityMismatch', 'destinationRejected', 'refreshFailed'] as const)( + 'round trips %s during init and a warm eval even when the driver discards the callback error', + async (reason): Promise => { + const rejectCallback = async (): Promise => { + const callback = driver.construct.mock.calls.at(-1)?.[1].authMechanismProperties?.OIDC_CALLBACK; + if (!callback) { + throw new Error('Expected worker OIDC callback'); + } + const pending = callback({ version: 1, timeoutContext: new AbortController().signal }); + const request = transport.postMessage.mock.calls + .map(([message]) => message as WorkerToMainMessage) + .findLast((message) => message.type === 'tokenRequest'); + expect(request).toBeDefined(); + receive({ type: 'tokenError', requestId: request!.requestId, error: 'private broker detail', reason }); + try { + await pending; + } catch { + throw new Error('Driver discarded the callback error'); + } + throw new Error('Unexpected successful callback'); + }; + driver.connect.mockImplementationOnce(rejectCallback); + init({ authMechanism: reason === 'refreshFailed' ? 'ManagedIdentity' : 'MicrosoftEntraID' }); + await waitForInit(); + expect(transport.postMessage).toHaveBeenCalledWith( + expect.objectContaining({ type: 'initResult', success: false, authReason: reason }), + ); + + transport.postMessage.mockClear(); + init(); + await waitForInit(); + expect(transport.postMessage).toHaveBeenCalledWith( + expect.objectContaining({ type: 'initResult', success: true }), + ); + driver.evaluate.mockImplementationOnce(rejectCallback); + receive({ + type: 'eval', requestId: 'warm', code: 'db.test.find()', displayBatchSize: 20, databaseName: 'test', + }); + await vi.waitFor(() => expect(transport.postMessage).toHaveBeenCalledWith( + expect.objectContaining({ type: 'evalError', requestId: 'warm', authReason: reason }), + )); + }, + ); + it.each([ 'mongodb://attacker.cloudapp.azure.com/', 'mongodb://resolved.mongocluster.cosmos.azure.com,attacker.example.com/', @@ -278,6 +324,7 @@ describe('playground worker OIDC configuration at the driver boundary', () => { success: false, error: "Microsoft Entra ID isn't allowed for this server.", errorName: 'EntraDestinationRejectedError', + authReason: 'destinationRejected', }); }, ); diff --git a/src/documentdb/playground/playgroundWorker.ts b/src/documentdb/playground/playgroundWorker.ts index 1bd7d3d27..1da8a4474 100644 --- a/src/documentdb/playground/playgroundWorker.ts +++ b/src/documentdb/playground/playgroundWorker.ts @@ -23,6 +23,7 @@ import { EJSON } from 'bson'; import { randomUUID } from 'crypto'; import { type MongoClientOptions, type MongoClient as MongoClientType } from 'mongodb'; import { parentPort } from 'worker_threads'; +import { AuthMethodId } from '../auth/AuthMethodId'; import { removeConflictingOidcMechanism } from '../auth/nonOidcConnectionString'; import { EntraDestinationRejectedError, normalizeCustomHostnameSuffix } from '../auth/oidcAllowedHosts'; import { @@ -31,7 +32,15 @@ import { type OidcDestinationPolicy, } from '../auth/oidcClientOptions'; import { expiresInSecondsFromTimestamp, readJwtTimes } from '../auth/tokenExpiry'; -import { type MainToWorkerMessage, type WorkerStartupStage, type WorkerToMainMessage } from './workerTypes'; +import { + getWorkerAuthReason, + isWorkerAuthReason, + workerAuthErrorName, + type MainToWorkerMessage, + type WorkerAuthReason, + type WorkerStartupStage, + type WorkerToMainMessage, +} from './workerTypes'; if (!parentPort) { throw new Error('playgroundWorker.ts must be run as a worker_thread'); @@ -41,6 +50,17 @@ if (!parentPort) { let mongoClient: MongoClientType | undefined; let shellRuntime: DocumentDBShellRuntime | undefined; +// Some driver/runtime error paths discard the original callback error (including its cause). +let callbackFailure: WorkerAuthReason | undefined; + +function relayError(reason: WorkerAuthReason): Error { + if (reason === 'destinationRejected') { + return new EntraDestinationRejectedError({ hostCount: 0 }); + } + const error = new Error(reason); + error.name = workerAuthErrorName(reason); + return error; +} /** * Tracks the requestId of the currently executing eval message. @@ -75,6 +95,7 @@ parentPort.on('message', (msg: MainToWorkerMessage) => { requestId: msg.requestId, success: false, error: errorMessage, + authReason: getWorkerAuthReason(err) ?? callbackFailure, ...(err instanceof EntraDestinationRejectedError ? { errorName: 'EntraDestinationRejectedError' as const } : {}), @@ -98,6 +119,7 @@ parentPort.on('message', (msg: MainToWorkerMessage) => { error: errorMessage, stack, code, + authReason: getWorkerAuthReason(err) ?? callbackFailure, }; parentPort!.postMessage(response); }); @@ -120,6 +142,7 @@ parentPort.on('message', (msg: MainToWorkerMessage) => { // ─── Init handler ──────────────────────────────────────────────────────────── async function handleInit(msg: Extract): Promise { + callbackFailure = undefined; let connecting = true; const reportTiming = (activity: 'databaseConnect' | 'tokenWait', activityId: string, started: boolean): void => { if (connecting) { @@ -154,7 +177,7 @@ async function handleInit(msg: Extract): // differs, and both are resolved on the main thread so there is one credential and one cache // per window, and so the worker never needs @azure/identity. let connectionString = msg.connectionString; - if (msg.authMechanism === 'MicrosoftEntraID' || msg.authMechanism === 'ManagedIdentity') { + if (msg.authMechanism === AuthMethodId.MicrosoftEntraID || msg.authMechanism === AuthMethodId.ManagedIdentity) { const snapshot = msg.oidcDestinationPolicy; if ( !snapshot || @@ -181,7 +204,7 @@ async function handleInit(msg: Extract): originalPolicy.assertAllowed(host); }, }; - const usesManagedIdentity = msg.authMechanism === 'ManagedIdentity'; + const usesManagedIdentity = msg.authMechanism === AuthMethodId.ManagedIdentity; const configuration = buildOidcClientConfiguration({ connectionString, policy, @@ -220,6 +243,21 @@ async function handleInit(msg: Extract): }); connectionString = configuration.connectionString; options = configuration.options; + const authProperties = options.authMechanismProperties; + const oidcCallback = authProperties?.OIDC_CALLBACK; + if (oidcCallback) { + authProperties.OIDC_CALLBACK = async (params) => { + if (callbackFailure) { + throw relayError(callbackFailure); + } + try { + return await oidcCallback(params); + } catch (error) { + callbackFailure ??= getWorkerAuthReason(error) ?? 'refreshFailed'; + throw error; + } + }; + } if (configuration.ignoredTlsBypass) { log('info', '[Auth] TLS validation bypass parameters are ignored for Microsoft Entra ID connections.'); } @@ -262,6 +300,7 @@ async function handleInit(msg: Extract): type: 'initResult', requestId: msg.requestId, success: true, + authReason: callbackFailure, }; parentPort!.postMessage(response); } @@ -269,6 +308,9 @@ async function handleInit(msg: Extract): // ─── Eval handler ──────────────────────────────────────────────────────────── async function handleEval(msg: Extract): Promise { + if (callbackFailure) { + throw relayError(callbackFailure); + } if (!mongoClient || !shellRuntime) { throw new Error('Worker not initialized — call init first'); } @@ -321,6 +363,7 @@ async function handleEval(msg: Extract): const response: WorkerToMainMessage = { type: 'evalResult', requestId: msg.requestId, + authReason: callbackFailure, result: { type: result.type, printable: printableStr, @@ -372,11 +415,10 @@ function handleTokenResponse(msg: Extract): void { const pending = pendingTokenRequests.get(msg.requestId); if (pending) { - pending.reject( - msg.errorName === 'EntraDestinationRejectedError' - ? new EntraDestinationRejectedError({ hostCount: 0 }) - : new Error(msg.error), - ); + const reason = isWorkerAuthReason(msg.reason) + ? msg.reason + : msg.errorName === 'EntraDestinationRejectedError' ? 'destinationRejected' : 'refreshFailed'; + pending.reject(relayError(reason)); pendingTokenRequests.delete(msg.requestId); } } @@ -392,6 +434,7 @@ process.on('uncaughtException', (error: Error) => { requestId: currentEvalRequestId, error: `Uncaught exception: ${error.message}`, stack: error.stack, + authReason: getWorkerAuthReason(error) ?? callbackFailure, }; parentPort!.postMessage(response); currentEvalRequestId = undefined; @@ -424,6 +467,7 @@ process.on('unhandledRejection', (reason: unknown) => { requestId: currentEvalRequestId, error: `Unhandled rejection: ${message}`, stack, + authReason: getWorkerAuthReason(reason) ?? callbackFailure, }; parentPort!.postMessage(response); currentEvalRequestId = undefined; diff --git a/src/documentdb/playground/types.ts b/src/documentdb/playground/types.ts index 359246db6..f2ac21027 100644 --- a/src/documentdb/playground/types.ts +++ b/src/documentdb/playground/types.ts @@ -3,6 +3,14 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import { type VerifiedEntraIdentity } from '../auth/AuthHandler'; + +/** In-memory binding owned by a document, including the pin if learned by a worker first. */ +export interface PlaygroundWorkerBinding { + readonly fingerprint: string; + readonly entraIdentity?: VerifiedEntraIdentity; +} + /** * Represents a query playground connection bound to a specific document. * Each playground document has its own connection to a cluster/database. @@ -14,6 +22,8 @@ export interface PlaygroundConnection { readonly clusterDisplayName: string; /** Target database name for query execution. */ readonly databaseName: string; + readonly fingerprint?: string; + readonly entraIdentity?: VerifiedEntraIdentity; /** * Identifies which tree view this cluster belongs to. * Used by cross-feature navigation to open the correct branch data provider. diff --git a/src/documentdb/playground/workerTypes.ts b/src/documentdb/playground/workerTypes.ts index 685773698..ddf017718 100644 --- a/src/documentdb/playground/workerTypes.ts +++ b/src/documentdb/playground/workerTypes.ts @@ -64,6 +64,63 @@ export interface SerializableOidcDestinationPolicy { readonly revoked: SharedArrayBuffer; } +export type WorkerAuthReason = 'signInRequired' | 'identityMismatch' | 'destinationRejected' | 'refreshFailed'; + +const authErrorNames = { + signInRequired: 'EntraSignInRequiredError', + identityMismatch: 'EntraIdentityMismatchError', + destinationRejected: 'EntraDestinationRejectedError', + refreshFailed: 'TokenCallbackError', +} as const satisfies Record; + +export function isWorkerAuthReason(reason: unknown): reason is WorkerAuthReason { + return typeof reason === 'string' && Object.hasOwn(authErrorNames, reason); +} + +export function workerAuthErrorName(reason: WorkerAuthReason): string { + return authErrorNames[reason]; +} + +/** Recognize only bounded callback failures, not driver message text. */ +export function getWorkerAuthReason(error: unknown): WorkerAuthReason | undefined { + const visited = new Set(); + const pending = [error]; + let reason: WorkerAuthReason | undefined; + while (pending.length) { + const current = pending.pop(); + if (typeof current !== 'object' || current === null || visited.has(current)) { + continue; + } + visited.add(current); + if ('name' in current) { + switch (current.name) { + case authErrorNames.signInRequired: + return 'signInRequired'; + case authErrorNames.identityMismatch: + return 'identityMismatch'; + case authErrorNames.destinationRejected: + return 'destinationRejected'; + case authErrorNames.refreshFailed: + reason = 'refreshFailed'; + } + } + if ('cause' in current) { + pending.push(current.cause); + } + // MongoServerSelectionError keeps per-server errors on its topology description. + if ('reason' in current) { + pending.push(current.reason); + } + if ('servers' in current && current.servers instanceof Map) { + pending.push(...current.servers.values()); + } + if ('error' in current) { + pending.push(current.error); + } + } + return reason; +} + export type MainToWorkerMessage = | { readonly type: 'init'; @@ -111,6 +168,7 @@ export type MainToWorkerMessage = readonly requestId: string; readonly error: string; readonly errorName?: 'EntraDestinationRejectedError'; + readonly reason?: WorkerAuthReason; }; // ─── Worker → Main messages ───────────────────────────────────────────────── @@ -142,11 +200,13 @@ export type WorkerToMainMessage = readonly success: boolean; readonly error?: string; readonly errorName?: 'EntraDestinationRejectedError'; + readonly authReason?: WorkerAuthReason; } | { readonly type: 'evalResult'; readonly requestId: string; readonly result: SerializableExecutionResult; + readonly authReason?: WorkerAuthReason; } | { readonly type: 'evalError'; @@ -155,6 +215,7 @@ export type WorkerToMainMessage = readonly stack?: string; /** Error code from the database (e.g. 50 for MaxTimeMSExpired). */ readonly code?: number; + readonly authReason?: WorkerAuthReason; } | { readonly type: 'shutdownComplete'; diff --git a/src/documentdb/shell/ShellSessionManager.test.ts b/src/documentdb/shell/ShellSessionManager.test.ts index 7a5df24cf..db42a395a 100644 --- a/src/documentdb/shell/ShellSessionManager.test.ts +++ b/src/documentdb/shell/ShellSessionManager.test.ts @@ -26,12 +26,14 @@ import { ClustersClient } from '../ClustersClient'; import { CredentialCache } from '../CredentialCache'; import { PlaygroundEvaluator } from '../playground/PlaygroundEvaluator'; import { type WorkerSessionCallbacks } from '../playground/WorkerSessionManager'; -import { type MainToWorkerMessage, type WorkerToMainMessage } from '../playground/workerTypes'; +import { getWorkerAuthReason, type MainToWorkerMessage, type WorkerToMainMessage } from '../playground/workerTypes'; import { ConnectionStartupTimings } from '../utils/ConnectionStartupTimings'; import { ShellSessionManager } from './ShellSessionManager'; const mockGetSessionFromVSCode = vi.fn(); const mockGetManagedIdentityAccessToken = vi.fn(); +const sendEval = vi.fn(); +const killWorker = vi.fn(); let workerCallbacks: WorkerSessionCallbacks; let workerClusterId: string | undefined; let requestTokenOnInit = false; @@ -50,7 +52,13 @@ vi.mock('../../extensionVariables', () => ({ vi.mock('@microsoft/vscode-azext-azureauth', async (importOriginal) => ({ ...(await importOriginal()), - getSessionFromVSCode: (...args: unknown[]) => mockGetSessionFromVSCode(...args), + getConfiguredAuthProviderId: () => 'microsoft', + getConfiguredAzureEnv: () => ({ name: 'AzureCloud' }), +})); + +vi.mock('vscode', async (importOriginal) => ({ + ...(await importOriginal()), + authentication: { getSession: (...args: unknown[]) => mockGetSessionFromVSCode(...args) }, })); vi.mock('../auth/managedIdentityTokenProvider', () => ({ @@ -88,7 +96,7 @@ vi.mock('../playground/WorkerSessionManager', () => ({ }, ), isConnectedTo: vi.fn(() => false), - sendEval: vi.fn().mockResolvedValue({ result: { type: 'number', printable: '1', durationMs: 0 } }), + sendEval, get isAlive(): boolean { return true; }, @@ -99,6 +107,7 @@ vi.mock('../playground/WorkerSessionManager', () => ({ return workerClusterId; }, dispose: vi.fn(), + killWorker, }; }), })); @@ -124,6 +133,7 @@ describe('ShellSessionManager', () => { beforeEach(() => { vi.clearAllMocks(); + sendEval.mockReset().mockResolvedValue({ result: { type: 'number', printable: '1', durationMs: 0 } }); resetEntraTokenFailuresForTests(); workerClusterId = clusterId; requestTokenOnInit = false; @@ -158,6 +168,49 @@ describe('ShellSessionManager', () => { resetEntraTokenFailuresForTests(); }); + it('permits a password-only respawn but blocks a username change', async (): Promise => { + const manager = new ShellSessionManager({ clusterId, clusterDisplayName: 'Cluster', databaseName: 'test' }); + const setNative = (connectionUser: string, connectionPassword: string): void => + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.NativeAuth, 'mongodb://native.example.com/', { + connectionUser, connectionPassword, + }); + setNative('account-a', 'first'); + await manager.initialize(); + manager.killWorker(); + setNative('account-a', 'rotated'); + await manager.evaluate('password-only'); + manager.killWorker(); + setNative('account-b', 'rotated'); + await expect(manager.evaluate('different-account')).rejects.toMatchObject({ reason: 'credentialsChanged' }); + expect(sendEval).toHaveBeenCalledOnce(); + manager.dispose(); + }); + + it('holds a silent miss until the same account explicitly signs in and never replays the command', async (): Promise => { + const manager = new ShellSessionManager({ clusterId, clusterDisplayName: 'Cluster', databaseName: 'test' }); + requestTokenOnInit = true; + mockGetSessionFromVSCode.mockResolvedValue({ + accessToken: 'private-token', account: { id: 'account-a', label: 'Account A' }, + }); + await manager.initialize(); + const identity = manager.pinnedEntraIdentity!; + const epoch = ClustersClient.getEpoch(clusterId); + sendEval.mockRejectedValueOnce(Object.assign(new Error('miss'), { name: 'EntraSignInRequiredError' })); + await expect(manager.evaluate('first')).rejects.toSatisfy((error: unknown) => getWorkerAuthReason(error) === 'signInRequired'); + await expect(manager.evaluate('blocked')).rejects.toMatchObject({ name: 'EntraSignInRequiredError' }); + expect(() => manager.resetAfterSignIn({ ...identity, accountId: 'account-b' }, epoch)).toThrow( + expect.objectContaining({ name: 'EntraIdentityMismatchError' }), + ); + manager.resetAfterSignIn(identity, epoch); + expect(sendEval).toHaveBeenCalledOnce(); + await manager.evaluate('next'); + expect(sendEval.mock.calls.map(([message]) => message.code)).toEqual(['first', 'next']); + expect(mockGetSessionFromVSCode.mock.calls[1][2]).toEqual({ + silent: true, account: { id: 'account-a', label: 'Account A' }, + }); + manager.dispose(); + }); + async function initializeSession( manager: ShellSessionManager | PlaygroundEvaluator, source?: 'vscode' | 'managedIdentity', @@ -181,6 +234,55 @@ describe('ShellSessionManager', () => { } } + it.each([ + ['shell', 'vscode', true], + ['shell', 'managedIdentity', false], + ['playground', 'vscode', false], + ['playground', 'managedIdentity', true], + ] as const)('ignores a late %s %s relay from an old epoch (rejects = %s)', async (surface, source, rejects) => { + const manager = + surface === 'shell' + ? new ShellSessionManager({ clusterId, clusterDisplayName: 'Cluster', databaseName: 'test' }) + : new PlaygroundEvaluator(); + await initializeSession(manager, source); + const provider = source === 'vscode' ? mockGetSessionFromVSCode : mockGetManagedIdentityAccessToken; + const result = { accessToken: 'private-token', account: { id: 'account-a', label: 'Account A' } }; + let complete!: () => void; + provider.mockImplementationOnce(async () => { + await new Promise((resolve) => { + complete = resolve; + }); + if (rejects) { + throw new Error('private provider failure'); + } + return result; + }); + const reply = vi.fn(); + const startupProperties: Record = {}; + const pending = workerCallbacks.onTokenRequest?.( + { type: 'tokenRequest', requestId: 'old' }, + reply, + () => true, + undefined, + { startupCorrelationId: 'old-startup', surface, startupProperties }, + ); + await vi.waitFor(() => expect(provider).toHaveBeenCalledOnce()); + ClustersClient.latch(clusterId, 'userDisconnected'); + manager.killWorker(); + ClustersClient.unlatch(clusterId); + await initializeSession(manager, source); + if (!rejects) { + recordEntraTokenFailure(clusterId, { cloudCategory: 'public', authMethod: 'interactive' }); + } + const newerFailure = getRecentEntraTokenFailure(clusterId); + complete(); + await pending; + expect(reply).not.toHaveBeenCalled(); + expect(startupProperties.entraFailureKind).not.toBe('tokenAcquisitionFailed'); + expect(getRecentEntraTokenFailure(clusterId)).toBe(newerFailure); + manager.dispose(); + }); + describe.each(['shell', 'playground'] as const)('%s relay destination enforcement', (surface) => { function createManager(): ShellSessionManager | PlaygroundEvaluator { return surface === 'shell' @@ -216,7 +318,7 @@ describe('ShellSessionManager', () => { authMethod === AuthMethodId.ManagedIdentity ? mockGetManagedIdentityAccessToken : mockGetSessionFromVSCode; - provider.mockResolvedValue({ accessToken: 'private-token', account: { label: 'private-account' } }); + provider.mockResolvedValue({ accessToken: 'private-token', account: { id: 'account', label: 'private-account' } }); const postResponse = vi.fn(); const forged = { type: 'tokenRequest', @@ -242,8 +344,8 @@ describe('ShellSessionManager', () => { expect(resolveInteractiveTokenResource).toHaveBeenCalledExactlyOnceWith(original); expect(mockGetManagedIdentityAccessToken).not.toHaveBeenCalled(); expect(provider).toHaveBeenCalledWith( - ['https://ossrdbms-aad.database.windows.net/.default'], - 'original-tenant', + 'microsoft', + ['https://ossrdbms-aad.database.windows.net/.default', 'VSCODE_TENANT:original-tenant'], { createIfNone: true }, ); } @@ -284,6 +386,7 @@ describe('ShellSessionManager', () => { requestId: 'rejected', error: "Microsoft Entra ID isn't allowed for this server.", errorName: 'EntraDestinationRejectedError', + reason: 'destinationRejected', }); expect(startupProperties).toEqual({ entraDestinationClass: 'otherAzure', @@ -309,7 +412,7 @@ describe('ShellSessionManager', () => { authMethod === AuthMethodId.ManagedIdentity ? mockGetManagedIdentityAccessToken : mockGetSessionFromVSCode; - provider.mockResolvedValue({ accessToken: 'private-token', account: { label: 'private-account' } }); + provider.mockResolvedValue({ accessToken: 'private-token', account: { id: 'account', label: 'private-account' } }); const postResponse = vi.fn(); await workerCallbacks.onTokenRequest?.( { type: 'tokenRequest', requestId: 'first' }, @@ -338,6 +441,7 @@ describe('ShellSessionManager', () => { requestId: 'refresh', error: "Microsoft Entra ID isn't allowed for this server.", errorName: 'EntraDestinationRejectedError', + reason: 'destinationRejected', }); manager.dispose(); }, @@ -366,7 +470,7 @@ describe('ShellSessionManager', () => { : mockGetSessionFromVSCode; provider.mockImplementationOnce(async () => { await gate; - return { accessToken: 'must-not-post', account: { label: 'private-account' } }; + return { accessToken: 'must-not-post', account: { id: 'account', label: 'private-account' } }; }); const response = vi.fn(); const startupProperties: Record = {}; @@ -386,6 +490,7 @@ describe('ShellSessionManager', () => { requestId: 'pending', error: "Microsoft Entra ID isn't allowed for this server.", errorName: 'EntraDestinationRejectedError', + reason: 'destinationRejected', }); expect(getRecentEntraTokenFailure(clusterId)).toBe(failure); expect(startupProperties.entraFailureKind).not.toBe('tokenAcquisitionFailed'); @@ -491,7 +596,7 @@ describe('ShellSessionManager', () => { const provider = source === 'vscode' ? mockGetSessionFromVSCode : mockGetManagedIdentityAccessToken; provider.mockImplementationOnce(async () => { now = 40; - return { accessToken: 'private-token', account: { label: 'private-account' } }; + return { accessToken: 'private-token', account: { id: 'account', label: 'private-account' } }; }); await initializeSession(manager, source); const stopDatabase = timings.startDatabaseConnect(); @@ -534,7 +639,7 @@ describe('ShellSessionManager', () => { } else { expect(ext.outputChannel.info).toHaveBeenCalledWith( expect.stringContaining( - `[Authentication] startup=startup-id surface=${surface} interactiveEntra.getSession`, + `[Authentication] startup=startup-id surface=${surface} workerTokenRelay.completed`, ), ); } @@ -569,7 +674,7 @@ describe('ShellSessionManager', () => { }, }); const provider = source === 'vscode' ? mockGetSessionFromVSCode : mockGetManagedIdentityAccessToken; - provider.mockResolvedValueOnce({ accessToken: 'private-token', account: { label: 'private-account' } }); + provider.mockResolvedValueOnce({ accessToken: 'private-token', account: { id: 'account', label: 'private-account' } }); const manager = surface === 'shell' ? new ShellSessionManager({ clusterId, clusterDisplayName: 'Test Cluster', databaseName: 'test' }) @@ -593,7 +698,8 @@ describe('ShellSessionManager', () => { entraFailureKind: 'none', }); expect(resolver).toHaveBeenCalledWith(connectionString); - expect(provider.mock.calls.at(-1)?.[0]).toEqual(['https://ossrdbms-aad.database.usgovcloudapi.net/.default']); + const args = provider.mock.calls.at(-1); + expect(args?.[source === 'vscode' ? 1 : 0]).toEqual(['https://ossrdbms-aad.database.usgovcloudapi.net/.default']); expect(postResponse).toHaveBeenCalledWith({ type: 'tokenResponse', requestId: 'token-request', @@ -642,7 +748,8 @@ describe('ShellSessionManager', () => { expect(postResponse).toHaveBeenCalledWith({ type: 'tokenError', requestId: 'token-request', - error: error.message, + error: 'Failed to obtain a Microsoft Entra ID token.', + reason: 'refreshFailed', }); manager.dispose(); }, @@ -694,7 +801,8 @@ describe('ShellSessionManager', () => { expect(postResponse).toHaveBeenCalledExactlyOnceWith({ type: 'tokenError', requestId: 'token-request', - error: error.message, + error: 'Failed to obtain a Microsoft Entra ID token.', + reason: 'refreshFailed', }); expect(error.code).toBe('original-code'); expect(getRecentEntraTokenFailure(clusterId)).toEqual({ @@ -743,7 +851,8 @@ describe('ShellSessionManager', () => { expect(postResponse).toHaveBeenLastCalledWith({ type: 'tokenError', requestId: 'failed-token-request', - error: error.message, + error: 'Failed to obtain a Microsoft Entra ID token.', + reason: 'refreshFailed', }); const failure = getRecentEntraTokenFailure(clusterId); expect(failure).toMatchObject({ @@ -755,7 +864,7 @@ describe('ShellSessionManager', () => { provider.mockImplementationOnce(async () => { expect(getRecentEntraTokenFailure(clusterId)).toBe(failure); - return { accessToken: 'private-token', account: { label: 'private-account' } }; + return { accessToken: 'private-token', account: { id: 'account', label: 'private-account' } }; }); const successfulProperties: Record = {}; await workerCallbacks.onTokenRequest?.( @@ -804,7 +913,8 @@ describe('ShellSessionManager', () => { expect(postResponse).toHaveBeenCalledExactlyOnceWith({ type: 'tokenError', requestId: 'token-request', - error: 'Failed to obtain Entra ID token.', + error: 'Failed to obtain a Microsoft Entra ID token.', + reason: 'refreshFailed', }); expect(getRecentEntraTokenFailure(clusterId)).toMatchObject({ cloudCategory: 'public', @@ -830,7 +940,7 @@ describe('ShellSessionManager', () => { () => true, ); - expect(postResponse).toHaveBeenCalledWith(expect.objectContaining({ type: 'tokenError' })); + expect(postResponse).not.toHaveBeenCalled(); expect(mockGetSessionFromVSCode).not.toHaveBeenCalled(); expect(getRecentEntraTokenFailure(clusterId)).toBeUndefined(); manager.dispose(); diff --git a/src/documentdb/shell/ShellSessionManager.ts b/src/documentdb/shell/ShellSessionManager.ts index ac111d75f..6db7d909f 100644 --- a/src/documentdb/shell/ShellSessionManager.ts +++ b/src/documentdb/shell/ShellSessionManager.ts @@ -7,33 +7,27 @@ import * as l10n from '@vscode/l10n'; import { randomUUID } from 'crypto'; import type * as vscode from 'vscode'; import { ext } from '../../extensionVariables'; -import { traceAuthFlow, traceAuthOperation, traceEntraDestination, type AuthTraceContext } from '../../utils/authTrace'; import { getBatchSizeSetting, getConnectionTimeoutMs } from '../../utils/workspacUtils'; import { ClustersClient } from '../ClustersClient'; import { ConnectionUnavailableError } from '../ConnectionUnavailableError'; import { CredentialCache } from '../CredentialCache'; -import { AuthMethodId } from '../auth/AuthMethod'; -import { - resolveInteractiveTokenResource, - resolveManagedIdentityTokenResource, - TokenResourceResolutionError, - type ResolvedTokenResource, -} from '../auth/documentdbTokenResource'; -import { evaluateEntraDestinationFromSettings } from '../auth/entraDestinationSettings'; -import { clearEntraTokenFailure, recordEntraTokenFailure } from '../auth/entraErrors/entraTokenFailures'; -import { EntraDestinationRejectedError } from '../auth/oidcAllowedHosts'; +import { type VerifiedEntraIdentity } from '../auth/AuthHandler'; +import { AuthMethodId } from '../auth/AuthMethodId'; +import { EntraIdentityMismatchError } from '../auth/entraErrors/entraCallbackErrors'; +import { createWorkerAuthError, sameEntraIdentity, WorkerTokenRelay } from '../auth/WorkerTokenRelay'; +import { computeConnectionFingerprint } from '../connectionFingerprint'; import { WorkerSessionManager, type WorkerSessionCallbacks, type WorkerStartupTelemetryContext, } from '../playground/WorkerSessionManager'; import { + getWorkerAuthReason, type MainToWorkerMessage, type SerializableExecutionResult, type SerializableMongoClientOptions, - type WorkerToMainMessage, + type WorkerAuthReason, } from '../playground/workerTypes'; -import { withTokenAcquisitionTiming, type ConnectionStartupTimings } from '../utils/ConnectionStartupTimings'; import { getHostsFromConnectionString } from '../utils/connectionStringHelpers'; import { resolveAllowInvalidCertificates } from '../utils/tlsException'; @@ -94,8 +88,11 @@ export interface ShellSessionCallbacks { */ export class ShellSessionManager implements vscode.Disposable { private readonly _workerManager: WorkerSessionManager; - private _sessionInitMessage: Extract | undefined; - private _resolvedTokenResource: ResolvedTokenResource | undefined; + private _relay: WorkerTokenRelay | undefined; + private _fingerprint: string | undefined; + private _pin: VerifiedEntraIdentity | undefined; + private _authFailure: WorkerAuthReason | undefined; + private _disposed = false; private readonly _connectionInfo: ShellConnectionInfo; private readonly _callbacks: ShellSessionCallbacks | undefined; private readonly _managedIdentityTokenCorrelationId = randomUUID(); @@ -143,13 +140,10 @@ export class ShellSessionManager implements vscode.Disposable { break; } }, - onTokenRequest: ( - msg: Extract, - postResponse: (response: MainToWorkerMessage) => void, - isCurrent: () => boolean, - timings?: ConnectionStartupTimings, - traceContext?: AuthTraceContext, - ) => this.handleTokenRequest(msg, postResponse, isCurrent, timings, traceContext), + onTokenRequest: async (request, post, isCurrent, timings, trace) => { + const relay = this._relay; + await relay?.relay(request, post, () => this._relay === relay && isCurrent(), timings, trace); + }, onWorkerExit: callbacks?.onWorkerExit, }; @@ -160,7 +154,7 @@ export class ShellSessionManager implements vscode.Disposable { * Whether the shell session has been initialized (worker spawned and connected). */ get isInitialized(): boolean { - return this._initialized && this._workerManager.isAlive; + return this._initialized && this._workerManager.isAlive && !this._authFailure && !this._workerManager.authFailure; } /** @@ -191,6 +185,26 @@ export class ShellSessionManager implements vscode.Disposable { return this._authMethod; } + get pinnedEntraIdentity(): VerifiedEntraIdentity | undefined { + return this._pin; + } + + /** Accept only the same verified account; the next command reconnects and runs once. */ + public resetAfterSignIn(identity: VerifiedEntraIdentity, epoch: number): void { + this.assertConnectionAvailable(); + if (ClustersClient.getEpoch(this._connectionInfo.clusterId) !== epoch) { + throw new ConnectionUnavailableError('credentialsChanged'); + } + if (!this._pin || !sameEntraIdentity(this._pin, identity)) { + throw new EntraIdentityMismatchError(); + } + if (ClustersClient.getExpectedFingerprint(this._connectionInfo.clusterId, this._pin) !== this._fingerprint) { + throw new ConnectionUnavailableError('credentialsChanged'); + } + this.killWorker(); + this._authFailure = undefined; + } + /** * Initialize the shell session: spawn the worker, connect to the cluster, * and set the initial database. @@ -199,20 +213,69 @@ export class ShellSessionManager implements vscode.Disposable { * @throws Error if initialization exceeds the configured timeout. */ async initialize(): Promise { + this._initPromise ??= this.initializeSession(); + const pending = this._initPromise; + try { + return await pending; + } finally { + if (this._initPromise === pending) { + this._initPromise = undefined; + } + } + } + + private async initializeSession(): Promise { this.assertConnectionAvailable(); + this.assertAuthRecovery(); + const { clusterId } = this._connectionInfo; + const epoch = ClustersClient.getEpoch(clusterId); + const fingerprint = ClustersClient.getExpectedFingerprint(clusterId, this._pin); + if (this._fingerprint !== undefined && this._fingerprint !== fingerprint) { + throw new ConnectionUnavailableError('credentialsChanged'); + } const initMsg = this.buildInitMessage(); - if (!this._initialized || !this._workerManager.isAlive) { - this._sessionInitMessage = initMsg; - this._resolvedTokenResource = undefined; + if (!this.isInitialized || this._relay?.epoch !== epoch) { + if (this._initialized && (this._authFailure || this._relay?.epoch !== epoch)) { + this._workerManager.killWorker(); + } + this._initialized = false; + this._fingerprint ??= fingerprint; + const verified = ClustersClient.getLastVerifiedIdentity(clusterId); + const pin = this._pin ?? (verified?.kind === 'entra' ? verified : undefined); + if (initMsg.authMechanism === AuthMethodId.MicrosoftEntraID) { + this._pin = pin; + } + this._relay = new WorkerTokenRelay( + clusterId, + initMsg, + epoch, + this._managedIdentityTokenCorrelationId, + initMsg.authMechanism === AuthMethodId.MicrosoftEntraID ? pin : undefined, + (identity) => { + this._pin = identity; + this._fingerprint ??= computeConnectionFingerprint({ + connectionString: initMsg.connectionString, + principal: identity, + }); + this._displayName = identity.accountLabel || undefined; + }, + ); } - const timeoutMs = getConnectionTimeoutMs(); - await this._workerManager.ensureWorker( - this._connectionInfo.clusterId, - initMsg, - timeoutMs, - this._telemetryContext, - ); + const relay = this._relay; + try { + await this._workerManager.ensureWorker(clusterId, initMsg, getConnectionTimeoutMs(), this._telemetryContext); + } catch (error) { + if (relay === this._relay && epoch === ClustersClient.getEpoch(clusterId) && !ClustersClient.getLatchReason(clusterId)) { + this._authFailure ??= getWorkerAuthReason(error); + } + throw error; + } + this.assertConnectionAvailable(); + if (relay !== this._relay || epoch !== ClustersClient.getEpoch(clusterId)) { + throw new ConnectionUnavailableError('credentialsChanged'); + } + this._authFailure = undefined; this._initialized = true; this._authMethod = initMsg.authMechanism; @@ -254,15 +317,10 @@ export class ShellSessionManager implements vscode.Disposable { this.assertConnectionAvailable(); // Reconnect if the worker is not alive — handles all cases: // timeout kills, Ctrl+C cancellation, unexpected worker crashes. - if (!this._initialized || !this._workerManager.isAlive) { - this._initialized = false; + if (!this.isInitialized || this._relay?.epoch !== ClustersClient.getEpoch(this._connectionInfo.clusterId)) { + this.assertAuthRecovery(); this._callbacks?.onReconnecting?.(); - if (!this._initPromise) { - this._initPromise = this.initialize().finally(() => { - this._initPromise = undefined; - }); - } - await this._initPromise; + await this.initialize(); this.assertConnectionAvailable(); this._callbacks?.onReconnected?.(); } @@ -276,27 +334,46 @@ export class ShellSessionManager implements vscode.Disposable { terminalColumns, }; - const workerResult = await this._workerManager.sendEval(evalMsg); - return workerResult.result; + const relay = this._relay; + try { + return (await this._workerManager.sendEval(evalMsg)).result; + } catch (error) { + if ( + relay === this._relay && + relay?.epoch === ClustersClient.getEpoch(this._connectionInfo.clusterId) && + !ClustersClient.getLatchReason(this._connectionInfo.clusterId) + ) { + this._authFailure ??= getWorkerAuthReason(error); + } + throw error; + } } /** * Gracefully shut down the shell session. */ async shutdown(): Promise { - await this._workerManager.shutdown(); this._initialized = false; + this._relay = undefined; + this._initPromise = undefined; + await this._workerManager.shutdown(); } /** * Force-terminate the worker thread immediately. */ killWorker(): void { + this._authFailure ??= this._workerManager.authFailure; + this._relay = undefined; + this._initPromise = undefined; this._workerManager.killWorker(); this._initialized = false; } dispose(): void { + this._disposed = true; + this._relay = undefined; + this._initPromise = undefined; this._workerManager.dispose(); this._initialized = false; } @@ -306,6 +383,16 @@ export class ShellSessionManager implements vscode.Disposable { if (reason) { throw new ConnectionUnavailableError(reason); } + if (this._disposed) { + throw new ConnectionUnavailableError('connectionRemoved'); + } + } + + private assertAuthRecovery(): void { + const reason = this._authFailure ?? this._workerManager.authFailure; + if (this._pin && (reason === 'signInRequired' || reason === 'identityMismatch')) { + throw createWorkerAuthError(reason); + } } // ─── Private: Init message ─────────────────────────────────────────────── @@ -361,8 +448,6 @@ export class ShellSessionManager implements vscode.Disposable { }; } - // ─── Private: Token handling ───────────────────────────────────────────── - /** * Extract the host portion from a connection string, stripping credentials. * Returns just the hostname:port for safe display. @@ -377,140 +462,4 @@ export class ShellSessionManager implements vscode.Disposable { return match?.[1].split(',') ?? ['unknown']; } } - - private async handleTokenRequest( - msg: Extract, - postResponse: (response: MainToWorkerMessage) => void, - isCurrent: () => boolean, - timings?: ConnectionStartupTimings, - traceContext?: AuthTraceContext, - ): Promise { - try { - const sessionInit = this._sessionInitMessage; - if ( - !sessionInit || - (sessionInit.authMechanism !== 'MicrosoftEntraID' && sessionInit.authMechanism !== 'ManagedIdentity') - ) { - throw new Error(l10n.t('No credentials found for cluster {0}', this._connectionInfo.clusterId)); - } - if (!isCurrent()) { - return; - } - const connectionString = sessionInit.connectionString; - const decision = evaluateEntraDestinationFromSettings(connectionString); - traceEntraDestination(decision, msg.requestId, traceContext); - if (!decision.allowed) { - throw new EntraDestinationRejectedError(decision); - } - const usesManagedIdentity = sessionInit.authMechanism === 'ManagedIdentity'; - let resolved: ResolvedTokenResource; - try { - resolved = - this._resolvedTokenResource ?? - (usesManagedIdentity - ? await resolveManagedIdentityTokenResource(connectionString) - : await resolveInteractiveTokenResource(connectionString)); - if (isCurrent()) { - this._resolvedTokenResource = resolved; - } - traceAuthFlow('entraCloud.resolved', resolved.details, msg.requestId, traceContext); - } catch (error) { - if (error instanceof TokenResourceResolutionError) { - traceAuthFlow('entraCloud.unresolved', error.details, msg.requestId, traceContext); - } - throw error; - } - let accessToken: string; - - if (usesManagedIdentity) { - const { getManagedIdentityAccessToken } = await import('../auth/managedIdentityTokenProvider'); - try { - accessToken = ( - await withTokenAcquisitionTiming(timings, () => - getManagedIdentityAccessToken( - [resolved.scope], - sessionInit.managedIdentityClientId, - sessionInit.tenantId, - this._managedIdentityTokenCorrelationId, - traceContext, - ), - ) - ).accessToken; - } catch (error) { - if (traceContext?.startupProperties) { - traceContext.startupProperties.entraFailureKind = 'tokenAcquisitionFailed'; - } - if (isCurrent()) { - recordEntraTokenFailure(this._connectionInfo.clusterId, { - cloudCategory: resolved.cloudCategory, - authMethod: 'managedIdentity', - }); - } - throw error; - } - } else { - const { getSessionFromVSCode } = await import('@microsoft/vscode-azext-azureauth'); - let session: vscode.AuthenticationSession | undefined; - try { - session = await traceAuthOperation( - 'interactiveEntra.getSession', - () => - withTokenAcquisitionTiming(timings, () => - getSessionFromVSCode([resolved.scope], sessionInit.tenantId, { createIfNone: true }), - ), - { - tenantSpecified: !!sessionInit.tenantId, - createIfNone: true, - cloudCategory: resolved.cloudCategory, - tokenResourceReason: resolved.reason, - }, - msg.requestId, - traceContext, - ); - - if (!session) { - throw new Error(l10n.t('Failed to obtain Entra ID token.')); - } - } catch (error) { - if (traceContext?.startupProperties) { - traceContext.startupProperties.entraFailureKind = 'tokenAcquisitionFailed'; - } - if (isCurrent()) { - recordEntraTokenFailure(this._connectionInfo.clusterId, { - cloudCategory: resolved.cloudCategory, - authMethod: 'interactive', - }); - } - throw error; - } - - accessToken = session.accessToken; - this._displayName = session.account.label || undefined; - } - - const currentDecision = evaluateEntraDestinationFromSettings(connectionString); - traceEntraDestination(currentDecision, msg.requestId, traceContext); - if (!currentDecision.allowed) { - throw new EntraDestinationRejectedError(currentDecision); - } - if (isCurrent()) { - clearEntraTokenFailure(this._connectionInfo.clusterId); - } - postResponse({ - type: 'tokenResponse', - requestId: msg.requestId, - accessToken, - }); - } catch (error: unknown) { - const errorMessage = error instanceof Error ? error.message : String(error); - postResponse({ - type: 'tokenError', - requestId: msg.requestId, - error: errorMessage, - ...(error instanceof EntraDestinationRejectedError - ? { errorName: 'EntraDestinationRejectedError' as const } - : {}), - }); - } - } } From 8c2ca3fdcb5f55696708f63f2de3c4da71480470 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Wed, 25 Nov 2026 13:16:44 +0000 Subject: [PATCH 02/23] fix: handle worker authentication failures in surfaces Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/commands/playground/connectDatabase.ts | 3 +- .../playground/executePlaygroundCode.test.ts | 42 ++++- .../playground/executePlaygroundCode.ts | 166 ++++++++++++++++-- src/commands/playground/newPlayground.ts | 2 +- src/commands/signInAgain/signInAgain.test.ts | 42 ++++- src/commands/signInAgain/signInAgain.ts | 125 ++++++++++--- .../playground/PlaygroundService.test.ts | 44 +++++ .../playground/PlaygroundService.ts | 52 +++++- .../shell/DocumentDBShellPty.test.ts | 65 +++++++ src/documentdb/shell/DocumentDBShellPty.ts | 128 +++++++++++++- 10 files changed, 618 insertions(+), 51 deletions(-) diff --git a/src/commands/playground/connectDatabase.ts b/src/commands/playground/connectDatabase.ts index 81988aaf6..c2e920099 100644 --- a/src/commands/playground/connectDatabase.ts +++ b/src/commands/playground/connectDatabase.ts @@ -120,8 +120,7 @@ export async function promptAndConnectPlayground( context.telemetry.properties.outcome = 'connected'; context.telemetry.properties.experience = node instanceof DatabaseItem ? node.experience?.api : undefined; - PlaygroundService.getInstance().setConnection(uri, connection); - return connection; + return PlaygroundService.getInstance().setConnectionFromHost(uri, connection); } /** diff --git a/src/commands/playground/executePlaygroundCode.test.ts b/src/commands/playground/executePlaygroundCode.test.ts index 2498908ab..0ce180cb3 100644 --- a/src/commands/playground/executePlaygroundCode.test.ts +++ b/src/commands/playground/executePlaygroundCode.test.ts @@ -4,7 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext-utils'; -import { describe, expect, it, vi } from 'vitest'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; import * as vscode from 'vscode'; import { executePlaygroundCode, stopPlaygroundEvaluator } from './executePlaygroundCode'; @@ -49,6 +49,10 @@ vi.mock('../../extensionVariables', () => ({ })); describe('executePlaygroundCode', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + it('cancels a stopped worker without replacing the retained result or showing an error', async () => { let stopEvaluation: (error: Error) => void = () => {}; evaluate.mockImplementation( @@ -83,4 +87,40 @@ describe('executePlaygroundCode', () => { stopPlaygroundEvaluator('cluster'); } }); + + it('writes one actionable result for a bounded worker failure without an unsolicited modal', async () => { + const failure = Object.assign(new Error('private callback details'), { + name: 'TokenCallbackError', + }); + evaluate.mockRejectedValueOnce(failure); + const showError = vi.spyOn(vscode.window, 'showErrorMessage'); + const showWarning = vi.spyOn(vscode.window, 'showWarningMessage'); + const progress = vi + .spyOn(vscode.window, 'withProgress') + .mockImplementation((_options, task) => + Promise.resolve( + task({ report: vi.fn() }, { isCancellationRequested: false, onCancellationRequested: vi.fn() }), + ), + ); + + try { + await expect( + executePlaygroundCode('db.stats()', 'runAll', vscode.Uri.file('test.documentdb.js')), + ).rejects.toBe(failure); + expect(showResult).toHaveBeenCalledExactlyOnceWith( + expect.anything(), + expect.stringContaining( + 'The sign-in token could not be refreshed. Run the query again to reconnect with the same connection.', + ), + ); + expect(showResult.mock.calls[0][1]).not.toContain('private callback details'); + expect(showError).not.toHaveBeenCalled(); + expect(showWarning).not.toHaveBeenCalled(); + } finally { + progress.mockRestore(); + showError.mockRestore(); + showWarning.mockRestore(); + stopPlaygroundEvaluator('cluster'); + } + }); }); diff --git a/src/commands/playground/executePlaygroundCode.ts b/src/commands/playground/executePlaygroundCode.ts index a95eb661c..5fc19dc8c 100644 --- a/src/commands/playground/executePlaygroundCode.ts +++ b/src/commands/playground/executePlaygroundCode.ts @@ -11,12 +11,14 @@ import { import * as l10n from '@vscode/l10n'; import * as vscode from 'vscode'; import { ClustersClient } from '../../documentdb/ClustersClient'; +import { ConnectionUnavailableError } from '../../documentdb/ConnectionUnavailableError'; import { CredentialCache } from '../../documentdb/CredentialCache'; import { feedResultToSchemaStore } from '../../documentdb/feedResultToSchemaStore'; import { PlaygroundEvaluator } from '../../documentdb/playground/PlaygroundEvaluator'; import { PlaygroundService } from '../../documentdb/playground/PlaygroundService'; import { formatError, formatResult } from '../../documentdb/playground/resultFormatter'; import { type PlaygroundConnection } from '../../documentdb/playground/types'; +import { getWorkerAuthReason, type WorkerAuthReason } from '../../documentdb/playground/workerTypes'; import { extractErrorCode } from '../../documentdb/shell/ShellOutputFormatter'; import { getHostsFromConnectionString } from '../../documentdb/utils/connectionStringHelpers'; import { addDomainInfoToProperties } from '../../documentdb/utils/getClusterMetadata'; @@ -24,6 +26,10 @@ import { ext } from '../../extensionVariables'; import { ErrorExplanationService } from '../../services/errorExplanationService'; import { recordSurveyActivity } from '../../services/survey/SurveyService'; import { classifyCodeBlock } from '../../utils/classifyCommand'; +import { + canSignInAgainForWorker, + signInAgainForWorker, +} from '../signInAgain/signInAgain'; import { promptAndConnectPlayground } from './connectDatabase'; /** Per-cluster evaluator pool — one worker per cluster, lazily created. */ @@ -121,17 +127,18 @@ export async function executePlaygroundCode( return; // user cancelled the connection picker } } + let boundConnection: PlaygroundConnection = connection; - const { clusterId } = connection; - if (ClustersClient.getLatchReason(clusterId)) { - void vscode.window.showWarningMessage( - l10n.t('This connection is unavailable. Reconnect from the tree to run this playground.'), - ); + const { clusterId } = boundConnection; + const latchReason = ClustersClient.getLatchReason(clusterId); + if (latchReason) { + const recovery = getPlaygroundRecovery(new ConnectionUnavailableError(latchReason), connection); + void vscode.window.showWarningMessage(recovery?.message ?? l10n.t('This connection is unavailable.')); return; } // Prevent concurrent runs on the same cluster — no queuing - if (service.isExecuting(connection.clusterId)) { + if (service.isExecuting(boundConnection.clusterId)) { void vscode.window.showInformationMessage( l10n.t('A playground is already running on this cluster. Wait for it to finish.'), ); @@ -139,14 +146,14 @@ export async function executePlaygroundCode( } // Get or create the evaluator for this cluster - let evaluator = evaluators.get(connection.clusterId); + let evaluator = evaluators.get(boundConnection.clusterId); const isNewEvaluator = !evaluator; if (!evaluator) { evaluator = new PlaygroundEvaluator(); - evaluators.set(connection.clusterId, evaluator); + evaluators.set(boundConnection.clusterId, evaluator); } - service.setExecuting(connection.clusterId, true); + service.setExecuting(boundConnection.clusterId, true); // callWithTelemetryAndErrorHandling automatically tracks: // - duration (measured from callback start to end) @@ -177,12 +184,14 @@ export async function executePlaygroundCode( // Domain info — privacy-safe hashed host data for platform analytics const domainProps: Record = {}; - collectDomainTelemetry(connection, domainProps); + if (isNewEvaluator) { + collectDomainTelemetry(boundConnection, domainProps); + } Object.assign(context.telemetry.properties, domainProps); // Link to server metadata via connectionCorrelationId try { - const existingClient = ClustersClient.getExistingClient(connection.clusterId); + const existingClient = ClustersClient.getExistingClient(boundConnection.clusterId); if (existingClient?.connectionCorrelationId) { context.telemetry.properties.connectionCorrelationId = existingClient.connectionCorrelationId; } @@ -214,9 +223,17 @@ export async function executePlaygroundCode( if (evaluators.get(clusterId) !== evaluator) { throw new UserCancelledError('playground.execute'); } - const result = await evaluator!.evaluate(connection, code, (message) => { - progress.report({ message }); - }); + const result = await evaluator!.evaluate( + boundConnection, + code, + (message) => { + progress.report({ message }); + }, + (binding) => { + boundConnection = + service.captureWorkerBinding(documentUri, boundConnection, binding) ?? boundConnection; + }, + ); if (evaluators.get(clusterId) !== evaluator) { return; @@ -229,8 +246,8 @@ export async function executePlaygroundCode( context.telemetry.measurements.sessionEvalCount = evaluator!.sessionEvalCount; context.telemetry.properties.authMethod = evaluator!.sessionAuthMethod ?? 'unknown'; - let formattedOutput = formatResult(result, code, connection); - feedResultToSchemaStore(result, connection.clusterId); + let formattedOutput = formatResult(result, code, boundConnection); + feedResultToSchemaStore(result, boundConnection.clusterId); // If console output was produced, append a hint to check the output channel if (evaluator!.lastEvalConsoleOutputCount > 0) { @@ -267,14 +284,21 @@ export async function executePlaygroundCode( // the extracted code is preserved for future telemetry. const { message: errorMessage } = extractErrorCode(rawMessage); const durationMs = Date.now() - startTime; - const formattedOutput = formatError(error, code, durationMs, connection); + const recovery = getPlaygroundRecovery(error, boundConnection); + const displayError = recovery ? new Error(recovery.message) : error; + const formattedOutput = formatError(displayError, code, durationMs, boundConnection); if (sourceUri) { await ext.playgroundResultProvider.showResult(sourceUri, formattedOutput); } + if (recovery) { + offerPlaygroundRecovery(context, sourceUri, boundConnection, recovery); + throw error; + } + const explanation = await ErrorExplanationService.explain({ - clusterId: connection.clusterId, + clusterId: boundConnection.clusterId, error, }); @@ -286,13 +310,117 @@ export async function executePlaygroundCode( // error, and errorMessage in telemetry throw error; } finally { - service.setExecuting(connection.clusterId, false); + service.setExecuting(boundConnection.clusterId, false); } }, ); }); } +interface PlaygroundRecovery { + readonly message: string; + readonly authReason?: WorkerAuthReason; +} + +function getPlaygroundRecovery( + error: unknown, + connection: PlaygroundConnection, +): PlaygroundRecovery | undefined { + const authReason = getWorkerAuthReason(error); + if (authReason) { + switch (authReason) { + case 'signInRequired': + return { + authReason, + message: + connection.entraIdentity && + canSignInAgainForWorker(connection.clusterId, connection.entraIdentity) + ? l10n.t('Microsoft sign-in expired for this playground. Sign in again to continue.') + : l10n.t( + 'Microsoft sign-in expired for this playground. Re-pick its connection from the tree.', + ), + }; + case 'identityMismatch': + return { + authReason, + message: l10n.t( + 'This playground is bound to a different Microsoft account. Re-pick its connection from the tree.', + ), + }; + case 'destinationRejected': + return { + authReason, + message: l10n.t( + 'This connection is not allowed for Microsoft sign-in. Review the trusted server settings, then re-pick the playground connection.', + ), + }; + case 'refreshFailed': + return { + authReason, + message: l10n.t( + 'The sign-in token could not be refreshed. Run the query again to reconnect with the same connection.', + ), + }; + } + } + + if (!(error instanceof ConnectionUnavailableError)) { + return undefined; + } + if (error.reason === 'credentialsChanged' || error.reason === 'identityChanged') { + return { + message: l10n.t( + 'This playground is bound to the previous connection. Re-pick its connection from the tree.', + ), + }; + } + return { + message: l10n.t('This connection is unavailable. Reconnect from the tree, then re-pick it here.'), + }; +} + +function offerPlaygroundRecovery( + context: IActionContext, + documentUri: vscode.Uri, + connection: PlaygroundConnection, + recovery: PlaygroundRecovery, +): void { + if ( + recovery.authReason !== 'signInRequired' || + !connection.entraIdentity || + !canSignInAgainForWorker(connection.clusterId, connection.entraIdentity) + ) { + return; + } + const identity = connection.entraIdentity; + const action = l10n.t('Sign in again'); + void vscode.window.showWarningMessage(recovery.message, action).then(async (choice) => { + if (choice !== action) { + return; + } + const epoch = ClustersClient.getEpoch(connection.clusterId); + try { + const result = await signInAgainForWorker(context, connection.clusterId, identity); + if ( + !result || + result.epoch !== epoch || + ClustersClient.getEpoch(connection.clusterId) !== epoch || + PlaygroundService.getInstance().getConnection(documentUri) !== connection + ) { + return; + } + stopPlaygroundEvaluator(connection.clusterId); + } catch (error) { + if (error instanceof UserCancelledError) { + return; + } + void vscode.window.showWarningMessage( + l10n.t('Could not sign in again. Re-pick the playground connection from the tree.'), + ); + } + }); +} + // ─── Domain telemetry ──────────────────────────────────────────────────────── /** diff --git a/src/commands/playground/newPlayground.ts b/src/commands/playground/newPlayground.ts index a133eb182..9e07f55cc 100644 --- a/src/commands/playground/newPlayground.ts +++ b/src/commands/playground/newPlayground.ts @@ -144,7 +144,7 @@ async function createPlaygroundWithContent( await vscode.window.showTextDocument(doc, { preview: true }); // Bind connection to this specific document - service.setConnection(doc.uri, connection); + service.setConnectionFromHost(doc.uri, connection); } function isCollectionItem(node: DatabaseItem | CollectionItem | undefined): node is CollectionItem { diff --git a/src/commands/signInAgain/signInAgain.test.ts b/src/commands/signInAgain/signInAgain.test.ts index 3b1170c6c..2e28bd824 100644 --- a/src/commands/signInAgain/signInAgain.test.ts +++ b/src/commands/signInAgain/signInAgain.test.ts @@ -7,12 +7,15 @@ import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext import { beforeEach, describe, expect, it, vi } from 'vitest'; import * as vscode from 'vscode'; import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; -import { EntraSignInRequiredError } from '../../documentdb/auth/entraErrors/entraCallbackErrors'; +import { + EntraIdentityMismatchError, + EntraSignInRequiredError, +} from '../../documentdb/auth/entraErrors/entraCallbackErrors'; import { getEntraSession } from '../../documentdb/auth/entraSession'; import { ClustersClient } from '../../documentdb/ClustersClient'; import { CredentialCache } from '../../documentdb/CredentialCache'; import { showClusterConnectFailure } from '../../documentdb/showClusterConnectFailure'; -import { signInAgain } from './signInAgain'; +import { signInAgain, signInAgainForWorker } from './signInAgain'; const pin = { kind: 'entra', @@ -149,4 +152,39 @@ describe('signInAgain', () => { }, ); }); + + it('never installs a different-label account during worker recovery', async (): Promise => { + vi.mocked(ClustersClient.getLatchReason).mockReturnValue(undefined); + vi.mocked(getEntraSession).mockResolvedValueOnce({ + account: { id: 'different-account', label: 'Different label' }, + } as vscode.AuthenticationSession); + + await expect(signInAgainForWorker(actionContext(), clusterId, pin)).rejects.toBeInstanceOf( + EntraIdentityMismatchError, + ); + + expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); + expect(showClusterConnectFailure).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + }); + + it('recovers the exact worker pin without requiring the host to retain it', async (): Promise => { + vi.mocked(ClustersClient.getLatchReason).mockReturnValue(undefined); + vi.mocked(ClustersClient.getLastVerifiedIdentity).mockReturnValue(undefined); + vi.mocked(getEntraSession).mockResolvedValueOnce({ + account: { id: pin.accountId, label: pin.accountLabel }, + } as vscode.AuthenticationSession); + vi.mocked(ClustersClient.startAfterSignIn).mockResolvedValueOnce({} as ClustersClient); + + const result = await signInAgainForWorker(actionContext(), clusterId, pin); + + expect(result).toEqual({ identity: pin, epoch: 1 }); + expect(getEntraSession).toHaveBeenCalledWith( + expect.objectContaining({ + providerId: pin.providerId, + tenantId: pin.tenantId, + account: { id: pin.accountId, label: pin.accountLabel }, + }), + ); + }); }); diff --git a/src/commands/signInAgain/signInAgain.ts b/src/commands/signInAgain/signInAgain.ts index ca454fd94..5b4a0db62 100644 --- a/src/commands/signInAgain/signInAgain.ts +++ b/src/commands/signInAgain/signInAgain.ts @@ -5,12 +5,14 @@ import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext-utils'; import * as vscode from 'vscode'; +import { type VerifiedEntraIdentity } from '../../documentdb/auth/AuthHandler'; import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; import { EntraIdentityMismatchError, EntraSignInRequiredError, } from '../../documentdb/auth/entraErrors/entraCallbackErrors'; import { getEntraSession } from '../../documentdb/auth/entraSession'; +import { sameEntraIdentity } from '../../documentdb/auth/WorkerTokenRelay'; import { MicrosoftEntraIDAuthHandler } from '../../documentdb/auth/MicrosoftEntraIDAuthHandler'; import { addEstablishedConnectionContext, ClustersClient } from '../../documentdb/ClustersClient'; import { classifyConnectionFailure } from '../../documentdb/connectionFailures'; @@ -19,6 +21,26 @@ import { showClusterConnectFailure } from '../../documentdb/showClusterConnectFa import { type ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; import { refreshAuthenticationNode } from '../retryAuthentication/retryAuthentication'; +interface WorkerSignInResult { + readonly identity: VerifiedEntraIdentity; + readonly epoch: number; +} + +export function canSignInAgainForWorker( + clusterId: string, + expectedIdentity: VerifiedEntraIdentity, +): boolean { + const credentials = CredentialCache.getCredentials(clusterId); + const hostIdentity = ClustersClient.getLastVerifiedIdentity(clusterId); + return ( + ClustersClient.getLatchReason(clusterId) === undefined && + credentials?.authMechanism === AuthMethodId.MicrosoftEntraID && + credentials.entraIdConfig?.tenantId === expectedIdentity.tenantId && + (hostIdentity === undefined || + (hostIdentity.kind === 'entra' && sameEntraIdentity(hostIdentity, expectedIdentity))) + ); +} + function isSignInDismissal(error: unknown): boolean { return ( error instanceof UserCancelledError || @@ -33,6 +55,31 @@ export async function signInAgain( context: IActionContext, target: ClusterItemBase | { readonly clusterId: string }, ): Promise { + await signInAgainInternal(context, target); +} + +/** + * Recover only the exact identity pinned by a shell or playground worker. + * + * Unlike the tree command, this path never accepts a different account selected + * by VS Code, even when its label differs. + */ +export async function signInAgainForWorker( + context: IActionContext, + clusterId: string, + expectedIdentity: VerifiedEntraIdentity, +): Promise { + if (!canSignInAgainForWorker(clusterId, expectedIdentity)) { + return undefined; + } + return signInAgainInternal(context, { clusterId }, expectedIdentity); +} + +async function signInAgainInternal( + context: IActionContext, + target: ClusterItemBase | { readonly clusterId: string }, + expectedIdentity?: VerifiedEntraIdentity, +): Promise { const node = target && 'cluster' in target ? target : undefined; const clusterId = target && ('cluster' in target ? target.cluster.clusterId : target.clusterId); if (!clusterId) { @@ -43,7 +90,8 @@ export async function signInAgain( if (reason && reason !== 'credentialsRejected') { return; } - const identity = ClustersClient.getLastVerifiedIdentity(clusterId); + const storedIdentity = ClustersClient.getLastVerifiedIdentity(clusterId); + const identity = expectedIdentity ?? storedIdentity; const credentials = CredentialCache.getCredentials(clusterId); if ( identity?.kind !== 'entra' || @@ -56,12 +104,28 @@ export async function signInAgain( context.telemetry.maskEntireErrorMessage = true; context.errorHandling.suppressDisplay = true; addEstablishedConnectionContext(context.telemetry, clusterId); - const isCurrent = (): boolean => - ClustersClient.getEpoch(clusterId) === epoch && CredentialCache.getCredentials(clusterId) === credentials; + const isCurrent = (): boolean => { + if ( + ClustersClient.getEpoch(clusterId) !== epoch || + CredentialCache.getCredentials(clusterId) !== credentials + ) { + return false; + } + if (!expectedIdentity) { + return true; + } + const currentIdentity = ClustersClient.getLastVerifiedIdentity(clusterId); + return ( + currentIdentity === undefined || + (currentIdentity.kind === 'entra' && sameEntraIdentity(currentIdentity, expectedIdentity)) + ); + }; const reportClosed = (): void => { - void vscode.window.showErrorMessage(vscode.l10n.t('The connection was closed while you were signing in.'), { - modal: true, - }); + if (!expectedIdentity) { + void vscode.window.showErrorMessage(vscode.l10n.t('The connection was closed while you were signing in.'), { + modal: true, + }); + } }; let starting = false; @@ -79,6 +143,9 @@ export async function signInAgain( throw new UserCancelledError('signInAgain'); } if (session.account.id !== identity.accountId) { + if (expectedIdentity) { + throw new EntraIdentityMismatchError(); + } // VS Code only confirms account changes when the account *label* is different. // A same-label/different-ID session is not an explicit user choice. if ( @@ -90,9 +157,16 @@ export async function signInAgain( } return session; }); + if ( + expectedIdentity && + (auth.verifiedIdentity?.kind !== 'entra' || + !sameEntraIdentity(auth.verifiedIdentity, expectedIdentity)) + ) { + throw new EntraIdentityMismatchError(); + } if (!isCurrent()) { reportClosed(); - return; + return undefined; } starting = true; const startup = ClustersClient.startAfterSignIn(clusterId, epoch, credentials, auth); @@ -100,7 +174,7 @@ export async function signInAgain( const client = await startup; if (!client || ClustersClient.getEpoch(clusterId) !== startupEpoch) { reportClosed(); - return; + return undefined; } if ( ClustersClient.getExistingClient(clusterId) === client && @@ -109,10 +183,13 @@ export async function signInAgain( ) { refreshAuthenticationNode(node); } + return auth.verifiedIdentity + ? { identity: auth.verifiedIdentity, epoch: startupEpoch } + : undefined; } catch (error) { if (!starting && !isCurrent()) { reportClosed(); - return; + return undefined; } if (isSignInDismissal(error)) { throw new UserCancelledError('signInAgain'); @@ -122,21 +199,25 @@ export async function signInAgain( AuthMethodId.MicrosoftEntraID, ).kind; if (error instanceof EntraSignInRequiredError && error.reason === 'providerChanged') { - await vscode.window.showErrorMessage(vscode.l10n.t('The Azure cloud or sign-in provider changed.'), { - modal: true, - detail: vscode.l10n.t( - 'Restore "microsoft-sovereign-cloud.environment" to the setting used when this connection was established, then choose Retry sign-in. If it used the Azure public cloud, reset the setting.', - ), - }); + if (!expectedIdentity) { + await vscode.window.showErrorMessage(vscode.l10n.t('The Azure cloud or sign-in provider changed.'), { + modal: true, + detail: vscode.l10n.t( + 'Restore "microsoft-sovereign-cloud.environment" to the setting used when this connection was established, then choose Retry sign-in. If it used the Azure public cloud, reset the setting.', + ), + }); + } throw error; } - await showClusterConnectFailure({ - clusterId, - clusterName: node?.cluster.name ?? vscode.l10n.t('connection'), - fallbackHeading: vscode.l10n.t('Could not sign in again.'), - error, - context, - }); + if (!expectedIdentity) { + await showClusterConnectFailure({ + clusterId, + clusterName: node?.cluster.name ?? vscode.l10n.t('connection'), + fallbackHeading: vscode.l10n.t('Could not sign in again.'), + error, + context, + }); + } throw error; } } diff --git a/src/documentdb/playground/PlaygroundService.test.ts b/src/documentdb/playground/PlaygroundService.test.ts index 52b844379..948e5ed8e 100644 --- a/src/documentdb/playground/PlaygroundService.test.ts +++ b/src/documentdb/playground/PlaygroundService.test.ts @@ -12,6 +12,7 @@ import { type PlaygroundConnection } from './types'; import * as vscode from 'vscode'; import { CredentialCache } from '../CredentialCache'; +import { ClustersClient } from '../ClustersClient'; vi.mock('../CredentialCache', () => ({ CredentialCache: { hasCredentials: vi.fn() }, @@ -31,6 +32,7 @@ describe('PlaygroundService', () => { afterEach(() => { service.dispose(); + vi.restoreAllMocks(); }); describe('singleton', () => { @@ -110,6 +112,48 @@ describe('PlaygroundService', () => { expect(service.getDisplayName(uri2)).toBe('OtherCluster / products'); }); + it('captures the host binding when a tree selection is bound', () => { + const identity = { + kind: 'entra', + providerId: 'microsoft', + accountId: 'account', + accountLabel: 'Account', + tenantId: 'tenant', + } as const; + vi.spyOn(ClustersClient, 'getBinding').mockReturnValue({ + clusterId: connection.clusterId, + fingerprint: 'fingerprint', + generation: 1, + }); + vi.spyOn(ClustersClient, 'getLastVerifiedIdentity').mockReturnValue(identity); + + const bound = service.setConnectionFromHost(mockUri, connection); + + expect(bound).toEqual({ + ...connection, + fingerprint: 'fingerprint', + entraIdentity: identity, + }); + expect(service.getConnection(mockUri)).toBe(bound); + }); + + it('captures a worker binding only while the original document binding is current', () => { + service.setConnection(mockUri, connection); + const replacement = { ...connection, databaseName: 'replacement' }; + const captured = service.captureWorkerBinding(mockUri, connection, { + fingerprint: 'worker-fingerprint', + }); + expect(captured?.fingerprint).toBe('worker-fingerprint'); + + service.setConnection(mockUri, replacement); + expect( + service.captureWorkerBinding(mockUri, connection, { + fingerprint: 'stale-fingerprint', + }), + ).toBeUndefined(); + expect(service.getConnection(mockUri)).toBe(replacement); + }); + it('getActiveClusterIds returns all unique cluster IDs', () => { const uri2 = { toString: () => 'untitled:playground-2.documentdb.js' } as vscode.Uri; const connection2: PlaygroundConnection = { diff --git a/src/documentdb/playground/PlaygroundService.ts b/src/documentdb/playground/PlaygroundService.ts index 3fa5d067d..62ed53546 100644 --- a/src/documentdb/playground/PlaygroundService.ts +++ b/src/documentdb/playground/PlaygroundService.ts @@ -6,9 +6,10 @@ import * as l10n from '@vscode/l10n'; import * as vscode from 'vscode'; import { ext } from '../../extensionVariables'; +import { ClustersClient } from '../ClustersClient'; import { CredentialCache } from '../CredentialCache'; import { PLAYGROUND_LANGUAGE_ID, PlaygroundCommandIds } from './constants'; -import { type PlaygroundConnection } from './types'; +import { type PlaygroundConnection, type PlaygroundWorkerBinding } from './types'; /** * Normalize playground text for content correlation across an untitled→file save. @@ -152,6 +153,7 @@ export class PlaygroundService implements vscode.Disposable { // ── Connection management ────────────────────────────────────────── setConnection(uri: vscode.Uri, connection: PlaygroundConnection): void { + connection = this.captureHostBinding(connection); ext.outputChannel?.trace( `[PlaygroundService] setConnection: ${uri.toString()} → cluster=${connection.clusterId}, db=${connection.databaseName}`, ); @@ -160,6 +162,54 @@ export class PlaygroundService implements vscode.Disposable { this._onDidChangeState.fire(); } + /** Bind a newly selected playground to the current connected host identity, when available. */ + setConnectionFromHost(uri: vscode.Uri, connection: PlaygroundConnection): PlaygroundConnection { + this.setConnection(uri, connection); + return this._connections.get(uri.toString()) ?? connection; + } + + private captureHostBinding(connection: PlaygroundConnection): PlaygroundConnection { + const binding = ClustersClient.getBinding(connection.clusterId); + const verifiedIdentity = ClustersClient.getLastVerifiedIdentity(connection.clusterId); + const hostIdentityIsCompatible = + connection.fingerprint === undefined || connection.fingerprint === binding?.fingerprint; + return ( + binding === undefined + ? connection + : { + ...connection, + fingerprint: connection.fingerprint ?? binding.fingerprint, + entraIdentity: + connection.entraIdentity ?? + (hostIdentityIsCompatible && verifiedIdentity?.kind === 'entra' + ? verifiedIdentity + : undefined), + } + ); + } + + /** Capture a worker-learned binding only while the document still holds the originating connection. */ + captureWorkerBinding( + uri: vscode.Uri, + expectedConnection: PlaygroundConnection, + binding: PlaygroundWorkerBinding, + ): PlaygroundConnection | undefined { + const key = uri.toString(); + const current = this._connections.get(key); + if (current !== expectedConnection) { + return undefined; + } + const bound = { + ...current, + fingerprint: binding.fingerprint, + entraIdentity: binding.entraIdentity, + }; + this._connections.set(key, bound); + this._lastBindingByPath.set(key, bound); + this._onDidChangeState.fire(); + return bound; + } + removeConnection(uri: vscode.Uri): void { ext.outputChannel?.trace(`[PlaygroundService] removeConnection: ${uri.toString()}`); this._connections.delete(uri.toString()); diff --git a/src/documentdb/shell/DocumentDBShellPty.test.ts b/src/documentdb/shell/DocumentDBShellPty.test.ts index 44dd8b038..563e92b41 100644 --- a/src/documentdb/shell/DocumentDBShellPty.test.ts +++ b/src/documentdb/shell/DocumentDBShellPty.test.ts @@ -17,6 +17,19 @@ import { ShellCompletionProvider } from './ShellCompletionProvider'; import { ShellSpinner } from './ShellSpinner'; const mockSessionTelemetry: Record[] = []; +const workerSignIn = vi.hoisted(() => ({ + canRecover: vi.fn(), + recover: vi.fn(), + pin: undefined as + | { + kind: 'entra'; + providerId: string; + accountId: string; + accountLabel: string; + tenantId: string; + } + | undefined, +})); // callWithTelemetryAndErrorHandling from @microsoft/vscode-azext-utils silently swallows // errors in the test environment because its internal error handling relies on extension @@ -75,6 +88,11 @@ vi.mock('../../utils/accumulatingTelemetry', () => ({ ), })); +vi.mock('../../commands/signInAgain/signInAgain', () => ({ + canSignInAgainForWorker: workerSignIn.canRecover, + signInAgainForWorker: workerSignIn.recover, +})); + // Mock ShellSessionManager const mockInitialize = vi.fn().mockResolvedValue({ host: 'test-host.documents.azure.com:10255', @@ -86,6 +104,7 @@ const mockEvaluate = vi.fn(); const mockDispose = vi.fn(); const mockKillWorker = vi.fn(); const mockSetActiveDatabase = vi.fn(); +const mockResetAfterSignIn = vi.fn(); vi.mock('./ShellSessionManager', () => ({ ShellSessionManager: vi.fn().mockImplementation(function (_connectionInfo, callbacks) { @@ -97,6 +116,8 @@ vi.mock('./ShellSessionManager', () => ({ dispose: mockDispose, killWorker: mockKillWorker, setActiveDatabase: mockSetActiveDatabase, + resetAfterSignIn: mockResetAfterSignIn, + pinnedEntraIdentity: workerSignIn.pin, isInitialized: true, }; }), @@ -121,6 +142,8 @@ describe('DocumentDBShellPty', () => { beforeEach(() => { vi.clearAllMocks(); mockSessionTelemetry.length = 0; + workerSignIn.pin = undefined; + workerSignIn.canRecover.mockReturnValue(false); written = ''; closeCode = undefined; terminalName = undefined; @@ -172,6 +195,48 @@ describe('DocumentDBShellPty', () => { }); describe('open', () => { + it('offers one non-modal recovery for a pinned shell sign-in miss', async (): Promise => { + workerSignIn.pin = { + kind: 'entra', + providerId: 'microsoft', + accountId: 'account', + accountLabel: 'Account', + tenantId: 'tenant', + }; + workerSignIn.canRecover.mockReturnValue(true); + workerSignIn.recover.mockResolvedValue({ identity: workerSignIn.pin, epoch: 0 }); + pty = new DocumentDBShellPty(defaultOptions); + pty.onDidWrite((data) => { + written += data; + }); + pty.open(undefined); + await new Promise((resolve) => setTimeout(resolve, 10)); + written = ''; + mockEvaluate.mockRejectedValueOnce( + Object.assign(new Error('private session miss'), { name: 'EntraSignInRequiredError' }), + ); + const action = vi + .spyOn(vscode.window, 'showWarningMessage') + .mockResolvedValue('Sign in again' as unknown as vscode.MessageItem); + const modal = vi.spyOn(vscode.window, 'showErrorMessage'); + + pty.handleInput('db.stats()'); + pty.handleInput('\r'); + await new Promise((resolve) => setTimeout(resolve, 20)); + + expect(written).toContain( + 'Microsoft sign-in expired for this shell. Sign in again to continue.', + ); + expect(written).not.toContain('private session miss'); + expect(action).toHaveBeenCalledExactlyOnceWith( + 'Microsoft sign-in expired for this shell. Sign in again to continue.', + 'Sign in again', + ); + expect(modal).not.toHaveBeenCalled(); + expect(workerSignIn.recover).toHaveBeenCalledOnce(); + expect(mockResetAfterSignIn).toHaveBeenCalledWith(workerSignIn.pin, 0); + }); + it('carries URL attribution into actual shell startup', async (): Promise => { const deepLink = { deepLinkCorrelationId: 'link-attempt', deepLinkSource: 'docs' }; pty = new DocumentDBShellPty({ ...defaultOptions, deepLink }); diff --git a/src/documentdb/shell/DocumentDBShellPty.ts b/src/documentdb/shell/DocumentDBShellPty.ts index a62471bed..b08c52492 100644 --- a/src/documentdb/shell/DocumentDBShellPty.ts +++ b/src/documentdb/shell/DocumentDBShellPty.ts @@ -7,6 +7,10 @@ import { callWithTelemetryAndErrorHandling, UserCancelledError } from '@microsof import * as l10n from '@vscode/l10n'; import { randomUUID } from 'crypto'; import * as vscode from 'vscode'; +import { + canSignInAgainForWorker, + signInAgainForWorker, +} from '../../commands/signInAgain/signInAgain'; import { type DeepLinkTelemetry, trackDeepLinkTelemetry } from '../../deepLinks/deepLinkTelemetry'; import { ext } from '../../extensionVariables'; import { ErrorExplanationService } from '../../services/errorExplanationService'; @@ -17,9 +21,14 @@ import { COMPLETION_OFFERED_EVENT, type CompletionCategory } from '../../telemet import { accumulateTelemetry } from '../../utils/accumulatingTelemetry'; import { classifyCommand, extractRunCommandName } from '../../utils/classifyCommand'; import { ClustersClient } from '../ClustersClient'; +import { ConnectionUnavailableError } from '../ConnectionUnavailableError'; import { CredentialCache } from '../CredentialCache'; import { deserializeResultForSchema, feedResultToSchemaStore } from '../feedResultToSchemaStore'; -import { type SerializableExecutionResult } from '../playground/workerTypes'; +import { + getWorkerAuthReason, + type SerializableExecutionResult, + type WorkerAuthReason, +} from '../playground/workerTypes'; import { SchemaStore } from '../SchemaStore'; import { getHostsFromConnectionString } from '../utils/connectionStringHelpers'; import { addDomainInfoToProperties } from '../utils/getClusterMetadata'; @@ -632,6 +641,12 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { this._spinner?.stop(); this._spinner = undefined; + if (this.handleWorkerFailure(error)) { + this._inputHandler.setEnabled(true); + this.showPrompt(); + return; + } + const rawMessage = error instanceof Error ? error.message : String(error); // Strip technical error codes for clean user-facing output; // the extracted code is preserved for future telemetry. @@ -690,8 +705,9 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { private async handleLineInput(line: string): Promise { const disconnectRevision = this._disconnectRevision; - if (ClustersClient.getLatchReason(this._connectionInfo.clusterId)) { - this.writeLine(this._outputFormatter.formatSystemMessage(l10n.t('Disconnected'))); + const latchReason = ClustersClient.getLatchReason(this._connectionInfo.clusterId); + if (latchReason) { + this.handleWorkerFailure(new ConnectionUnavailableError(latchReason)); if (!this._closed) { this.showPrompt(); } @@ -836,6 +852,10 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { return; } + if (this.handleWorkerFailure(error)) { + return; + } + const rawMessage = error instanceof Error ? error.message : String(error); // Strip technical error codes for clean user-facing output; // the extracted code is preserved for future telemetry. @@ -869,6 +889,108 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { } } + private handleWorkerFailure(error: unknown): boolean { + const authReason = getWorkerAuthReason(error); + if (authReason) { + this.writeBoundedWorkerFailure(authReason); + return true; + } + if (error instanceof ConnectionUnavailableError) { + const message = + error.reason === 'userDisconnected' + ? l10n.t('Disconnected. Reconnect from the tree, then open a new shell.') + : error.reason === 'credentialsChanged' || error.reason === 'identityChanged' + ? l10n.t('This shell is bound to the previous connection. Open a new shell from the tree.') + : l10n.t('This connection is unavailable. Reconnect from the tree, then open a new shell.'); + this.writeLine(this._outputFormatter.formatError(message)); + return true; + } + return false; + } + + private writeBoundedWorkerFailure(reason: WorkerAuthReason): void { + const pin = this._sessionManager.pinnedEntraIdentity; + if (reason === 'signInRequired' && pin && canSignInAgainForWorker(this._connectionInfo.clusterId, pin)) { + const message = l10n.t('Microsoft sign-in expired for this shell. Sign in again to continue.'); + this.writeLine(this._outputFormatter.formatError(message)); + this.offerShellSignInAgain(pin, message); + return; + } + + let message: string; + switch (reason) { + case 'signInRequired': + message = l10n.t('Microsoft sign-in expired for this shell. Open a new shell from the tree.'); + break; + case 'identityMismatch': + message = l10n.t( + 'This shell is bound to a different Microsoft account. Open a new shell from the tree.', + ); + break; + case 'destinationRejected': + message = l10n.t( + 'This shell is not allowed to sign in to this connection. Review the trusted server settings, then reconnect from the tree.', + ); + break; + case 'refreshFailed': + message = l10n.t( + 'The sign-in token could not be refreshed. Run the next command to reconnect with the same connection.', + ); + break; + } + this.writeLine(this._outputFormatter.formatError(message)); + } + + private offerShellSignInAgain( + identity: NonNullable, + message: string, + ): void { + const action = l10n.t('Sign in again'); + const revision = this._disconnectRevision; + const epoch = ClustersClient.getEpoch(this._connectionInfo.clusterId); + void vscode.window.showWarningMessage(message, action).then(async (choice) => { + if (choice !== action) { + return; + } + try { + await callWithTelemetryAndErrorHandling('shell.signInAgain', async (context) => { + context.errorHandling.suppressDisplay = true; + context.errorHandling.rethrow = true; + context.telemetry.properties.shellSessionId = this._shellSessionId; + const result = await signInAgainForWorker( + context, + this._connectionInfo.clusterId, + identity, + ); + if ( + !result || + this._closed || + revision !== this._disconnectRevision || + result.epoch !== epoch || + ClustersClient.getEpoch(this._connectionInfo.clusterId) !== epoch + ) { + return; + } + this._sessionManager.resetAfterSignIn(result.identity, result.epoch); + this.writeLine( + this._outputFormatter.formatSystemMessage( + l10n.t('Sign-in restored. Run your command again.'), + ), + ); + }); + } catch (error) { + if (error instanceof UserCancelledError) { + return; + } + if (!this._closed && revision === this._disconnectRevision) { + void vscode.window.showWarningMessage( + l10n.t('Could not sign in again. Open a new shell from the tree.'), + ); + } + } + }); + } + /** * Handle special intercepted results (exit, clear). * Returns true if the result was handled (no further output needed). From f997696af6b9ee2aefa5116e6e428400916026f1 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Wed, 25 Nov 2026 13:25:31 +0000 Subject: [PATCH 03/23] docs: record WI-2 pre-review findings for author decisions Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iterations/01-dev-plan.md | 4 + .../01-pr6a-worker-token-relays-review.md | 78 +++++++++++++++++++ 2 files changed, 82 insertions(+) create mode 100644 docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr6a-worker-token-relays-review.md diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index f52238187..76c020e2e 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md @@ -767,6 +767,10 @@ verdict exists, do not start the work it gates. The fingerprint table (formerly - **Rescheduled (2026-11-20), operator decision:** Finish PR 1 with WI-1 only. Deliver WI-2 intact after WI-4's verified identity and fingerprint and WI-7's disconnect latch exist, retaining the planned **Sign in again** action. Do not implement the partial relay option. +- **PR6a ([#1133](https://github.com/microsoft/vscode-documentdb/pull/1133)):** The complete relay + and recovery flow is in a draft stacked on PR6. The initial Case 1 build and 310 focused tests + passed. The [AI pre-review](./01-pr6a-worker-token-relays-review.md) found four issues and + awaits author decisions. Live Shell and Playground verification stays at OP-6. --- diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr6a-worker-token-relays-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr6a-worker-token-relays-review.md new file mode 100644 index 000000000..f2d32c876 --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr6a-worker-token-relays-review.md @@ -0,0 +1,78 @@ +# PR6a pre-review: Shell and Playground token relays + +[PR #1133](https://github.com/microsoft/vscode-documentdb/pull/1133) · WI-2 · reviewed head `8c2ca3fdc` + +Claude Opus 5.5 performed the first pass. OpenAI GPT-5.6-Luna validated both findings and +independently found two more. There were no GitHub Copilot review threads on the draft at this +head. Findings are based on code inspection; the initial Case 1 build and 310 focused tests +passed, but those tests did not exercise the failing cases below. + +## F1. Successful Sign in again does not restart the worker (high) + +[`signInAgain`](../../../../../src/commands/signInAgain/signInAgain.ts#L172) replaces the host +client and advances its epoch. Both [Shell](../../../../../src/documentdb/shell/DocumentDBShellPty.ts#L950) +and [Playground](../../../../../src/commands/playground/executePlaygroundCode.ts#L401) reject this +successful result because it does not match the epoch captured before sign-in. The worker then +remains blocked and offers the same action again. + +**Recommendation:** Before opening sign-in, confirm the notification still belongs to the +same shell revision or document binding. After sign-in, check that the exact epoch returned +by that sign-in is still current and that the same surface owns the action. Do not accept +arbitrary newer epochs or remove the fence. Test a successful epoch change and a superseding +invalidation without replaying the old operation. + +**Author decision:** Pending. + +## F2. Re-picking a Playground connection leaves Run blocked (medium) + +The [connection picker](../../../../../src/commands/playground/connectDatabase.ts#L120) updates +the document binding, but the [evaluator](../../../../../src/documentdb/playground/PlaygroundEvaluator.ts#L194) +keeps the previous worker's authentication failure for the whole cluster. The next Run can +reject before it checks the new binding. + +**Recommendation:** Let an explicit re-pick advance past that failed worker on the next +deliberate Run, after the existing identity and execution checks. Do not stop an evaluator +from the picker: another document may be using it. Separate failure tracking for every +document would be more complex without removing the need to replace the failed worker. +Test successful re-pick and Run, preservation of the old binding's identity, and a second +document's in-flight run. + +**Author decision:** Pending. + +## F3. A no-op saved edit can discard healthy Shell state (medium) + +The [Shell manager](../../../../../src/documentdb/shell/ShellSessionManager.ts#L227) kills a +healthy worker when the host epoch changes. [Saving unchanged settings](../../../../../src/commands/saveConnectionEdit.ts#L54) +can advance the host epoch even though the Shell remains connected and the identity has not +changed. The next command then loses the Shell's variables and cursors. + +**Recommendation:** Keep the healthy Shell worker across a host-only epoch change. Keep the +epoch fence for startup and token replies, and keep the latch and fingerprint checks before +respawn. Do not add a separate epoch counter. Test that a no-op edit does not respawn the +healthy worker, while explicit Disconnect still stops it. + +**Author decision:** Pending. + +## F4. A stale token request can hang a worker that is still attached (medium) + +The [host relay](../../../../../src/documentdb/auth/WorkerTokenRelay.ts#L71) drops the token reply +when the host epoch changes, even if the worker is still attached. The worker is awaiting +that reply and a warm evaluation has no IPC timeout. The existing late-reply test only +covers a worker that has been terminated. + +**Recommendation:** Keep ignoring detached workers. Settle an obsolete request on a worker +that is still attached with a bounded lifecycle cancellation. Do not send the stale token, +update diagnostics, or replay the evaluation. Adding a timeout alone would leave the +request running until the timeout and would not express why it was interrupted. Test +invalidation with an attached worker and no stale token or diagnostics. + +**Author decision:** Pending. + +## Scope clarification + +[Decision 0018](../decisions.md#0018-saved-connection-edits-permanently-lock-existing-views) +retires registered webviews after a saved settings change. It does not make Shell terminals +or Playground documents Close-only. WI-2 and +[D12](../../sovereign-clouds/decisions.md#d12-open-sessions-keep-what-they-started-with) +allow a needed same-identity respawn after a password-only edit, but do not require a healthy +Shell worker to restart. From e7a7c7b4d4e1ec9e75d1171cb89a2774c6c710f1 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Wed, 25 Nov 2026 13:58:07 +0000 Subject: [PATCH 04/23] docs: record approved fixes for WI-2 pre-review Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iterations/01-pr6a-worker-token-relays-review.md | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr6a-worker-token-relays-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr6a-worker-token-relays-review.md index f2d32c876..7390f8a46 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr6a-worker-token-relays-review.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr6a-worker-token-relays-review.md @@ -21,7 +21,8 @@ by that sign-in is still current and that the same surface owns the action. Do n arbitrary newer epochs or remove the fence. Test a successful epoch change and a superseding invalidation without replaying the old operation. -**Author decision:** Pending. +**Author decision:** Approved as recommended. Use the confirmed post-sign-in epoch without +loosening the ownership checks or replaying the operation. ## F2. Re-picking a Playground connection leaves Run blocked (medium) @@ -37,7 +38,8 @@ document would be more complex without removing the need to replace the failed w Test successful re-pick and Run, preservation of the old binding's identity, and a second document's in-flight run. -**Author decision:** Pending. +**Author decision:** Approved as recommended. Apply the explicit re-pick on the next Run +without interrupting another document. ## F3. A no-op saved edit can discard healthy Shell state (medium) @@ -51,7 +53,7 @@ epoch fence for startup and token replies, and keep the latch and fingerprint ch respawn. Do not add a separate epoch counter. Test that a no-op edit does not respawn the healthy worker, while explicit Disconnect still stops it. -**Author decision:** Pending. +**Author decision:** Approved as recommended. Preserve healthy Shell state on an unchanged save. ## F4. A stale token request can hang a worker that is still attached (medium) @@ -66,7 +68,8 @@ update diagnostics, or replay the evaluation. Adding a timeout alone would leave request running until the timeout and would not express why it was interrupted. Test invalidation with an attached worker and no stale token or diagnostics. -**Author decision:** Pending. +**Author decision:** Approved as recommended. Cancel the obsolete request without returning a +stale token or recording a stale failure. ## Scope clarification From 72fb52da6fa884f5dead97ed493b09f64d3ff279 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Wed, 25 Nov 2026 13:59:23 +0000 Subject: [PATCH 05/23] fix: preserve healthy shells across host-only invalidation Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/documentdb/auth/WorkerTokenRelay.ts | 3 +- .../shell/ShellSessionManager.test.ts | 35 +++++++++++++++++++ src/documentdb/shell/ShellSessionManager.ts | 14 +++++--- 3 files changed, 46 insertions(+), 6 deletions(-) diff --git a/src/documentdb/auth/WorkerTokenRelay.ts b/src/documentdb/auth/WorkerTokenRelay.ts index f5b2af28c..849962827 100644 --- a/src/documentdb/auth/WorkerTokenRelay.ts +++ b/src/documentdb/auth/WorkerTokenRelay.ts @@ -67,11 +67,12 @@ export class WorkerTokenRelay { isCurrentWorker: () => boolean, timings?: ConnectionStartupTimings, trace?: AuthTraceContext, + epoch = this.epoch, ): Promise { const isCurrent = (): boolean => isCurrentWorker() && !ClustersClient.getLatchReason(this.clusterId) && - ClustersClient.getEpoch(this.clusterId) === this.epoch; + ClustersClient.getEpoch(this.clusterId) === epoch; const activeTrace = (): AuthTraceContext | undefined => (isCurrent() ? trace : undefined); const { connectionString, authMechanism, tenantId, managedIdentityClientId } = this.init; const managed = authMechanism === AuthMethodId.ManagedIdentity; diff --git a/src/documentdb/shell/ShellSessionManager.test.ts b/src/documentdb/shell/ShellSessionManager.test.ts index db42a395a..3d8a19821 100644 --- a/src/documentdb/shell/ShellSessionManager.test.ts +++ b/src/documentdb/shell/ShellSessionManager.test.ts @@ -186,6 +186,41 @@ describe('ShellSessionManager', () => { manager.dispose(); }); + it('keeps a healthy Shell and its pinned relay across a no-op save, but honors Disconnect', async (): Promise => { + const onReconnecting = vi.fn(); + const manager = new ShellSessionManager( + { clusterId, clusterDisplayName: 'Cluster', databaseName: 'test' }, + { onReconnecting }, + ); + requestTokenOnInit = true; + const account = { id: 'account-a', label: 'Account A' }; + mockGetSessionFromVSCode.mockResolvedValue({ accessToken: 'private-token', account }); + await manager.initialize(); + await manager.evaluate('let keep = 1'); + + ClustersClient.latch(clusterId, 'credentialsUpdating'); + await expect(manager.evaluate('keep')).rejects.toMatchObject({ reason: 'credentialsUpdating' }); + ClustersClient.unlatch(clusterId); + await manager.evaluate('keep'); + const reply = vi.fn(); + await workerCallbacks.onTokenRequest?.({ type: 'tokenRequest', requestId: 'refresh' }, reply, () => true); + expect(reply).toHaveBeenCalledWith({ type: 'tokenResponse', requestId: 'refresh', accessToken: 'private-token' }); + expect(mockGetSessionFromVSCode.mock.calls[1][2]).toEqual({ silent: true, account }); + expect(killWorker).not.toHaveBeenCalled(); + expect(onReconnecting).not.toHaveBeenCalled(); + + ClustersClient.latch(clusterId, 'userDisconnected'); + try { + manager.killWorker(); + await expect(manager.evaluate('keep')).rejects.toMatchObject({ reason: 'userDisconnected' }); + expect(killWorker).toHaveBeenCalledOnce(); + expect(sendEval).toHaveBeenCalledTimes(2); + } finally { + ClustersClient.unlatch(clusterId); + manager.dispose(); + } + }); + it('holds a silent miss until the same account explicitly signs in and never replays the command', async (): Promise => { const manager = new ShellSessionManager({ clusterId, clusterDisplayName: 'Cluster', databaseName: 'test' }); requestTokenOnInit = true; diff --git a/src/documentdb/shell/ShellSessionManager.ts b/src/documentdb/shell/ShellSessionManager.ts index 6db7d909f..01eda6c82 100644 --- a/src/documentdb/shell/ShellSessionManager.ts +++ b/src/documentdb/shell/ShellSessionManager.ts @@ -142,7 +142,10 @@ export class ShellSessionManager implements vscode.Disposable { }, onTokenRequest: async (request, post, isCurrent, timings, trace) => { const relay = this._relay; - await relay?.relay(request, post, () => this._relay === relay && isCurrent(), timings, trace); + // Warm Shells survive host-only invalidation. Fence each refresh at receipt; + // startup still uses the epoch captured before opening the connection. + const epoch = this._initialized ? ClustersClient.getEpoch(this._connectionInfo.clusterId) : relay?.epoch; + await relay?.relay(request, post, () => this._relay === relay && isCurrent(), timings, trace, epoch); }, onWorkerExit: callbacks?.onWorkerExit, }; @@ -234,8 +237,8 @@ export class ShellSessionManager implements vscode.Disposable { throw new ConnectionUnavailableError('credentialsChanged'); } const initMsg = this.buildInitMessage(); - if (!this.isInitialized || this._relay?.epoch !== epoch) { - if (this._initialized && (this._authFailure || this._relay?.epoch !== epoch)) { + if (!this.isInitialized) { + if (this._initialized && this._authFailure) { this._workerManager.killWorker(); } this._initialized = false; @@ -317,7 +320,7 @@ export class ShellSessionManager implements vscode.Disposable { this.assertConnectionAvailable(); // Reconnect if the worker is not alive — handles all cases: // timeout kills, Ctrl+C cancellation, unexpected worker crashes. - if (!this.isInitialized || this._relay?.epoch !== ClustersClient.getEpoch(this._connectionInfo.clusterId)) { + if (!this.isInitialized) { this.assertAuthRecovery(); this._callbacks?.onReconnecting?.(); await this.initialize(); @@ -335,12 +338,13 @@ export class ShellSessionManager implements vscode.Disposable { }; const relay = this._relay; + const epoch = ClustersClient.getEpoch(this._connectionInfo.clusterId); try { return (await this._workerManager.sendEval(evalMsg)).result; } catch (error) { if ( relay === this._relay && - relay?.epoch === ClustersClient.getEpoch(this._connectionInfo.clusterId) && + epoch === ClustersClient.getEpoch(this._connectionInfo.clusterId) && !ClustersClient.getLatchReason(this._connectionInfo.clusterId) ) { this._authFailure ??= getWorkerAuthReason(error); From 8faa1ba8f3e677ae01eed3bb0d07f24f0848d03a Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Wed, 25 Nov 2026 13:59:48 +0000 Subject: [PATCH 06/23] fix: honor the epoch established by worker sign-in Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../playground/executePlaygroundCode.test.ts | 66 ++++++++++++- .../playground/executePlaygroundCode.ts | 24 ++--- .../shell/DocumentDBShellPty.test.ts | 96 +++++++++++-------- src/documentdb/shell/DocumentDBShellPty.ts | 19 ++-- 4 files changed, 141 insertions(+), 64 deletions(-) diff --git a/src/commands/playground/executePlaygroundCode.test.ts b/src/commands/playground/executePlaygroundCode.test.ts index 0ce180cb3..53e1bb154 100644 --- a/src/commands/playground/executePlaygroundCode.test.ts +++ b/src/commands/playground/executePlaygroundCode.test.ts @@ -6,13 +6,18 @@ import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext-utils'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import * as vscode from 'vscode'; +import { type PlaygroundConnection } from '../../documentdb/playground/types'; import { executePlaygroundCode, stopPlaygroundEvaluator } from './executePlaygroundCode'; -const { evaluate, dispose, setExecuting, showResult } = vi.hoisted(() => ({ +const { evaluate, dispose, setExecuting, showResult, getConnection, getEpoch, canRecover, recover } = vi.hoisted(() => ({ evaluate: vi.fn(), dispose: vi.fn(), setExecuting: vi.fn(), showResult: vi.fn(), + getConnection: vi.fn<() => PlaygroundConnection | undefined>(), + getEpoch: vi.fn<() => number>(), + canRecover: vi.fn(), + recover: vi.fn(), })); vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ @@ -24,7 +29,12 @@ vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ })); vi.mock('../../documentdb/ClustersClient', () => ({ - ClustersClient: { getLatchReason: vi.fn(), getExistingClient: vi.fn() }, + ClustersClient: { getLatchReason: vi.fn(), getExistingClient: vi.fn(), getEpoch }, +})); + +vi.mock('../signInAgain/signInAgain', () => ({ + canSignInAgainForWorker: canRecover, + signInAgainForWorker: recover, })); vi.mock('../../documentdb/playground/PlaygroundEvaluator', () => ({ @@ -37,7 +47,7 @@ vi.mock('../../documentdb/playground/PlaygroundEvaluator', () => ({ vi.mock('../../documentdb/playground/PlaygroundService', () => ({ PlaygroundService: { getInstance: () => ({ - getConnection: () => ({ clusterId: 'cluster', clusterDisplayName: 'Cluster', databaseName: 'test' }), + getConnection, isExecuting: () => false, setExecuting, }), @@ -51,6 +61,9 @@ vi.mock('../../extensionVariables', () => ({ describe('executePlaygroundCode', () => { beforeEach(() => { vi.clearAllMocks(); + getConnection.mockReturnValue({ clusterId: 'cluster', clusterDisplayName: 'Cluster', databaseName: 'test' }); + getEpoch.mockReturnValue(0); + canRecover.mockReturnValue(false); }); it('cancels a stopped worker without replacing the retained result or showing an error', async () => { @@ -92,6 +105,7 @@ describe('executePlaygroundCode', () => { const failure = Object.assign(new Error('private callback details'), { name: 'TokenCallbackError', }); + evaluate.mockRejectedValueOnce(failure); const showError = vi.spyOn(vscode.window, 'showErrorMessage'); const showWarning = vi.spyOn(vscode.window, 'showWarningMessage'); @@ -123,4 +137,50 @@ describe('executePlaygroundCode', () => { stopPlaygroundEvaluator('cluster'); } }); + + it.each([false, true])('honors the sign-in epoch unless superseded (%s)', async (superseded) => { + const identity: NonNullable = { + kind: 'entra', + providerId: 'microsoft', + accountId: 'account', + accountLabel: 'Account', + tenantId: 'tenant', + }; + getConnection.mockReturnValue({ + clusterId: 'cluster', + clusterDisplayName: 'Cluster', + databaseName: 'test', + entraIdentity: identity, + }); + canRecover.mockReturnValue(true); + recover.mockImplementationOnce(async () => { + getEpoch.mockReturnValue(superseded ? 2 : 1); + return { identity, epoch: 1 }; + }); + const failure = Object.assign(new Error('private session miss'), { name: 'EntraSignInRequiredError' }); + evaluate.mockRejectedValueOnce(failure); + const warning = vi + .spyOn(vscode.window, 'showWarningMessage') + .mockResolvedValue('Sign in again' as unknown as vscode.MessageItem); + const progress = vi + .spyOn(vscode.window, 'withProgress') + .mockImplementation((_options, task) => + Promise.resolve( + task({ report: vi.fn() }, { isCancellationRequested: false, onCancellationRequested: vi.fn() }), + ), + ); + + try { + await expect( + executePlaygroundCode('db.stats()', 'runAll', vscode.Uri.file('test.documentdb.js')), + ).rejects.toBe(failure); + expect(recover).toHaveBeenCalledExactlyOnceWith(expect.anything(), 'cluster', identity); + expect(evaluate).toHaveBeenCalledOnce(); + expect(dispose).toHaveBeenCalledTimes(superseded ? 0 : 1); + } finally { + progress.mockRestore(); + warning.mockRestore(); + stopPlaygroundEvaluator('cluster'); + } + }); }); diff --git a/src/commands/playground/executePlaygroundCode.ts b/src/commands/playground/executePlaygroundCode.ts index 5fc19dc8c..1dee85c5e 100644 --- a/src/commands/playground/executePlaygroundCode.ts +++ b/src/commands/playground/executePlaygroundCode.ts @@ -393,25 +393,27 @@ function offerPlaygroundRecovery( return; } const identity = connection.entraIdentity; + const { clusterId } = connection; + const service = PlaygroundService.getInstance(); + const evaluator = evaluators.get(clusterId); + const epoch = ClustersClient.getEpoch(clusterId); + const stillOwnsAction = (): boolean => + service.getConnection(documentUri) === connection && + evaluators.get(clusterId) === evaluator && + !service.isExecuting(clusterId); const action = l10n.t('Sign in again'); void vscode.window.showWarningMessage(recovery.message, action).then(async (choice) => { - if (choice !== action) { + if (choice !== action || ClustersClient.getEpoch(clusterId) !== epoch || !stillOwnsAction()) { return; } - const epoch = ClustersClient.getEpoch(connection.clusterId); try { - const result = await signInAgainForWorker(context, connection.clusterId, identity); - if ( - !result || - result.epoch !== epoch || - ClustersClient.getEpoch(connection.clusterId) !== epoch || - PlaygroundService.getInstance().getConnection(documentUri) !== connection - ) { + const result = await signInAgainForWorker(context, clusterId, identity); + if (!result || ClustersClient.getEpoch(clusterId) !== result.epoch || !stillOwnsAction()) { return; } - stopPlaygroundEvaluator(connection.clusterId); + stopPlaygroundEvaluator(clusterId); } catch (error) { - if (error instanceof UserCancelledError) { + if (error instanceof UserCancelledError || !stillOwnsAction()) { return; } void vscode.window.showWarningMessage( diff --git a/src/documentdb/shell/DocumentDBShellPty.test.ts b/src/documentdb/shell/DocumentDBShellPty.test.ts index 563e92b41..1e88343ac 100644 --- a/src/documentdb/shell/DocumentDBShellPty.test.ts +++ b/src/documentdb/shell/DocumentDBShellPty.test.ts @@ -195,47 +195,61 @@ describe('DocumentDBShellPty', () => { }); describe('open', () => { - it('offers one non-modal recovery for a pinned shell sign-in miss', async (): Promise => { - workerSignIn.pin = { - kind: 'entra', - providerId: 'microsoft', - accountId: 'account', - accountLabel: 'Account', - tenantId: 'tenant', - }; - workerSignIn.canRecover.mockReturnValue(true); - workerSignIn.recover.mockResolvedValue({ identity: workerSignIn.pin, epoch: 0 }); - pty = new DocumentDBShellPty(defaultOptions); - pty.onDidWrite((data) => { - written += data; - }); - pty.open(undefined); - await new Promise((resolve) => setTimeout(resolve, 10)); - written = ''; - mockEvaluate.mockRejectedValueOnce( - Object.assign(new Error('private session miss'), { name: 'EntraSignInRequiredError' }), - ); - const action = vi - .spyOn(vscode.window, 'showWarningMessage') - .mockResolvedValue('Sign in again' as unknown as vscode.MessageItem); - const modal = vi.spyOn(vscode.window, 'showErrorMessage'); - - pty.handleInput('db.stats()'); - pty.handleInput('\r'); - await new Promise((resolve) => setTimeout(resolve, 20)); - - expect(written).toContain( - 'Microsoft sign-in expired for this shell. Sign in again to continue.', - ); - expect(written).not.toContain('private session miss'); - expect(action).toHaveBeenCalledExactlyOnceWith( - 'Microsoft sign-in expired for this shell. Sign in again to continue.', - 'Sign in again', - ); - expect(modal).not.toHaveBeenCalled(); - expect(workerSignIn.recover).toHaveBeenCalledOnce(); - expect(mockResetAfterSignIn).toHaveBeenCalledWith(workerSignIn.pin, 0); - }); + it.each([false, true])( + 'offers one non-modal pinned recovery, respecting a superseding epoch (%s)', + async (superseded): Promise => { + workerSignIn.pin = { + kind: 'entra', + providerId: 'microsoft', + accountId: 'account', + accountLabel: 'Account', + tenantId: 'tenant', + }; + workerSignIn.canRecover.mockReturnValue(true); + let epoch = 0; + vi.spyOn(ClustersClient, 'getEpoch').mockImplementation(() => epoch); + workerSignIn.recover.mockImplementationOnce(async () => { + const signInEpoch = ++epoch; + if (superseded) { + epoch++; + } + return { identity: workerSignIn.pin, epoch: signInEpoch }; + }); + pty = new DocumentDBShellPty(defaultOptions); + pty.onDidWrite((data) => { + written += data; + }); + pty.open(undefined); + await new Promise((resolve) => setTimeout(resolve, 10)); + written = ''; + mockEvaluate.mockRejectedValueOnce( + Object.assign(new Error('private session miss'), { name: 'EntraSignInRequiredError' }), + ); + const action = vi + .spyOn(vscode.window, 'showWarningMessage') + .mockResolvedValue('Sign in again' as unknown as vscode.MessageItem); + const modal = vi.spyOn(vscode.window, 'showErrorMessage'); + + pty.handleInput('db.stats()'); + pty.handleInput('\r'); + await new Promise((resolve) => setTimeout(resolve, 20)); + + expect(written).toContain('Microsoft sign-in expired for this shell. Sign in again to continue.'); + expect(written).not.toContain('private session miss'); + expect(action).toHaveBeenCalledExactlyOnceWith( + 'Microsoft sign-in expired for this shell. Sign in again to continue.', + 'Sign in again', + ); + expect(modal).not.toHaveBeenCalled(); + expect(workerSignIn.recover).toHaveBeenCalledOnce(); + expect(mockEvaluate).toHaveBeenCalledOnce(); + if (superseded) { + expect(mockResetAfterSignIn).not.toHaveBeenCalled(); + } else { + expect(mockResetAfterSignIn).toHaveBeenCalledExactlyOnceWith(workerSignIn.pin, 1); + } + }, + ); it('carries URL attribution into actual shell startup', async (): Promise => { const deepLink = { deepLinkCorrelationId: 'link-attempt', deepLinkSource: 'docs' }; diff --git a/src/documentdb/shell/DocumentDBShellPty.ts b/src/documentdb/shell/DocumentDBShellPty.ts index b08c52492..3efae7706 100644 --- a/src/documentdb/shell/DocumentDBShellPty.ts +++ b/src/documentdb/shell/DocumentDBShellPty.ts @@ -946,10 +946,16 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { message: string, ): void { const action = l10n.t('Sign in again'); + const { clusterId } = this._connectionInfo; const revision = this._disconnectRevision; - const epoch = ClustersClient.getEpoch(this._connectionInfo.clusterId); + const epoch = ClustersClient.getEpoch(clusterId); void vscode.window.showWarningMessage(message, action).then(async (choice) => { - if (choice !== action) { + if ( + choice !== action || + this._closed || + revision !== this._disconnectRevision || + ClustersClient.getEpoch(clusterId) !== epoch + ) { return; } try { @@ -957,17 +963,12 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { context.errorHandling.suppressDisplay = true; context.errorHandling.rethrow = true; context.telemetry.properties.shellSessionId = this._shellSessionId; - const result = await signInAgainForWorker( - context, - this._connectionInfo.clusterId, - identity, - ); + const result = await signInAgainForWorker(context, clusterId, identity); if ( !result || this._closed || revision !== this._disconnectRevision || - result.epoch !== epoch || - ClustersClient.getEpoch(this._connectionInfo.clusterId) !== epoch + ClustersClient.getEpoch(clusterId) !== result.epoch ) { return; } From 25e686f938d587352f61ec3ce85924c9674cf9f6 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Wed, 25 Nov 2026 14:00:17 +0000 Subject: [PATCH 07/23] fix: cancel invalidated token relays on attached workers Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/documentdb/auth/WorkerTokenRelay.ts | 29 +++-- .../playground/WorkerSessionManager.test.ts | 105 ++++++++++++++++++ .../playground/WorkerSessionManager.ts | 67 ++++++----- 3 files changed, 167 insertions(+), 34 deletions(-) diff --git a/src/documentdb/auth/WorkerTokenRelay.ts b/src/documentdb/auth/WorkerTokenRelay.ts index 849962827..7d8b91452 100644 --- a/src/documentdb/auth/WorkerTokenRelay.ts +++ b/src/documentdb/auth/WorkerTokenRelay.ts @@ -3,6 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import { UserCancelledError } from '@microsoft/vscode-azext-utils'; import { traceAuthFlow, traceEntraDestination, type AuthTraceContext } from '../../utils/authTrace'; import { ClustersClient } from '../ClustersClient'; import { @@ -69,11 +70,21 @@ export class WorkerTokenRelay { trace?: AuthTraceContext, epoch = this.epoch, ): Promise { - const isCurrent = (): boolean => - isCurrentWorker() && + const isCurrentEpoch = (): boolean => !ClustersClient.getLatchReason(this.clusterId) && ClustersClient.getEpoch(this.clusterId) === epoch; - const activeTrace = (): AuthTraceContext | undefined => (isCurrent() ? trace : undefined); + const canReply = (): boolean => { + if (!isCurrentWorker()) { + return false; + } + if (!isCurrentEpoch()) { + // The driver is still waiting. Cancel via the supervisor, not an authentication error. + throw new UserCancelledError('workerTokenRelay'); + } + return true; + }; + const activeTrace = (): AuthTraceContext | undefined => + isCurrentWorker() && isCurrentEpoch() ? trace : undefined; const { connectionString, authMechanism, tenantId, managedIdentityClientId } = this.init; const managed = authMechanism === AuthMethodId.ManagedIdentity; const assertDestination = (): void => { @@ -84,7 +95,7 @@ export class WorkerTokenRelay { } }; const run = async (): Promise => { - if (!isCurrent()) { + if (!canReply()) { return; } let mode: 'managedIdentity' | 'silent' | 'interactive' | undefined; @@ -115,7 +126,7 @@ export class WorkerTokenRelay { (managed ? await resolveManagedIdentityTokenResource(connectionString) : await resolveInteractiveTokenResource(connectionString)); - if (!isCurrent()) { + if (!canReply()) { return; } this.resource = resolved; @@ -126,7 +137,7 @@ export class WorkerTokenRelay { acquiring = true; if (managed) { const { getManagedIdentityAccessToken } = await import('./managedIdentityTokenProvider'); - if (!isCurrent()) { + if (!canReply()) { return; } assertDestination(); @@ -153,7 +164,7 @@ export class WorkerTokenRelay { mode: pin ? 'silent' : 'interactive', }), ); - if (!isCurrent()) { + if (!canReply()) { return; } assertEnvironment(); @@ -175,7 +186,7 @@ export class WorkerTokenRelay { }; accessToken = session.accessToken; } - if (!isCurrent()) { + if (!canReply()) { return; } assertDestination(); @@ -192,7 +203,7 @@ export class WorkerTokenRelay { traceAuthFlow('workerTokenRelay.completed', { mode, outcome: 'returned' }, requestId, activeTrace()); postResponse({ type: 'tokenResponse', requestId, accessToken }); } catch (error) { - if (!isCurrent()) { + if (!canReply()) { return; } const reason = getWorkerAuthReason(error) ?? 'refreshFailed'; diff --git a/src/documentdb/playground/WorkerSessionManager.test.ts b/src/documentdb/playground/WorkerSessionManager.test.ts index d4e437c54..d4a1fe4b7 100644 --- a/src/documentdb/playground/WorkerSessionManager.test.ts +++ b/src/documentdb/playground/WorkerSessionManager.test.ts @@ -15,7 +15,16 @@ import { Worker } from 'worker_threads'; import { ext } from '../../extensionVariables'; import { traceAuthFlow, type AuthTraceContext } from '../../utils/authTrace'; import { AuthMethodId } from '../auth/AuthMethod'; +import * as tokenResource from '../auth/documentdbTokenResource'; +import { + getRecentEntraTokenFailure, + recordEntraTokenFailure, + resetEntraTokenFailuresForTests, +} from '../auth/entraErrors/entraTokenFailures'; +import * as managedIdentityProvider from '../auth/managedIdentityTokenProvider'; import { EntraDestinationRejectedError } from '../auth/oidcAllowedHosts'; +import { WorkerTokenRelay } from '../auth/WorkerTokenRelay'; +import { ClustersClient } from '../ClustersClient'; import { CredentialCache } from '../CredentialCache'; import { ShellSessionManager } from '../shell/ShellSessionManager'; import { @@ -824,6 +833,102 @@ describe('WorkerSessionManager', () => { }, ); + it.each(['returned', 'failed'] as const)( + 'cancels a still-attached worker when an invalidated token lookup %s', + async (outcome): Promise => { + const clusterId = 'test-cluster'; + const connectionString = 'mongodb://cluster.mongocluster.cosmos.azure.com/'; + const resolver = vi.spyOn(tokenResource, 'resolveManagedIdentityTokenResource').mockResolvedValue({ + cloudCategory: 'public', + reason: 'host', + resource: 'https://ossrdbms-aad.database.windows.net', + scope: 'https://ossrdbms-aad.database.windows.net/.default', + details: {}, + }); + type Token = Awaited>; + let signalStarted!: () => void; + const started = new Promise((resolve) => { + signalStarted = resolve; + }); + let finishLookup!: () => void; + const lookup = new Promise((resolve, reject) => { + finishLookup = (): void => { + if (outcome === 'returned') { + resolve({ accessToken: 'must-not-send', expiresOnTimestamp: 0 }); + } else { + reject(new Error('obsolete provider failure')); + } + }; + }); + const provider = vi + .spyOn(managedIdentityProvider, 'getManagedIdentityAccessToken') + .mockImplementation(() => { + signalStarted(); + return lookup; + }); + const relay = new WorkerTokenRelay( + clusterId, + { + type: 'init', + requestId: '', + connectionString, + clientOptions: {}, + databaseName: 'test', + authMechanism: AuthMethodId.ManagedIdentity, + }, + ClustersClient.getEpoch(clusterId), + 'relay-id', + undefined, + ); + callbacks.onTokenRequest = relay.relay.bind(relay); + const manager = new WorkerSessionManager(callbacks); + try { + const active = await startWorker(true, {}, manager); + active.worker._emit('message', { type: 'initResult', requestId: active.requestId, success: true }); + await active.initPromise; + const evalMessage = { + type: 'eval', + requestId: '', + code: '1', + databaseName: 'test', + displayBatchSize: 20, + } as const; + const evaluating = manager.sendEval(evalMessage); + const canceled = expect(evaluating).rejects.toBeInstanceOf(UserCancelledError); + active.worker._emit('message', { type: 'tokenRequest', requestId: 'obsolete-token' }); + await started; + ClustersClient.invalidate(clusterId); + resetEntraTokenFailuresForTests(); + if (outcome === 'returned') { + recordEntraTokenFailure(clusterId, { cloudCategory: 'china', authMethod: 'interactive' }); + } + const newerFailure = getRecentEntraTokenFailure(clusterId); + finishLookup(); + await canceled; + expect(manager.isAlive).toBe(false); + expect(manager.authFailure).toBeUndefined(); + expect(getRecentEntraTokenFailure(clusterId)).toBe(newerFailure); + + const replacement = await startWorker(true, {}, manager); + replacement.worker._emit('message', { + type: 'initResult', + requestId: replacement.requestId, + success: true, + }); + await replacement.initPromise; + const worker = vi.mocked(Worker).mock.results.at(-1)?.value as { postMessage: Mock }; + const messages = worker.postMessage.mock.calls as [MainToWorkerMessage][]; + expect(messages.map(([message]) => message.type)).toEqual(['init', 'eval', 'init']); + expect(manager.isAlive).toBe(true); + } finally { + manager.dispose(); + resetEntraTokenFailuresForTests(); + provider.mockRestore(); + resolver.mockRestore(); + } + }, + ); + it('reports a stalled token request with total and stage timings without connection details', async () => { const { initPromise, requestId, worker } = await startWorker(); vi.advanceTimersByTime(200); diff --git a/src/documentdb/playground/WorkerSessionManager.ts b/src/documentdb/playground/WorkerSessionManager.ts index d4db91fc6..ff9319695 100644 --- a/src/documentdb/playground/WorkerSessionManager.ts +++ b/src/documentdb/playground/WorkerSessionManager.ts @@ -93,7 +93,8 @@ export interface WorkerSessionCallbacks { /** * Called when the worker requests an OIDC token (Entra ID auth). * The implementation must acquire the token via VS Code auth APIs - * and post it back to the worker. + * and post it back to the worker, or throw UserCancelledError if the + * still-attached worker's request was invalidated. */ onTokenRequest?: ( msg: Extract, @@ -711,27 +712,7 @@ export class WorkerSessionManager implements vscode.Disposable { } case 'tokenRequest': { - const isCurrent = (): boolean => this._worker === worker && this._shuttingDownWorker !== worker; - if (isCurrent() && this._callbacks.onTokenRequest) { - void this._callbacks.onTokenRequest( - msg, - (response) => { - if (isCurrent()) { - if (response.type === 'tokenError') { - this._authFailure ??= isWorkerAuthReason(response.reason) - ? response.reason - : response.errorName === 'EntraDestinationRejectedError' - ? 'destinationRejected' - : 'refreshFailed'; - } - worker.postMessage(response); - } - }, - isCurrent, - this._startup?.costTimings, - connection, - ); - } + void this.handleTokenRequest(msg, connection, worker); break; } @@ -747,12 +728,48 @@ export class WorkerSessionManager implements vscode.Disposable { } } + private async handleTokenRequest( + msg: Extract, + connection: AuthTraceContext, + worker: Worker, + ): Promise { + const isCurrent = (): boolean => this._worker === worker && this._shuttingDownWorker !== worker; + if (!isCurrent()) { + return; + } + try { + await this._callbacks.onTokenRequest?.( + msg, + (response) => { + if (isCurrent()) { + if (response.type === 'tokenError') { + this._authFailure ??= isWorkerAuthReason(response.reason) + ? response.reason + : response.errorName === 'EntraDestinationRejectedError' + ? 'destinationRejected' + : 'refreshFailed'; + } + worker.postMessage(response); + } + }, + isCurrent, + this._startup?.costTimings, + connection, + ); + } catch (error) { + if (isCurrent()) { + // Reject the pending startup/eval and discard the driver blocked in its callback. + this.terminateWorker('intentional', error instanceof UserCancelledError ? error : undefined); + } + } + } + // ─── Private: Worker cleanup ───────────────────────────────────────────── - private terminateWorker(reason: 'intentional' | 'forced'): void { + private terminateWorker(reason: 'intentional' | 'forced', cancellation?: UserCancelledError): void { this.revokeOidcDestinationPolicy(); this._startupAbortController?.abort(); - this.finishStartup('terminated'); + this.finishStartup(cancellation ? 'canceled' : 'terminated'); const wasAlive = !!this._worker; if (this._worker) { @@ -768,7 +785,7 @@ export class WorkerSessionManager implements vscode.Disposable { // Reject all pending requests for (const [, entry] of this._pendingRequests) { - entry.reject(new Error('Worker terminated')); + entry.reject(cancellation ?? new Error('Worker terminated')); } this._pendingRequests.clear(); From f5b79a3e9a665985bbe09e4dff617b96683b488b Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Wed, 25 Nov 2026 14:02:27 +0000 Subject: [PATCH 08/23] fix: honor explicit playground connection re-pick Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../playground/PlaygroundEvaluator.test.ts | 83 +++++++++++++++++++ .../playground/PlaygroundEvaluator.ts | 40 +++++++-- .../playground/PlaygroundService.test.ts | 24 ++++++ .../playground/PlaygroundService.ts | 11 ++- src/documentdb/playground/types.ts | 6 ++ 5 files changed, 157 insertions(+), 7 deletions(-) diff --git a/src/documentdb/playground/PlaygroundEvaluator.test.ts b/src/documentdb/playground/PlaygroundEvaluator.test.ts index 0f8c00987..6040b3bdd 100644 --- a/src/documentdb/playground/PlaygroundEvaluator.test.ts +++ b/src/documentdb/playground/PlaygroundEvaluator.test.ts @@ -304,6 +304,89 @@ describe('PlaygroundEvaluator token relay lifecycle', () => { mocks.getCredentials.mockClear(); }); + it('lets a re-picked document replace one failed worker without moving its old identity', async (): Promise => { + const oldIdentity = { + kind: 'entra', + providerId: 'microsoft', + tenantId: 'interactive-tenant', + accountId: 'account-a', + accountLabel: 'Account A', + } as const; + const newIdentity = { + ...oldIdentity, + accountId: 'account-b', + accountLabel: 'Account B', + } as const; + const identity = vi.spyOn(ClustersClient, 'getLastVerifiedIdentity').mockReturnValue(oldIdentity); + try { + await initializeSession(AuthMethodId.MicrosoftEntraID); + mocks.worker.isConnectedTo.mockReturnValue(true); + const capture = vi.fn(); + await evaluator.evaluate(connection, '2', undefined, capture); + const oldBinding = { + ...connection, + ...(capture.mock.calls[0][0] as { fingerprint: string; entraIdentity?: typeof oldIdentity }), + }; + mocks.worker.sendEval.mockRejectedValueOnce( + Object.assign(new Error('sign in required'), { name: 'EntraSignInRequiredError' }), + ); + await expect(evaluator.evaluate(oldBinding, 'failed')).rejects.toSatisfy( + (error: unknown) => getWorkerAuthReason(error) === 'signInRequired', + ); + + mocks.getCredentials.mockReturnValue({ + clusterId, + connectionString: originalConnection, + authMechanism: AuthMethodId.MicrosoftEntraID, + entraIdConfig: { tenantId: 'interactive-tenant' }, + }); + identity.mockReturnValue(newIdentity); + vi.spyOn(ClustersClient, 'getBinding').mockReturnValue({ + clusterId, + fingerprint: 'fingerprint-b', + generation: 2, + }); + const expected = vi + .spyOn(ClustersClient, 'getExpectedFingerprint') + .mockReturnValue('fingerprint-b'); + + await expect(evaluator.evaluate(oldBinding, 'old-document')).rejects.toMatchObject({ + reason: 'credentialsChanged', + }); + const replacement = { fingerprint: 'fingerprint-b' }; + const repicked = { + ...connection, + fingerprint: 'fingerprint-b', + entraIdentity: newIdentity, + workerReplacement: replacement, + }; + await evaluator.evaluate(repicked, 'replacement'); + await expect(evaluator.evaluate(oldBinding, 'still-old')).rejects.toMatchObject({ + reason: 'credentialsChanged', + }); + mocks.worker.sendEval.mockRejectedValueOnce( + Object.assign(new Error('sign in required again'), { name: 'EntraSignInRequiredError' }), + ); + await expect(evaluator.evaluate(repicked, 'second-failure')).rejects.toSatisfy( + (error: unknown) => getWorkerAuthReason(error) === 'signInRequired', + ); + await expect(evaluator.evaluate(repicked, 'already-consumed')).rejects.toMatchObject({ + name: 'EntraSignInRequiredError', + }); + expect(expected).toHaveBeenCalled(); + expect(mocks.worker.sendEval.mock.calls.map(([message]) => message.type === 'eval' && message.code)).toEqual([ + '1', + '2', + 'failed', + 'replacement', + 'second-failure', + ]); + mocks.getCredentials.mockClear(); + } finally { + vi.restoreAllMocks(); + } + }); + it.each([AuthMethodId.MicrosoftEntraID, AuthMethodId.ManagedIdentity])( 'restarts %s at the next Run after refresh fails, without replaying the failed query', async (authMechanism): Promise => { diff --git a/src/documentdb/playground/PlaygroundEvaluator.ts b/src/documentdb/playground/PlaygroundEvaluator.ts index 9836c3e7a..86dfab8bf 100644 --- a/src/documentdb/playground/PlaygroundEvaluator.ts +++ b/src/documentdb/playground/PlaygroundEvaluator.ts @@ -32,6 +32,8 @@ import { type WorkerAuthReason, } from './workerTypes'; +const consumedWorkerReplacements = new WeakSet(); + /** * Evaluates query playground code in a persistent worker thread. * @@ -201,21 +203,48 @@ export class PlaygroundEvaluator implements vscode.Disposable { const reason = (this._authFailure?.clusterId === clusterId ? this._authFailure.reason : undefined) ?? (sameCluster ? this._workerManager.authFailure : undefined); + const replacement = connection.workerReplacement; + let replaceFailedWorker = false; + let replacementFingerprint: string | undefined; + if ( + replacement && + !consumedWorkerReplacements.has(replacement) && + replacement.fingerprint === fingerprint && + (reason === 'signInRequired' || reason === 'identityMismatch') + ) { + replacementFingerprint = ClustersClient.getExpectedFingerprint(clusterId, connection.entraIdentity); + const currentFingerprint = ClustersClient.getBinding(clusterId)?.fingerprint; + if ( + replacementFingerprint === undefined || + fingerprint !== replacementFingerprint || + (currentFingerprint !== undefined && currentFingerprint !== fingerprint) + ) { + throw new ConnectionUnavailableError('credentialsChanged'); + } + replaceFailedWorker = true; + } if (sameCluster && this._relay?.epoch === epoch) { const currentFingerprint = ClustersClient.getBinding(clusterId)?.fingerprint; if ( (fingerprint !== undefined && - (fingerprint !== this._workerFingerprint || + ((!replaceFailedWorker && fingerprint !== this._workerFingerprint) || (currentFingerprint !== undefined && fingerprint !== currentFingerprint))) || - (pin && entraPin && !sameEntraIdentity(pin, entraPin)) + (!replaceFailedWorker && pin && entraPin && !sameEntraIdentity(pin, entraPin)) ) { throw new ConnectionUnavailableError('credentialsChanged'); } } - if ((pin || fingerprint) && (reason === 'signInRequired' || reason === 'identityMismatch')) { + if ( + !replaceFailedWorker && + (pin || fingerprint) && + (reason === 'signInRequired' || reason === 'identityMismatch') + ) { throw createWorkerAuthError(reason); } - const needsSpawn = !sameCluster || !!reason || this._relay?.epoch !== epoch; + if (replaceFailedWorker && replacement) { + consumedWorkerReplacements.add(replacement); + } + const needsSpawn = replaceFailedWorker || !sameCluster || !!reason || this._relay?.epoch !== epoch; const initStartTime = Date.now(); let initMsg: Extract; @@ -223,7 +252,8 @@ export class PlaygroundEvaluator implements vscode.Disposable { onProgress?.(l10n.t('Initializing…')); this.assertConnectionAvailable(clusterId); const pinned = connection.entraIdentity ?? pin; - const expected = ClustersClient.getExpectedFingerprint(clusterId, pinned); + const expected = + replacementFingerprint ?? ClustersClient.getExpectedFingerprint(clusterId, pinned); if (fingerprint !== undefined && fingerprint !== expected) { throw new ConnectionUnavailableError('credentialsChanged'); } diff --git a/src/documentdb/playground/PlaygroundService.test.ts b/src/documentdb/playground/PlaygroundService.test.ts index 948e5ed8e..971b4c60d 100644 --- a/src/documentdb/playground/PlaygroundService.test.ts +++ b/src/documentdb/playground/PlaygroundService.test.ts @@ -137,6 +137,30 @@ describe('PlaygroundService', () => { expect(service.getConnection(mockUri)).toBe(bound); }); + it('marks only the explicitly re-picked document for one failed-worker replacement', () => { + const uri2 = { toString: () => 'untitled:playground-2.documentdb.js' } as vscode.Uri; + vi.spyOn(ClustersClient, 'getBinding').mockReturnValue({ + clusterId: connection.clusterId, + fingerprint: 'new-fingerprint', + generation: 2, + }); + vi.spyOn(ClustersClient, 'getLastVerifiedIdentity').mockReturnValue(undefined); + service.setConnection(mockUri, connection); + service.setConnection(uri2, connection); + + const repicked = service.setConnectionFromHost(mockUri, { + ...connection, + databaseName: 'replacement', + }); + + expect(repicked.workerReplacement).toEqual({ fingerprint: 'new-fingerprint' }); + expect(service.getConnection(uri2)).toEqual({ + ...connection, + fingerprint: 'new-fingerprint', + }); + expect(service.getConnection(uri2)?.workerReplacement).toBeUndefined(); + }); + it('captures a worker binding only while the original document binding is current', () => { service.setConnection(mockUri, connection); const replacement = { ...connection, databaseName: 'replacement' }; diff --git a/src/documentdb/playground/PlaygroundService.ts b/src/documentdb/playground/PlaygroundService.ts index 62ed53546..7f7163d25 100644 --- a/src/documentdb/playground/PlaygroundService.ts +++ b/src/documentdb/playground/PlaygroundService.ts @@ -164,8 +164,15 @@ export class PlaygroundService implements vscode.Disposable { /** Bind a newly selected playground to the current connected host identity, when available. */ setConnectionFromHost(uri: vscode.Uri, connection: PlaygroundConnection): PlaygroundConnection { - this.setConnection(uri, connection); - return this._connections.get(uri.toString()) ?? connection; + const key = uri.toString(); + const isRepick = this._connections.has(key); + const bound = this.captureHostBinding(connection); + const activated = + isRepick && bound.fingerprint !== undefined + ? { ...bound, workerReplacement: { fingerprint: bound.fingerprint } } + : bound; + this.setConnection(uri, activated); + return this._connections.get(key) ?? activated; } private captureHostBinding(connection: PlaygroundConnection): PlaygroundConnection { diff --git a/src/documentdb/playground/types.ts b/src/documentdb/playground/types.ts index f2ac21027..5662d9144 100644 --- a/src/documentdb/playground/types.ts +++ b/src/documentdb/playground/types.ts @@ -11,6 +11,11 @@ export interface PlaygroundWorkerBinding { readonly entraIdentity?: VerifiedEntraIdentity; } +/** One-shot activation created only by an explicit, successful connection re-pick. */ +export interface PlaygroundWorkerReplacement { + readonly fingerprint: string; +} + /** * Represents a query playground connection bound to a specific document. * Each playground document has its own connection to a cluster/database. @@ -24,6 +29,7 @@ export interface PlaygroundConnection { readonly databaseName: string; readonly fingerprint?: string; readonly entraIdentity?: VerifiedEntraIdentity; + readonly workerReplacement?: PlaygroundWorkerReplacement; /** * Identifies which tree view this cluster belongs to. * Used by cross-feature navigation to open the correct branch data provider. From fce9000a0507fb43afc77daabfa76b115e7d938e Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Wed, 25 Nov 2026 14:03:49 +0000 Subject: [PATCH 09/23] docs: record verification of the four WI-2 review fixes Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iterations/01-dev-plan.md | 6 ++--- .../01-pr6a-worker-token-relays-review.md | 22 +++++++++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index 76c020e2e..449bdd0fd 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md @@ -768,9 +768,9 @@ verdict exists, do not start the work it gates. The fingerprint table (formerly intact after WI-4's verified identity and fingerprint and WI-7's disconnect latch exist, retaining the planned **Sign in again** action. Do not implement the partial relay option. - **PR6a ([#1133](https://github.com/microsoft/vscode-documentdb/pull/1133)):** The complete relay - and recovery flow is in a draft stacked on PR6. The initial Case 1 build and 310 focused tests - passed. The [AI pre-review](./01-pr6a-worker-token-relays-review.md) found four issues and - awaits author decisions. Live Shell and Playground verification stays at OP-6. + and recovery flow is in a draft stacked on PR6. The operator approved all four fixes in the + [AI pre-review](./01-pr6a-worker-token-relays-review.md). All four are implemented; the combined + Case 1 build and 534 focused tests passed. Live Shell and Playground verification stays at OP-6. --- diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr6a-worker-token-relays-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr6a-worker-token-relays-review.md index 7390f8a46..5c4c3fad1 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr6a-worker-token-relays-review.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr6a-worker-token-relays-review.md @@ -24,6 +24,10 @@ invalidation without replaying the old operation. **Author decision:** Approved as recommended. Use the confirmed post-sign-in epoch without loosening the ownership checks or replaying the operation. +**Fixed:** [`8faa1ba8f`](https://github.com/microsoft/vscode-documentdb/commit/8faa1ba8f). +Shell and Playground use the confirmed epoch and reject stale or superseded recovery +actions. The two surface suites passed 99 tests, including no replay. + ## F2. Re-picking a Playground connection leaves Run blocked (medium) The [connection picker](../../../../../src/commands/playground/connectDatabase.ts#L120) updates @@ -41,6 +45,11 @@ document's in-flight run. **Author decision:** Approved as recommended. Apply the explicit re-pick on the next Run without interrupting another document. +**Fixed:** [`f5b79a3e9`](https://github.com/microsoft/vscode-documentdb/commit/f5b79a3e9). +The re-pick is scoped to that document and used on its next Run. The picker never stops +an active worker, and other documents cannot inherit the new binding. The two focused +Playground suites passed 51 tests. + ## F3. A no-op saved edit can discard healthy Shell state (medium) The [Shell manager](../../../../../src/documentdb/shell/ShellSessionManager.ts#L227) kills a @@ -55,6 +64,10 @@ healthy worker, while explicit Disconnect still stops it. **Author decision:** Approved as recommended. Preserve healthy Shell state on an unchanged save. +**Fixed:** [`72fb52da6`](https://github.com/microsoft/vscode-documentdb/commit/72fb52da6). +A host-only invalidation no longer restarts a healthy Shell. The startup, latch and +explicit Disconnect checks remain in effect. + ## F4. A stale token request can hang a worker that is still attached (medium) The [host relay](../../../../../src/documentdb/auth/WorkerTokenRelay.ts#L71) drops the token reply @@ -71,6 +84,10 @@ invalidation with an attached worker and no stale token or diagnostics. **Author decision:** Approved as recommended. Cancel the obsolete request without returning a stale token or recording a stale failure. +**Fixed:** [`25e686f93`](https://github.com/microsoft/vscode-documentdb/commit/25e686f93). +The supervisor cancels an obsolete operation and discards its attached worker. Detached +replies remain ignored. The combined F3 and F4 focused suites passed 114 tests. + ## Scope clarification [Decision 0018](../decisions.md#0018-saved-connection-edits-permanently-lock-existing-views) @@ -79,3 +96,8 @@ or Playground documents Close-only. WI-2 and [D12](../../sovereign-clouds/decisions.md#d12-open-sessions-keep-what-they-started-with) allow a needed same-identity respawn after a password-only edit, but do not require a healthy Shell worker to restart. + +## Verification after the fixes + +Case 1 passed on `f5b79a3e9`: `npm run build` and 534 focused tests across 18 suites. +Case 2 is deferred until formal handoff. The packaged live checks remain at OP-6. From e1e0f317b022604e0b3d81b042ac0c2b92d89c76 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 26 Nov 2026 09:44:48 +0000 Subject: [PATCH 10/23] chore: prepare worker relay formatting and localization for review Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- l10n/bundle.l10n.json | 22 ++++++++- .../playground/executePlaygroundCode.test.ts | 22 +++++---- .../playground/executePlaygroundCode.ts | 10 +--- src/commands/signInAgain/signInAgain.ts | 19 ++------ src/documentdb/ClustersClient.test.ts | 4 +- src/documentdb/auth/WorkerTokenRelay.ts | 7 +-- .../playground/PlaygroundEvaluator.test.ts | 47 +++++++++++-------- .../playground/PlaygroundEvaluator.ts | 28 ++++------- .../playground/PlaygroundService.test.ts | 2 +- .../playground/PlaygroundService.ts | 22 ++++----- .../playground/WorkerSessionManager.test.ts | 21 +++++++-- .../playground/WorkerSessionManager.ts | 4 +- .../playground/playgroundWorker.test.ts | 14 ++++-- src/documentdb/playground/playgroundWorker.ts | 4 +- src/documentdb/shell/DocumentDBShellPty.ts | 13 ++--- .../shell/ShellSessionManager.test.ts | 38 +++++++++++---- src/documentdb/shell/ShellSessionManager.ts | 27 ++++++++--- 17 files changed, 180 insertions(+), 124 deletions(-) diff --git a/l10n/bundle.l10n.json b/l10n/bundle.l10n.json index 4d4e927f2..18ce9e5e7 100644 --- a/l10n/bundle.l10n.json +++ b/l10n/bundle.l10n.json @@ -969,6 +969,8 @@ "Could not save the report: {0}": "Could not save the report: {0}", "Could not show the report: {0}": "Could not show the report: {0}", "Could not sign in again.": "Could not sign in again.", + "Could not sign in again. Open a new shell from the tree.": "Could not sign in again. Open a new shell from the tree.", + "Could not sign in again. Re-pick the playground connection from the tree.": "Could not sign in again. Re-pick the playground connection from the tree.", "Could not verify the saved connection settings.": "Could not verify the saved connection settings.", "Counting documents in the source collection...": "Counting documents in the source collection...", "Counting source indexes…": "Counting source indexes…", @@ -1122,6 +1124,7 @@ "disconnect this connection": "disconnect this connection", "Disconnect?": "Disconnect?", "Disconnected": "Disconnected", + "Disconnected. Reconnect from the tree, then open a new shell.": "Disconnected. Reconnect from the tree, then open a new shell.", "Discovery plugin error: clusterId \"{0}\" must start with provider ID \"{1}\". Plugin \"{2}\" must prefix clusterId with its provider ID.": "Discovery plugin error: clusterId \"{0}\" must start with provider ID \"{1}\". Plugin \"{2}\" must prefix clusterId with its provider ID.", "Discovery Plugins: {0}": "Discovery Plugins: {0}", "Discovery view": "Discovery view", @@ -1935,6 +1938,10 @@ "Microsoft Entra ID sign-in appears to require Microsoft to preauthorize VS Code. Only Microsoft can change this.": "Microsoft Entra ID sign-in appears to require Microsoft to preauthorize VS Code. Only Microsoft can change this.", "Microsoft Entra ID sign-in failed": "Microsoft Entra ID sign-in failed", "Microsoft Entra ID sign-in for Azure DocumentDB appears to require Microsoft to preauthorize VS Code. Only Microsoft can change this, not you or your tenant administrator. Use Username and Password authentication or managed identity on an Azure VM as a workaround, and report this on GitHub. See {link}": "Microsoft Entra ID sign-in for Azure DocumentDB appears to require Microsoft to preauthorize VS Code. Only Microsoft can change this, not you or your tenant administrator. Use Username and Password authentication or managed identity on an Azure VM as a workaround, and report this on GitHub. See {link}", + "Microsoft sign-in expired for this playground. Re-pick its connection from the tree.": "Microsoft sign-in expired for this playground. Re-pick its connection from the tree.", + "Microsoft sign-in expired for this playground. Sign in again to continue.": "Microsoft sign-in expired for this playground. Sign in again to continue.", + "Microsoft sign-in expired for this shell. Open a new shell from the tree.": "Microsoft sign-in expired for this shell. Open a new shell from the tree.", + "Microsoft sign-in expired for this shell. Sign in again to continue.": "Microsoft sign-in expired for this shell. Sign in again to continue.", "Migration Providers: {0}": "Migration Providers: {0}", "Mode: {0}": "Mode: {0}", "Moderate efficiency ratio": "Moderate efficiency ratio", @@ -2039,7 +2046,6 @@ "No copyable indexes are selected.": "No copyable indexes are selected.", "No credentials found for cluster \"{0}\"": "No credentials found for cluster \"{0}\"", "No credentials found for cluster {0}": "No credentials found for cluster {0}", - "No credentials found for the query playground connection.": "No credentials found for the query playground connection.", "No credentials found for the selected cluster.": "No credentials found for the selected cluster.", "No credentials found.": "No credentials found.", "No databases in this cluster": "No databases in this cluster", @@ -2750,6 +2756,7 @@ "Showing the first {shown} collections; {omitted} more are not listed.": "Showing the first {shown} collections; {omitted} more are not listed.", "Showing the first {shown} databases; {omitted} more are not listed.": "Showing the first {shown} databases; {omitted} more are not listed.", "Sign in": "Sign in", + "Sign in again": "Sign in again", "Sign in again to continue using Microsoft Entra ID.": "Sign in again to continue using Microsoft Entra ID.", "Sign in again to continue using this connection.": "Sign in again to continue using this connection.", "Sign in from the connection tree, then click Retry.": "Sign in from the connection tree, then click Retry.", @@ -2782,6 +2789,7 @@ "Sign-in required": "Sign-in required", "Sign-in required to use this connection": "Sign-in required to use this connection", "Sign-in resource unavailable": "Sign-in resource unavailable", + "Sign-in restored. Run your command again.": "Sign-in restored. Run your command again.", "Sign-in set to {0}": "Sign-in set to {0}", "Sign-in succeeded, but the cluster did not accept this identity.": "Sign-in succeeded, but the cluster did not accept this identity.", "Sign-in to tenant was cancelled or failed: {0}": "Sign-in to tenant was cancelled or failed: {0}", @@ -3182,6 +3190,8 @@ "The sign-in application could not be found in the selected directory.": "The sign-in application could not be found in the selected directory.", "The sign-in resource could not be determined from the cloud configuration.": "The sign-in resource could not be determined from the cloud configuration.", "The sign-in service reported an error without further details.": "The sign-in service reported an error without further details.", + "The sign-in token could not be refreshed. Run the next command to reconnect with the same connection.": "The sign-in token could not be refreshed. Run the next command to reconnect with the same connection.", + "The sign-in token could not be refreshed. Run the query again to reconnect with the same connection.": "The sign-in token could not be refreshed. Run the query again to reconnect with the same connection.", "The sign-in window reported an error without details. Check the error code shown in that window, or open Developer: Show Logs... > {authenticationLog} in VS Code. Your IT help desk can help interpret the code; if the problem persists, report it on GitHub. See {link}": "The sign-in window reported an error without details. Check the error code shown in that window, or open Developer: Show Logs... > {authenticationLog} in VS Code. Your IT help desk can help interpret the code; if the problem persists, report it on GitHub. See {link}", "The silent sign-in lookup cannot distinguish not being signed in from a consent or preauthorization failure. Open Developer: Show Logs… → {0} to check the sign-in error.": "The silent sign-in lookup cannot distinguish not being signed in from a consent or preauthorization failure. Open Developer: Show Logs… → {0} to check the sign-in error.", "The SORT stage exceeded the {0}MB memory limit.\n\n**Solutions:**\n1. Add .allowDiskUse(true) to allow disk-based sorting for large result sets\n2. Create an index matching the sort pattern: {1}\n3. Add filters to reduce the number of documents being sorted\n4. Increase server memory limit (requires server configuration)": "The SORT stage exceeded the {0}MB memory limit.\n\n**Solutions:**\n1. Add .allowDiskUse(true) to allow disk-based sorting for large result sets\n2. Create an index matching the sort pattern: {1}\n3. Add filters to reduce the number of documents being sorted\n4. Increase server memory limit (requires server configuration)", @@ -3257,7 +3267,10 @@ "This Codespaces environment": "This Codespaces environment", "This connection has no connection string.": "This connection has no connection string.", "This connection is no longer in the tree. Close this view.": "This connection is no longer in the tree. Close this view.", - "This connection is unavailable. Reconnect from the tree to run this playground.": "This connection is unavailable. Reconnect from the tree to run this playground.", + "This connection is not allowed for Microsoft sign-in. Review the trusted server settings, then re-pick the playground connection.": "This connection is not allowed for Microsoft sign-in. Review the trusted server settings, then re-pick the playground connection.", + "This connection is unavailable.": "This connection is unavailable.", + "This connection is unavailable. Reconnect from the tree, then open a new shell.": "This connection is unavailable. Reconnect from the tree, then open a new shell.", + "This connection is unavailable. Reconnect from the tree, then re-pick it here.": "This connection is unavailable. Reconnect from the tree, then re-pick it here.", "This connection no longer exists. It may have been removed.": "This connection no longer exists. It may have been removed.", "This connection string asked for Microsoft Entra ID": "This connection string asked for Microsoft Entra ID", "This connection targets a local or private network host. TLS certificate validation:": "This connection targets a local or private network host. TLS certificate validation:", @@ -3301,6 +3314,8 @@ "This operation will copy all documents from the source to the target collection.": "This operation will copy all documents from the source to the target collection.", "This playground has no connection.": "This playground has no connection.", "This playground has no connection. Click to connect it to a database.": "This playground has no connection. Click to connect it to a database.", + "This playground is bound to a different Microsoft account. Re-pick its connection from the tree.": "This playground is bound to a different Microsoft account. Re-pick its connection from the tree.", + "This playground is bound to the previous connection. Re-pick its connection from the tree.": "This playground is bound to the previous connection. Re-pick its connection from the tree.", "This playground is connected to {0} / {1}.": "This playground is connected to {0} / {1}.", "This project does not contain any clusters yet.": "This project does not contain any clusters yet.", "This project does not currently contain any MongoDB Atlas clusters.": "This project does not currently contain any MongoDB Atlas clusters.", @@ -3313,6 +3328,9 @@ "This report was generated using the DocumentDB extension for Visual Studio Code.": "This report was generated using the DocumentDB extension for Visual Studio Code.", "this resource": "this resource", "This service type has no address that can be reached from the host running these checks.": "This service type has no address that can be reached from the host running these checks.", + "This shell is bound to a different Microsoft account. Open a new shell from the tree.": "This shell is bound to a different Microsoft account. Open a new shell from the tree.", + "This shell is bound to the previous connection. Open a new shell from the tree.": "This shell is bound to the previous connection. Open a new shell from the tree.", + "This shell is not allowed to sign in to this connection. Review the trusted server settings, then reconnect from the tree.": "This shell is not allowed to sign in to this connection. Review the trusted server settings, then reconnect from the tree.", "This step did not finish within the time limit. This alone does not show that the server is unreachable.": "This step did not finish within the time limit. This alone does not show that the server is unreachable.", "This stops all running WSL distributions so the new group membership applies when WSL starts again.": "This stops all running WSL distributions so the new group membership applies when WSL starts again.", "This table view presents data at the root level by default.": "This table view presents data at the root level by default.", diff --git a/src/commands/playground/executePlaygroundCode.test.ts b/src/commands/playground/executePlaygroundCode.test.ts index 53e1bb154..519e0c40f 100644 --- a/src/commands/playground/executePlaygroundCode.test.ts +++ b/src/commands/playground/executePlaygroundCode.test.ts @@ -9,16 +9,18 @@ import * as vscode from 'vscode'; import { type PlaygroundConnection } from '../../documentdb/playground/types'; import { executePlaygroundCode, stopPlaygroundEvaluator } from './executePlaygroundCode'; -const { evaluate, dispose, setExecuting, showResult, getConnection, getEpoch, canRecover, recover } = vi.hoisted(() => ({ - evaluate: vi.fn(), - dispose: vi.fn(), - setExecuting: vi.fn(), - showResult: vi.fn(), - getConnection: vi.fn<() => PlaygroundConnection | undefined>(), - getEpoch: vi.fn<() => number>(), - canRecover: vi.fn(), - recover: vi.fn(), -})); +const { evaluate, dispose, setExecuting, showResult, getConnection, getEpoch, canRecover, recover } = vi.hoisted( + () => ({ + evaluate: vi.fn(), + dispose: vi.fn(), + setExecuting: vi.fn(), + showResult: vi.fn(), + getConnection: vi.fn<() => PlaygroundConnection | undefined>(), + getEpoch: vi.fn<() => number>(), + canRecover: vi.fn(), + recover: vi.fn(), + }), +); vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ ...(await importOriginal<{ UserCancelledError: typeof UserCancelledError }>()), diff --git a/src/commands/playground/executePlaygroundCode.ts b/src/commands/playground/executePlaygroundCode.ts index 1dee85c5e..7714bf9bc 100644 --- a/src/commands/playground/executePlaygroundCode.ts +++ b/src/commands/playground/executePlaygroundCode.ts @@ -26,10 +26,7 @@ import { ext } from '../../extensionVariables'; import { ErrorExplanationService } from '../../services/errorExplanationService'; import { recordSurveyActivity } from '../../services/survey/SurveyService'; import { classifyCodeBlock } from '../../utils/classifyCommand'; -import { - canSignInAgainForWorker, - signInAgainForWorker, -} from '../signInAgain/signInAgain'; +import { canSignInAgainForWorker, signInAgainForWorker } from '../signInAgain/signInAgain'; import { promptAndConnectPlayground } from './connectDatabase'; /** Per-cluster evaluator pool — one worker per cluster, lazily created. */ @@ -322,10 +319,7 @@ interface PlaygroundRecovery { readonly authReason?: WorkerAuthReason; } -function getPlaygroundRecovery( - error: unknown, - connection: PlaygroundConnection, -): PlaygroundRecovery | undefined { +function getPlaygroundRecovery(error: unknown, connection: PlaygroundConnection): PlaygroundRecovery | undefined { const authReason = getWorkerAuthReason(error); if (authReason) { switch (authReason) { diff --git a/src/commands/signInAgain/signInAgain.ts b/src/commands/signInAgain/signInAgain.ts index 5b4a0db62..05f05ea8d 100644 --- a/src/commands/signInAgain/signInAgain.ts +++ b/src/commands/signInAgain/signInAgain.ts @@ -12,8 +12,8 @@ import { EntraSignInRequiredError, } from '../../documentdb/auth/entraErrors/entraCallbackErrors'; import { getEntraSession } from '../../documentdb/auth/entraSession'; -import { sameEntraIdentity } from '../../documentdb/auth/WorkerTokenRelay'; import { MicrosoftEntraIDAuthHandler } from '../../documentdb/auth/MicrosoftEntraIDAuthHandler'; +import { sameEntraIdentity } from '../../documentdb/auth/WorkerTokenRelay'; import { addEstablishedConnectionContext, ClustersClient } from '../../documentdb/ClustersClient'; import { classifyConnectionFailure } from '../../documentdb/connectionFailures'; import { CredentialCache } from '../../documentdb/CredentialCache'; @@ -26,10 +26,7 @@ interface WorkerSignInResult { readonly epoch: number; } -export function canSignInAgainForWorker( - clusterId: string, - expectedIdentity: VerifiedEntraIdentity, -): boolean { +export function canSignInAgainForWorker(clusterId: string, expectedIdentity: VerifiedEntraIdentity): boolean { const credentials = CredentialCache.getCredentials(clusterId); const hostIdentity = ClustersClient.getLastVerifiedIdentity(clusterId); return ( @@ -105,10 +102,7 @@ async function signInAgainInternal( context.errorHandling.suppressDisplay = true; addEstablishedConnectionContext(context.telemetry, clusterId); const isCurrent = (): boolean => { - if ( - ClustersClient.getEpoch(clusterId) !== epoch || - CredentialCache.getCredentials(clusterId) !== credentials - ) { + if (ClustersClient.getEpoch(clusterId) !== epoch || CredentialCache.getCredentials(clusterId) !== credentials) { return false; } if (!expectedIdentity) { @@ -159,8 +153,7 @@ async function signInAgainInternal( }); if ( expectedIdentity && - (auth.verifiedIdentity?.kind !== 'entra' || - !sameEntraIdentity(auth.verifiedIdentity, expectedIdentity)) + (auth.verifiedIdentity?.kind !== 'entra' || !sameEntraIdentity(auth.verifiedIdentity, expectedIdentity)) ) { throw new EntraIdentityMismatchError(); } @@ -183,9 +176,7 @@ async function signInAgainInternal( ) { refreshAuthenticationNode(node); } - return auth.verifiedIdentity - ? { identity: auth.verifiedIdentity, epoch: startupEpoch } - : undefined; + return auth.verifiedIdentity ? { identity: auth.verifiedIdentity, epoch: startupEpoch } : undefined; } catch (error) { if (!starting && !isCurrent()) { reportClosed(); diff --git a/src/documentdb/ClustersClient.test.ts b/src/documentdb/ClustersClient.test.ts index 1e6218c59..ac9f4e58d 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -331,7 +331,9 @@ describe('regular connection startup diagnostics', () => { expect(ClustersClient.getExpectedFingerprint(clusterId, verifiedIdentity)).toBe( computeConnectionFingerprint({ connectionString: uri, principal: verifiedIdentity }), ); - expect(ClustersClient.getExpectedFingerprint(clusterId, { ...verifiedIdentity, tenantId: 'other' })).toBeUndefined(); + expect( + ClustersClient.getExpectedFingerprint(clusterId, { ...verifiedIdentity, tenantId: 'other' }), + ).toBeUndefined(); }); it('does not open a changed connection for an old surface, even with no cached client', async (): Promise => { diff --git a/src/documentdb/auth/WorkerTokenRelay.ts b/src/documentdb/auth/WorkerTokenRelay.ts index 7d8b91452..12b1428c7 100644 --- a/src/documentdb/auth/WorkerTokenRelay.ts +++ b/src/documentdb/auth/WorkerTokenRelay.ts @@ -71,8 +71,7 @@ export class WorkerTokenRelay { epoch = this.epoch, ): Promise { const isCurrentEpoch = (): boolean => - !ClustersClient.getLatchReason(this.clusterId) && - ClustersClient.getEpoch(this.clusterId) === epoch; + !ClustersClient.getLatchReason(this.clusterId) && ClustersClient.getEpoch(this.clusterId) === epoch; const canReply = (): boolean => { if (!isCurrentWorker()) { return false; @@ -230,7 +229,9 @@ export class WorkerTokenRelay { requestId, error: createWorkerAuthError(reason, authMechanism as AuthMethodId).message, reason, - ...(reason === 'destinationRejected' ? { errorName: 'EntraDestinationRejectedError' as const } : {}), + ...(reason === 'destinationRejected' + ? { errorName: 'EntraDestinationRejectedError' as const } + : {}), }); } }; diff --git a/src/documentdb/playground/PlaygroundEvaluator.test.ts b/src/documentdb/playground/PlaygroundEvaluator.test.ts index 6040b3bdd..3aac3799c 100644 --- a/src/documentdb/playground/PlaygroundEvaluator.test.ts +++ b/src/documentdb/playground/PlaygroundEvaluator.test.ts @@ -22,8 +22,8 @@ import { recordEntraTokenFailure, resetEntraTokenFailuresForTests, } from '../auth/entraErrors/entraTokenFailures'; -import { ClustersClient } from '../ClustersClient'; import { type getManagedIdentityAccessToken } from '../auth/managedIdentityTokenProvider'; +import { ClustersClient } from '../ClustersClient'; import { type CachedClusterCredentials } from '../CredentialCache'; import { PlaygroundEvaluator } from './PlaygroundEvaluator'; import { type WorkerSessionCallbacks } from './WorkerSessionManager'; @@ -52,7 +52,12 @@ const mocks = vi.hoisted(() => ({ clusterId: undefined as string | undefined, worker: { isConnectedTo: vi.fn<(clusterId: string) => boolean>(), - sendEval: vi.fn<(message: MainToWorkerMessage) => Promise<{ result: { type: string; printable: string; durationMs: number } }>>(), + sendEval: + vi.fn< + ( + message: MainToWorkerMessage, + ) => Promise<{ result: { type: string; printable: string; durationMs: number } }> + >(), killWorker: vi.fn(), }, })); @@ -260,7 +265,9 @@ describe('PlaygroundEvaluator token relay lifecycle', () => { accessToken: 'other-token', }); const mismatch = await requestToken({ type: 'tokenRequest', requestId: 'different-account' }); - expect(mismatch).toHaveBeenCalledWith(expect.objectContaining({ type: 'tokenError', reason: 'identityMismatch' })); + expect(mismatch).toHaveBeenCalledWith( + expect.objectContaining({ type: 'tokenError', reason: 'identityMismatch' }), + ); mocks.configuredProvider.mockReturnValue('microsoft-sovereign-cloud'); const changed = await requestToken({ type: 'tokenRequest', requestId: 'different-provider' }); expect(changed).toHaveBeenCalledWith(expect.objectContaining({ type: 'tokenError', reason: 'signInRequired' })); @@ -297,7 +304,11 @@ describe('PlaygroundEvaluator token relay lifecycle', () => { } finally { ClustersClient.unlatch(clusterId); } - mocks.getCredentials.mockReturnValue({ clusterId, connectionString: 'mongodb://other.example.com/', authMechanism: AuthMethodId.NoAuth }); + mocks.getCredentials.mockReturnValue({ + clusterId, + connectionString: 'mongodb://other.example.com/', + authMechanism: AuthMethodId.NoAuth, + }); await evaluator.evaluate(connection, '3'); mocks.worker.isConnectedTo.mockReturnValue(true); await expect(evaluator.evaluate(oldDocument, '4')).rejects.toMatchObject({ reason: 'credentialsChanged' }); @@ -346,9 +357,7 @@ describe('PlaygroundEvaluator token relay lifecycle', () => { fingerprint: 'fingerprint-b', generation: 2, }); - const expected = vi - .spyOn(ClustersClient, 'getExpectedFingerprint') - .mockReturnValue('fingerprint-b'); + const expected = vi.spyOn(ClustersClient, 'getExpectedFingerprint').mockReturnValue('fingerprint-b'); await expect(evaluator.evaluate(oldBinding, 'old-document')).rejects.toMatchObject({ reason: 'credentialsChanged', @@ -374,13 +383,9 @@ describe('PlaygroundEvaluator token relay lifecycle', () => { name: 'EntraSignInRequiredError', }); expect(expected).toHaveBeenCalled(); - expect(mocks.worker.sendEval.mock.calls.map(([message]) => message.type === 'eval' && message.code)).toEqual([ - '1', - '2', - 'failed', - 'replacement', - 'second-failure', - ]); + expect( + mocks.worker.sendEval.mock.calls.map(([message]) => message.type === 'eval' && message.code), + ).toEqual(['1', '2', 'failed', 'replacement', 'second-failure']); mocks.getCredentials.mockClear(); } finally { vi.restoreAllMocks(); @@ -397,9 +402,13 @@ describe('PlaygroundEvaluator token relay lifecycle', () => { await evaluator.evaluate(connection, '2', undefined, capture); const binding = capture.mock.calls[0][0] as { fingerprint: string }; const bound = { ...connection, ...binding }; - const failure = new Error('outer driver error', { cause: Object.assign(new Error('private broker'), { name: 'TokenCallbackError' }) }); + const failure = new Error('outer driver error', { + cause: Object.assign(new Error('private broker'), { name: 'TokenCallbackError' }), + }); mocks.worker.sendEval.mockRejectedValueOnce(failure); - await expect(evaluator.evaluate(bound, 'failed')).rejects.toSatisfy((error: unknown) => getWorkerAuthReason(error) === 'refreshFailed'); + await expect(evaluator.evaluate(bound, 'failed')).rejects.toSatisfy( + (error: unknown) => getWorkerAuthReason(error) === 'refreshFailed', + ); mocks.worker.isConnectedTo.mockReturnValue(false); mocks.getCredentials.mockReturnValue({ clusterId, @@ -412,9 +421,9 @@ describe('PlaygroundEvaluator token relay lifecycle', () => { mocks.worker.isConnectedTo.mockReturnValue(true); mocks.getCredentials.mockClear(); await evaluator.evaluate(bound, 'after'); - expect(mocks.worker.sendEval.mock.calls.map(([message]) => message.type === 'eval' && message.code)).toEqual([ - '1', '2', 'failed', 'next', 'after', - ]); + expect( + mocks.worker.sendEval.mock.calls.map(([message]) => message.type === 'eval' && message.code), + ).toEqual(['1', '2', 'failed', 'next', 'after']); }, ); diff --git a/src/documentdb/playground/PlaygroundEvaluator.ts b/src/documentdb/playground/PlaygroundEvaluator.ts index 86dfab8bf..e8b454170 100644 --- a/src/documentdb/playground/PlaygroundEvaluator.ts +++ b/src/documentdb/playground/PlaygroundEvaluator.ts @@ -252,8 +252,7 @@ export class PlaygroundEvaluator implements vscode.Disposable { onProgress?.(l10n.t('Initializing…')); this.assertConnectionAvailable(clusterId); const pinned = connection.entraIdentity ?? pin; - const expected = - replacementFingerprint ?? ClustersClient.getExpectedFingerprint(clusterId, pinned); + const expected = replacementFingerprint ?? ClustersClient.getExpectedFingerprint(clusterId, pinned); if (fingerprint !== undefined && fingerprint !== expected) { throw new ConnectionUnavailableError('credentialsChanged'); } @@ -265,27 +264,21 @@ export class PlaygroundEvaluator implements vscode.Disposable { this._workerManager.killWorker(); } this.resetSession(); - const workerPin = initMsg.authMechanism === AuthMethodId.MicrosoftEntraID ? entraPin ?? pinned : undefined; + const workerPin = + initMsg.authMechanism === AuthMethodId.MicrosoftEntraID ? (entraPin ?? pinned) : undefined; this._pinContext = workerPin && { clusterId, identity: workerPin }; this._sessionInitMessage = initMsg; this._workerFingerprint = expected; this._sessionId = randomUUID(); this._sessionAuthMethod = initMsg.authMechanism; const originalUri = initMsg.connectionString; - this._relay = new WorkerTokenRelay( - clusterId, - initMsg, - epoch, - this._sessionId, - workerPin, - (identity) => { - this._pinContext = { clusterId, identity }; - this._workerFingerprint = computeConnectionFingerprint({ - connectionString: originalUri, - principal: identity, - }); - }, - ); + this._relay = new WorkerTokenRelay(clusterId, initMsg, epoch, this._sessionId, workerPin, (identity) => { + this._pinContext = { clusterId, identity }; + this._workerFingerprint = computeConnectionFingerprint({ + connectionString: originalUri, + principal: identity, + }); + }); } else { initMsg = this._sessionInitMessage; } @@ -503,7 +496,6 @@ export class PlaygroundEvaluator implements vscode.Disposable { }; } - // ─── Private: Session telemetry ────────────────────────────────────────── private resetSession(): void { diff --git a/src/documentdb/playground/PlaygroundService.test.ts b/src/documentdb/playground/PlaygroundService.test.ts index 971b4c60d..d39446b90 100644 --- a/src/documentdb/playground/PlaygroundService.test.ts +++ b/src/documentdb/playground/PlaygroundService.test.ts @@ -11,8 +11,8 @@ import { type PlaygroundConnection } from './types'; // Access the vscode mock (aliased to test/vitest/vscode.ts) import * as vscode from 'vscode'; -import { CredentialCache } from '../CredentialCache'; import { ClustersClient } from '../ClustersClient'; +import { CredentialCache } from '../CredentialCache'; vi.mock('../CredentialCache', () => ({ CredentialCache: { hasCredentials: vi.fn() }, diff --git a/src/documentdb/playground/PlaygroundService.ts b/src/documentdb/playground/PlaygroundService.ts index 7f7163d25..a6a3e86cb 100644 --- a/src/documentdb/playground/PlaygroundService.ts +++ b/src/documentdb/playground/PlaygroundService.ts @@ -180,19 +180,15 @@ export class PlaygroundService implements vscode.Disposable { const verifiedIdentity = ClustersClient.getLastVerifiedIdentity(connection.clusterId); const hostIdentityIsCompatible = connection.fingerprint === undefined || connection.fingerprint === binding?.fingerprint; - return ( - binding === undefined - ? connection - : { - ...connection, - fingerprint: connection.fingerprint ?? binding.fingerprint, - entraIdentity: - connection.entraIdentity ?? - (hostIdentityIsCompatible && verifiedIdentity?.kind === 'entra' - ? verifiedIdentity - : undefined), - } - ); + return binding === undefined + ? connection + : { + ...connection, + fingerprint: connection.fingerprint ?? binding.fingerprint, + entraIdentity: + connection.entraIdentity ?? + (hostIdentityIsCompatible && verifiedIdentity?.kind === 'entra' ? verifiedIdentity : undefined), + }; } /** Capture a worker-learned binding only while the document still holds the originating connection. */ diff --git a/src/documentdb/playground/WorkerSessionManager.test.ts b/src/documentdb/playground/WorkerSessionManager.test.ts index d4a1fe4b7..e4edd3a43 100644 --- a/src/documentdb/playground/WorkerSessionManager.test.ts +++ b/src/documentdb/playground/WorkerSessionManager.test.ts @@ -814,19 +814,32 @@ describe('WorkerSessionManager', () => { async (reason): Promise => { const failed = await startWorker(); failed.worker._emit('message', { - type: 'initResult', requestId: failed.requestId, success: false, authReason: reason, + type: 'initResult', + requestId: failed.requestId, + success: false, + authReason: reason, }); - await expect(failed.initPromise).rejects.toSatisfy((error: unknown) => getWorkerAuthReason(error) === reason); + await expect(failed.initPromise).rejects.toSatisfy( + (error: unknown) => getWorkerAuthReason(error) === reason, + ); const active = await startWorker(); active.worker._emit('message', { type: 'initResult', requestId: active.requestId, success: true }); await active.initPromise; const evaluating = active.manager.sendEval({ - type: 'eval', requestId: '', code: '1', databaseName: 'test', displayBatchSize: 20, + type: 'eval', + requestId: '', + code: '1', + databaseName: 'test', + displayBatchSize: 20, }); const worker = vi.mocked(Worker).mock.results.at(-1)?.value as { postMessage: Mock }; const evaluation = worker.postMessage.mock.calls.at(-1)?.[0] as MainToWorkerMessage; - active.worker._emit('message', { type: 'evalError', requestId: evaluation.requestId, authReason: reason }); + active.worker._emit('message', { + type: 'evalError', + requestId: evaluation.requestId, + authReason: reason, + }); await expect(evaluating).rejects.toSatisfy((error: unknown) => getWorkerAuthReason(error) === reason); expect(active.manager.authFailure).toBe(reason); active.manager.dispose(); diff --git a/src/documentdb/playground/WorkerSessionManager.ts b/src/documentdb/playground/WorkerSessionManager.ts index ff9319695..3bb6ac9ec 100644 --- a/src/documentdb/playground/WorkerSessionManager.ts +++ b/src/documentdb/playground/WorkerSessionManager.ts @@ -654,7 +654,9 @@ export class WorkerSessionManager implements vscode.Disposable { this._pendingRequests.delete(msg.requestId); const reason = isWorkerAuthReason(msg.authReason) ? msg.authReason - : (msg.errorName === 'EntraDestinationRejectedError' ? 'destinationRejected' : this._authFailure); + : msg.errorName === 'EntraDestinationRejectedError' + ? 'destinationRejected' + : this._authFailure; this._authFailure ??= reason; if (msg.success && !reason) { pending.resolve(undefined); diff --git a/src/documentdb/playground/playgroundWorker.test.ts b/src/documentdb/playground/playgroundWorker.test.ts index c70f47710..82fde16e9 100644 --- a/src/documentdb/playground/playgroundWorker.test.ts +++ b/src/documentdb/playground/playgroundWorker.test.ts @@ -298,11 +298,17 @@ describe('playground worker OIDC configuration at the driver boundary', () => { ); driver.evaluate.mockImplementationOnce(rejectCallback); receive({ - type: 'eval', requestId: 'warm', code: 'db.test.find()', displayBatchSize: 20, databaseName: 'test', + type: 'eval', + requestId: 'warm', + code: 'db.test.find()', + displayBatchSize: 20, + databaseName: 'test', }); - await vi.waitFor(() => expect(transport.postMessage).toHaveBeenCalledWith( - expect.objectContaining({ type: 'evalError', requestId: 'warm', authReason: reason }), - )); + await vi.waitFor(() => + expect(transport.postMessage).toHaveBeenCalledWith( + expect.objectContaining({ type: 'evalError', requestId: 'warm', authReason: reason }), + ), + ); }, ); diff --git a/src/documentdb/playground/playgroundWorker.ts b/src/documentdb/playground/playgroundWorker.ts index 1da8a4474..b2fc7ae1f 100644 --- a/src/documentdb/playground/playgroundWorker.ts +++ b/src/documentdb/playground/playgroundWorker.ts @@ -417,7 +417,9 @@ function handleTokenError(msg: Extract { const manager = new ShellSessionManager({ clusterId, clusterDisplayName: 'Cluster', databaseName: 'test' }); const setNative = (connectionUser: string, connectionPassword: string): void => CredentialCache.setAuthCredentials(clusterId, AuthMethodId.NativeAuth, 'mongodb://native.example.com/', { - connectionUser, connectionPassword, + connectionUser, + connectionPassword, }); setNative('account-a', 'first'); await manager.initialize(); @@ -204,7 +205,11 @@ describe('ShellSessionManager', () => { await manager.evaluate('keep'); const reply = vi.fn(); await workerCallbacks.onTokenRequest?.({ type: 'tokenRequest', requestId: 'refresh' }, reply, () => true); - expect(reply).toHaveBeenCalledWith({ type: 'tokenResponse', requestId: 'refresh', accessToken: 'private-token' }); + expect(reply).toHaveBeenCalledWith({ + type: 'tokenResponse', + requestId: 'refresh', + accessToken: 'private-token', + }); expect(mockGetSessionFromVSCode.mock.calls[1][2]).toEqual({ silent: true, account }); expect(killWorker).not.toHaveBeenCalled(); expect(onReconnecting).not.toHaveBeenCalled(); @@ -225,13 +230,16 @@ describe('ShellSessionManager', () => { const manager = new ShellSessionManager({ clusterId, clusterDisplayName: 'Cluster', databaseName: 'test' }); requestTokenOnInit = true; mockGetSessionFromVSCode.mockResolvedValue({ - accessToken: 'private-token', account: { id: 'account-a', label: 'Account A' }, + accessToken: 'private-token', + account: { id: 'account-a', label: 'Account A' }, }); await manager.initialize(); const identity = manager.pinnedEntraIdentity!; const epoch = ClustersClient.getEpoch(clusterId); sendEval.mockRejectedValueOnce(Object.assign(new Error('miss'), { name: 'EntraSignInRequiredError' })); - await expect(manager.evaluate('first')).rejects.toSatisfy((error: unknown) => getWorkerAuthReason(error) === 'signInRequired'); + await expect(manager.evaluate('first')).rejects.toSatisfy( + (error: unknown) => getWorkerAuthReason(error) === 'signInRequired', + ); await expect(manager.evaluate('blocked')).rejects.toMatchObject({ name: 'EntraSignInRequiredError' }); expect(() => manager.resetAfterSignIn({ ...identity, accountId: 'account-b' }, epoch)).toThrow( expect.objectContaining({ name: 'EntraIdentityMismatchError' }), @@ -241,7 +249,8 @@ describe('ShellSessionManager', () => { await manager.evaluate('next'); expect(sendEval.mock.calls.map(([message]) => message.code)).toEqual(['first', 'next']); expect(mockGetSessionFromVSCode.mock.calls[1][2]).toEqual({ - silent: true, account: { id: 'account-a', label: 'Account A' }, + silent: true, + account: { id: 'account-a', label: 'Account A' }, }); manager.dispose(); }); @@ -353,7 +362,10 @@ describe('ShellSessionManager', () => { authMethod === AuthMethodId.ManagedIdentity ? mockGetManagedIdentityAccessToken : mockGetSessionFromVSCode; - provider.mockResolvedValue({ accessToken: 'private-token', account: { id: 'account', label: 'private-account' } }); + provider.mockResolvedValue({ + accessToken: 'private-token', + account: { id: 'account', label: 'private-account' }, + }); const postResponse = vi.fn(); const forged = { type: 'tokenRequest', @@ -447,7 +459,10 @@ describe('ShellSessionManager', () => { authMethod === AuthMethodId.ManagedIdentity ? mockGetManagedIdentityAccessToken : mockGetSessionFromVSCode; - provider.mockResolvedValue({ accessToken: 'private-token', account: { id: 'account', label: 'private-account' } }); + provider.mockResolvedValue({ + accessToken: 'private-token', + account: { id: 'account', label: 'private-account' }, + }); const postResponse = vi.fn(); await workerCallbacks.onTokenRequest?.( { type: 'tokenRequest', requestId: 'first' }, @@ -709,7 +724,10 @@ describe('ShellSessionManager', () => { }, }); const provider = source === 'vscode' ? mockGetSessionFromVSCode : mockGetManagedIdentityAccessToken; - provider.mockResolvedValueOnce({ accessToken: 'private-token', account: { id: 'account', label: 'private-account' } }); + provider.mockResolvedValueOnce({ + accessToken: 'private-token', + account: { id: 'account', label: 'private-account' }, + }); const manager = surface === 'shell' ? new ShellSessionManager({ clusterId, clusterDisplayName: 'Test Cluster', databaseName: 'test' }) @@ -734,7 +752,9 @@ describe('ShellSessionManager', () => { }); expect(resolver).toHaveBeenCalledWith(connectionString); const args = provider.mock.calls.at(-1); - expect(args?.[source === 'vscode' ? 1 : 0]).toEqual(['https://ossrdbms-aad.database.usgovcloudapi.net/.default']); + expect(args?.[source === 'vscode' ? 1 : 0]).toEqual([ + 'https://ossrdbms-aad.database.usgovcloudapi.net/.default', + ]); expect(postResponse).toHaveBeenCalledWith({ type: 'tokenResponse', requestId: 'token-request', diff --git a/src/documentdb/shell/ShellSessionManager.ts b/src/documentdb/shell/ShellSessionManager.ts index 01eda6c82..0da3ca526 100644 --- a/src/documentdb/shell/ShellSessionManager.ts +++ b/src/documentdb/shell/ShellSessionManager.ts @@ -8,14 +8,14 @@ import { randomUUID } from 'crypto'; import type * as vscode from 'vscode'; import { ext } from '../../extensionVariables'; import { getBatchSizeSetting, getConnectionTimeoutMs } from '../../utils/workspacUtils'; -import { ClustersClient } from '../ClustersClient'; -import { ConnectionUnavailableError } from '../ConnectionUnavailableError'; -import { CredentialCache } from '../CredentialCache'; import { type VerifiedEntraIdentity } from '../auth/AuthHandler'; import { AuthMethodId } from '../auth/AuthMethodId'; import { EntraIdentityMismatchError } from '../auth/entraErrors/entraCallbackErrors'; import { createWorkerAuthError, sameEntraIdentity, WorkerTokenRelay } from '../auth/WorkerTokenRelay'; +import { ClustersClient } from '../ClustersClient'; import { computeConnectionFingerprint } from '../connectionFingerprint'; +import { ConnectionUnavailableError } from '../ConnectionUnavailableError'; +import { CredentialCache } from '../CredentialCache'; import { WorkerSessionManager, type WorkerSessionCallbacks, @@ -144,7 +144,9 @@ export class ShellSessionManager implements vscode.Disposable { const relay = this._relay; // Warm Shells survive host-only invalidation. Fence each refresh at receipt; // startup still uses the epoch captured before opening the connection. - const epoch = this._initialized ? ClustersClient.getEpoch(this._connectionInfo.clusterId) : relay?.epoch; + const epoch = this._initialized + ? ClustersClient.getEpoch(this._connectionInfo.clusterId) + : relay?.epoch; await relay?.relay(request, post, () => this._relay === relay && isCurrent(), timings, trace, epoch); }, onWorkerExit: callbacks?.onWorkerExit, @@ -157,7 +159,9 @@ export class ShellSessionManager implements vscode.Disposable { * Whether the shell session has been initialized (worker spawned and connected). */ get isInitialized(): boolean { - return this._initialized && this._workerManager.isAlive && !this._authFailure && !this._workerManager.authFailure; + return ( + this._initialized && this._workerManager.isAlive && !this._authFailure && !this._workerManager.authFailure + ); } /** @@ -267,9 +271,18 @@ export class ShellSessionManager implements vscode.Disposable { const relay = this._relay; try { - await this._workerManager.ensureWorker(clusterId, initMsg, getConnectionTimeoutMs(), this._telemetryContext); + await this._workerManager.ensureWorker( + clusterId, + initMsg, + getConnectionTimeoutMs(), + this._telemetryContext, + ); } catch (error) { - if (relay === this._relay && epoch === ClustersClient.getEpoch(clusterId) && !ClustersClient.getLatchReason(clusterId)) { + if ( + relay === this._relay && + epoch === ClustersClient.getEpoch(clusterId) && + !ClustersClient.getLatchReason(clusterId) + ) { this._authFailure ??= getWorkerAuthReason(error); } throw error; From 27410085fbfb90ccdcbb27af5b22b8028f880c32 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 26 Nov 2026 09:45:08 +0000 Subject: [PATCH 11/23] fix: require a verified host identity for worker sign-in Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/commands/signInAgain/signInAgain.test.ts | 20 ++++---------------- src/commands/signInAgain/signInAgain.ts | 9 +++------ 2 files changed, 7 insertions(+), 22 deletions(-) diff --git a/src/commands/signInAgain/signInAgain.test.ts b/src/commands/signInAgain/signInAgain.test.ts index 2e28bd824..9a179d04d 100644 --- a/src/commands/signInAgain/signInAgain.test.ts +++ b/src/commands/signInAgain/signInAgain.test.ts @@ -168,23 +168,11 @@ describe('signInAgain', () => { expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); }); - it('recovers the exact worker pin without requiring the host to retain it', async (): Promise => { + it('does not prompt when only the worker retains the identity pin', async (): Promise => { vi.mocked(ClustersClient.getLatchReason).mockReturnValue(undefined); vi.mocked(ClustersClient.getLastVerifiedIdentity).mockReturnValue(undefined); - vi.mocked(getEntraSession).mockResolvedValueOnce({ - account: { id: pin.accountId, label: pin.accountLabel }, - } as vscode.AuthenticationSession); - vi.mocked(ClustersClient.startAfterSignIn).mockResolvedValueOnce({} as ClustersClient); - - const result = await signInAgainForWorker(actionContext(), clusterId, pin); - - expect(result).toEqual({ identity: pin, epoch: 1 }); - expect(getEntraSession).toHaveBeenCalledWith( - expect.objectContaining({ - providerId: pin.providerId, - tenantId: pin.tenantId, - account: { id: pin.accountId, label: pin.accountLabel }, - }), - ); + await expect(signInAgainForWorker(actionContext(), clusterId, pin)).resolves.toBeUndefined(); + expect(getEntraSession).not.toHaveBeenCalled(); + expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); }); }); diff --git a/src/commands/signInAgain/signInAgain.ts b/src/commands/signInAgain/signInAgain.ts index 05f05ea8d..4eba12306 100644 --- a/src/commands/signInAgain/signInAgain.ts +++ b/src/commands/signInAgain/signInAgain.ts @@ -33,8 +33,8 @@ export function canSignInAgainForWorker(clusterId: string, expectedIdentity: Ver ClustersClient.getLatchReason(clusterId) === undefined && credentials?.authMechanism === AuthMethodId.MicrosoftEntraID && credentials.entraIdConfig?.tenantId === expectedIdentity.tenantId && - (hostIdentity === undefined || - (hostIdentity.kind === 'entra' && sameEntraIdentity(hostIdentity, expectedIdentity))) + hostIdentity?.kind === 'entra' && + sameEntraIdentity(hostIdentity, expectedIdentity) ); } @@ -109,10 +109,7 @@ async function signInAgainInternal( return true; } const currentIdentity = ClustersClient.getLastVerifiedIdentity(clusterId); - return ( - currentIdentity === undefined || - (currentIdentity.kind === 'entra' && sameEntraIdentity(currentIdentity, expectedIdentity)) - ); + return currentIdentity?.kind === 'entra' && sameEntraIdentity(currentIdentity, expectedIdentity); }; const reportClosed = (): void => { if (!expectedIdentity) { From 50cb05dc325a21ca61985dac2dd9ed745978fe08 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 26 Nov 2026 09:46:01 +0000 Subject: [PATCH 12/23] fix: report Playground sign-in recovery separately from the run Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../playground/executePlaygroundCode.test.ts | 17 +++++++--- .../playground/executePlaygroundCode.ts | 33 ++++++++++--------- 2 files changed, 31 insertions(+), 19 deletions(-) diff --git a/src/commands/playground/executePlaygroundCode.test.ts b/src/commands/playground/executePlaygroundCode.test.ts index 519e0c40f..c57f2d54e 100644 --- a/src/commands/playground/executePlaygroundCode.test.ts +++ b/src/commands/playground/executePlaygroundCode.test.ts @@ -9,7 +9,7 @@ import * as vscode from 'vscode'; import { type PlaygroundConnection } from '../../documentdb/playground/types'; import { executePlaygroundCode, stopPlaygroundEvaluator } from './executePlaygroundCode'; -const { evaluate, dispose, setExecuting, showResult, getConnection, getEpoch, canRecover, recover } = vi.hoisted( +const { evaluate, dispose, setExecuting, showResult, getConnection, getEpoch, canRecover, recover, contexts } = vi.hoisted( () => ({ evaluate: vi.fn(), dispose: vi.fn(), @@ -19,15 +19,20 @@ const { evaluate, dispose, setExecuting, showResult, getConnection, getEpoch, ca getEpoch: vi.fn<() => number>(), canRecover: vi.fn(), recover: vi.fn(), + contexts: new Map(), }), ); vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ ...(await importOriginal<{ UserCancelledError: typeof UserCancelledError }>()), callWithTelemetryAndErrorHandling: ( - _name: string, + name: string, run: (context: IActionContext) => Promise, - ): Promise => run({ errorHandling: {}, telemetry: { measurements: {}, properties: {} } } as IActionContext), + ): Promise => { + const context = { errorHandling: {}, telemetry: { measurements: {}, properties: {} } } as IActionContext; + contexts.set(name, context); + return run(context); + }, })); vi.mock('../../documentdb/ClustersClient', () => ({ @@ -63,6 +68,7 @@ vi.mock('../../extensionVariables', () => ({ describe('executePlaygroundCode', () => { beforeEach(() => { vi.clearAllMocks(); + contexts.clear(); getConnection.mockReturnValue({ clusterId: 'cluster', clusterDisplayName: 'Cluster', databaseName: 'test' }); getEpoch.mockReturnValue(0); canRecover.mockReturnValue(false); @@ -176,7 +182,10 @@ describe('executePlaygroundCode', () => { await expect( executePlaygroundCode('db.stats()', 'runAll', vscode.Uri.file('test.documentdb.js')), ).rejects.toBe(failure); - expect(recover).toHaveBeenCalledExactlyOnceWith(expect.anything(), 'cluster', identity); + const signInContext = contexts.get('playground.signInAgain'); + expect(signInContext).toBeDefined(); + expect(signInContext).not.toBe(contexts.get('playground.execute')); + expect(recover).toHaveBeenCalledExactlyOnceWith(signInContext, 'cluster', identity); expect(evaluate).toHaveBeenCalledOnce(); expect(dispose).toHaveBeenCalledTimes(superseded ? 0 : 1); } finally { diff --git a/src/commands/playground/executePlaygroundCode.ts b/src/commands/playground/executePlaygroundCode.ts index 7714bf9bc..d1842883d 100644 --- a/src/commands/playground/executePlaygroundCode.ts +++ b/src/commands/playground/executePlaygroundCode.ts @@ -290,7 +290,7 @@ export async function executePlaygroundCode( } if (recovery) { - offerPlaygroundRecovery(context, sourceUri, boundConnection, recovery); + offerPlaygroundRecovery(sourceUri, boundConnection, recovery); throw error; } @@ -374,7 +374,6 @@ function getPlaygroundRecovery(error: unknown, connection: PlaygroundConnection) } function offerPlaygroundRecovery( - context: IActionContext, documentUri: vscode.Uri, connection: PlaygroundConnection, recovery: PlaygroundRecovery, @@ -400,20 +399,24 @@ function offerPlaygroundRecovery( if (choice !== action || ClustersClient.getEpoch(clusterId) !== epoch || !stillOwnsAction()) { return; } - try { - const result = await signInAgainForWorker(context, clusterId, identity); - if (!result || ClustersClient.getEpoch(clusterId) !== result.epoch || !stillOwnsAction()) { - return; - } - stopPlaygroundEvaluator(clusterId); - } catch (error) { - if (error instanceof UserCancelledError || !stillOwnsAction()) { - return; + await callWithTelemetryAndErrorHandling('playground.signInAgain', async (context) => { + context.errorHandling.suppressDisplay = true; + context.telemetry.properties.sessionId = evaluator?.sessionId ?? 'none'; + try { + const result = await signInAgainForWorker(context, clusterId, identity); + if (!result || ClustersClient.getEpoch(clusterId) !== result.epoch || !stillOwnsAction()) { + return; + } + stopPlaygroundEvaluator(clusterId); + } catch (error) { + if (!(error instanceof UserCancelledError) && stillOwnsAction()) { + void vscode.window.showWarningMessage( + l10n.t('Could not sign in again. Re-pick the playground connection from the tree.'), + ); + } + throw error; } - void vscode.window.showWarningMessage( - l10n.t('Could not sign in again. Re-pick the playground connection from the tree.'), - ); - } + }); }); } From 2967db64649c1c581ae6fb4d16e9fc3c89b271ca Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 26 Nov 2026 09:46:37 +0000 Subject: [PATCH 13/23] fix: compare worker auth mechanisms using their wire types Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/documentdb/playground/WorkerSessionManager.ts | 2 +- src/documentdb/playground/playgroundWorker.ts | 5 ++--- src/documentdb/shell/ShellSessionManager.ts | 4 ++-- 3 files changed, 5 insertions(+), 6 deletions(-) diff --git a/src/documentdb/playground/WorkerSessionManager.ts b/src/documentdb/playground/WorkerSessionManager.ts index 3bb6ac9ec..ed9024eb2 100644 --- a/src/documentdb/playground/WorkerSessionManager.ts +++ b/src/documentdb/playground/WorkerSessionManager.ts @@ -16,7 +16,7 @@ import { Worker } from 'worker_threads'; import { ext } from '../../extensionVariables'; import { settingsKeys } from '../../settingsKeys'; import { traceEntraDestination, type AuthTraceContext } from '../../utils/authTrace'; -import { AuthMethodId } from '../auth/AuthMethodId'; +import { type AuthMethodId } from '../auth/AuthMethodId'; import { getEntraCustomHostnameSuffix } from '../auth/entraDestinationSettings'; import { removeConflictingOidcMechanism } from '../auth/nonOidcConnectionString'; import { diff --git a/src/documentdb/playground/playgroundWorker.ts b/src/documentdb/playground/playgroundWorker.ts index b2fc7ae1f..12673add2 100644 --- a/src/documentdb/playground/playgroundWorker.ts +++ b/src/documentdb/playground/playgroundWorker.ts @@ -23,7 +23,6 @@ import { EJSON } from 'bson'; import { randomUUID } from 'crypto'; import { type MongoClientOptions, type MongoClient as MongoClientType } from 'mongodb'; import { parentPort } from 'worker_threads'; -import { AuthMethodId } from '../auth/AuthMethodId'; import { removeConflictingOidcMechanism } from '../auth/nonOidcConnectionString'; import { EntraDestinationRejectedError, normalizeCustomHostnameSuffix } from '../auth/oidcAllowedHosts'; import { @@ -177,7 +176,7 @@ async function handleInit(msg: Extract): // differs, and both are resolved on the main thread so there is one credential and one cache // per window, and so the worker never needs @azure/identity. let connectionString = msg.connectionString; - if (msg.authMechanism === AuthMethodId.MicrosoftEntraID || msg.authMechanism === AuthMethodId.ManagedIdentity) { + if (msg.authMechanism === 'MicrosoftEntraID' || msg.authMechanism === 'ManagedIdentity') { const snapshot = msg.oidcDestinationPolicy; if ( !snapshot || @@ -204,7 +203,7 @@ async function handleInit(msg: Extract): originalPolicy.assertAllowed(host); }, }; - const usesManagedIdentity = msg.authMechanism === AuthMethodId.ManagedIdentity; + const usesManagedIdentity = msg.authMechanism === 'ManagedIdentity'; const configuration = buildOidcClientConfiguration({ connectionString, policy, diff --git a/src/documentdb/shell/ShellSessionManager.ts b/src/documentdb/shell/ShellSessionManager.ts index 0da3ca526..162accb07 100644 --- a/src/documentdb/shell/ShellSessionManager.ts +++ b/src/documentdb/shell/ShellSessionManager.ts @@ -249,7 +249,7 @@ export class ShellSessionManager implements vscode.Disposable { this._fingerprint ??= fingerprint; const verified = ClustersClient.getLastVerifiedIdentity(clusterId); const pin = this._pin ?? (verified?.kind === 'entra' ? verified : undefined); - if (initMsg.authMechanism === AuthMethodId.MicrosoftEntraID) { + if (initMsg.authMechanism === 'MicrosoftEntraID') { this._pin = pin; } this._relay = new WorkerTokenRelay( @@ -257,7 +257,7 @@ export class ShellSessionManager implements vscode.Disposable { initMsg, epoch, this._managedIdentityTokenCorrelationId, - initMsg.authMechanism === AuthMethodId.MicrosoftEntraID ? pin : undefined, + initMsg.authMechanism === 'MicrosoftEntraID' ? pin : undefined, (identity) => { this._pin = identity; this._fingerprint ??= computeConnectionFingerprint({ From a5ce99b9764276f446ef0d68752cb8988f280301 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 26 Nov 2026 09:47:05 +0000 Subject: [PATCH 14/23] fix: retain the playground Entra pin after startup failure Addresses Copilot review comment 4704909901. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../playground/PlaygroundEvaluator.test.ts | 98 ++++++++++++++++++- .../playground/PlaygroundEvaluator.ts | 21 +++- 2 files changed, 114 insertions(+), 5 deletions(-) diff --git a/src/documentdb/playground/PlaygroundEvaluator.test.ts b/src/documentdb/playground/PlaygroundEvaluator.test.ts index 3aac3799c..1ae512096 100644 --- a/src/documentdb/playground/PlaygroundEvaluator.test.ts +++ b/src/documentdb/playground/PlaygroundEvaluator.test.ts @@ -6,7 +6,11 @@ import type * as azureAuth from '@microsoft/vscode-azext-azureauth'; import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest'; -import { type callWithTelemetryAndErrorHandling, type IActionContext } from '@microsoft/vscode-azext-utils'; +import { + type callWithTelemetryAndErrorHandling, + type IActionContext, + UserCancelledError, +} from '@microsoft/vscode-azext-utils'; import * as vscode from 'vscode'; import { ext } from '../../extensionVariables'; import { type AuthTraceContext } from '../../utils/authTrace'; @@ -24,8 +28,10 @@ import { } from '../auth/entraErrors/entraTokenFailures'; import { type getManagedIdentityAccessToken } from '../auth/managedIdentityTokenProvider'; import { ClustersClient } from '../ClustersClient'; +import { computeConnectionFingerprint } from '../connectionFingerprint'; import { type CachedClusterCredentials } from '../CredentialCache'; import { PlaygroundEvaluator } from './PlaygroundEvaluator'; +import { type PlaygroundWorkerBinding } from './types'; import { type WorkerSessionCallbacks } from './WorkerSessionManager'; import { getWorkerAuthReason, type MainToWorkerMessage, type WorkerToMainMessage } from './workerTypes'; @@ -50,6 +56,7 @@ const mocks = vi.hoisted(() => ({ callbacks: undefined as WorkerSessionCallbacks | undefined, initMessage: undefined as InitMessage | undefined, clusterId: undefined as string | undefined, + startup: vi.fn<() => Promise>(), worker: { isConnectedTo: vi.fn<(clusterId: string) => boolean>(), sendEval: @@ -122,6 +129,7 @@ vi.mock('./WorkerSessionManager', () => ({ ensureWorker: vi.fn(async (clusterId: string, initMessage: InitMessage): Promise => { mocks.clusterId = clusterId; mocks.initMessage = initMessage; + await mocks.startup(); }), get workerClusterId(): string | undefined { return mocks.clusterId; @@ -157,6 +165,7 @@ describe('PlaygroundEvaluator token relay lifecycle', () => { mocks.callbacks = undefined; mocks.initMessage = undefined; mocks.clusterId = undefined; + mocks.startup.mockReset(); mocks.configuredProvider.mockReturnValue('microsoft'); mocks.worker.isConnectedTo.mockReturnValue(false); mocks.worker.sendEval.mockResolvedValue({ result: { type: 'number', printable: '1', durationMs: 0 } }); @@ -232,6 +241,93 @@ describe('PlaygroundEvaluator token relay lifecycle', () => { } const connection = { clusterId, clusterDisplayName: 'Test Cluster', databaseName: 'test' }; + const learnedIdentity = { + kind: 'entra', + providerId: 'microsoft', + tenantId: 'interactive-tenant', + accountId: 'private-account', + accountLabel, + } as const; + + function configureEntraStartup(): void { + mocks.getCredentials.mockReturnValue({ + clusterId, + connectionString: originalConnection, + authMechanism: AuthMethodId.MicrosoftEntraID, + entraIdConfig: { tenantId: learnedIdentity.tenantId }, + }); + } + + it('retains the first relay pin on startup failure without running the query', async (): Promise => { + const failure = new Error('database startup failed'); + const capture = vi.fn<(binding: PlaygroundWorkerBinding) => void>(); + configureEntraStartup(); + mocks.startup.mockImplementationOnce(async () => { + const response = await requestToken({ type: 'tokenRequest', requestId: 'startup' }); + expect(response).toHaveBeenCalledWith(expect.objectContaining({ type: 'tokenResponse' })); + throw failure; + }); + + try { + await expect(evaluator.evaluate(connection, 'first Run', undefined, capture)).rejects.toBe(failure); + expect(capture).toHaveBeenCalledExactlyOnceWith({ + fingerprint: computeConnectionFingerprint({ + connectionString: originalConnection, + principal: learnedIdentity, + }), + entraIdentity: learnedIdentity, + }); + + evaluator.dispose(); + evaluator = new PlaygroundEvaluator(); + const verified = vi.spyOn(ClustersClient, 'getLastVerifiedIdentity').mockReturnValue({ + ...learnedIdentity, + accountId: 'different-account', + }); + try { + await expect( + evaluator.evaluate({ ...connection, ...capture.mock.calls[0][0] }, 'next Run'), + ).rejects.toMatchObject({ reason: 'credentialsChanged' }); + } finally { + verified.mockRestore(); + } + expect(mocks.worker.sendEval).not.toHaveBeenCalled(); + } finally { + mocks.getCredentials.mockClear(); + } + }); + + it.each(['relay replaced', 'epoch changed', 'latched', 'cancelled'] as const)( + 'does not capture a learned pin on startup failure after %s', + async (invalidation): Promise => { + const failure = + invalidation === 'cancelled' ? new UserCancelledError('workerStartup') : new Error('startup failed'); + const capture = vi.fn(); + configureEntraStartup(); + const latch = vi.spyOn(ClustersClient, 'getLatchReason'); + mocks.startup.mockImplementationOnce(async () => { + const response = await requestToken({ type: 'tokenRequest', requestId: 'startup' }); + expect(response).toHaveBeenCalledWith(expect.objectContaining({ type: 'tokenResponse' })); + if (invalidation === 'relay replaced') { + evaluator.killWorker(); + } else if (invalidation === 'epoch changed') { + ClustersClient.invalidate(clusterId); + } else if (invalidation === 'latched') { + latch.mockReturnValue('userDisconnected'); + } + throw failure; + }); + + try { + await expect(evaluator.evaluate(connection, 'first Run', undefined, capture)).rejects.toBe(failure); + expect(capture).not.toHaveBeenCalled(); + expect(mocks.worker.sendEval).not.toHaveBeenCalled(); + } finally { + mocks.getCredentials.mockClear(); + latch.mockRestore(); + } + }, + ); it('uses a verified cluster identity silently on the first relay', async (): Promise => { const verified = vi.spyOn(ClustersClient, 'getLastVerifiedIdentity').mockReturnValue({ diff --git a/src/documentdb/playground/PlaygroundEvaluator.ts b/src/documentdb/playground/PlaygroundEvaluator.ts index e8b454170..9c7613ace 100644 --- a/src/documentdb/playground/PlaygroundEvaluator.ts +++ b/src/documentdb/playground/PlaygroundEvaluator.ts @@ -3,7 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { callWithTelemetryAndErrorHandling } from '@microsoft/vscode-azext-utils'; +import { callWithTelemetryAndErrorHandling, UserCancelledError } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; // Static or `await import('bson')`, this is the driver's CommonJS copy: vite.config.ext.mjs and // vitest.config.ts alias `bson` to it. Without the alias an ES-module importer gets bson's ESM @@ -247,6 +247,7 @@ export class PlaygroundEvaluator implements vscode.Disposable { const needsSpawn = replaceFailedWorker || !sameCluster || !!reason || this._relay?.epoch !== epoch; const initStartTime = Date.now(); + let learnedBinding: PlaygroundWorkerBinding | undefined; let initMsg: Extract; if (needsSpawn || !this._sessionInitMessage) { onProgress?.(l10n.t('Initializing…')); @@ -264,8 +265,7 @@ export class PlaygroundEvaluator implements vscode.Disposable { this._workerManager.killWorker(); } this.resetSession(); - const workerPin = - initMsg.authMechanism === AuthMethodId.MicrosoftEntraID ? (entraPin ?? pinned) : undefined; + const workerPin = initMsg.authMechanism === 'MicrosoftEntraID' ? (entraPin ?? pinned) : undefined; this._pinContext = workerPin && { clusterId, identity: workerPin }; this._sessionInitMessage = initMsg; this._workerFingerprint = expected; @@ -278,15 +278,17 @@ export class PlaygroundEvaluator implements vscode.Disposable { connectionString: originalUri, principal: identity, }); + learnedBinding = { fingerprint: this._workerFingerprint, entraIdentity: identity }; }); } else { initMsg = this._sessionInitMessage; } const relay = this._relay; + const isCurrentRelay = (): boolean => relay === this._relay && epoch === ClustersClient.getEpoch(clusterId); const assertCurrent = (): void => { this.assertConnectionAvailable(clusterId); - if (relay !== this._relay || epoch !== ClustersClient.getEpoch(clusterId)) { + if (!isCurrentRelay()) { throw new ConnectionUnavailableError('credentialsChanged'); } }; @@ -314,6 +316,17 @@ export class PlaygroundEvaluator implements vscode.Disposable { // The telemetry wrapper swallows cancellation even when rethrow is enabled. if (originalFailure) { this.recordWorkerFailure(clusterId, relay, originalFailure.error); + // Startup can fail after sign-in; keep the document pinned without replaying its query. + if ( + learnedBinding && + fingerprint === undefined && + !(originalFailure.error instanceof UserCancelledError) && + isCurrentRelay() && + !this._disposed && + !ClustersClient.getLatchReason(clusterId) + ) { + onFirstBinding?.(learnedBinding); + } throw originalFailure.error; } assertCurrent(); From 1e9fc144657ea4e6ec5e0fd6613169ac285799b3 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 26 Nov 2026 09:48:00 +0000 Subject: [PATCH 15/23] fix: follow playground worker bindings across Save As Addresses Copilot review comment 4704909945. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../playground/PlaygroundService.test.ts | 72 ++++++++++++++++--- .../playground/PlaygroundService.ts | 24 +++++-- 2 files changed, 80 insertions(+), 16 deletions(-) diff --git a/src/documentdb/playground/PlaygroundService.test.ts b/src/documentdb/playground/PlaygroundService.test.ts index d39446b90..b6c6de60d 100644 --- a/src/documentdb/playground/PlaygroundService.test.ts +++ b/src/documentdb/playground/PlaygroundService.test.ts @@ -25,6 +25,16 @@ describe('PlaygroundService', () => { const mockUri = { toString: () => 'untitled:playground-1.documentdb.js' } as vscode.Uri; + function getCloseDocHandler(): (doc: Partial) => void { + const calls = vi.mocked(vscode.workspace.onDidCloseTextDocument).mock.calls; + return calls[calls.length - 1][0]; + } + + function getOpenDocHandler(): (doc: Partial) => void { + const calls = vi.mocked(vscode.workspace.onDidOpenTextDocument).mock.calls; + return calls[calls.length - 1][0]; + } + beforeEach(() => { // Reset singleton between tests service = PlaygroundService.getInstance(); @@ -313,6 +323,16 @@ describe('PlaygroundService', () => { clusterDisplayName: 'MyCluster', databaseName: 'orders', }; + const learnedBinding = { + fingerprint: 'worker-fingerprint', + entraIdentity: { + kind: 'entra', + providerId: 'microsoft', + accountId: 'worker-account', + accountLabel: 'Worker Account', + tenantId: 'tenant', + }, + } as const; function getSaveDocHandler(): (doc: Partial) => void { const calls = (vscode.workspace.onDidSaveTextDocument as Mock).mock.calls; @@ -382,6 +402,48 @@ describe('PlaygroundService', () => { expect(service.isConnected(oldFile.uri as vscode.Uri)).toBe(false); }); + it('remembers the first worker binding at the new URI after Save As', () => { + hasCredentialsMock.mockReturnValue(true); + const content = 'db.orders.find({})'; + const source = makeFileDoc('file:///home/u/orders.documentdb.js', content); + const saved = makeFileDoc('file:///home/u/orders-copy.documentdb.js', content); + const sourceUri = source.uri as vscode.Uri; + const savedUri = saved.uri as vscode.Uri; + const original = service.setConnectionFromHost(sourceUri, connection); + expect(original.fingerprint).toBeUndefined(); + setOpenDocuments([source, saved]); + getSaveDocHandler()(saved); + getCloseDocHandler()(source); + expect(service.getConnection(savedUri)).toBe(original); + + const bound = service.captureWorkerBinding(sourceUri, original, learnedBinding); + + expect(bound).toEqual({ ...original, ...learnedBinding }); + expect(service.getConnection(savedUri)).toBe(bound); + getCloseDocHandler()(saved); + getOpenDocHandler()(saved); + getOpenDocHandler()(source); + expect(service.getConnection(savedUri)).toBe(bound); + expect(service.getConnection(sourceUri)).toBeUndefined(); + }); + + it('rejects a worker binding after re-picking the same unpinned target at the saved URI', () => { + const content = 'db.orders.find({})'; + const source = makeFileDoc('file:///home/u/orders.documentdb.js', content); + const saved = makeFileDoc('file:///home/u/orders-copy.documentdb.js', content); + const sourceUri = source.uri as vscode.Uri; + const savedUri = saved.uri as vscode.Uri; + const original = service.setConnectionFromHost(sourceUri, connection); + setOpenDocuments([source, saved]); + getSaveDocHandler()(saved); + const repicked = service.setConnectionFromHost(savedUri, original); + + expect(service.captureWorkerBinding(sourceUri, original, learnedBinding)).toBeUndefined(); + expect(repicked).not.toBe(original); + expect(service.getConnection(savedUri)).toBe(repicked); + expect(repicked.fingerprint).toBeUndefined(); + }); + it('is a no-op when saving a file that already has a connection (regular save)', () => { const content = 'db.orders.find({})'; const fileDoc = makeFileDoc('file:///home/u/orders.documentdb.documentdb.js', content); @@ -451,16 +513,6 @@ describe('PlaygroundService', () => { databaseName: 'orders', }; - function getCloseDocHandler(): (doc: Partial) => void { - const calls = (vscode.workspace.onDidCloseTextDocument as Mock).mock.calls; - return calls[calls.length - 1][0] as (doc: Partial) => void; - } - - function getOpenDocHandler(): (doc: Partial) => void { - const calls = (vscode.workspace.onDidOpenTextDocument as Mock).mock.calls; - return calls[calls.length - 1][0] as (doc: Partial) => void; - } - const reopenDoc: Partial = { uri: mockUri, languageId: 'documentdb-playground' }; beforeEach(() => { diff --git a/src/documentdb/playground/PlaygroundService.ts b/src/documentdb/playground/PlaygroundService.ts index a6a3e86cb..814123b4a 100644 --- a/src/documentdb/playground/PlaygroundService.ts +++ b/src/documentdb/playground/PlaygroundService.ts @@ -51,6 +51,9 @@ export class PlaygroundService implements vscode.Disposable { /** Per-document connections keyed by `uri.toString()`. */ private readonly _connections = new Map(); + /** Save As moves the original object, which an in-flight worker may still hold. */ + private readonly _transferredConnectionKeys = new WeakMap(); + /** * Last-known binding per document URI, kept in memory only (never persisted). * @@ -166,7 +169,8 @@ export class PlaygroundService implements vscode.Disposable { setConnectionFromHost(uri: vscode.Uri, connection: PlaygroundConnection): PlaygroundConnection { const key = uri.toString(); const isRepick = this._connections.has(key); - const bound = this.captureHostBinding(connection); + // A selection is a new binding even if it targets the same unpinned cluster and database. + const bound = this.captureHostBinding({ ...connection }); const activated = isRepick && bound.fingerprint !== undefined ? { ...bound, workerReplacement: { fingerprint: bound.fingerprint } } @@ -191,19 +195,26 @@ export class PlaygroundService implements vscode.Disposable { }; } - /** Capture a worker-learned binding only while the document still holds the originating connection. */ + /** Capture a worker-learned binding only while the originating connection is still current and unpinned. */ captureWorkerBinding( uri: vscode.Uri, expectedConnection: PlaygroundConnection, binding: PlaygroundWorkerBinding, ): PlaygroundConnection | undefined { - const key = uri.toString(); - const current = this._connections.get(key); - if (current !== expectedConnection) { + const originalKey = uri.toString(); + const key = + this._connections.get(originalKey) === expectedConnection + ? originalKey + : this._transferredConnectionKeys.get(expectedConnection); + if ( + key === undefined || + this._connections.get(key) !== expectedConnection || + expectedConnection.fingerprint !== undefined + ) { return undefined; } const bound = { - ...current, + ...expectedConnection, fingerprint: binding.fingerprint, entraIdentity: binding.entraIdentity, }; @@ -281,6 +292,7 @@ export class PlaygroundService implements vscode.Disposable { this._connections.delete(sourceKey); this._connections.set(fileKey, connection); + this._transferredConnectionKeys.set(connection, fileKey); // Move the remembered binding onto the saved file too, so a later in-session // reopen of that file can be restored silently. this._lastBindingByPath.delete(sourceKey); From 56b5143c8edc171e1f15cf12907b6552071de255 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 26 Nov 2026 09:49:57 +0000 Subject: [PATCH 16/23] fix: preserve destination telemetry across warm Playground runs Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../playground/executePlaygroundCode.test.ts | 23 +++++++++++++ .../playground/executePlaygroundCode.ts | 33 +------------------ .../playground/PlaygroundEvaluator.ts | 13 ++++++++ 3 files changed, 37 insertions(+), 32 deletions(-) diff --git a/src/commands/playground/executePlaygroundCode.test.ts b/src/commands/playground/executePlaygroundCode.test.ts index c57f2d54e..720d4ec75 100644 --- a/src/commands/playground/executePlaygroundCode.test.ts +++ b/src/commands/playground/executePlaygroundCode.test.ts @@ -48,6 +48,7 @@ vi.mock('../../documentdb/playground/PlaygroundEvaluator', () => ({ PlaygroundEvaluator: class { evaluate = evaluate; dispose = dispose; + sessionDomainProperties = { domainInfo_isAzure: 'true' }; }, })); @@ -146,6 +147,28 @@ describe('executePlaygroundCode', () => { } }); + it('keeps the worker destination properties on a warm run', async () => { + const failure = Object.assign(new Error('token unavailable'), { name: 'TokenCallbackError' }); + evaluate.mockRejectedValueOnce(failure).mockRejectedValueOnce(failure); + const progress = vi.spyOn(vscode.window, 'withProgress').mockImplementation((_options, task) => + Promise.resolve( + task({ report: vi.fn() }, { isCancellationRequested: false, onCancellationRequested: vi.fn() }), + ), + ); + try { + const uri = vscode.Uri.file('test.documentdb.js'); + await expect(executePlaygroundCode('db.stats()', 'runAll', uri)).rejects.toBe(failure); + await expect(executePlaygroundCode('db.stats()', 'runAll', uri)).rejects.toBe(failure); + expect(contexts.get('playground.execute')?.telemetry.properties).toMatchObject({ + isNewEvaluator: 'false', + domainInfo_isAzure: 'true', + }); + } finally { + progress.mockRestore(); + stopPlaygroundEvaluator('cluster'); + } + }); + it.each([false, true])('honors the sign-in epoch unless superseded (%s)', async (superseded) => { const identity: NonNullable = { kind: 'entra', diff --git a/src/commands/playground/executePlaygroundCode.ts b/src/commands/playground/executePlaygroundCode.ts index d1842883d..497cd58c8 100644 --- a/src/commands/playground/executePlaygroundCode.ts +++ b/src/commands/playground/executePlaygroundCode.ts @@ -12,7 +12,6 @@ import * as l10n from '@vscode/l10n'; import * as vscode from 'vscode'; import { ClustersClient } from '../../documentdb/ClustersClient'; import { ConnectionUnavailableError } from '../../documentdb/ConnectionUnavailableError'; -import { CredentialCache } from '../../documentdb/CredentialCache'; import { feedResultToSchemaStore } from '../../documentdb/feedResultToSchemaStore'; import { PlaygroundEvaluator } from '../../documentdb/playground/PlaygroundEvaluator'; import { PlaygroundService } from '../../documentdb/playground/PlaygroundService'; @@ -20,8 +19,6 @@ import { formatError, formatResult } from '../../documentdb/playground/resultFor import { type PlaygroundConnection } from '../../documentdb/playground/types'; import { getWorkerAuthReason, type WorkerAuthReason } from '../../documentdb/playground/workerTypes'; import { extractErrorCode } from '../../documentdb/shell/ShellOutputFormatter'; -import { getHostsFromConnectionString } from '../../documentdb/utils/connectionStringHelpers'; -import { addDomainInfoToProperties } from '../../documentdb/utils/getClusterMetadata'; import { ext } from '../../extensionVariables'; import { ErrorExplanationService } from '../../services/errorExplanationService'; import { recordSurveyActivity } from '../../services/survey/SurveyService'; @@ -179,13 +176,6 @@ export async function executePlaygroundCode( context.telemetry.measurements[`cmd_${category}`] = count; } - // Domain info — privacy-safe hashed host data for platform analytics - const domainProps: Record = {}; - if (isNewEvaluator) { - collectDomainTelemetry(boundConnection, domainProps); - } - Object.assign(context.telemetry.properties, domainProps); - // Link to server metadata via connectionCorrelationId try { const existingClient = ClustersClient.getExistingClient(boundConnection.clusterId); @@ -307,6 +297,7 @@ export async function executePlaygroundCode( // error, and errorMessage in telemetry throw error; } finally { + Object.assign(context.telemetry.properties, evaluator?.sessionDomainProperties); service.setExecuting(boundConnection.clusterId, false); } }, @@ -419,25 +410,3 @@ function offerPlaygroundRecovery( }); }); } - -// ─── Domain telemetry ──────────────────────────────────────────────────────── - -/** - * Collects domain info from the query playground connection's cached credentials. - * Reuses the same hashing logic as the connection metadata telemetry. - */ -function collectDomainTelemetry( - connection: PlaygroundConnection, - properties: Record, -): void { - try { - const credentials = CredentialCache.getCredentials(connection.clusterId); - if (!credentials?.connectionString) { - return; - } - const hosts = getHostsFromConnectionString(credentials.connectionString); - addDomainInfoToProperties(hosts, properties); - } catch { - // Domain info is best-effort — don't fail telemetry if parsing fails - } -} diff --git a/src/documentdb/playground/PlaygroundEvaluator.ts b/src/documentdb/playground/PlaygroundEvaluator.ts index 9c7613ace..f49b4fd87 100644 --- a/src/documentdb/playground/PlaygroundEvaluator.ts +++ b/src/documentdb/playground/PlaygroundEvaluator.ts @@ -22,6 +22,8 @@ import { ClustersClient } from '../ClustersClient'; import { computeConnectionFingerprint } from '../connectionFingerprint'; import { ConnectionUnavailableError } from '../ConnectionUnavailableError'; import { CredentialCache } from '../CredentialCache'; +import { getHostsFromConnectionString } from '../utils/connectionStringHelpers'; +import { addDomainInfoToProperties } from '../utils/getClusterMetadata'; import { resolveAllowInvalidCertificates } from '../utils/tlsException'; import { type ExecutionResult, type PlaygroundConnection, type PlaygroundWorkerBinding } from './types'; import { WorkerSessionManager } from './WorkerSessionManager'; @@ -98,6 +100,7 @@ export class PlaygroundEvaluator implements vscode.Disposable { /** Auth mechanism used for the current worker session (for telemetry). */ private _sessionAuthMethod: string | undefined; + private _sessionDomainProperties: Record | undefined; /** Telemetry accessors — read by the command layer for telemetry properties. */ get sessionId(): string | undefined { @@ -109,6 +112,9 @@ export class PlaygroundEvaluator implements vscode.Disposable { get sessionAuthMethod(): string | undefined { return this._sessionAuthMethod; } + get sessionDomainProperties(): Readonly> | undefined { + return this._sessionDomainProperties; + } /** Duration of the last worker init (spawn + auth), in ms. 0 if worker was already alive. */ private _lastInitDurationMs: number = 0; @@ -271,7 +277,13 @@ export class PlaygroundEvaluator implements vscode.Disposable { this._workerFingerprint = expected; this._sessionId = randomUUID(); this._sessionAuthMethod = initMsg.authMechanism; + this._sessionDomainProperties = {}; const originalUri = initMsg.connectionString; + try { + addDomainInfoToProperties(getHostsFromConnectionString(originalUri), this._sessionDomainProperties); + } catch { + meterSilentCatch('PlaygroundEvaluator_domainInfo'); + } this._relay = new WorkerTokenRelay(clusterId, initMsg, epoch, this._sessionId, workerPin, (identity) => { this._pinContext = { clusterId, identity }; this._workerFingerprint = computeConnectionFingerprint({ @@ -524,6 +536,7 @@ export class PlaygroundEvaluator implements vscode.Disposable { } this._sessionInitMessage = undefined; + this._sessionDomainProperties = undefined; this._relay = undefined; this._workerFingerprint = undefined; this._sessionId = undefined; From f9dbc4ee013f81aa73a4075125b0ced2b7c371a5 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 26 Nov 2026 09:51:12 +0000 Subject: [PATCH 17/23] fix: bind worker token relay to audience environment Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/documentdb/auth/WorkerTokenRelay.ts | 64 ++++++--- .../playground/WorkerSessionManager.test.ts | 135 ++++++++++++++++++ 2 files changed, 183 insertions(+), 16 deletions(-) diff --git a/src/documentdb/auth/WorkerTokenRelay.ts b/src/documentdb/auth/WorkerTokenRelay.ts index 12b1428c7..bc1d43f0a 100644 --- a/src/documentdb/auth/WorkerTokenRelay.ts +++ b/src/documentdb/auth/WorkerTokenRelay.ts @@ -28,7 +28,11 @@ import { TokenCallbackError, } from './entraErrors/entraCallbackErrors'; import { clearEntraTokenFailure, recordEntraTokenFailure } from './entraErrors/entraTokenFailures'; -import { getEntraSession, readEntraSignInEnvironment } from './entraSession'; +import { + getEntraSession, + readEntraSignInEnvironment, + type EntraSignInEnvironment, +} from './entraSession'; import { EntraDestinationRejectedError } from './oidcAllowedHosts'; export function sameEntraIdentity(a: VerifiedEntraIdentity, b: VerifiedEntraIdentity): boolean { @@ -51,6 +55,7 @@ export function createWorkerAuthError(reason: WorkerAuthReason, method?: AuthMet /** Host-only token relay for a single worker. The worker cannot select its own identity or destination. */ export class WorkerTokenRelay { private resource: ResolvedTokenResource | undefined; + private environment: EntraSignInEnvironment | undefined; private pending: Promise = Promise.resolve(); constructor( @@ -105,30 +110,54 @@ export class WorkerTokenRelay { } assertDestination(); const pin = this.pin; - const environment = managed ? undefined : readEntraSignInEnvironment(); - const assertEnvironment = (): string => { - const now = readEntraSignInEnvironment(); + const readEnvironment = (): EntraSignInEnvironment => { + try { + return readEntraSignInEnvironment(); + } catch { + throw new EntraSignInRequiredError('providerChanged'); + } + }; + const assertEnvironment = (expected: EntraSignInEnvironment): string => { + const now = readEnvironment(); if ( - !environment || (pin && (pin.providerId !== now.providerId || pin.tenantId !== tenantId)) || - environment.providerId !== now.providerId || - environment.cloudName !== now.cloudName || - environment.authority !== now.authority + expected.providerId !== now.providerId || + expected.cloudName !== now.cloudName || + expected.authority !== now.authority ) { throw new EntraSignInRequiredError('providerChanged'); } - return environment.providerId; + return expected.providerId; }; mode = managed ? 'managedIdentity' : pin ? 'silent' : 'interactive'; - const resolved = - this.resource ?? - (managed + let resolved = this.resource; + let environment = this.environment; + if (!resolved) { + const resolutionEnvironment = managed ? undefined : readEnvironment(); + if (resolutionEnvironment) { + assertEnvironment(resolutionEnvironment); + } + resolved = managed ? await resolveManagedIdentityTokenResource(connectionString) - : await resolveInteractiveTokenResource(connectionString)); + : await resolveInteractiveTokenResource(connectionString); + if (!canReply()) { + return; + } + if (resolutionEnvironment) { + assertEnvironment(resolutionEnvironment); + } + this.resource = resolved; + this.environment = resolutionEnvironment; + environment = resolutionEnvironment; + } else if (!managed) { + if (!environment) { + throw new EntraSignInRequiredError('providerChanged'); + } + assertEnvironment(environment); + } if (!canReply()) { return; } - this.resource = resolved; const { tokenResource: _resource, ...details } = resolved.details; traceAuthFlow('entraCloud.resolved', details, requestId, activeTrace()); let identity: VerifiedEntraIdentity | undefined; @@ -153,7 +182,10 @@ export class WorkerTokenRelay { ).accessToken; } else { assertDestination(); - const providerId = assertEnvironment(); + if (!environment) { + throw new EntraSignInRequiredError('providerChanged'); + } + const providerId = assertEnvironment(environment); const session = await withTokenAcquisitionTiming(timings, () => getEntraSession({ providerId, @@ -166,7 +198,7 @@ export class WorkerTokenRelay { if (!canReply()) { return; } - assertEnvironment(); + assertEnvironment(environment); if (!session && pin) { throw new EntraSignInRequiredError('noSession'); } diff --git a/src/documentdb/playground/WorkerSessionManager.test.ts b/src/documentdb/playground/WorkerSessionManager.test.ts index e4edd3a43..fc0297f9c 100644 --- a/src/documentdb/playground/WorkerSessionManager.test.ts +++ b/src/documentdb/playground/WorkerSessionManager.test.ts @@ -21,6 +21,7 @@ import { recordEntraTokenFailure, resetEntraTokenFailuresForTests, } from '../auth/entraErrors/entraTokenFailures'; +import * as entraSession from '../auth/entraSession'; import * as managedIdentityProvider from '../auth/managedIdentityTokenProvider'; import { EntraDestinationRejectedError } from '../auth/oidcAllowedHosts'; import { WorkerTokenRelay } from '../auth/WorkerTokenRelay'; @@ -755,6 +756,140 @@ describe('WorkerSessionManager', () => { }); }); + describe('worker token relay environment binding', () => { + const originalEnvironment = { + providerId: 'microsoft-sovereign-cloud', + cloudName: 'CustomCloud', + authority: 'https://authority.example.com/original/', + }; + const resolvedResource = { + resource: 'https://database.example.com', + scope: 'https://database.example.com/.default', + cloudCategory: 'custom', + reason: 'customLoginHost', + details: { + flow: 'interactive', + tokenResource: 'https://database.example.com', + }, + } as const; + + function createRelay(clusterId: string): WorkerTokenRelay { + return new WorkerTokenRelay( + clusterId, + { + type: 'init', + requestId: '', + connectionString: 'mongodb://cluster.mongocluster.cosmos.azure.com/', + clientOptions: {}, + databaseName: 'test', + authMechanism: 'MicrosoftEntraID', + }, + ClustersClient.getEpoch(clusterId), + 'relay-id', + undefined, + ); + } + + it.each([ + ['provider', (environment: typeof originalEnvironment) => ({ ...environment, providerId: 'changed' })], + ['cloud', (environment: typeof originalEnvironment) => ({ ...environment, cloudName: 'AzureCloud' })], + [ + 'authority', + (environment: typeof originalEnvironment) => ({ + ...environment, + authority: 'https://authority.example.com/changed/', + }), + ], + ] as const)('rejects later %s drift against the cached audience environment', async (_name, change) => { + let environment: typeof originalEnvironment = originalEnvironment; + const environmentSpy = vi + .spyOn(entraSession, 'readEntraSignInEnvironment') + .mockImplementation(() => environment); + const resolver = vi.spyOn(tokenResource, 'resolveInteractiveTokenResource').mockResolvedValue(resolvedResource); + const lookup = vi.spyOn(entraSession, 'getEntraSession').mockResolvedValue({ + id: 'session-id', + accessToken: 'access-token', + account: { id: 'account-id', label: 'Account' }, + scopes: [], + }); + const relay = createRelay(`relay-environment-${_name}`); + const responses: MainToWorkerMessage[] = []; + try { + await relay.relay( + { type: 'tokenRequest', requestId: 'first' }, + (response) => responses.push(response), + () => true, + ); + environment = change(environment); + await relay.relay( + { type: 'tokenRequest', requestId: 'second' }, + (response) => responses.push(response), + () => true, + ); + + expect(responses).toEqual([ + { type: 'tokenResponse', requestId: 'first', accessToken: 'access-token' }, + expect.objectContaining({ + type: 'tokenError', + requestId: 'second', + reason: 'signInRequired', + }), + ]); + expect(resolver).toHaveBeenCalledTimes(1); + expect(lookup).toHaveBeenCalledTimes(1); + } finally { + environmentSpy.mockRestore(); + resolver.mockRestore(); + lookup.mockRestore(); + } + }); + + it('fails closed when the cached audience environment cannot be read later', async () => { + let readable = true; + const environmentSpy = vi.spyOn(entraSession, 'readEntraSignInEnvironment').mockImplementation(() => { + if (!readable) { + throw new Error('private-configuration-cause'); + } + return originalEnvironment; + }); + const resolver = vi.spyOn(tokenResource, 'resolveInteractiveTokenResource').mockResolvedValue(resolvedResource); + const lookup = vi.spyOn(entraSession, 'getEntraSession').mockResolvedValue({ + id: 'session-id', + accessToken: 'access-token', + account: { id: 'account-id', label: 'Account' }, + scopes: [], + }); + const relay = createRelay('relay-unreadable-environment'); + const responses: MainToWorkerMessage[] = []; + try { + await relay.relay( + { type: 'tokenRequest', requestId: 'first' }, + (response) => responses.push(response), + () => true, + ); + readable = false; + await relay.relay( + { type: 'tokenRequest', requestId: 'second' }, + (response) => responses.push(response), + () => true, + ); + + expect(responses.at(-1)).toMatchObject({ + type: 'tokenError', + requestId: 'second', + reason: 'signInRequired', + }); + expect(resolver).toHaveBeenCalledTimes(1); + expect(lookup).toHaveBeenCalledTimes(1); + expect(JSON.stringify(responses)).not.toContain('private-configuration-cause'); + } finally { + environmentSpy.mockRestore(); + resolver.mockRestore(); + lookup.mockRestore(); + } + }); + }); + describe('startup tracking', () => { let trace: MockInstance; From a42fa23f8d8692400879bbff029eacb5dcb87250 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 26 Nov 2026 09:53:25 +0000 Subject: [PATCH 18/23] fix: validate worker environment after rejected lookup Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/documentdb/auth/WorkerTokenRelay.ts | 26 +++-- .../playground/WorkerSessionManager.test.ts | 105 ++++++++++++++++++ 2 files changed, 121 insertions(+), 10 deletions(-) diff --git a/src/documentdb/auth/WorkerTokenRelay.ts b/src/documentdb/auth/WorkerTokenRelay.ts index bc1d43f0a..77ff9af88 100644 --- a/src/documentdb/auth/WorkerTokenRelay.ts +++ b/src/documentdb/auth/WorkerTokenRelay.ts @@ -186,19 +186,25 @@ export class WorkerTokenRelay { throw new EntraSignInRequiredError('providerChanged'); } const providerId = assertEnvironment(environment); - const session = await withTokenAcquisitionTiming(timings, () => - getEntraSession({ - providerId, - resource: resolved.scope, - tenantId, - account: pin ? { id: pin.accountId, label: pin.accountLabel } : undefined, - mode: pin ? 'silent' : 'interactive', - }), - ); + let session: Awaited>; + try { + session = await withTokenAcquisitionTiming(timings, () => + getEntraSession({ + providerId, + resource: resolved.scope, + tenantId, + account: pin ? { id: pin.accountId, label: pin.accountLabel } : undefined, + mode: pin ? 'silent' : 'interactive', + }), + ); + } finally { + if (canReply()) { + assertEnvironment(environment); + } + } if (!canReply()) { return; } - assertEnvironment(environment); if (!session && pin) { throw new EntraSignInRequiredError('noSession'); } diff --git a/src/documentdb/playground/WorkerSessionManager.test.ts b/src/documentdb/playground/WorkerSessionManager.test.ts index fc0297f9c..f0197bd86 100644 --- a/src/documentdb/playground/WorkerSessionManager.test.ts +++ b/src/documentdb/playground/WorkerSessionManager.test.ts @@ -888,6 +888,111 @@ describe('WorkerSessionManager', () => { lookup.mockRestore(); } }); + + it('validates the environment when the Entra lookup rejects', async () => { + const clusterId = 'relay-rejected-lookup'; + let environment: typeof originalEnvironment = originalEnvironment; + const environmentSpy = vi + .spyOn(entraSession, 'readEntraSignInEnvironment') + .mockImplementation(() => environment); + const resolver = vi.spyOn(tokenResource, 'resolveInteractiveTokenResource').mockResolvedValue(resolvedResource); + const lookup = vi.spyOn(entraSession, 'getEntraSession').mockImplementation(async () => { + environment = { + ...environment, + authority: 'https://authority.example.com/changed/', + }; + throw new Error('private-lookup-cause'); + }); + const relay = createRelay(clusterId); + const responses: MainToWorkerMessage[] = []; + const startupProperties: Record = {}; + recordEntraTokenFailure(clusterId, { cloudCategory: 'custom', authMethod: 'interactive' }); + const priorFailure = getRecentEntraTokenFailure(clusterId); + try { + await relay.relay( + { type: 'tokenRequest', requestId: 'rejected' }, + (response) => responses.push(response), + () => true, + undefined, + { startupProperties }, + ); + + expect(responses).toEqual([ + expect.objectContaining({ + type: 'tokenError', + requestId: 'rejected', + reason: 'signInRequired', + }), + ]); + expect(getRecentEntraTokenFailure(clusterId)).toBe(priorFailure); + expect(startupProperties.entraFailureKind).not.toBe('tokenAcquisitionFailed'); + expect(JSON.stringify(responses)).not.toContain('private-lookup-cause'); + } finally { + resetEntraTokenFailuresForTests(); + environmentSpy.mockRestore(); + resolver.mockRestore(); + lookup.mockRestore(); + } + }); + + it.each(['oldWorker', 'epoch'] as const)( + 'does not validate or diagnose a rejected lookup from a stale %s', + async (staleBy) => { + const clusterId = `relay-stale-${staleBy}`; + let current = true; + const environmentSpy = vi + .spyOn(entraSession, 'readEntraSignInEnvironment') + .mockReturnValue(originalEnvironment); + const resolver = vi + .spyOn(tokenResource, 'resolveInteractiveTokenResource') + .mockResolvedValue(resolvedResource); + let signalStarted!: () => void; + const started = new Promise((resolve) => { + signalStarted = resolve; + }); + let rejectLookup!: () => void; + const lookup = vi.spyOn(entraSession, 'getEntraSession').mockImplementation( + async () => + await new Promise((_, reject) => { + rejectLookup = () => reject(new Error('obsolete lookup failure')); + signalStarted(); + }), + ); + const relay = createRelay(clusterId); + const responses: MainToWorkerMessage[] = []; + recordEntraTokenFailure(clusterId, { cloudCategory: 'china', authMethod: 'interactive' }); + const priorFailure = getRecentEntraTokenFailure(clusterId); + try { + const relaying = relay.relay( + { type: 'tokenRequest', requestId: 'stale' }, + (response) => responses.push(response), + () => current, + ); + const outcome = + staleBy === 'epoch' + ? expect(relaying).rejects.toBeInstanceOf(UserCancelledError) + : relaying; + await started; + const readsBeforeRejection = environmentSpy.mock.calls.length; + if (staleBy === 'oldWorker') { + current = false; + } else { + ClustersClient.invalidate(clusterId); + } + rejectLookup(); + await outcome; + + expect(responses).toEqual([]); + expect(environmentSpy).toHaveBeenCalledTimes(readsBeforeRejection); + expect(getRecentEntraTokenFailure(clusterId)).toBe(priorFailure); + } finally { + resetEntraTokenFailuresForTests(); + environmentSpy.mockRestore(); + resolver.mockRestore(); + lookup.mockRestore(); + } + }, + ); }); describe('startup tracking', () => { From 1a481060e848ed7d73a1db2ce266bf5b7ddeb7bf Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 26 Nov 2026 09:54:03 +0000 Subject: [PATCH 19/23] chore: fix worker token relay lint Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/documentdb/auth/WorkerTokenRelay.ts | 7 +++---- src/documentdb/playground/WorkerSessionManager.test.ts | 2 +- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/documentdb/auth/WorkerTokenRelay.ts b/src/documentdb/auth/WorkerTokenRelay.ts index 77ff9af88..b098b7136 100644 --- a/src/documentdb/auth/WorkerTokenRelay.ts +++ b/src/documentdb/auth/WorkerTokenRelay.ts @@ -90,7 +90,7 @@ export class WorkerTokenRelay { const activeTrace = (): AuthTraceContext | undefined => isCurrentWorker() && isCurrentEpoch() ? trace : undefined; const { connectionString, authMechanism, tenantId, managedIdentityClientId } = this.init; - const managed = authMechanism === AuthMethodId.ManagedIdentity; + const managed = authMechanism === 'ManagedIdentity'; const assertDestination = (): void => { const decision = evaluateEntraDestinationFromSettings(connectionString); traceEntraDestination(decision, requestId, activeTrace()); @@ -105,7 +105,7 @@ export class WorkerTokenRelay { let mode: 'managedIdentity' | 'silent' | 'interactive' | undefined; let acquiring = false; try { - if (!managed && authMechanism !== AuthMethodId.MicrosoftEntraID) { + if (!managed && authMechanism !== 'MicrosoftEntraID') { throw new Error('Token request from a non-OIDC worker'); } assertDestination(); @@ -158,8 +158,7 @@ export class WorkerTokenRelay { if (!canReply()) { return; } - const { tokenResource: _resource, ...details } = resolved.details; - traceAuthFlow('entraCloud.resolved', details, requestId, activeTrace()); + traceAuthFlow('entraCloud.resolved', resolved.details, requestId, activeTrace()); let identity: VerifiedEntraIdentity | undefined; let accessToken: string; acquiring = true; diff --git a/src/documentdb/playground/WorkerSessionManager.test.ts b/src/documentdb/playground/WorkerSessionManager.test.ts index f0197bd86..5fef0c712 100644 --- a/src/documentdb/playground/WorkerSessionManager.test.ts +++ b/src/documentdb/playground/WorkerSessionManager.test.ts @@ -914,7 +914,7 @@ describe('WorkerSessionManager', () => { (response) => responses.push(response), () => true, undefined, - { startupProperties }, + { startupCorrelationId: 'relay-startup', surface: 'playground', startupProperties }, ); expect(responses).toEqual([ From de06cca6c26ccc129a45777bb2906a0139538de2 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 26 Nov 2026 11:16:46 +0000 Subject: [PATCH 20/23] test: verify sovereign worker recovery fails closed Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../auth/sovereignAuth.integration.test.ts | 108 ++++++++++++------ 1 file changed, 71 insertions(+), 37 deletions(-) diff --git a/src/documentdb/auth/sovereignAuth.integration.test.ts b/src/documentdb/auth/sovereignAuth.integration.test.ts index 185d48f3f..3e3405328 100644 --- a/src/documentdb/auth/sovereignAuth.integration.test.ts +++ b/src/documentdb/auth/sovereignAuth.integration.test.ts @@ -3,7 +3,6 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import type * as azureAuth from '@microsoft/vscode-azext-azureauth'; import { type callWithTelemetryAndErrorHandling, type ITelemetryContext } from '@microsoft/vscode-azext-utils'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import * as vscode from 'vscode'; @@ -21,7 +20,6 @@ interface TokenWorker { } const workers = vi.hoisted((): TokenWorker[] => []); -const getSession = vi.hoisted(() => vi.fn()); const getHandlerSession = vi.hoisted(() => vi.fn()); const getManagedToken = vi.hoisted(() => vi.fn()); const postedMessages = vi.hoisted((): MainToWorkerMessage[] => []); @@ -34,11 +32,6 @@ vi.mock('../../extensionVariables', () => ({ }, })); -vi.mock('@microsoft/vscode-azext-azureauth', async (importOriginal) => ({ - ...(await importOriginal()), - getSessionFromVSCode: getSession, -})); - vi.mock('vscode', async (importOriginal) => ({ ...(await importOriginal()), authentication: { getSession: getHandlerSession }, @@ -183,7 +176,6 @@ describe('sovereign authentication with real audience resolvers', () => { events.length = 0; selectedCloud = 'USGovernment'; resetEntraTokenFailuresForTests(); - getSession.mockResolvedValue({ accessToken: 'private-token', account: { label: 'private-account' } }); getHandlerSession.mockResolvedValue({ accessToken: 'private-token', account: { id: 'account-id', label: 'private-account' }, @@ -256,7 +248,6 @@ describe('sovereign authentication with real audience resolvers', () => { undefined, ); expect(getHandlerSession).not.toHaveBeenCalled(); - expect(getSession).not.toHaveBeenCalled(); }, ); @@ -307,8 +298,15 @@ describe('sovereign authentication with real audience resolvers', () => { requestId: 'token-request', accessToken: 'private-token', }); - const provider = authMethod === AuthMethodId.ManagedIdentity ? getManagedToken : getSession; - expect(provider.mock.calls[0]?.[0]).toEqual([clouds[0].scope]); + if (authMethod === AuthMethodId.ManagedIdentity) { + expect(getManagedToken.mock.calls[0]?.[0]).toEqual([clouds[0].scope]); + } else { + expect(getHandlerSession).toHaveBeenCalledExactlyOnceWith( + 'microsoft-sovereign-cloud', + [clouds[0].scope, 'VSCODE_TENANT:private-tenant'], + { createIfNone: true }, + ); + } const startup = events.find((event) => event.eventName === 'worker.startup'); expect(startup?.telemetry.properties).toMatchObject({ surface, @@ -329,7 +327,20 @@ describe('sovereign authentication with real audience resolvers', () => { describe.each(workerSessions)('%s %s worker lifetime', (surface, authMethod) => { let manager: ShellSessionManager | PlaygroundEvaluator; const connection = { clusterId, clusterDisplayName: 'Test cluster', databaseName: 'test' }; - const provider = authMethod === AuthMethodId.ManagedIdentity ? getManagedToken : getSession; + const managed = authMethod === AuthMethodId.ManagedIdentity; + const provider = managed ? getManagedToken : getHandlerSession; + + function requestedScopes(): unknown[] { + return provider.mock.calls.map((args) => (managed ? args[0] : args[1])); + } + + function scopedTo(scope: string): string[] { + return managed ? [scope] : [scope, 'VSCODE_TENANT:private-tenant']; + } + + function newSurface(): ShellSessionManager | PlaygroundEvaluator { + return surface === 'shell' ? new ShellSessionManager(connection) : new PlaygroundEvaluator(); + } function storeCredentials(suffix: string): void { const stored = credentials(authMethod, suffix); @@ -363,7 +374,7 @@ describe('sovereign authentication with real audience resolvers', () => { beforeEach(() => { storeCredentials('us'); - manager = surface === 'shell' ? new ShellSessionManager(connection) : new PlaygroundEvaluator(); + manager = newSurface(); }); afterEach(() => manager.dispose()); @@ -379,12 +390,18 @@ describe('sovereign authentication with real audience resolvers', () => { requestId: 'refresh-request', accessToken: 'private-token', }); - expect(provider.mock.calls.map((call) => call[0])).toEqual([[clouds[0].scope], [clouds[0].scope]]); + expect(requestedScopes()).toEqual([scopedTo(clouds[0].scope), scopedTo(clouds[0].scope)]); + if (!managed) { + expect(getHandlerSession.mock.calls[1]?.[2]).toEqual({ + silent: true, + account: { id: 'account-id', label: 'private-account' }, + }); + } }); - it('keeps the first audience after cloud configuration changes', async () => { + it('retains the audience and refuses Entra renewal after a cloud change', async () => { await initializeSession(); - if (authMethod === AuthMethodId.ManagedIdentity) { + if (managed) { customEndpoint = clouds[1].scope.replace('/.default', ''); } else { selectedCloud = 'ChinaCloud'; @@ -396,12 +413,23 @@ describe('sovereign authentication with real audience resolvers', () => { await refreshToken(workers[0], 'refresh-request'); expect(workers).toHaveLength(1); - expect(postedMessages).toContainEqual({ - type: 'tokenResponse', - requestId: 'refresh-request', - accessToken: 'private-token', - }); - expect(provider.mock.calls.map((call) => call[0])).toEqual([[clouds[0].scope], [clouds[0].scope]]); + if (managed) { + expect(postedMessages).toContainEqual({ + type: 'tokenResponse', + requestId: 'refresh-request', + accessToken: 'private-token', + }); + expect(requestedScopes()).toEqual([scopedTo(clouds[0].scope), scopedTo(clouds[0].scope)]); + } else { + expect(postedMessages).toContainEqual( + expect.objectContaining({ + type: 'tokenError', + requestId: 'refresh-request', + reason: 'signInRequired', + }), + ); + expect(requestedScopes()).toEqual([scopedTo(clouds[0].scope)]); + } }); it('retries audience resolution after a resolution failure', async () => { @@ -415,13 +443,13 @@ describe('sovereign authentication with real audience resolvers', () => { await refreshToken(workers[0], 'failed-resolution'); - expect(postedMessages).toContainEqual({ - type: 'tokenError', - requestId: 'failed-resolution', - error: expect.stringContaining( - authMethod === AuthMethodId.ManagedIdentity ? 'HTTPS' : 'sign-in is set to', - ), - }); + expect(postedMessages).toContainEqual( + expect.objectContaining({ + type: 'tokenError', + requestId: 'failed-resolution', + reason: 'refreshFailed', + }), + ); expect(provider).not.toHaveBeenCalled(); expect(getRecentEntraTokenFailure(clusterId)).toBeUndefined(); @@ -434,15 +462,20 @@ describe('sovereign authentication with real audience resolvers', () => { requestId: 'retry-resolution', accessToken: 'private-token', }); - expect(provider.mock.calls[0]?.[0]).toEqual([clouds[0].scope]); + expect(requestedScopes()).toEqual([scopedTo(clouds[0].scope)]); }); - it('replaces the captured connection and audience when a new worker starts', async () => { + it('requires a new surface or binding to use a changed destination', async () => { await initializeSession(); manager.killWorker(); storeCredentials('cn'); selectedCloud = 'ChinaCloud'; + if (manager instanceof ShellSessionManager) { + await expect(initializeSession()).rejects.toMatchObject({ reason: 'credentialsChanged' }); + } + manager.dispose(); + manager = newSurface(); await initializeSession(); CredentialCache.deleteCredentials(clusterId); await refreshToken(workers[1], 'replacement-refresh'); @@ -453,10 +486,10 @@ describe('sovereign authentication with real audience resolvers', () => { requestId: 'replacement-refresh', accessToken: 'private-token', }); - expect(provider.mock.calls.map((call) => call[0])).toEqual([ - [clouds[0].scope], - [clouds[1].scope], - [clouds[1].scope], + expect(requestedScopes()).toEqual([ + scopedTo(clouds[0].scope), + scopedTo(clouds[1].scope), + scopedTo(clouds[1].scope), ]); }); @@ -523,9 +556,10 @@ describe('sovereign authentication with real audience resolvers', () => { await new Promise((resolve, reject) => { // Replace the worker before the old resolver's await continuation runs. queueMicrotask(() => { - manager.killWorker(); + manager.dispose(); storeCredentials('cn'); selectedCloud = 'ChinaCloud'; + manager = newSurface(); void initializeSession().then(resolve, reject); }); }); @@ -534,7 +568,7 @@ describe('sovereign authentication with real audience resolvers', () => { await refreshToken(workers[1], 'replacement-refresh'); expect(workers).toHaveLength(2); - expect(provider.mock.calls.at(-1)?.[0]).toEqual([clouds[1].scope]); + expect(requestedScopes().at(-1)).toEqual(scopedTo(clouds[1].scope)); expect(postedMessages).not.toContainEqual(expect.objectContaining({ requestId: 'late-resolution' })); }); }); From 8a70988ce929852a5398c807217dbf1e1882f93a Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 26 Nov 2026 11:16:46 +0000 Subject: [PATCH 21/23] docs: record the PR6a Copilot review dispositions Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../01-pr6a-worker-token-relays-review.md | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr6a-worker-token-relays-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr6a-worker-token-relays-review.md index 5c4c3fad1..83dc75ed2 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr6a-worker-token-relays-review.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr6a-worker-token-relays-review.md @@ -101,3 +101,36 @@ Shell worker to restart. Case 1 passed on `f5b79a3e9`: `npm run build` and 534 focused tests across 18 suites. Case 2 is deferred until formal handoff. The packaged live checks remain at OP-6. + +## Copilot review follow-up + +The advisor confirmed that a worker-only account pin cannot complete host recovery. +[`27410085f`](https://github.com/microsoft/vscode-documentdb/commit/27410085f) requires a +matching host-verified pin before offering **Sign in again**. Otherwise, the existing +surface guidance points to the tree; no worker-learned identity is promoted to a host pin. + +- A Playground document retains the account learned before a later startup failure + ([`a5ce99b97`](https://github.com/microsoft/vscode-documentdb/commit/a5ce99b97)). +- Late binding capture follows the same Playground connection through Save As but not + through an explicit re-pick ([`1e9fc1446`](https://github.com/microsoft/vscode-documentdb/commit/1e9fc1446)). +- Warm Playground runs retain the worker's destination metadata without reading cached + credentials ([`56b5143c8`](https://github.com/microsoft/vscode-documentdb/commit/56b5143c8)). +- The notification action records its own Playground sign-in outcome rather than writing + to the completed Run event ([`50cb05dc3`](https://github.com/microsoft/vscode-documentdb/commit/50cb05dc3)). +- A worker keeps its token audience and sign-in environment together and refuses cloud + or authority changes ([`f9dbc4ee0`](https://github.com/microsoft/vscode-documentdb/commit/f9dbc4ee0)). + The environment check also runs when a current token lookup rejects + ([`a42fa23f8`](https://github.com/microsoft/vscode-documentdb/commit/a42fa23f8)). + +The [configuration-guidance finding](https://github.com/microsoft/vscode-documentdb/pull/1133#discussion_r4704910161) +is not being changed in this PR. Some cloud or managed identity configuration errors +still receive the generic worker retry guidance. Keeping the bounded worker failure +contract avoids expanding error transport or adding a second guidance path just for these +failures. The tree connection and **Diagnose Connection** remain available for configuration +troubleshooting. + +The operator approved the sovereign-auth integration expectations after the full test run: +a warm Entra worker keeps the original token audience but refuses renewal if the configured +provider, cloud or authority changes. A different destination requires a new Shell or an +explicit Playground re-pick. Same-identity respawn and managed identity's existing audience +snapshot are unchanged. From 6ab3abdd3daf5e04d05b86b7ad5d4076eb7ae81f Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 26 Nov 2026 11:16:47 +0000 Subject: [PATCH 22/23] style: format the PR6a review fixes Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../playground/executePlaygroundCode.test.ts | 19 ++++++++++--------- src/documentdb/auth/WorkerTokenRelay.ts | 6 +----- .../playground/PlaygroundEvaluator.test.ts | 2 +- .../playground/WorkerSessionManager.test.ts | 16 ++++++++++------ 4 files changed, 22 insertions(+), 21 deletions(-) diff --git a/src/commands/playground/executePlaygroundCode.test.ts b/src/commands/playground/executePlaygroundCode.test.ts index 720d4ec75..2a61da142 100644 --- a/src/commands/playground/executePlaygroundCode.test.ts +++ b/src/commands/playground/executePlaygroundCode.test.ts @@ -9,8 +9,8 @@ import * as vscode from 'vscode'; import { type PlaygroundConnection } from '../../documentdb/playground/types'; import { executePlaygroundCode, stopPlaygroundEvaluator } from './executePlaygroundCode'; -const { evaluate, dispose, setExecuting, showResult, getConnection, getEpoch, canRecover, recover, contexts } = vi.hoisted( - () => ({ +const { evaluate, dispose, setExecuting, showResult, getConnection, getEpoch, canRecover, recover, contexts } = + vi.hoisted(() => ({ evaluate: vi.fn(), dispose: vi.fn(), setExecuting: vi.fn(), @@ -20,8 +20,7 @@ const { evaluate, dispose, setExecuting, showResult, getConnection, getEpoch, ca canRecover: vi.fn(), recover: vi.fn(), contexts: new Map(), - }), -); + })); vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ ...(await importOriginal<{ UserCancelledError: typeof UserCancelledError }>()), @@ -150,11 +149,13 @@ describe('executePlaygroundCode', () => { it('keeps the worker destination properties on a warm run', async () => { const failure = Object.assign(new Error('token unavailable'), { name: 'TokenCallbackError' }); evaluate.mockRejectedValueOnce(failure).mockRejectedValueOnce(failure); - const progress = vi.spyOn(vscode.window, 'withProgress').mockImplementation((_options, task) => - Promise.resolve( - task({ report: vi.fn() }, { isCancellationRequested: false, onCancellationRequested: vi.fn() }), - ), - ); + const progress = vi + .spyOn(vscode.window, 'withProgress') + .mockImplementation((_options, task) => + Promise.resolve( + task({ report: vi.fn() }, { isCancellationRequested: false, onCancellationRequested: vi.fn() }), + ), + ); try { const uri = vscode.Uri.file('test.documentdb.js'); await expect(executePlaygroundCode('db.stats()', 'runAll', uri)).rejects.toBe(failure); diff --git a/src/documentdb/auth/WorkerTokenRelay.ts b/src/documentdb/auth/WorkerTokenRelay.ts index b098b7136..42f8e32be 100644 --- a/src/documentdb/auth/WorkerTokenRelay.ts +++ b/src/documentdb/auth/WorkerTokenRelay.ts @@ -28,11 +28,7 @@ import { TokenCallbackError, } from './entraErrors/entraCallbackErrors'; import { clearEntraTokenFailure, recordEntraTokenFailure } from './entraErrors/entraTokenFailures'; -import { - getEntraSession, - readEntraSignInEnvironment, - type EntraSignInEnvironment, -} from './entraSession'; +import { getEntraSession, readEntraSignInEnvironment, type EntraSignInEnvironment } from './entraSession'; import { EntraDestinationRejectedError } from './oidcAllowedHosts'; export function sameEntraIdentity(a: VerifiedEntraIdentity, b: VerifiedEntraIdentity): boolean { diff --git a/src/documentdb/playground/PlaygroundEvaluator.test.ts b/src/documentdb/playground/PlaygroundEvaluator.test.ts index 1ae512096..ca56a3536 100644 --- a/src/documentdb/playground/PlaygroundEvaluator.test.ts +++ b/src/documentdb/playground/PlaygroundEvaluator.test.ts @@ -7,9 +7,9 @@ import type * as azureAuth from '@microsoft/vscode-azext-azureauth'; import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest'; import { + UserCancelledError, type callWithTelemetryAndErrorHandling, type IActionContext, - UserCancelledError, } from '@microsoft/vscode-azext-utils'; import * as vscode from 'vscode'; import { ext } from '../../extensionVariables'; diff --git a/src/documentdb/playground/WorkerSessionManager.test.ts b/src/documentdb/playground/WorkerSessionManager.test.ts index 5fef0c712..537b236af 100644 --- a/src/documentdb/playground/WorkerSessionManager.test.ts +++ b/src/documentdb/playground/WorkerSessionManager.test.ts @@ -805,7 +805,9 @@ describe('WorkerSessionManager', () => { const environmentSpy = vi .spyOn(entraSession, 'readEntraSignInEnvironment') .mockImplementation(() => environment); - const resolver = vi.spyOn(tokenResource, 'resolveInteractiveTokenResource').mockResolvedValue(resolvedResource); + const resolver = vi + .spyOn(tokenResource, 'resolveInteractiveTokenResource') + .mockResolvedValue(resolvedResource); const lookup = vi.spyOn(entraSession, 'getEntraSession').mockResolvedValue({ id: 'session-id', accessToken: 'access-token', @@ -852,7 +854,9 @@ describe('WorkerSessionManager', () => { } return originalEnvironment; }); - const resolver = vi.spyOn(tokenResource, 'resolveInteractiveTokenResource').mockResolvedValue(resolvedResource); + const resolver = vi + .spyOn(tokenResource, 'resolveInteractiveTokenResource') + .mockResolvedValue(resolvedResource); const lookup = vi.spyOn(entraSession, 'getEntraSession').mockResolvedValue({ id: 'session-id', accessToken: 'access-token', @@ -895,7 +899,9 @@ describe('WorkerSessionManager', () => { const environmentSpy = vi .spyOn(entraSession, 'readEntraSignInEnvironment') .mockImplementation(() => environment); - const resolver = vi.spyOn(tokenResource, 'resolveInteractiveTokenResource').mockResolvedValue(resolvedResource); + const resolver = vi + .spyOn(tokenResource, 'resolveInteractiveTokenResource') + .mockResolvedValue(resolvedResource); const lookup = vi.spyOn(entraSession, 'getEntraSession').mockImplementation(async () => { environment = { ...environment, @@ -969,9 +975,7 @@ describe('WorkerSessionManager', () => { () => current, ); const outcome = - staleBy === 'epoch' - ? expect(relaying).rejects.toBeInstanceOf(UserCancelledError) - : relaying; + staleBy === 'epoch' ? expect(relaying).rejects.toBeInstanceOf(UserCancelledError) : relaying; await started; const readsBeforeRejection = environmentSpy.mock.calls.length; if (staleBy === 'oldWorker') { From 8e86157cd08610cbe68045824fe30adff9d9f1ec Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 26 Nov 2026 11:20:35 +0000 Subject: [PATCH 23/23] docs: record completed PR6a handoff checks Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iterations/01-pr6a-worker-token-relays-review.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr6a-worker-token-relays-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr6a-worker-token-relays-review.md index 83dc75ed2..4c3abab86 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr6a-worker-token-relays-review.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr6a-worker-token-relays-review.md @@ -100,7 +100,7 @@ Shell worker to restart. ## Verification after the fixes Case 1 passed on `f5b79a3e9`: `npm run build` and 534 focused tests across 18 suites. -Case 2 is deferred until formal handoff. The packaged live checks remain at OP-6. +The packaged live checks remain at OP-6. ## Copilot review follow-up @@ -134,3 +134,7 @@ a warm Entra worker keeps the original token audience but refuses renewal if the provider, cloud or authority changes. A different destination requires a new Shell or an explicit Playground re-pick. Same-identity respawn and managed identity's existing audience snapshot are unchanged. + +**Case 2 handoff:** Localization, formatting, lint, build, strict workspace test +type-checking, 9,959 tests across 444 suites (one skipped), and VSIX packaging passed. +The VSIX was built for verification, not published as a new operator candidate.