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..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 @@ -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 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 new file mode 100644 index 000000000..4c3abab86 --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr6a-worker-token-relays-review.md @@ -0,0 +1,140 @@ +# 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:** 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 +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:** 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 +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:** 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 +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:** 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) +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. + +## Verification after the fixes + +Case 1 passed on `f5b79a3e9`: `npm run build` and 534 focused tests across 18 suites. +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. + +**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. 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/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..2a61da142 100644 --- a/src/commands/playground/executePlaygroundCode.test.ts +++ b/src/commands/playground/executePlaygroundCode.test.ts @@ -4,40 +4,57 @@ *--------------------------------------------------------------------------------------------*/ 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 { type PlaygroundConnection } from '../../documentdb/playground/types'; import { executePlaygroundCode, stopPlaygroundEvaluator } from './executePlaygroundCode'; -const { evaluate, dispose, setExecuting, showResult } = vi.hoisted(() => ({ - evaluate: vi.fn(), - dispose: vi.fn(), - setExecuting: vi.fn(), - showResult: vi.fn(), -})); +const { evaluate, dispose, setExecuting, showResult, getConnection, getEpoch, canRecover, recover, contexts } = + 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(), + 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', () => ({ - 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', () => ({ PlaygroundEvaluator: class { evaluate = evaluate; dispose = dispose; + sessionDomainProperties = { domainInfo_isAzure: 'true' }; }, })); vi.mock('../../documentdb/playground/PlaygroundService', () => ({ PlaygroundService: { getInstance: () => ({ - getConnection: () => ({ clusterId: 'cluster', clusterDisplayName: 'Cluster', databaseName: 'test' }), + getConnection, isExecuting: () => false, setExecuting, }), @@ -49,6 +66,14 @@ vi.mock('../../extensionVariables', () => ({ })); describe('executePlaygroundCode', () => { + beforeEach(() => { + vi.clearAllMocks(); + contexts.clear(); + 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 () => { let stopEvaluation: (error: Error) => void = () => {}; evaluate.mockImplementation( @@ -83,4 +108,114 @@ 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'); + } + }); + + 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', + 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); + 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 { + progress.mockRestore(); + warning.mockRestore(); + stopPlaygroundEvaluator('cluster'); + } + }); }); diff --git a/src/commands/playground/executePlaygroundCode.ts b/src/commands/playground/executePlaygroundCode.ts index a95eb661c..497cd58c8 100644 --- a/src/commands/playground/executePlaygroundCode.ts +++ b/src/commands/playground/executePlaygroundCode.ts @@ -11,19 +11,19 @@ import { import * as l10n from '@vscode/l10n'; import * as vscode from 'vscode'; import { ClustersClient } from '../../documentdb/ClustersClient'; -import { CredentialCache } from '../../documentdb/CredentialCache'; +import { ConnectionUnavailableError } from '../../documentdb/ConnectionUnavailableError'; 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'; 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 +121,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 +140,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) @@ -175,14 +176,9 @@ export async function executePlaygroundCode( context.telemetry.measurements[`cmd_${category}`] = count; } - // Domain info — privacy-safe hashed host data for platform analytics - const domainProps: Record = {}; - collectDomainTelemetry(connection, 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 +210,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 +233,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 +271,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(sourceUri, boundConnection, recovery); + throw error; + } + const explanation = await ErrorExplanationService.explain({ - clusterId: connection.clusterId, + clusterId: boundConnection.clusterId, error, }); @@ -286,31 +297,116 @@ export async function executePlaygroundCode( // error, and errorMessage in telemetry throw error; } finally { - service.setExecuting(connection.clusterId, false); + Object.assign(context.telemetry.properties, evaluator?.sessionDomainProperties); + service.setExecuting(boundConnection.clusterId, false); } }, ); }); } -// ─── Domain telemetry ──────────────────────────────────────────────────────── +interface PlaygroundRecovery { + readonly message: string; + readonly authReason?: WorkerAuthReason; +} -/** - * Collects domain info from the query playground connection's cached credentials. - * Reuses the same hashing logic as the connection metadata telemetry. - */ -function collectDomainTelemetry( +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( + documentUri: vscode.Uri, connection: PlaygroundConnection, - properties: Record, + recovery: PlaygroundRecovery, ): void { - try { - const credentials = CredentialCache.getCredentials(connection.clusterId); - if (!credentials?.connectionString) { + if ( + recovery.authReason !== 'signInRequired' || + !connection.entraIdentity || + !canSignInAgainForWorker(connection.clusterId, connection.entraIdentity) + ) { + 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 || ClustersClient.getEpoch(clusterId) !== epoch || !stillOwnsAction()) { return; } - const hosts = getHostsFromConnectionString(credentials.connectionString); - addDomainInfoToProperties(hosts, properties); - } catch { - // Domain info is best-effort — don't fail telemetry if parsing fails - } + 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; + } + }); + }); } 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..9a179d04d 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,27 @@ 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('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); + 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 ca454fd94..4eba12306 100644 --- a/src/commands/signInAgain/signInAgain.ts +++ b/src/commands/signInAgain/signInAgain.ts @@ -5,6 +5,7 @@ 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, @@ -12,6 +13,7 @@ import { } from '../../documentdb/auth/entraErrors/entraCallbackErrors'; import { getEntraSession } from '../../documentdb/auth/entraSession'; 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'; @@ -19,6 +21,23 @@ 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?.kind === 'entra' && + sameEntraIdentity(hostIdentity, expectedIdentity) + ); +} + function isSignInDismissal(error: unknown): boolean { return ( error instanceof UserCancelledError || @@ -33,6 +52,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 +87,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 +101,22 @@ 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?.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 +134,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 +148,15 @@ 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 +164,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 +173,11 @@ 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 +187,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/ClustersClient.test.ts b/src/documentdb/ClustersClient.test.ts index 511803848..ac9f4e58d 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -298,12 +298,44 @@ 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..42f8e32be --- /dev/null +++ b/src/documentdb/auth/WorkerTokenRelay.ts @@ -0,0 +1,277 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * 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 { + 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, type EntraSignInEnvironment } 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 environment: EntraSignInEnvironment | 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, + epoch = this.epoch, + ): Promise { + const isCurrentEpoch = (): boolean => + !ClustersClient.getLatchReason(this.clusterId) && ClustersClient.getEpoch(this.clusterId) === epoch; + 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 === 'ManagedIdentity'; + const assertDestination = (): void => { + const decision = evaluateEntraDestinationFromSettings(connectionString); + traceEntraDestination(decision, requestId, activeTrace()); + if (!decision.allowed) { + throw new EntraDestinationRejectedError(decision); + } + }; + const run = async (): Promise => { + if (!canReply()) { + return; + } + let mode: 'managedIdentity' | 'silent' | 'interactive' | undefined; + let acquiring = false; + try { + if (!managed && authMechanism !== 'MicrosoftEntraID') { + throw new Error('Token request from a non-OIDC worker'); + } + assertDestination(); + const pin = this.pin; + const readEnvironment = (): EntraSignInEnvironment => { + try { + return readEntraSignInEnvironment(); + } catch { + throw new EntraSignInRequiredError('providerChanged'); + } + }; + const assertEnvironment = (expected: EntraSignInEnvironment): string => { + const now = readEnvironment(); + if ( + (pin && (pin.providerId !== now.providerId || pin.tenantId !== tenantId)) || + expected.providerId !== now.providerId || + expected.cloudName !== now.cloudName || + expected.authority !== now.authority + ) { + throw new EntraSignInRequiredError('providerChanged'); + } + return expected.providerId; + }; + mode = managed ? 'managedIdentity' : pin ? 'silent' : 'interactive'; + 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); + 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; + } + traceAuthFlow('entraCloud.resolved', resolved.details, requestId, activeTrace()); + let identity: VerifiedEntraIdentity | undefined; + let accessToken: string; + acquiring = true; + if (managed) { + const { getManagedIdentityAccessToken } = await import('./managedIdentityTokenProvider'); + if (!canReply()) { + return; + } + assertDestination(); + accessToken = ( + await withTokenAcquisitionTiming(timings, () => + getManagedIdentityAccessToken( + [resolved.scope], + managedIdentityClientId, + tenantId, + this.correlationId, + activeTrace(), + ), + ) + ).accessToken; + } else { + assertDestination(); + if (!environment) { + throw new EntraSignInRequiredError('providerChanged'); + } + const providerId = assertEnvironment(environment); + 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; + } + 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 (!canReply()) { + 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 (!canReply()) { + 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/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' })); }); }); diff --git a/src/documentdb/playground/PlaygroundEvaluator.test.ts b/src/documentdb/playground/PlaygroundEvaluator.test.ts index fa24e08b9..ca56a3536 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 { + UserCancelledError, + type callWithTelemetryAndErrorHandling, + type IActionContext, +} from '@microsoft/vscode-azext-utils'; import * as vscode from 'vscode'; import { ext } from '../../extensionVariables'; import { type AuthTraceContext } from '../../utils/authTrace'; @@ -23,10 +27,13 @@ import { resetEntraTokenFailuresForTests, } 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 { type MainToWorkerMessage, type WorkerToMainMessage } from './workerTypes'; +import { getWorkerAuthReason, type MainToWorkerMessage, type WorkerToMainMessage } from './workerTypes'; type InitMessage = Extract; type TokenRequest = Extract; @@ -37,17 +44,29 @@ 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, + startup: vi.fn<() => Promise>(), + 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 +102,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,15 +125,16 @@ 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; + await mocks.startup(); }), 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 +165,10 @@ 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 } }); customSuffix = undefined; vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ get: vi.fn((_key: string, defaultValue: unknown): unknown => defaultValue), @@ -179,7 +209,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 +240,289 @@ describe('PlaygroundEvaluator token relay lifecycle', () => { expect(mocks.managedIdentityToken).not.toHaveBeenCalled(); } + 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({ + 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('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 => { + 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 +562,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 +609,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 +665,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 +700,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 +721,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..f49b4fd87 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 @@ -14,24 +14,27 @@ 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 { getHostsFromConnectionString } from '../utils/connectionStringHelpers'; +import { addDomainInfoToProperties } from '../utils/getClusterMetadata'; 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'; + +const consumedWorkerReplacements = new WeakSet(); /** * Evaluates query playground code in a persistent worker thread. @@ -78,7 +81,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 @@ -92,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 { @@ -103,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; @@ -162,13 +174,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 +197,113 @@ 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); + 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 && + ((!replaceFailedWorker && fingerprint !== this._workerFingerprint) || + (currentFingerprint !== undefined && fingerprint !== currentFingerprint))) || + (!replaceFailedWorker && pin && entraPin && !sameEntraIdentity(pin, entraPin)) + ) { + throw new ConnectionUnavailableError('credentialsChanged'); + } + } + if ( + !replaceFailedWorker && + (pin || fingerprint) && + (reason === 'signInRequired' || reason === 'identityMismatch') + ) { + throw createWorkerAuthError(reason); + } + if (replaceFailedWorker && replacement) { + consumedWorkerReplacements.add(replacement); + } + const needsSpawn = replaceFailedWorker || !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 learnedBinding: PlaygroundWorkerBinding | undefined; + let initMsg: Extract; + if (needsSpawn || !this._sessionInitMessage) { + onProgress?.(l10n.t('Initializing…')); + this.assertConnectionAvailable(clusterId); + const pinned = connection.entraIdentity ?? pin; + const expected = replacementFingerprint ?? 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 === '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; + 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({ + 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 (!isCurrentRelay()) { + throw new ConnectionUnavailableError('credentialsChanged'); + } + }; onProgress?.(l10n.t('Authenticating…')); let originalFailure: { error: unknown } | undefined; try { @@ -219,7 +313,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 +323,29 @@ 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); + // 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(); + 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 +353,7 @@ export class PlaygroundEvaluator implements vscode.Disposable { // Send eval message and await result onProgress?.(l10n.t('Running query…')); + assertCurrent(); this._sessionEvalCount++; @@ -252,8 +365,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 +380,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 +391,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,150 +521,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 ────────────────────────────────────────── private resetSession(): void { @@ -533,7 +536,9 @@ export class PlaygroundEvaluator implements vscode.Disposable { } this._sessionInitMessage = undefined; - this._resolvedTokenResource = undefined; + this._sessionDomainProperties = undefined; + this._relay = undefined; + this._workerFingerprint = undefined; this._sessionId = undefined; this._sessionEvalCount = 0; this._sessionAuthMethod = undefined; diff --git a/src/documentdb/playground/PlaygroundService.test.ts b/src/documentdb/playground/PlaygroundService.test.ts index 52b844379..b6c6de60d 100644 --- a/src/documentdb/playground/PlaygroundService.test.ts +++ b/src/documentdb/playground/PlaygroundService.test.ts @@ -11,6 +11,7 @@ import { type PlaygroundConnection } from './types'; // Access the vscode mock (aliased to test/vitest/vscode.ts) import * as vscode from 'vscode'; +import { ClustersClient } from '../ClustersClient'; import { CredentialCache } from '../CredentialCache'; vi.mock('../CredentialCache', () => ({ @@ -24,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(); @@ -31,6 +42,7 @@ describe('PlaygroundService', () => { afterEach(() => { service.dispose(); + vi.restoreAllMocks(); }); describe('singleton', () => { @@ -110,6 +122,72 @@ 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('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' }; + 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 = { @@ -245,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; @@ -314,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); @@ -383,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 3fa5d067d..814123b4a 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. @@ -50,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). * @@ -152,6 +156,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 +165,65 @@ 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 { + const key = uri.toString(); + const isRepick = this._connections.has(key); + // 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 } } + : bound; + this.setConnection(uri, activated); + return this._connections.get(key) ?? activated; + } + + 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 originating connection is still current and unpinned. */ + captureWorkerBinding( + uri: vscode.Uri, + expectedConnection: PlaygroundConnection, + binding: PlaygroundWorkerBinding, + ): PlaygroundConnection | undefined { + 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 = { + ...expectedConnection, + 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()); @@ -228,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); diff --git a/src/documentdb/playground/WorkerSessionManager.test.ts b/src/documentdb/playground/WorkerSessionManager.test.ts index d1725634d..537b236af 100644 --- a/src/documentdb/playground/WorkerSessionManager.test.ts +++ b/src/documentdb/playground/WorkerSessionManager.test.ts @@ -15,7 +15,17 @@ 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 entraSession from '../auth/entraSession'; +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 { @@ -28,7 +38,7 @@ import { type WorkerSessionCallbacks, type WorkerStartupTelemetryContext, } from './WorkerSessionManager'; -import { type MainToWorkerMessage } from './workerTypes'; +import { getWorkerAuthReason, type MainToWorkerMessage } from './workerTypes'; interface RecordedTelemetry { readonly eventName: string; @@ -746,6 +756,249 @@ 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(); + } + }); + + 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, + { startupCorrelationId: 'relay-startup', surface: 'playground', 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', () => { let trace: MockInstance; @@ -800,6 +1053,139 @@ 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.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 53ea35c56..ed9024eb2 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 { type 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'; @@ -87,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, @@ -116,6 +123,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 +162,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 +193,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 +209,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 +233,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 +346,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 +433,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 +447,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 +478,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 +618,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 +652,18 @@ 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 +675,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 +688,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,20 +714,7 @@ export class WorkerSessionManager implements vscode.Disposable { } case 'tokenRequest': { - if (this._callbacks.onTokenRequest) { - const worker = this._worker; - void this._callbacks.onTokenRequest( - msg, - (response) => { - if (this._worker === worker) { - worker?.postMessage(response); - } - }, - () => this._worker === worker, - this._startup?.costTimings, - connection, - ); - } + void this.handleTokenRequest(msg, connection, worker); break; } @@ -697,12 +730,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) { @@ -712,10 +781,13 @@ 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) { - entry.reject(new Error('Worker terminated')); + entry.reject(cancellation ?? new Error('Worker terminated')); } this._pendingRequests.clear(); @@ -748,6 +820,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..82fde16e9 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,60 @@ 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 +330,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..12673add2 100644 --- a/src/documentdb/playground/playgroundWorker.ts +++ b/src/documentdb/playground/playgroundWorker.ts @@ -31,7 +31,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 +49,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 +94,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 +118,7 @@ parentPort.on('message', (msg: MainToWorkerMessage) => { error: errorMessage, stack, code, + authReason: getWorkerAuthReason(err) ?? callbackFailure, }; parentPort!.postMessage(response); }); @@ -120,6 +141,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) { @@ -220,6 +242,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 +299,7 @@ async function handleInit(msg: Extract): type: 'initResult', requestId: msg.requestId, success: true, + authReason: callbackFailure, }; parentPort!.postMessage(response); } @@ -269,6 +307,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 +362,7 @@ async function handleEval(msg: Extract): const response: WorkerToMainMessage = { type: 'evalResult', requestId: msg.requestId, + authReason: callbackFailure, result: { type: result.type, printable: printableStr, @@ -372,11 +414,12 @@ 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 +435,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 +468,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..5662d9144 100644 --- a/src/documentdb/playground/types.ts +++ b/src/documentdb/playground/types.ts @@ -3,6 +3,19 @@ * 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; +} + +/** 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. @@ -14,6 +27,9 @@ export interface PlaygroundConnection { readonly clusterDisplayName: string; /** Target database name for query execution. */ 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. 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/DocumentDBShellPty.test.ts b/src/documentdb/shell/DocumentDBShellPty.test.ts index 44dd8b038..1e88343ac 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,62 @@ describe('DocumentDBShellPty', () => { }); describe('open', () => { + 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' }; pty = new DocumentDBShellPty({ ...defaultOptions, deepLink }); diff --git a/src/documentdb/shell/DocumentDBShellPty.ts b/src/documentdb/shell/DocumentDBShellPty.ts index a62471bed..6c087dc2b 100644 --- a/src/documentdb/shell/DocumentDBShellPty.ts +++ b/src/documentdb/shell/DocumentDBShellPty.ts @@ -7,6 +7,7 @@ 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 +18,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 +638,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 +702,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 +849,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 +886,107 @@ 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 { clusterId } = this._connectionInfo; + const revision = this._disconnectRevision; + const epoch = ClustersClient.getEpoch(clusterId); + void vscode.window.showWarningMessage(message, action).then(async (choice) => { + if ( + choice !== action || + this._closed || + revision !== this._disconnectRevision || + ClustersClient.getEpoch(clusterId) !== epoch + ) { + 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, clusterId, identity); + if ( + !result || + this._closed || + revision !== this._disconnectRevision || + ClustersClient.getEpoch(clusterId) !== result.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). diff --git a/src/documentdb/shell/ShellSessionManager.test.ts b/src/documentdb/shell/ShellSessionManager.test.ts index 7a5df24cf..a9ce75850 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,93 @@ 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('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; + 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 +278,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 +362,10 @@ 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 +391,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 +433,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 +459,10 @@ 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 +491,7 @@ describe('ShellSessionManager', () => { requestId: 'refresh', error: "Microsoft Entra ID isn't allowed for this server.", errorName: 'EntraDestinationRejectedError', + reason: 'destinationRejected', }); manager.dispose(); }, @@ -366,7 +520,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 +540,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 +646,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 +689,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 +724,10 @@ 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 +751,10 @@ 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 +803,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 +856,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 +906,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 +919,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 +968,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 +995,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..162accb07 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 { 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 { 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 { 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,15 @@ 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; + // 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, }; @@ -160,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; + return ( + this._initialized && this._workerManager.isAlive && !this._authFailure && !this._workerManager.authFailure + ); } /** @@ -191,6 +192,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 +220,78 @@ 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) { + if (this._initialized && this._authFailure) { + 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 === 'MicrosoftEntraID') { + this._pin = pin; + } + this._relay = new WorkerTokenRelay( + clusterId, + initMsg, + epoch, + this._managedIdentityTokenCorrelationId, + initMsg.authMechanism === '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 +333,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.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 +350,47 @@ export class ShellSessionManager implements vscode.Disposable { terminalColumns, }; - const workerResult = await this._workerManager.sendEval(evalMsg); - return workerResult.result; + 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 && + 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 +400,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 +465,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 +479,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 } - : {}), - }); - } - } }