From 247bc68d31b4d79a6b7868228ab7cc1206c7fe52 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 13:48:28 +0000 Subject: [PATCH 01/29] feat: classify connection failures before deciding how to recover (WI-5) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../auth/driverOidcContract.test.ts | 25 ++ .../auth/entraErrors/entraCallbackErrors.ts | 9 +- src/documentdb/connectionFailures.test.ts | 219 ++++++++++++++++++ src/documentdb/connectionFailures.ts | 159 +++++++++++++ 4 files changed, 409 insertions(+), 3 deletions(-) create mode 100644 src/documentdb/connectionFailures.test.ts create mode 100644 src/documentdb/connectionFailures.ts diff --git a/src/documentdb/auth/driverOidcContract.test.ts b/src/documentdb/auth/driverOidcContract.test.ts index 8048bce08..0f864bcee 100644 --- a/src/documentdb/auth/driverOidcContract.test.ts +++ b/src/documentdb/auth/driverOidcContract.test.ts @@ -18,6 +18,8 @@ import { AutomatedCallbackWorkflow as DriverWorkflow } from 'mongodb/lib/cmap/au // eslint-disable-next-line import/no-internal-modules -- The workflow needs the driver's real token cache. import { TokenCache as DriverTokenCache } from 'mongodb/lib/cmap/auth/mongodb_oidc/token_cache.js'; import { describe, expect, it, vi } from 'vitest'; +import { classifyConnectionFailure } from '../connectionFailures'; +import { AuthMethodId } from './AuthMethod'; // The driver's public declarations omit these internals. Type only the surface the suite uses. interface SaslStart { @@ -121,6 +123,29 @@ describe('driver contract: mongodb OIDC workflow (7.2.0)', () => { ]); }); + it('propagates the final code 18 unchanged when the callback-supplied token is also rejected', async (): Promise => { + const cache = new TokenCache(); + cache.put({ accessToken: 'dummy-cached-token' }); + const callback = vi.fn().mockResolvedValue({ accessToken: 'dummy-callback-token' }); + const workflow = new AutomatedCallbackWorkflow(cache, callback); + const finalError = new MongoServerError({ code: 18, errmsg: 'dummy authentication failure' }); + const command = vi + .fn() + .mockRejectedValueOnce(new MongoServerError({ code: 18, errmsg: 'dummy authentication failure' })) + .mockRejectedValueOnce(finalError); + + await expect(workflow.execute({ command }, credentials)).rejects.toBe(finalError); + expect(classifyConnectionFailure(finalError, AuthMethodId.MicrosoftEntraID)).toEqual({ + kind: 'credentialsRejected', + generation: 'evict', + }); + expect(callback).toHaveBeenCalledTimes(1); + expect(command.mock.calls.map(([, request]) => BSON.deserialize(request.payload.value()))).toEqual([ + { jwt: 'dummy-cached-token' }, + { jwt: 'dummy-callback-token' }, + ]); + }); + it('propagates a network error without calling the callback again or retrying the command', async () => { const callback = vi.fn().mockResolvedValue({ accessToken: 'dummy-cached-token' }); const workflow = new AutomatedCallbackWorkflow(new TokenCache(), callback); diff --git a/src/documentdb/auth/entraErrors/entraCallbackErrors.ts b/src/documentdb/auth/entraErrors/entraCallbackErrors.ts index ab2167fbe..016651b1b 100644 --- a/src/documentdb/auth/entraErrors/entraCallbackErrors.ts +++ b/src/documentdb/auth/entraErrors/entraCallbackErrors.ts @@ -20,10 +20,13 @@ export class EntraIdentityMismatchError extends Error { } } -export class TokenCallbackError extends Error { - public readonly authMethod = AuthMethodId.MicrosoftEntraID; +type TokenCallbackAuthMethod = AuthMethodId.MicrosoftEntraID | AuthMethodId.ManagedIdentity; - constructor(cause: unknown) { +export class TokenCallbackError extends Error { + constructor( + cause: unknown, + public readonly authMethod: TokenCallbackAuthMethod = AuthMethodId.MicrosoftEntraID, + ) { super(l10n.t('Failed to obtain a Microsoft Entra ID token.'), { cause }); this.name = 'TokenCallbackError'; } diff --git a/src/documentdb/connectionFailures.test.ts b/src/documentdb/connectionFailures.test.ts new file mode 100644 index 000000000..6fd96898c --- /dev/null +++ b/src/documentdb/connectionFailures.test.ts @@ -0,0 +1,219 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { + MongoNetworkError, + MongoNetworkTimeoutError, + MongoNotConnectedError, + MongoOperationTimeoutError, + MongoServerError, + MongoServerSelectionError, + MongoTopologyClosedError, + TopologyType, + type ServerDescription, + type TopologyDescription, +} from 'mongodb'; +// eslint-disable-next-line import/no-internal-modules -- These constructors are not public runtime exports. +import { ServerDescription as DriverServerDescription } from 'mongodb/lib/sdam/server_description.js'; +// eslint-disable-next-line import/no-internal-modules -- Use the real .error getter, which aliases the first failed server. +import { TopologyDescription as DriverTopologyDescription } from 'mongodb/lib/sdam/topology_description.js'; +import { describe, expect, it } from 'vitest'; +import { AuthMethodId } from './auth/AuthMethod'; +import { + EntraIdentityMismatchError, + EntraSignInRequiredError, + TokenCallbackError, +} from './auth/entraErrors/entraCallbackErrors'; +import { EntraDestinationRejectedError } from './auth/oidcAllowedHosts'; +import { classifyConnectionFailure } from './connectionFailures'; +import { ConnectionUnavailableError } from './ConnectionUnavailableError'; + +const makeServer = DriverServerDescription as new ( + address: string, + hello: undefined, + options: { error: Error | null }, +) => ServerDescription; +const makeTopology = DriverTopologyDescription as typeof TopologyDescription; + +function selectionError(...errors: (Error | null)[]): MongoServerSelectionError { + const servers = new Map( + errors.map((error, index): [string, ServerDescription] => { + const server = new makeServer(`example-${index}.test:27017`, undefined, { error }); + return [server.address, server]; + }), + ); + return new MongoServerSelectionError('Server selection timed out', new makeTopology(TopologyType.Unknown, servers)); +} + +const entra = AuthMethodId.MicrosoftEntraID; +const native = AuthMethodId.NativeAuth; +const rejected = new MongoServerError({ code: 18, errmsg: 'Authentication failed' }); +const network = new MongoNetworkError('connection closed'); +const refused = Object.assign(new Error('connect ECONNREFUSED 127.0.0.1:27017'), { code: 'ECONNREFUSED' }); + +describe('classifyConnectionFailure', (): void => { + it.each(['noSession', 'providerChanged'] as const)('recognizes typed Entra sign-in: %s', (reason): void => { + const error = new Error('Wrapper', { cause: new EntraSignInRequiredError(reason) }); + expect(classifyConnectionFailure(error, entra)).toEqual({ + kind: 'signInRequired', + generation: 'replaceOnRecovery', + }); + expect(classifyConnectionFailure(error, native)).toEqual({ kind: 'other', generation: 'keep' }); + }); + + it.each([new EntraIdentityMismatchError(), new ConnectionUnavailableError('identityChanged')])( + 'requires a rebind for %s', + (error): void => { + expect(classifyConnectionFailure(new Error('Wrapper', { cause: error }))).toEqual({ + kind: 'identityChanged', + generation: 'evict', + }); + }, + ); + + it('reports missing credentials without inventing a generation to evict', (): void => { + expect(classifyConnectionFailure(new ConnectionUnavailableError('credentialsMissing'))).toEqual({ + kind: 'credentialsMissing', + generation: 'none', + }); + }); + + it.each([AuthMethodId.MicrosoftEntraID, AuthMethodId.ManagedIdentity] as const)( + 'distinguishes a broken %s callback from its underlying network cause', + (authMethod): void => { + const error = new TokenCallbackError(network, authMethod); + expect(classifyConnectionFailure(error, authMethod)).toEqual({ + kind: 'transient', + generation: 'replaceOnNextForeground', + }); + }, + ); + + it('classifies code 18 for native or RU key auth, including through real selection errors', (): void => { + const error = selectionError(rejected, null, new MongoServerError({ code: 18 })); + expect(error.cause).toBe(rejected); + expect(error.code).toBe(18); + expect(classifyConnectionFailure(error, native)).toEqual({ kind: 'credentialsRejected', generation: 'evict' }); + }); + + it('evicts a rejected Entra client without classifying the failure as a missing session', (): void => { + expect(classifyConnectionFailure(selectionError(rejected), entra)).toEqual({ + kind: 'credentialsRejected', + generation: 'evict', + }); + expect(classifyConnectionFailure(rejected, AuthMethodId.ManagedIdentity)).toEqual({ + kind: 'other', + generation: 'keep', + }); + }); + + it.each([ + new MongoTopologyClosedError(), + new MongoNotConnectedError('Client must be connected before running operations'), + ])('recognizes a typed closed client or topology: %s', (error): void => { + expect(classifyConnectionFailure(new Error('Wrapper', { cause: error }))).toEqual({ + kind: 'clientClosed', + generation: 'replaceOnNextForeground', + }); + }); + + it.each([ + network, + new MongoNetworkError('Sign in again (AADSTS50058)'), + new MongoNetworkTimeoutError('timed out'), + new MongoOperationTimeoutError('Timed out during server selection', { cause: selectionError(null) }), + selectionError(new Error('unrecognized server error')), + ])('keeps an Entra client on plain network, timeout, or selection failures: %s', (error): void => { + expect(classifyConnectionFailure(error, entra)).toEqual({ kind: 'transient', generation: 'keep' }); + }); + + it('keeps the generation when a Kubernetes port-forward refuses the connection', (): void => { + const socketError = new MongoNetworkError(refused.message, { cause: refused }); + expect(classifyConnectionFailure(selectionError(socketError), native)).toEqual({ + kind: 'transient', + generation: 'keep', + }); + expect(classifyConnectionFailure(refused, native)).toEqual({ kind: 'transient', generation: 'keep' }); + }); + + it('does not treat the first server’s code 18 as authoritative when peers failed differently', (): void => { + const firstAuth = selectionError(rejected, network); + const firstNetwork = selectionError(network, rejected); + expect(firstAuth.cause).toBe(rejected); + expect(firstNetwork.cause).toBe(network); + for (const error of [firstAuth, firstNetwork]) { + expect(classifyConnectionFailure(error, native)).toEqual({ + kind: 'transient', + generation: 'keep', + note: 'mixedServerErrors', + }); + } + }); + + it('distinguishes consistent and mixed typed causes in constructed driver descriptions', (): void => { + // A MongoError can be retained by SDAM. The installed OIDC path does not create this wrapper. + const wrappedMiss = new MongoNetworkError('wrapped failure', { + cause: new EntraSignInRequiredError('noSession'), + }); + expect(classifyConnectionFailure(selectionError(null, wrappedMiss), entra)).toEqual({ + kind: 'signInRequired', + generation: 'replaceOnRecovery', + }); + for (const error of [selectionError(wrappedMiss, network), selectionError(network, wrappedMiss)]) { + expect(classifyConnectionFailure(error, entra)).toEqual({ + kind: 'transient', + generation: 'keep', + note: 'mixedServerErrors', + }); + } + }); + + it('leaves cancellation and destination rejection to their existing handlers', (): void => { + const cancellation = new TokenCallbackError(new UserCancelledError()); + const rejectedHost = new EntraDestinationRejectedError({ firstHost: 'not-allowed.test', hostCount: 1 }); + const tlsError = new MongoNetworkError('TLS failed', { cause: rejectedHost }); + + expect(classifyConnectionFailure(cancellation, entra)).toEqual({ + kind: 'other', + generation: 'keep', + note: 'cancelled', + }); + expect(classifyConnectionFailure(selectionError(network, tlsError), entra)).toEqual({ + kind: 'other', + generation: 'keep', + note: 'destinationRejected', + }); + const disconnected = new ConnectionUnavailableError('userDisconnected', { cause: rejected }); + expect(classifyConnectionFailure(disconnected)).toEqual({ + kind: 'other', + generation: 'keep', + note: 'alreadyUnavailable', + }); + }); + + it('does not classify messages or an arbitrary code as typed failures', (): void => { + for (const error of [ + 'EntraSignInRequiredError', + new Error('Client must be connected before running operations'), + Object.assign(new Error('Sign in again (AADSTS50058)'), { code: 18 }), + ]) { + expect(classifyConnectionFailure(error, entra)).toEqual({ kind: 'other', generation: 'keep' }); + } + }); + + it('keeps the generation on cyclic or uninspected server evidence', (): void => { + const cyclic = new Error('cycle'); + cyclic.cause = cyclic; + const tooManyServers = Array(64).fill(null); + for (const error of [cyclic, selectionError(rejected, ...tooManyServers, network)]) { + expect(classifyConnectionFailure(error, native)).toEqual({ + kind: 'other', + generation: 'keep', + note: 'incompleteEvidence', + }); + } + }); +}); diff --git a/src/documentdb/connectionFailures.ts b/src/documentdb/connectionFailures.ts new file mode 100644 index 000000000..2966504a4 --- /dev/null +++ b/src/documentdb/connectionFailures.ts @@ -0,0 +1,159 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { + MongoNetworkError, + MongoNotConnectedError, + MongoOperationTimeoutError, + MongoServerError, + MongoServerSelectionError, + MongoTopologyClosedError, + type TopologyDescription, +} from 'mongodb'; +import { networkCode } from '../utils/connectionErrorClassification'; +import { AuthMethodId } from './auth/AuthMethod'; +import { isEntraDestinationRejectedError } from './auth/oidcAllowedHosts'; +import { ConnectionUnavailableError } from './ConnectionUnavailableError'; + +export interface ConnectionFailure { + readonly kind: + | 'signInRequired' + | 'identityChanged' + | 'credentialsMissing' + | 'credentialsRejected' + | 'clientClosed' + | 'transient' + | 'other'; + readonly generation: 'keep' | 'evict' | 'replaceOnRecovery' | 'replaceOnNextForeground' | 'none'; + readonly note?: + | 'cancelled' + | 'destinationRejected' + | 'alreadyUnavailable' + | 'mixedServerErrors' + | 'incompleteEvidence'; +} + +const OTHER: ConnectionFailure = { kind: 'other', generation: 'keep' }; +const TRANSIENT: ConnectionFailure = { kind: 'transient', generation: 'keep' }; +const INCOMPLETE: ConnectionFailure = { ...OTHER, note: 'incompleteEvidence' }; +const MAX_DEPTH = 8; +const MAX_NODES = 64; + +/** Classifies failures using the auth method actually used (RU key connections use NativeAuth). */ +export function classifyConnectionFailure(error: unknown, authMethod?: AuthMethodId): ConnectionFailure { + let remaining = MAX_NODES; + const path = new Set(); + + function inspect(candidate: unknown, depth: number): ConnectionFailure | undefined { + if (!(candidate instanceof Error)) { + return undefined; + } + if (depth >= MAX_DEPTH || remaining-- <= 0 || path.has(candidate)) { + return INCOMPLETE; + } + path.add(candidate); + try { + return classify(candidate, depth); + } finally { + path.delete(candidate); + } + } + + function classify(candidate: Error, depth: number): ConnectionFailure { + if (candidate instanceof UserCancelledError) { + return { ...OTHER, note: 'cancelled' }; + } + if (isEntraDestinationRejectedError(candidate)) { + return { ...OTHER, note: 'destinationRejected' }; + } + if (candidate instanceof ConnectionUnavailableError) { + switch (candidate.reason) { + case 'identityChanged': + return { kind: 'identityChanged', generation: 'evict' }; + case 'credentialsMissing': + return { kind: 'credentialsMissing', generation: 'none' }; + default: + return { ...OTHER, note: 'alreadyUnavailable' }; + } + } + if (candidate instanceof MongoServerSelectionError && candidate.reason?.servers instanceof Map) { + return classifyServers(candidate.reason.servers, depth + 1); + } + + const cause = inspect(candidate.cause, depth + 1); + if (cause?.note !== undefined) { + return cause; + } + switch (candidate.name) { + case 'EntraSignInRequiredError': + return authMethod === undefined || authMethod === AuthMethodId.MicrosoftEntraID + ? { kind: 'signInRequired', generation: 'replaceOnRecovery' } + : OTHER; + case 'EntraIdentityMismatchError': + return { kind: 'identityChanged', generation: 'evict' }; + case 'TokenCallbackError': + return { kind: 'transient', generation: 'replaceOnNextForeground' }; + } + if (candidate instanceof MongoServerError && candidate.code === 18) { + // The OIDC workflow already tries its callback after a cached token is rejected. + return authMethod === AuthMethodId.NativeAuth || authMethod === AuthMethodId.MicrosoftEntraID + ? { kind: 'credentialsRejected', generation: 'evict' } + : OTHER; + } + if (candidate instanceof MongoNotConnectedError || candidate instanceof MongoTopologyClosedError) { + return { kind: 'clientClosed', generation: 'replaceOnNextForeground' }; + } + if (cause && cause.kind !== 'other') { + return cause; + } + if ( + candidate instanceof MongoNetworkError || + candidate instanceof MongoOperationTimeoutError || + candidate instanceof MongoServerSelectionError || + networkCode(candidate) + ) { + return TRANSIENT; + } + return OTHER; + } + + function classifyServers(servers: TopologyDescription['servers'], depth: number): ConnectionFailure { + // In 7.2.0, selection.cause and .code summarize the *first* server error, not the topology. + // Consider the per-server errors instead, so reversing the map cannot change the verdict. + let agreed: ConnectionFailure | undefined; + let mixed = false; + let constraint: ConnectionFailure | undefined; + for (const server of servers.values()) { + if (remaining <= 0) { + return constraint ?? INCOMPLETE; + } + remaining--; // Bound map iteration even when descriptions have no error. + const result = inspect(server?.error, depth); + if (!result) { + continue; + } + if (result.note === 'cancelled' || result.note === 'destinationRejected') { + // Preserve both constraints without enlarging either policy. + constraint = result.note === 'cancelled' ? result : (constraint ?? result); + } + if (agreed) { + mixed ||= + result.kind !== agreed.kind || result.generation !== agreed.generation || result.note !== agreed.note; + } else { + agreed = result; + } + } + if (constraint) { + return constraint; + } + if (mixed) { + return { ...TRANSIENT, note: 'mixedServerErrors' }; + } + return agreed && (agreed.kind !== 'other' || agreed.note) ? agreed : TRANSIENT; + } + + return inspect(error, 0) ?? OTHER; +} From afe4bc2e193690b14ef83aeef1e1bf0e744c82d3 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 13:48:28 +0000 Subject: [PATCH 02/29] docs: record CP-2 and retain verified Entra settings for explicit sign-in Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../features/connection-lifecycle/README.md | 4 +++ .../connection-lifecycle/decisions.md | 13 +++++++++ .../iterations/01-dev-plan.md | 28 +++++++++++++++++-- .../iterations/01-implementation-plan.md | 2 ++ 4 files changed, 44 insertions(+), 3 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/README.md b/docs/ai-and-plans/features/connection-lifecycle/README.md index 87b66ed56..8d5207066 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/README.md +++ b/docs/ai-and-plans/features/connection-lifecycle/README.md @@ -49,6 +49,9 @@ Evidence, telemetry and source pointers: [research-findings.md](./research-findi fingerprint and generation. - **Never change identity under an open surface.** It becomes disconnected, keeps its state, says why and offers one action. +- After a database rejects a verified Entra identity, discard the client but keep its in-memory + connection settings for explicit **Sign in again**. Do not retain the rejected token or retry + silently. - **One teardown** serves Disconnect, Remove Connection and identity-changing credential updates. - Disconnect uses the existing task-conflict guard: if a copy or export is using the cluster, leave the task and connection running. The user can retry after the task finishes or is stopped. @@ -79,6 +82,7 @@ See [decisions.md](./decisions.md): - 0011 Disconnect keeps the cached credentials and the verified identity; only Remove drops them; - 0012 a minimal lifecycle design: no state machine, one epoch, no prompts in `getClient`, one-step teardown; - 0013 corrections to 0012: latch before a credential save, epoch checks on replies, bindings carried through handoffs, an operation wrapper, folder deletion runs teardown. +- 0014 retain in-memory settings for explicit sign-in recovery after verified Entra rejection. ## Timeline diff --git a/docs/ai-and-plans/features/connection-lifecycle/decisions.md b/docs/ai-and-plans/features/connection-lifecycle/decisions.md index dcbef7f08..e83c02dc9 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/decisions.md +++ b/docs/ai-and-plans/features/connection-lifecycle/decisions.md @@ -25,6 +25,7 @@ created: 2026-11-19 | 0011 | Disconnect keeps the cached credentials and the verified identity; only Remove drops them | Accepted | Operator: reverses the #1059 proposal (plan Q3) | 2026-11-19 | — | | 0012 | Keep the lifecycle design minimal: no state machine, one epoch, no prompts in getClient, one-step teardown | Accepted | Operator: approved every proposed simplification | 2026-11-19 | — | | 0013 | Correct the minimal design where it lost edits, identity or recovery: latch before save, epoch checks | Accepted (modifies 0012) | Operator: "update the plan" after the omissions review | 2026-11-19 | — | +| 0014 | Keep in-memory connection settings after a rejection for a verified Entra identity | Accepted | Operator selected A to make sign-in recovery smoother | 2026-11-23 | Yes; WI-5 previously said to delete the entry | > Entries below are **semantically** immutable: append new entries rather than rewriting old ones, > and record reversals as a new entry plus a status change above. Heading text is frozen once @@ -399,3 +400,15 @@ The findings, each confirmed in the code, and the corrections now in the dev pla submission, no replay, no stale UI update and no claim that an unacknowledged write was not applied. None of the corrections adds a state machine or a service; 0012's other rules stand. + +## 0014. Keep in-memory connection settings after a rejection for a verified Entra identity + +A final Entra database authentication rejection still evicts the client. If the connection has a +verified Entra identity, keep its existing in-memory connection settings so **Sign in again** can +start from that identity, including when invoked with only `clusterId`. The operator chose this +over deleting the settings and losing that recovery action, to keep recovery smooth. + +This does not retain the rejected token, write anything to persistent storage, change destination +checks, or start a silent retry. Native authentication and RU key handling are unchanged. The +explicit sign-in path still checks the epoch after prompting and never moves an open surface to a +different identity. 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 9db2e2406..ed50ecd3f 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 @@ -1171,8 +1171,8 @@ shim (0005). | `TokenCallbackError` (step 2) | Entra, MI | `transient`, workflow broken | replace on the next **foreground** operation | Retry | | `ConnectionUnavailableError('credentialsMissing')` (F-20) | any | `credentialsMissing` | none to keep | Update credentials | | code 18 | Native, RU | `credentialsRejected` | evict; no automatic retry | Update credentials (RU: Retry re-reads the key) | - | code 18 after a fresh callback | Entra | per T-5 | evict | per T-5 | - | `MongoNotConnectedError`, `topologyClosed`, "Client must be connected" | any | `clientClosed` | new generation on the next foreground call | none | + | final code 18 | Entra | `credentialsRejected` | evict; no automatic retry | Sign in again with a verified Entra identity | + | `MongoNotConnectedError`, `MongoTopologyClosedError` | any | `clientClosed` | new generation on the next foreground call | none | | network errors, timeouts, server selection with no auth cause | any | `transient` | keep | Retry | | anything else | any | `other` | keep | existing behavior | @@ -1213,7 +1213,9 @@ shim (0005). - Call `addEstablishedConnectionContext` on the failure events of `connect`, `getchildren` and the tree. - **Keep credentials on recoverable failures (F-20).** In every provider item's `authenticateAndConnect` failure path, still call `deleteClient`, but call `CredentialCache.deleteCredentials` only when the - kind is `credentialsRejected`, or `other` as today. For `transient`, `clientClosed` and + kind is `credentialsRejected`, or `other` as today. For `credentialsRejected` with a verified + Entra identity, retain the in-memory settings for explicit **Sign in again** (decision 0014). + For `transient`, `clientClosed` and `signInRequired`, keep the entry: a network outage during a tree expand must not leave open surfaces with nothing to reconnect from, nor make the user retype a discovery password. Put the decision in one shared helper, not in ten copies. @@ -1272,6 +1274,26 @@ shim (0005). **Progress:** +- **CP-2, advisor verdict: revise before wiring.** The classifier draft builds and 32 focused + tests pass. The pinned 7.2.0 workflow test shows that if a cached OIDC token receives code 18, + the driver calls the callback and propagates the final rejection unchanged if that token is + also refused. This does not prove that the callback returned newly issued token bytes. + Treat the final Entra authentication rejection as `credentialsRejected` and evict the client, + rather than adding callback-freshness fields with no reliable producer (85% advisor confidence). + Keep typed `noSession` distinct. Plain network failures (including the OP-1a shape and tunnel + refusal) and mixed per-server failures keep the client. Closed-client checks are typed only. + Plain callback errors do not reach the per-server descriptions through the pinned OIDC path, + so R5 does not require changing the Entra explainer now. Cancellation and destination handling + stay in place. +- **CP-2 / OC-1, accepted (2026-11-23):** The operator chose A for smoother recovery and asked + to record it in [decision 0014](../decisions.md#0014-keep-in-memory-connection-settings-after-a-rejection-for-a-verified-entra-identity). + Evict the rejected client, but keep the in-memory settings for a verified Entra identity. + Explicit **Sign in again** then works when invoked with just `clusterId`. No rejected token is + retained, no automatic retry is started, and Native/RU rejection and persistent storage are unchanged. +- **CP-2 revision verified:** Removed the unproducible freshness inputs. The contract test now + sends the exact final code 18 from the driver workflow through the classifier. Case 1 passed: + build and 31 focused tests across classification, the driver contract, and the Entra explainer. + --- ## WI-6: Bind surfaces and add the unavailable state (PR 5) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-implementation-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-implementation-plan.md index 8b0bb4bd0..c83e4ecc2 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-implementation-plan.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-implementation-plan.md @@ -314,6 +314,8 @@ In [ClustersClient.ts](../../../../../src/documentdb/ClustersClient.ts): - `signInRequired` (Entra): offer **Sign in again**. - `credentialsRejected` (Native code 18 after a reconnect): offer **Update credentials**, and **no automatic retry loop**. + - `credentialsRejected` (final Entra code 18): evict the client. With a verified Entra identity, + keep its in-memory connection settings and offer explicit **Sign in again** (decision 0014). - `clientClosed`: create a new generation with the same identity. - `transient` (network or timeout): no eviction, because the driver recovers. Offer Retry. From 6565f5f3d1f88cfe941597a9d209bc00e6525953 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 13:57:27 +0000 Subject: [PATCH 03/29] feat: fence authentication recovery to the failed client generation (WI-5) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/documentdb/ClustersClient.test.ts | 132 +++++++++++++++++- src/documentdb/ClustersClient.ts | 79 ++++++++++- .../auth/ManagedIdentityAuthHandler.test.ts | 32 ++--- .../auth/ManagedIdentityAuthHandler.ts | 2 + .../auth/MicrosoftEntraIDAuthHandler.ts | 6 +- src/documentdb/auth/oidcClientOptions.ts | 28 +++- src/documentdb/runWithClient.ts | 65 +++++++++ 7 files changed, 315 insertions(+), 29 deletions(-) create mode 100644 src/documentdb/runWithClient.ts diff --git a/src/documentdb/ClustersClient.test.ts b/src/documentdb/ClustersClient.test.ts index 1c5f97c3f..09436fc69 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -20,6 +20,11 @@ import { traceAuthFlow, type AuthTraceContext } from '../utils/authTrace'; import { type VerifiedEntraIdentity } from './auth/AuthHandler'; import { AuthMethodId } from './auth/AuthMethod'; import * as authHandlerFactory from './auth/createAuthHandler'; +import { + EntraIdentityMismatchError, + EntraSignInRequiredError, + TokenCallbackError, +} from './auth/entraErrors/entraCallbackErrors'; import { ManagedIdentityAuthHandler } from './auth/ManagedIdentityAuthHandler'; import { MicrosoftEntraIDAuthHandler } from './auth/MicrosoftEntraIDAuthHandler'; import { NativeAuthHandler } from './auth/NativeAuthHandler'; @@ -33,6 +38,7 @@ import { import { computeConnectionFingerprint } from './connectionFingerprint'; import { ConnectionUnavailableError } from './ConnectionUnavailableError'; import { CredentialCache } from './CredentialCache'; +import { runWithClient } from './runWithClient'; import { prepareDriverConnectionString } from './srv/prepareDriverConnectionString'; import { type SrvResolutionSummary } from './srv/srvResolutionSummary'; import { getClusterMetadata, getDomainMetadata } from './utils/getClusterMetadata'; @@ -320,7 +326,7 @@ describe('regular connection startup diagnostics', () => { const background = (): Promise => ClustersClient.getClient(clusterId, undefined, onStartup, 'clusterDashboardPoll', { background: true }); - await expect(background()).rejects.toBeInstanceOf(MongoNotConnectedError); + await expect(background()).rejects.toMatchObject({ name: 'ConnectionUnavailableError', reason: 'unreachable' }); CredentialCache.deleteCredentials(clusterId); await expect(background()).rejects.toMatchObject({ name: 'ConnectionUnavailableError', @@ -388,7 +394,7 @@ describe('regular connection startup diagnostics', () => { const background = (): Promise => ClustersClient.getClient(clusterId, undefined, onBackground, 'clusterDashboardPoll', { background: true }); - await expect(background()).rejects.toBeInstanceOf(MongoNotConnectedError); + await expect(background()).rejects.toMatchObject({ name: 'ConnectionUnavailableError', reason: 'unreachable' }); expect(onBackground).not.toHaveBeenCalled(); expect(mockConnect).toHaveBeenCalledOnce(); expect(MongoClient).toHaveBeenCalledOnce(); @@ -439,6 +445,128 @@ describe('regular connection startup diagnostics', () => { expect(mockConnect).toHaveBeenCalledOnce(); }); + it.each([ + ['transient', new TokenCallbackError(new Error('IMDS unavailable'), AuthMethodId.ManagedIdentity)], + ['clientClosed', new MongoNotConnectedError('driver closed')], + ] as const)('reports %s and replaces once on foreground, fencing late failures and close', async (kind, error) => { + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.ManagedIdentity, 'mongodb://private-host:27017'); + const old = await ClustersClient.getClient(clusterId); + const background = (): Promise => + ClustersClient.getClient(clusterId, undefined, undefined, 'clusterDashboardPoll', { background: true }); + + expect(ClustersClient.reportFailure(old.binding, error)).toBe(kind); + await expect(background()).rejects.toMatchObject({ reason: 'unreachable' }); + expect(mockConnect).toHaveBeenCalledOnce(); + expect(mockClose).not.toHaveBeenCalled(); + + const closing = deferred(); + mockClose.mockReturnValueOnce(closing.promise); + const foreground = ClustersClient.getClient(clusterId); + const [replacement, joined] = await Promise.all([foreground, background()]); + expect(joined).toBe(replacement); + expect(replacement.binding).toEqual({ ...old.binding, generation: old.generation + 1 }); + expect(mockConnect).toHaveBeenCalledTimes(2); + expect(mockClose).toHaveBeenCalledExactlyOnceWith(true); + expect(mockClose.mock.contexts[0]).toBe(old.getMongoClient()); + + expect(ClustersClient.reportFailure(old.binding, new EntraIdentityMismatchError())).toBeUndefined(); + expect( + ClustersClient.reportFailure({ ...replacement.binding, fingerprint: 'unmatched' }, error), + ).toBeUndefined(); + expect(ClustersClient.reportFailure(replacement.binding, new ConnectionUnavailableError('unreachable'))).toBe( + 'other', + ); + closing.reject(new Error('old close failed')); + await expect(background()).resolves.toBe(replacement); + }); + + it('holds a sign-in miss for explicit recovery and does not let a pending replacement bypass it', async () => { + const client = await ClustersClient.connectInteractive(clusterId); + const pin = ClustersClient.getLastVerifiedIdentity(clusterId); + const credentials = CredentialCache.getCredentials(clusterId); + ClustersClient.reportFailure(client.binding, new MongoNotConnectedError('driver closed')); + const handshake = pauseNextConnect(); + const pending = ClustersClient.getClient(clusterId); + await handshake.started; + + expect(ClustersClient.reportFailure(client.binding, new EntraSignInRequiredError('noSession'))).toBe( + 'signInRequired', + ); + handshake.resolve(); + await expect(pending).rejects.toMatchObject({ reason: 'signInRequired' }); + await expect(ClustersClient.getClient(clusterId)).rejects.toMatchObject({ reason: 'signInRequired' }); + expect(ClustersClient.getBinding(clusterId)).toBe(client.binding); + expect(ClustersClient.getLastVerifiedIdentity(clusterId)).toBe(pin); + expect(CredentialCache.getCredentials(clusterId)).toBe(credentials); + expect(mockConnect).toHaveBeenCalledTimes(2); + + await ClustersClient.deleteClient(clusterId); + const recovered = await ClustersClient.getClient(clusterId); + expect(recovered.binding).toEqual({ ...client.binding, generation: client.generation + 1 }); + }); + + it('evicts rejected clients without silently retrying or losing the verified Entra settings', async () => { + const client = await ClustersClient.connectInteractive(clusterId); + const settings = CredentialCache.getCredentials(clusterId); + const identity = ClustersClient.getLastVerifiedIdentity(clusterId); + const error = new MongoServerError({ code: 18 }); + + expect(ClustersClient.reportFailure(client.binding, error)).toBe('credentialsRejected'); + expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); + expect(mockClose).toHaveBeenCalledExactlyOnceWith(true); + expect(CredentialCache.getCredentials(clusterId)).toBe(settings); + expect(ClustersClient.getLastVerifiedIdentity(clusterId)).toBe(identity); + await expect(ClustersClient.getClient(clusterId)).rejects.toMatchObject({ reason: 'credentialsRejected' }); + await expect(ClustersClient.getClient(clusterId, undefined, undefined, 'treeChildren', { + background: true, + })).rejects.toMatchObject({ reason: 'credentialsRejected' }); + expect(MongoClient).toHaveBeenCalledOnce(); + + expect(ClustersClient.clearCredentialRejection(clusterId, ClustersClient.getEpoch(clusterId))).toBe(true); + const recovered = await ClustersClient.getClient(clusterId); + expect(recovered.binding).toEqual({ ...client.binding, generation: client.generation + 1 }); + expect(ClustersClient.reportFailure(client.binding, error)).toBeUndefined(); + expect(ClustersClient.getBinding(clusterId)).toBe(recovered.binding); + }); + + it('does not let recovery from a credential rejection clear a newer Disconnect', async () => { + const client = await ClustersClient.connectInteractive(clusterId); + ClustersClient.reportFailure(client.binding, new MongoServerError({ code: 18 })); + const epoch = ClustersClient.getEpoch(clusterId); + ClustersClient.latch(clusterId, 'userDisconnected'); + + expect(ClustersClient.clearCredentialRejection(clusterId, epoch)).toBe(false); + expect(ClustersClient.clearCredentialRejection(clusterId, ClustersClient.getEpoch(clusterId))).toBe(false); + await expect(ClustersClient.getClient(clusterId)).rejects.toMatchObject({ reason: 'userDisconnected' }); + expect(MongoClient).toHaveBeenCalledOnce(); + }); + + it('uses the resolved binding, preserves nonterminal errors and returns terminal unavailability without replay', async () => { + const old = await ClustersClient.connectInteractive(clusterId); + poolEvents.emit('topologyClosed'); + const client = await ClustersClient.getClient(clusterId); + const resolveClient = vi.fn(async (): Promise => client); + const network = Object.freeze(new MongoNetworkError('tunnel refused')); + const op = vi.fn<() => Promise>().mockRejectedValueOnce(network); + resolveClient.mockRejectedValueOnce(new ConnectionUnavailableError('unreachable')); + await expect(runWithClient(old.binding, op, { resolveClient, background: true })).resolves.toEqual({ + unavailable: { reason: 'unreachable' }, + }); + expect(op).not.toHaveBeenCalled(); + + await expect(runWithClient(old.binding, op, { resolveClient, background: true })).rejects.toBe(network); + expect(resolveClient).toHaveBeenLastCalledWith(old.binding, { background: true }); + expect(op).toHaveBeenCalledExactlyOnceWith(client); + expect(await ClustersClient.getClient(clusterId)).toBe(client); + + op.mockRejectedValueOnce(new EntraIdentityMismatchError()); + await expect(runWithClient(old.binding, op, { resolveClient })).resolves.toEqual({ + unavailable: { reason: 'identityChanged' }, + }); + expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); + expect(op).toHaveBeenCalledTimes(2); + }); + it('binds Entra to the original cached URI and the verified identity, even if credentials change during startup', async () => { const originalUri = 'mongodb+srv://original.example.com/database?authSource=admin'; const driverUri = 'mongodb://localhost:27018/database'; diff --git a/src/documentdb/ClustersClient.ts b/src/documentdb/ClustersClient.ts index 51bbb8d32..f64979c97 100644 --- a/src/documentdb/ClustersClient.ts +++ b/src/documentdb/ClustersClient.ts @@ -50,6 +50,7 @@ import { createAuthHandler } from './auth/createAuthHandler'; import { EntraSignInRequiredError } from './auth/entraErrors/entraCallbackErrors'; import { getAzureHostSuffix } from './auth/oidcAllowedHosts'; import { QueryInsightsApis, type ExplainVerbosity } from './client/QueryInsightsApis'; +import { classifyConnectionFailure, type ConnectionFailure } from './connectionFailures'; import { computeConnectionFingerprint, type ConnectionPrincipal } from './connectionFingerprint'; import { ConnectionUnavailableError, type ConnectionUnavailableReason } from './ConnectionUnavailableError'; import { CredentialCache, type CachedClusterCredentials } from './CredentialCache'; @@ -307,6 +308,17 @@ export class ClustersClient { return ClustersClient._latches.get(clusterId); } + public static clearCredentialRejection(clusterId: string, epoch: number): boolean { + if ( + ClustersClient.getEpoch(clusterId) !== epoch || + ClustersClient.getLatchReason(clusterId) !== 'credentialsRejected' + ) { + return false; + } + ClustersClient.unlatch(clusterId); + return true; + } + #startupCredentials: Readonly; #verifiedIdentity: VerifiedIdentity; private _fingerprint: string; @@ -314,6 +326,7 @@ export class ClustersClient { private _createdAt: number; private _mongoClient: MongoClient; private _closed = false; + private _replacement?: 'replaceOnNextForeground' | 'replaceOnRecovery'; private _interactiveEntraStartupId?: string; private _llmEnhancedFeatureApis: llmEnhancedFeatureApis | null = null; private _queryInsightsApis: QueryInsightsApis | null = null; @@ -758,7 +771,10 @@ export class ClustersClient { const epoch = ClustersClient.getEpoch(clusterId); const cached = ClustersClient._clients.get(clusterId); - if (cached && !cached._closed) { + if (cached?._replacement === 'replaceOnRecovery') { + throw new ConnectionUnavailableError('signInRequired'); + } + if (cached?.canReuse()) { const id = cached.connectionCorrelationId; if (id) { onStartup?.(id); @@ -770,12 +786,12 @@ export class ClustersClient { ext.outputChannel.debug(`[ClustersClient] startup=${id} wait canceled by user surface=extension`); throw new UserCancelledError('abortConnection'); } - if (!cached._closed) { + if (cached.canReuse()) { return cached; } } - // Until a replacement succeeds, the closed entry still pins the connection identity. + // Until a replacement succeeds, the old entry still pins the connection identity. const { id, promise } = ClustersClient.getOrStartClient( clusterId, epoch, @@ -787,7 +803,7 @@ export class ClustersClient { onStartup?.(id); try { const client = await waitForClient(promise, abortSignal, id); - if (epoch === ClustersClient.getEpoch(clusterId)) { + if (epoch === ClustersClient.getEpoch(clusterId) && client.canReuse()) { return client; } } catch (error) { @@ -817,7 +833,8 @@ export class ClustersClient { if (!credentials) { throw new ConnectionUnavailableError('credentialsMissing'); } - throw new MongoNotConnectedError(l10n.t('The connection is unavailable.')); + // This caller didn't run anything on a client. Don't treat this as a driver close. + throw new ConnectionUnavailableError('unreachable'); } if ( !allowInteractive && @@ -854,6 +871,9 @@ export class ClustersClient { const client = new ClustersClient(clusterId); try { await client.initClient(id, trigger, epoch, allowInteractive, expectedFingerprint); + if (client._closed) { + throw new MongoNotConnectedError(l10n.t('The connection is unavailable.')); + } } catch (error) { if (!(error instanceof UserCancelledError) && epoch === ClustersClient.getEpoch(clusterId)) { ClustersClient._lastFailedStartups.set(clusterId, id); @@ -873,6 +893,7 @@ export class ClustersClient { ); }); } else { + const previous = ClustersClient._clients.get(clusterId); const generation = (ClustersClient._generations.get(clusterId) ?? 0) + 1; client._binding = Object.freeze({ clusterId, fingerprint: client._fingerprint, generation }); client._createdAt = Date.now(); @@ -880,10 +901,58 @@ export class ClustersClient { ClustersClient._lastVerifiedIdentities.set(clusterId, Object.freeze({ ...client.#verifiedIdentity })); ClustersClient._clients.set(clusterId, client); ClustersClient._lastFailedStartups.delete(clusterId); + if (previous && !previous._closed) { + previous._closed = true; + void previous._mongoClient.close(true).catch(() => { + // Closing a retired driver must not affect its replacement. + }); + } } return client; } + private canReuse(): boolean { + return !this._closed && this._replacement === undefined; + } + + /** Reports an operation's failure against the generation that actually ran it. */ + public static reportFailure(binding: ConnectionBinding, error: unknown): ConnectionFailure['kind'] | undefined { + const { clusterId, fingerprint, generation } = binding; + const client = ClustersClient._clients.get(clusterId); + if ( + !client || + client.generation !== generation || + client.fingerprint !== fingerprint || + ClustersClient.getLatchReason(clusterId) + ) { + return undefined; + } + + const failure = classifyConnectionFailure(error, client.authMethod); + if (client._replacement === 'replaceOnRecovery') { + return failure.kind; + } + switch (failure.generation) { + case 'replaceOnNextForeground': + client._replacement = failure.generation; + break; + case 'replaceOnRecovery': + client._replacement = failure.generation; + // An already-started replacement must not bypass explicit recovery. + ClustersClient.invalidate(clusterId); + break; + case 'evict': + if (failure.kind === 'credentialsRejected') { + ClustersClient.latch(clusterId, 'credentialsRejected'); + } + void ClustersClient.deleteClient(clusterId).catch(() => { + ext.outputChannel.debug('[ClustersClient] failed to close an evicted client'); + }); + break; + } + return failure.kind; + } + /** * Retrieves cluster metadata for this client instance. * diff --git a/src/documentdb/auth/ManagedIdentityAuthHandler.test.ts b/src/documentdb/auth/ManagedIdentityAuthHandler.test.ts index e5a8bb7c4..503004071 100644 --- a/src/documentdb/auth/ManagedIdentityAuthHandler.test.ts +++ b/src/documentdb/auth/ManagedIdentityAuthHandler.test.ts @@ -15,6 +15,7 @@ import { type AuthPhaseObserver } from './authCallerPolicy'; import { buildAuthConnectionTarget } from './authConnectionTarget'; import { AuthMethodId } from './AuthMethod'; import * as tokenResources from './documentdbTokenResource'; +import { TokenCallbackError } from './entraErrors/entraCallbackErrors'; import { EntraErrorExplainer } from './entraErrors/EntraErrorExplainer'; import { getRecentEntraTokenFailure, @@ -341,16 +342,7 @@ describe('ManagedIdentityAuthHandler', () => { expect(getManagedIdentityAccessToken.mock.calls[0][3]).toBe(getManagedIdentityAccessToken.mock.calls[1][3]); }); - it('propagates the provider readable failure', async () => { - getManagedIdentityAccessToken.mockRejectedValue(new Error('More than one managed identity is available.')); - const handler = new ManagedIdentityAuthHandler(buildCredentials()); - - const { options } = await handler.configureAuth(); - - await expect(invokeOidcCallback(options)).rejects.toThrow(/more than one managed identity/i); - }); - - it('records failures only inside the deferred token callback and rethrows the same error', async (): Promise => { + it('wraps and records failures only inside the deferred token callback', async (): Promise => { const connectionString = 'mongodb://cluster.mongocluster.cosmos.azure.us/'; const handler = new ManagedIdentityAuthHandler( buildCredentials({ connectionString, connectionStringWithPassword: connectionString }), @@ -367,7 +359,10 @@ describe('ManagedIdentityAuthHandler', () => { expect(getRecentEntraTokenFailure('cluster-1')).toBeUndefined(); expect(getManagedIdentityAccessToken).not.toHaveBeenCalled(); - await expect(invokeOidcCallback(options)).rejects.toBe(error); + const callback = invokeOidcCallback(options); + await expect(callback).rejects.toBeInstanceOf(TokenCallbackError); + await expect(callback).rejects.toMatchObject({ authMethod: AuthMethodId.ManagedIdentity, cause: error }); + await expect(callback).rejects.not.toThrow(/AADSTS500011/); expect(startupProperties.entraFailureKind).toBe('tokenAcquisitionFailed'); expect(JSON.stringify(startupProperties)).not.toMatch(/cluster-1|AADSTS|https/); expect(getRecentEntraTokenFailure('cluster-1')).toEqual({ @@ -416,11 +411,12 @@ describe('ManagedIdentityAuthHandler', () => { surface: 'extension', startupProperties: failedProperties, }); - await expect(invokeOidcCallback(failed.options)).rejects.toBe(error); + const callbackError: unknown = await invokeOidcCallback(failed.options).catch((failure: unknown) => failure); + expect(callbackError).toMatchObject({ cause: error }); const failure = getRecentEntraTokenFailure('cluster-1'); expect(failure).toMatchObject({ cloudCategory: 'usgov', authMethod: 'managedIdentity' }); const diagnostics = new EntraErrorExplainer(); - expect(await diagnostics.explain({ clusterId: 'cluster-1', error })).toContain( + expect(await diagnostics.explain({ clusterId: 'cluster-1', error: callbackError })).toContain( 'Sign-in failed in Azure US Government', ); @@ -600,14 +596,18 @@ describe('ManagedIdentityAuthHandler', () => { const error = new Error('AADSTS700016: identity not found'); getManagedIdentityAccessToken.mockRejectedValueOnce(error); const events: string[] = []; + const onTokenFailed = vi.fn(() => { + events.push('tokenFailed'); + }); const handler = new ManagedIdentityAuthHandler(buildCredentials(), { interactive: false, - observer: recordingObserver(events), + observer: { ...recordingObserver(events), onTokenFailed }, }); const { options } = await handler.configureAuth(); expect(events).toEqual(['resolved:public:host:*.mongocluster.cosmos.azure.com']); - await expect(invokeOidcCallback(options)).rejects.toBe(error); + await expect(invokeOidcCallback(options)).rejects.toMatchObject({ cause: error }); + expect(onTokenFailed).toHaveBeenCalledExactlyOnceWith(error); expect(events).toEqual([ 'resolved:public:host:*.mongocluster.cosmos.azure.com', 'tokenStarted', @@ -655,7 +655,7 @@ describe('ManagedIdentityAuthHandler', () => { await expect(invokeOidcCallback(options)).resolves.toMatchObject({ accessToken: 'a-token' }); const error = new Error('token failure'); getManagedIdentityAccessToken.mockRejectedValueOnce(error); - await expect(invokeOidcCallback(options)).rejects.toBe(error); + await expect(invokeOidcCallback(options)).rejects.toMatchObject({ cause: error }); }); }); }); diff --git a/src/documentdb/auth/ManagedIdentityAuthHandler.ts b/src/documentdb/auth/ManagedIdentityAuthHandler.ts index aaad4b268..265d7f6d9 100644 --- a/src/documentdb/auth/ManagedIdentityAuthHandler.ts +++ b/src/documentdb/auth/ManagedIdentityAuthHandler.ts @@ -12,6 +12,7 @@ import { type CachedClusterCredentials } from '../CredentialCache'; import { withTokenAcquisitionTiming, type ConnectionStartupTimings } from '../utils/ConnectionStartupTimings'; import { notifyAuthPhaseObserver, type AuthCallerPolicy, type AuthPhaseObserver } from './authCallerPolicy'; import { type AuthHandler, type AuthHandlerResponse } from './AuthHandler'; +import { AuthMethodId } from './AuthMethod'; import { resolveManagedIdentityTokenResource, TokenResourceResolutionError } from './documentdbTokenResource'; import { evaluateEntraDestinationFromSettings, getEntraCustomHostnameSuffix } from './entraDestinationSettings'; import { classifyEntraError } from './entraErrors/classifyEntraError'; @@ -100,6 +101,7 @@ export class ManagedIdentityAuthHandler implements AuthHandler { const configuration = buildOidcClientConfiguration({ connectionString, policy, + callbackAuthMethod: AuthMethodId.ManagedIdentity, oidcCallback: async (): Promise => { const currentDecision = evaluateEntraDestinationFromSettings(connectionString); traceEntraDestination(currentDecision, this.tokenCorrelationId, traceContext); diff --git a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts index cda5b17d7..b767942c3 100644 --- a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts +++ b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts @@ -18,6 +18,7 @@ import { type AuthPhaseObserver, } from './authCallerPolicy'; import { type AuthHandler, type AuthHandlerResponse, type VerifiedEntraIdentity } from './AuthHandler'; +import { AuthMethodId } from './AuthMethod'; import { resolveInteractiveTokenResource, TokenResourceResolutionError } from './documentdbTokenResource'; import { evaluateEntraDestinationFromSettings, getEntraCustomHostnameSuffix } from './entraDestinationSettings'; import { classifyEntraError } from './entraErrors/classifyEntraError'; @@ -227,6 +228,7 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { const configuration = buildOidcClientConfiguration({ connectionString, policy, + callbackAuthMethod: AuthMethodId.MicrosoftEntraID, oidcCallback: async (_params: OIDCCallbackParams): Promise => { const currentInvocation = ++invocation; let observation: EntraTokenLookupObservation = { outcome: 'failed' }; @@ -263,7 +265,7 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { observation = { outcome: 'noSession' }; throw error; } - if (observation.outcome === 'identityMismatch') { + if (error instanceof EntraIdentityMismatchError || error instanceof EntraDestinationRejectedError) { throw error; } recordEntraTokenFailure(clusterId, { @@ -271,7 +273,7 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { authMethod: 'interactive', ruleId: classifyEntraError(error instanceof Error ? error.message : String(error))?.ruleId, }); - throw new TokenCallbackError(error); + throw error; } finally { traceAuthFlow( 'interactiveEntra.oidcCallback', diff --git a/src/documentdb/auth/oidcClientOptions.ts b/src/documentdb/auth/oidcClientOptions.ts index 9cc953536..aa1a89d4e 100644 --- a/src/documentdb/auth/oidcClientOptions.ts +++ b/src/documentdb/auth/oidcClientOptions.ts @@ -6,10 +6,16 @@ import { type MongoClientOptions, type OIDCCallbackFunction, type OIDCResponse } from 'mongodb'; import { checkServerIdentity, type PeerCertificate } from 'tls'; import { DocumentDBConnectionString } from '../utils/DocumentDBConnectionString'; +import { + EntraIdentityMismatchError, + EntraSignInRequiredError, + TokenCallbackError, +} from './entraErrors/entraCallbackErrors'; import { EntraDestinationRejectedError, evaluateEntraDestination, isEntraDestinationHostAllowed, + isEntraDestinationRejectedError, } from './oidcAllowedHosts'; const TLS_BYPASS_KEYS = new Set([ @@ -97,6 +103,7 @@ export function buildOidcClientConfiguration(input: { connectionString: string; policy: OidcDestinationPolicy; oidcCallback: OIDCCallbackFunction; + callbackAuthMethod?: TokenCallbackError['authMethod']; baseOptions?: MongoClientOptions; }): { connectionString: string; @@ -149,10 +156,23 @@ export function buildOidcClientConfiguration(input: { authMechanismProperties: { ALLOWED_HOSTS: [...input.policy.allowedHostPatterns], OIDC_CALLBACK: async (params): Promise => { - input.policy.assertAllowed(); - const response = await input.oidcCallback(params); - input.policy.assertAllowed(); - return response; + try { + input.policy.assertAllowed(); + const response = await input.oidcCallback(params); + input.policy.assertAllowed(); + return response; + } catch (error) { + if ( + input.callbackAuthMethod === undefined || + error instanceof EntraSignInRequiredError || + error instanceof EntraIdentityMismatchError || + error instanceof TokenCallbackError || + isEntraDestinationRejectedError(error) + ) { + throw error; + } + throw new TokenCallbackError(error, input.callbackAuthMethod); + } }, }, tls: true, diff --git a/src/documentdb/runWithClient.ts b/src/documentdb/runWithClient.ts new file mode 100644 index 000000000..5bcf53a7b --- /dev/null +++ b/src/documentdb/runWithClient.ts @@ -0,0 +1,65 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { ClustersClient, type ConnectionBinding } from './ClustersClient'; +import { classifyConnectionFailure, type ConnectionFailure } from './connectionFailures'; +import { ConnectionUnavailableError, type ConnectionUnavailableReason } from './ConnectionUnavailableError'; + +interface ResolveOptions { + readonly background?: boolean; +} + +interface RunOptions extends ResolveOptions { + resolveClient(binding: ConnectionBinding, options: ResolveOptions): Promise; +} + +interface Unavailable { + readonly unavailable: { readonly reason: ConnectionUnavailableReason }; +} + +function unavailableFor(kind: ConnectionFailure['kind'] | undefined): Unavailable | undefined { + switch (kind) { + case 'signInRequired': + case 'credentialsRejected': + case 'credentialsMissing': + case 'identityChanged': + return { unavailable: { reason: kind } }; + default: + return undefined; + } +} + +/** @internal The bound resolver and conversion to a surface response are supplied by WI-6. */ +export async function runWithClient( + binding: ConnectionBinding, + op: (client: ClustersClient) => Promise, + { resolveClient, background }: RunOptions, +): Promise { + let client: ClustersClient; + try { + client = await resolveClient(binding, { background }); + } catch (error) { + // No operation ran, so there is no client generation to report against. + const unavailable = + error instanceof ConnectionUnavailableError + ? { unavailable: { reason: error.reason } } + : unavailableFor(classifyConnectionFailure(error).kind); + if (unavailable) { + return unavailable; + } + throw error; + } + + try { + return await op(client); + } catch (error) { + // Resolution can advance the generation without changing the surface's identity. + const unavailable = unavailableFor(ClustersClient.reportFailure(client.binding, error)); + if (unavailable) { + return unavailable; + } + throw error; + } +} From 7c515413095eecc9ee6c147d983b1f011b23efa2 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 13:57:27 +0000 Subject: [PATCH 04/29] docs: reuse the existing latch for explicit rejection recovery Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../features/connection-lifecycle/README.md | 1 + .../features/connection-lifecycle/decisions.md | 12 ++++++++++++ .../connection-lifecycle/iterations/01-dev-plan.md | 7 +++++++ 3 files changed, 20 insertions(+) diff --git a/docs/ai-and-plans/features/connection-lifecycle/README.md b/docs/ai-and-plans/features/connection-lifecycle/README.md index 8d5207066..f32fb1728 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/README.md +++ b/docs/ai-and-plans/features/connection-lifecycle/README.md @@ -83,6 +83,7 @@ See [decisions.md](./decisions.md): - 0012 a minimal lifecycle design: no state machine, one epoch, no prompts in `getClient`, one-step teardown; - 0013 corrections to 0012: latch before a credential save, epoch checks on replies, bindings carried through handoffs, an operation wrapper, folder deletion runs teardown. - 0014 retain in-memory settings for explicit sign-in recovery after verified Entra rejection. +- 0015 use the existing latch to block startup after authentication rejection until explicit recovery. ## Timeline diff --git a/docs/ai-and-plans/features/connection-lifecycle/decisions.md b/docs/ai-and-plans/features/connection-lifecycle/decisions.md index e83c02dc9..2f6b7a190 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/decisions.md +++ b/docs/ai-and-plans/features/connection-lifecycle/decisions.md @@ -26,6 +26,7 @@ created: 2026-11-19 | 0012 | Keep the lifecycle design minimal: no state machine, one epoch, no prompts in getClient, one-step teardown | Accepted | Operator: approved every proposed simplification | 2026-11-19 | — | | 0013 | Correct the minimal design where it lost edits, identity or recovery: latch before save, epoch checks | Accepted (modifies 0012) | Operator: "update the plan" after the omissions review | 2026-11-19 | — | | 0014 | Keep in-memory connection settings after a rejection for a verified Entra identity | Accepted | Operator selected A to make sign-in recovery smoother | 2026-11-23 | Yes; WI-5 previously said to delete the entry | +| 0015 | Use the existing latch to block startup after authentication rejection | Accepted | Operator selected A; keep the approach simple and pragmatic | 2026-11-23 | Yes; expands the existing latch rather than adding a second hold | > Entries below are **semantically** immutable: append new entries rather than rewriting old ones, > and record reversals as a new entry plus a status change above. Heading text is frozen once @@ -412,3 +413,14 @@ This does not retain the rejected token, write anything to persistent storage, c checks, or start a silent retry. Native authentication and RU key handling are unchanged. The explicit sign-in path still checks the epoch after prompting and never moves an open surface to a different identity. + +## 0015. Use the existing latch to block startup after authentication rejection + +Evicting a rejected client is not enough: a subsequent operation could immediately start a new +one with the same settings. Set the existing in-memory latch to `credentialsRejected` before +evicting the rejected generation. The matching explicit recovery can clear that reason only if +the epoch still matches. It cannot clear a latch set by Disconnect, Remove or a credential change. + +The operator chose to reuse the existing latch rather than introduce a separate authentication +hold, keeping one place to check for an unavailable connection. The rejection latch uses the +existing epoch and does not add a subscription, new persistence, or a retry loop. 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 ed50ecd3f..a8dbe8a1e 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 @@ -414,6 +414,8 @@ a checkpoint changes them. Only the explicit Connect and Reconnect actions clear the latch, plus one internal case: an identity-changing credential update whose save reached nothing clears the latch it set (WI-7 step 5). New tasks and resource leases are refused while the latch is set. + A `credentialsRejected` latch blocks startup until the matching explicit recovery clears it + with an unchanged epoch (decision 0015). That recovery cannot clear a teardown latch. - **One epoch:** a per-cluster counter that `invalidate` increases **synchronously** on every latch, unlatch, eviction and teardown. A startup publishes only if the epoch is unchanged. Every recovery command (Retry, Sign in again, Reconnect) captures the epoch **before** its first `await`, and applies @@ -1293,6 +1295,11 @@ shim (0005). - **CP-2 revision verified:** Removed the unproducible freshness inputs. The contract test now sends the exact final code 18 from the driver workflow through the classifier. Case 1 passed: build and 31 focused tests across classification, the driver contract, and the Entra explainer. +- **CP-2 / OC-2, accepted:** Reuse the existing latch for `credentialsRejected` rather than + adding a separate hold. Eviction must not let an ordinary operation open another client with + rejected settings. Only the matching explicit recovery can clear the rejection, and only if + its epoch is current. The operator preferred the simpler option and asked to record + [decision 0015](../decisions.md#0015-use-the-existing-latch-to-block-startup-after-authentication-rejection). --- From d4412690bdbc8778fd2622982232670cf3495015 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 14:14:16 +0000 Subject: [PATCH 05/29] feat: recover tree connections through explicit retry and sign-in (WI-5) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../retryAuthentication.test.ts | 126 +++++++- .../retryAuthentication.ts | 93 +++++- src/commands/signInAgain/signInAgain.test.ts | 104 +++++++ src/commands/signInAgain/signInAgain.ts | 114 +++++++ .../updateConnectionString/ExecuteStep.ts | 9 + .../UpdateCSWizardContext.ts | 1 + .../updateConnectionString.test.ts | 6 +- .../updateConnectionString.ts | 28 +- src/commands/updateCredentials/ExecuteStep.ts | 10 + .../UpdateCredentialsWizardContext.ts | 2 + .../updateCredentials.test.ts | 2 + .../updateCredentials/updateCredentials.ts | 31 +- src/documentdb/ClustersClient.test.ts | 21 ++ src/documentdb/ClustersClient.ts | 71 ++++- src/documentdb/ClustersExtension.ts | 5 + .../auth/MicrosoftEntraIDAuthHandler.ts | 7 +- src/documentdb/connectionFailures.ts | 3 + .../discovery-tree/AtlasClusterItem.test.ts | 3 + .../discovery-tree/AtlasClusterItem.ts | 4 +- .../documentdb/MongoRUResourceItem.ts | 8 +- .../documentdb/DocumentDBResourceItem.ts | 4 +- .../discovery-tree/vm/AzureVMResourceItem.ts | 4 +- .../documentdb/KubernetesResourceItem.test.ts | 3 + .../documentdb/KubernetesResourceItem.ts | 6 +- src/tree/BaseExtendedTreeDataProvider.ts | 7 + .../documentdb/VCoreResourceItem.ts | 4 +- .../mongo-ru/RUCoreResourceItem.ts | 8 +- .../DocumentDBClusterItem.test.ts | 15 +- .../connections-view/DocumentDBClusterItem.ts | 25 +- .../LocalQuickStart/LocalQuickStartItem.ts | 7 +- src/tree/documentdb/ClusterItemBase.test.ts | 41 ++- src/tree/documentdb/ClusterItemBase.ts | 284 ++++++++++-------- 32 files changed, 884 insertions(+), 172 deletions(-) create mode 100644 src/commands/signInAgain/signInAgain.test.ts create mode 100644 src/commands/signInAgain/signInAgain.ts diff --git a/src/commands/retryAuthentication/retryAuthentication.test.ts b/src/commands/retryAuthentication/retryAuthentication.test.ts index e0c080d82..60c81da13 100644 --- a/src/commands/retryAuthentication/retryAuthentication.test.ts +++ b/src/commands/retryAuthentication/retryAuthentication.test.ts @@ -5,6 +5,12 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { UserCancelledError } from '@microsoft/vscode-azext-utils'; +import { window } from 'vscode'; +import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; +import { ClustersClient } from '../../documentdb/ClustersClient'; +import { CredentialCache } from '../../documentdb/CredentialCache'; +import { type ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; import { ext } from '../../extensionVariables'; import { retryAuthentication } from './retryAuthentication'; @@ -30,17 +36,28 @@ vi.mock('../../extensionVariables', () => ({ })); vi.mock('../../documentdb/ClustersClient', () => ({ + addEstablishedConnectionContext: vi.fn(), ClustersClient: { + getEpoch: vi.fn(() => 0), + getLatchReason: vi.fn(), + clearCredentialRejection: vi.fn(), + deleteClient: vi.fn(), getLastFailedStartupCorrelationId: vi.fn((clusterId: string) => clusterId === 'failed-cluster' ? 'failed-attempt' : undefined, ), }, })); -vi.mock('vscode', () => ({ +vi.mock('../../documentdb/CredentialCache', () => ({ + CredentialCache: { getCredentials: vi.fn(), deleteCredentials: vi.fn(), setAuthCredentials: vi.fn() }, +})); + +vi.mock('vscode', async (importOriginal) => ({ + ...(await importOriginal()), l10n: { t: vi.fn((value: string) => value), }, + window: { showErrorMessage: vi.fn() }, })); describe('retryAuthentication', () => { @@ -124,4 +141,111 @@ describe('retryAuthentication', () => { }), ).rejects.toThrow('Unsupported view for an authentication retry.'); }); + + function ruNode(): Parameters[1] & { + readReplacementKey: ReturnType>>; + } { + return { + id: 'discoveryView/azure/ru', + cluster: { clusterId: 'ru' }, + getTreeItem, + readReplacementKey: vi.fn>(), + }; + } + + it('discards the old RU key and installs the single replacement read', async (): Promise => { + const node = ruNode(); + const nativeAuthConfig = { connectionUser: 'test', connectionPassword: 'new-key' }; + node.readReplacementKey.mockResolvedValue({ + connectionString: 'mongodb://test', availableAuthMethods: [AuthMethodId.NativeAuth], nativeAuthConfig, + }); + vi.mocked(ClustersClient.getLatchReason).mockReturnValueOnce('credentialsRejected'); + vi.mocked(ClustersClient.clearCredentialRejection).mockReturnValueOnce(true); + + await retryAuthentication(actionContext as never, node); + + expect(CredentialCache.deleteCredentials).toHaveBeenCalledExactlyOnceWith('ru'); + expect(node.readReplacementKey).toHaveBeenCalledTimes(1); + expect(CredentialCache.setAuthCredentials).toHaveBeenCalledExactlyOnceWith( + 'ru', AuthMethodId.NativeAuth, 'mongodb://test', nativeAuthConfig, + ); + expect(ext.discoveryBranchDataProvider.refresh).toHaveBeenCalledExactlyOnceWith(node); + }); + + it.each([ + ['discoveryView', AuthMethodId.NativeAuth, true], + ['discoveryView', AuthMethodId.MicrosoftEntraID, false], + ['connectionsView', AuthMethodId.NativeAuth, false], + ] as const)( + 'allows the existing discovery credential setup only for Native auth (%s, %s)', + async (view, authMechanism, shouldRefresh): Promise => { + const node = { id: `${view}/test`, cluster: { clusterId: 'test' }, getTreeItem }; + vi.mocked(CredentialCache.getCredentials).mockReturnValueOnce({ + clusterId: 'test', + connectionString: 'mongodb://test', + authMechanism, + }); + vi.mocked(ClustersClient.getLatchReason).mockReturnValueOnce('credentialsRejected'); + if (shouldRefresh) { + vi.mocked(ClustersClient.clearCredentialRejection).mockReturnValueOnce(true); + } + + await retryAuthentication(actionContext as never, node); + + if (shouldRefresh) { + expect(CredentialCache.deleteCredentials).toHaveBeenCalledExactlyOnceWith('test'); + expect(CredentialCache.deleteCredentials).toHaveBeenCalledBefore( + vi.mocked(ext.discoveryBranchDataProvider.refresh), + ); + expect(ext.discoveryBranchDataProvider.refresh).toHaveBeenCalledExactlyOnceWith(node); + } else { + expect(ClustersClient.clearCredentialRejection).not.toHaveBeenCalled(); + expect(CredentialCache.deleteCredentials).not.toHaveBeenCalled(); + expect(ext.discoveryBranchDataProvider.refresh).not.toHaveBeenCalled(); + expect(ext.connectionsBranchDataProvider.refresh).not.toHaveBeenCalled(); + } + }, + ); + + it('abandons a successful key read if the epoch changed', async (): Promise => { + const node = ruNode(); + node.readReplacementKey.mockResolvedValue({ connectionString: 'mongodb://test', availableAuthMethods: [] }); + vi.mocked(ClustersClient.getLatchReason).mockReturnValueOnce('credentialsRejected'); + vi.mocked(ClustersClient.getEpoch).mockReturnValueOnce(1).mockReturnValueOnce(2); + await retryAuthentication(actionContext as never, node); + expect(ClustersClient.clearCredentialRejection).not.toHaveBeenCalled(); + expect(CredentialCache.setAuthCredentials).not.toHaveBeenCalled(); + expect(ext.discoveryBranchDataProvider.refresh).not.toHaveBeenCalled(); + }); + + it('does not refresh an old Retry after the client was replaced while its close was pending', async (): Promise => { + const node = { + id: 'connectionsView/stale', cluster: { clusterId: 'stale' }, getTreeItem, + lastConnectionFailureKind: 'clientClosed' as const, + }; + vi.mocked(ClustersClient.getEpoch).mockReturnValueOnce(0).mockReturnValueOnce(1).mockReturnValueOnce(2); + vi.mocked(ClustersClient.deleteClient).mockResolvedValueOnce(undefined); + + await retryAuthentication(actionContext as never, node); + + expect(ClustersClient.deleteClient).toHaveBeenCalledExactlyOnceWith('stale'); + expect(ext.connectionsBranchDataProvider.refresh).not.toHaveBeenCalled(); + }); + + it.each([new UserCancelledError(), Object.assign(new Error('ARM rejected access'), { statusCode: 401 })])( + 'distinguishes ARM sign-in failure from dismissal and keeps the rejection latch', + async (error): Promise => { + const node = ruNode(); + node.readReplacementKey.mockRejectedValue(error); + vi.mocked(ClustersClient.getLatchReason).mockReturnValueOnce('credentialsRejected'); + await expect(retryAuthentication(actionContext as never, node)).rejects.toBe(error); + if (error instanceof UserCancelledError) { + expect(window.showErrorMessage).not.toHaveBeenCalled(); + } else { + expect(window.showErrorMessage).toHaveBeenCalledWith('Azure sign-in needed', expect.anything()); + } + expect(ClustersClient.clearCredentialRejection).not.toHaveBeenCalled(); + expect(ext.discoveryBranchDataProvider.refresh).not.toHaveBeenCalled(); + }, + ); }); diff --git a/src/commands/retryAuthentication/retryAuthentication.ts b/src/commands/retryAuthentication/retryAuthentication.ts index 9389931b0..48a917026 100644 --- a/src/commands/retryAuthentication/retryAuthentication.ts +++ b/src/commands/retryAuthentication/retryAuthentication.ts @@ -3,14 +3,19 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { type IActionContext } from '@microsoft/vscode-azext-utils'; -import { l10n } from 'vscode'; -import { ClustersClient } from '../../documentdb/ClustersClient'; +import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext-utils'; +import { l10n, window } from 'vscode'; +import { classifyResolutionFailure } from '../../connectionDiagnostics/checks/resolveTarget'; +import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; +import { addEstablishedConnectionContext, ClustersClient } from '../../documentdb/ClustersClient'; +import { CredentialCache } from '../../documentdb/CredentialCache'; import { inferViewIdFromTreeId, Views } from '../../documentdb/Views'; import { ext } from '../../extensionVariables'; import { type TreeElement } from '../../tree/TreeElement'; import { type TreeElementWithContextValue } from '../../tree/TreeElementWithContextValue'; import { isTreeElementWithExplicitReload } from '../../tree/TreeElementWithExplicitReload'; +import { type ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; +import { ConnectionSourceUnavailableError } from '../../tree/documentdb/diagnosticCredentialRead'; const containsDelimited = (fullContext: string | undefined, value: string): boolean => { if (!fullContext) { @@ -19,7 +24,10 @@ const containsDelimited = (fullContext: string | undefined, value: string): bool return new RegExp(`\\b${value}\\b`, 'i').test(fullContext); }; -type RetryableTreeNode = TreeElement & Partial; +type RetryableTreeNode = TreeElement & + Partial> & { + readonly cluster?: { readonly clusterId: string }; + }; function getViewId(node: RetryableTreeNode): Views | undefined { if (containsDelimited(node.contextValue, Views.ConnectionsView)) { @@ -66,6 +74,83 @@ export async function retryAuthentication(context: IActionContext, node: Retryab context.telemetry.properties.failedStartupCorrelationId = failedStartupCorrelationId; } + const clusterId = node.cluster?.clusterId; + if (clusterId) { + let epoch = ClustersClient.getEpoch(clusterId); + const latch = ClustersClient.getLatchReason(clusterId); + const kind = latch === 'credentialsRejected' ? latch : node.lastConnectionFailureKind; + if (latch && latch !== 'credentialsRejected') { + return; + } + addEstablishedConnectionContext(context.telemetry, clusterId); + if (kind) { + context.telemetry.properties.connectionFailureKind = kind; + } + if (latch === 'credentialsRejected') { + if (!node.readReplacementKey) { + const view = getViewId(node); + const credentials = CredentialCache.getCredentials(clusterId); + // Native discovery nodes have no saved-credential editor. Retry through the + // existing provider flow, but never with the rejected cached credentials. + if ( + (view !== Views.DiscoveryView && view !== Views.AzureResourcesView) || + !credentials || + (credentials.authMechanism ?? AuthMethodId.NativeAuth) !== AuthMethodId.NativeAuth || + !ClustersClient.clearCredentialRejection(clusterId, epoch) + ) { + return; + } + CredentialCache.deleteCredentials(clusterId); + refreshAuthenticationNode(node); + return; + } + context.telemetry.maskEntireErrorMessage = true; + CredentialCache.deleteCredentials(clusterId); + let credentials: Awaited>>; + try { + credentials = await node.readReplacementKey(context); + } catch (error) { + if (ClustersClient.getEpoch(clusterId) !== epoch) { + return; + } + if (error instanceof UserCancelledError) { + throw error; + } + const finding = classifyResolutionFailure(new ConnectionSourceUnavailableError('azure', error)); + const signInNeeded = finding.code === 'target.sourceInaccessible' && finding.data?.reason === 'signInRequired'; + context.telemetry.properties.azureKeyReadFailure = signInNeeded ? 'signInRequired' : 'other'; + context.errorHandling.suppressDisplay = true; + void window.showErrorMessage( + signInNeeded ? l10n.t('Azure sign-in needed') : l10n.t('Could not read the database key from Azure.'), + { modal: true, detail: signInNeeded ? l10n.t('Sign in to Azure and try Retry again.') : l10n.t('Check access to the Azure resource and try again.') }, + ); + throw error; + } + if (ClustersClient.getEpoch(clusterId) !== epoch) { + return; + } + // One fresh ARM read per explicit click. A subsequent database rejection re-latches in + // the tree; it cannot start another ARM read. + if (credentials.nativeAuthConfig?.connectionPassword && + ClustersClient.clearCredentialRejection(clusterId, epoch)) { + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.NativeAuth, credentials.connectionString, credentials.nativeAuthConfig); + } else { + return; + } + } else if (kind === 'signInRequired' || kind === 'credentialsRejected' || kind === 'clientClosed') { + const closing = ClustersClient.deleteClient(clusterId); + epoch = ClustersClient.getEpoch(clusterId); + await closing; + if (ClustersClient.getEpoch(clusterId) !== epoch) { + return; + } + } + } + + refreshAuthenticationNode(node); +} + +export function refreshAuthenticationNode(node: RetryableTreeNode): void { const contextValue = node.contextValue; const viewId = getViewId(node); diff --git a/src/commands/signInAgain/signInAgain.test.ts b/src/commands/signInAgain/signInAgain.test.ts new file mode 100644 index 000000000..e4a419f6c --- /dev/null +++ b/src/commands/signInAgain/signInAgain.test.ts @@ -0,0 +1,104 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext-utils'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import * as vscode from 'vscode'; +import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; +import { getEntraSession } from '../../documentdb/auth/entraSession'; +import { ClustersClient } from '../../documentdb/ClustersClient'; +import { CredentialCache } from '../../documentdb/CredentialCache'; +import { signInAgain } from './signInAgain'; + +const pin = { kind: 'entra', providerId: 'microsoft', accountId: 'pinned', accountLabel: 'Pinned', tenantId: 'tenant' } as const; +const clusterId = 'cluster'; + +vi.mock('../../documentdb/ClustersClient', () => ({ + addEstablishedConnectionContext: vi.fn(), + ClustersClient: { + getEpoch: vi.fn(() => 1), + getLatchReason: vi.fn(() => 'credentialsRejected'), + getLastVerifiedIdentity: vi.fn(() => pin), + startAfterSignIn: vi.fn(), + getExistingClient: vi.fn(), + }, +})); +vi.mock('../../documentdb/auth/entraSession', () => ({ getEntraSession: vi.fn() })); +vi.mock('../../documentdb/auth/MicrosoftEntraIDAuthHandler', () => ({ + MicrosoftEntraIDAuthHandler: class { + public async configureAuth( + _timings: undefined, + _trace: undefined, + acquire: typeof getEntraSession, + ): Promise { + const session = await acquire({ + mode: 'forceNew', providerId: pin.providerId, resource: 'scope', tenantId: pin.tenantId, + account: { id: pin.accountId, label: pin.accountLabel }, + }); + return { verifiedIdentity: { ...pin, accountId: session?.account.id } }; + } + }, +})); +vi.mock('../retryAuthentication/retryAuthentication', () => ({ refreshAuthenticationNode: vi.fn() })); +vi.mock('../../documentdb/showClusterConnectFailure', () => ({ showClusterConnectFailure: vi.fn() })); + +function actionContext(): IActionContext { + return { telemetry: { properties: {}, measurements: {} }, errorHandling: {} } as IActionContext; +} + +describe('signInAgain', () => { + beforeEach(() => { + vi.clearAllMocks(); + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.MicrosoftEntraID, 'mongodb://test', undefined, + undefined, { tenantId: pin.tenantId }); + }); + + it.each([ + { id: pin.accountId, label: pin.accountLabel }, + { id: 'different-account', label: 'Explicitly selected in VS Code' }, + ])('requests one pinned forced session and forwards the accepted account', async (account): Promise => { + vi.mocked(getEntraSession).mockResolvedValueOnce({ account } as vscode.AuthenticationSession); + vi.mocked(ClustersClient.startAfterSignIn).mockResolvedValueOnce({} as ClustersClient); + + await signInAgain(actionContext(), { clusterId }); + + expect(getEntraSession).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ + mode: 'forceNew', tenantId: pin.tenantId, providerId: pin.providerId, + account: { id: pin.accountId, label: pin.accountLabel }, + })); + expect(ClustersClient.startAfterSignIn).toHaveBeenCalledExactlyOnceWith( + clusterId, 1, CredentialCache.getCredentials(clusterId), + { verifiedIdentity: expect.objectContaining({ accountId: account.id }) }, + ); + }); + + it.each([undefined, new Error('User did not consent to login.')])( + 'dismisses without reconnecting or retrying session acquisition', + async (error): Promise => { + if (error) { + vi.mocked(getEntraSession).mockRejectedValueOnce(error); + } else { + vi.mocked(getEntraSession).mockResolvedValueOnce(undefined); + } + await expect(signInAgain(actionContext(), { clusterId })).rejects.toBeInstanceOf(UserCancelledError); + expect(getEntraSession).toHaveBeenCalledTimes(1); + expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + }, + ); + + it('does not reconnect when the epoch changes during sign-in', async (): Promise => { + vi.mocked(getEntraSession).mockImplementationOnce(async () => { + vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); + return { account: { id: pin.accountId, label: pin.accountLabel } } as vscode.AuthenticationSession; + }); + await signInAgain(actionContext(), { clusterId }); + expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( + 'The connection was closed while you were signing in.', { modal: true }, + ); + vi.mocked(ClustersClient.getEpoch).mockReturnValue(1); + }); +}); diff --git a/src/commands/signInAgain/signInAgain.ts b/src/commands/signInAgain/signInAgain.ts new file mode 100644 index 000000000..3890cbb57 --- /dev/null +++ b/src/commands/signInAgain/signInAgain.ts @@ -0,0 +1,114 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext-utils'; +import * as vscode from 'vscode'; +import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; +import { EntraIdentityMismatchError } from '../../documentdb/auth/entraErrors/entraCallbackErrors'; +import { getEntraSession } from '../../documentdb/auth/entraSession'; +import { MicrosoftEntraIDAuthHandler } from '../../documentdb/auth/MicrosoftEntraIDAuthHandler'; +import { classifyConnectionFailure } from '../../documentdb/connectionFailures'; +import { addEstablishedConnectionContext, ClustersClient } from '../../documentdb/ClustersClient'; +import { CredentialCache } from '../../documentdb/CredentialCache'; +import { showClusterConnectFailure } from '../../documentdb/showClusterConnectFailure'; +import { type ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; +import { refreshAuthenticationNode } from '../retryAuthentication/retryAuthentication'; + +function isSignInDismissal(error: unknown): boolean { + return error instanceof UserCancelledError || + (error instanceof Error && + (error.name === 'Canceled' || + error.message === 'User did not consent to login.' || + ('errorCode' in error && error.errorCode === 'user_cancelled'))); +} + +export async function signInAgain( + context: IActionContext, + target: ClusterItemBase | { readonly clusterId: string }, +): Promise { + const node = target && 'cluster' in target ? target : undefined; + const clusterId = target && ('cluster' in target ? target.cluster.clusterId : target.clusterId); + if (!clusterId) { + throw new Error(vscode.l10n.t('No node selected.')); + } + const epoch = ClustersClient.getEpoch(clusterId); + const reason = ClustersClient.getLatchReason(clusterId); + if (reason && reason !== 'credentialsRejected') { + return; + } + const identity = ClustersClient.getLastVerifiedIdentity(clusterId); + const credentials = CredentialCache.getCredentials(clusterId); + if (identity?.kind !== 'entra' || + credentials?.authMechanism !== AuthMethodId.MicrosoftEntraID || + identity.tenantId !== credentials.entraIdConfig?.tenantId) { + throw new Error(vscode.l10n.t('No verified Microsoft Entra ID connection is available to sign in again.')); + } + + context.telemetry.maskEntireErrorMessage = true; + context.errorHandling.suppressDisplay = true; + addEstablishedConnectionContext(context.telemetry, clusterId); + const isCurrent = (): boolean => + ClustersClient.getEpoch(clusterId) === epoch && CredentialCache.getCredentials(clusterId) === credentials; + const reportClosed = (): void => { + void vscode.window.showErrorMessage(vscode.l10n.t('The connection was closed while you were signing in.'), { + modal: true, + }); + }; + + let starting = false; + try { + const handler = new MicrosoftEntraIDAuthHandler(credentials, { interactive: false, pinnedEntraIdentity: identity }); + const auth = await handler.configureAuth(undefined, undefined, async (request) => { + if (!isCurrent()) { + throw new UserCancelledError('signInAgain'); + } + const session = await getEntraSession(request); + if (!session || !isCurrent()) { + throw new UserCancelledError('signInAgain'); + } + if (session.account.id !== identity.accountId) { + // 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 (session.account.label === identity.accountLabel || + (identity.providerId !== 'microsoft' && identity.providerId !== 'microsoft-sovereign-cloud')) { + throw new EntraIdentityMismatchError(); + } + } + return session; + }); + if (!isCurrent()) { + reportClosed(); + return; + } + starting = true; + const startup = ClustersClient.startAfterSignIn(clusterId, epoch, credentials, auth); + const startupEpoch = ClustersClient.getEpoch(clusterId); + const client = await startup; + if (!client || ClustersClient.getEpoch(clusterId) !== startupEpoch) { + reportClosed(); + return; + } + if (ClustersClient.getExistingClient(clusterId) === client && !ClustersClient.getLatchReason(clusterId) && node) { + refreshAuthenticationNode(node); + } + } catch (error) { + if (!starting && !isCurrent()) { + reportClosed(); + return; + } + if (isSignInDismissal(error)) { + throw new UserCancelledError('signInAgain'); + } + context.telemetry.properties.connectionFailureKind = classifyConnectionFailure(error, AuthMethodId.MicrosoftEntraID).kind; + 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/commands/updateConnectionString/ExecuteStep.ts b/src/commands/updateConnectionString/ExecuteStep.ts index 72f517229..948097962 100644 --- a/src/commands/updateConnectionString/ExecuteStep.ts +++ b/src/commands/updateConnectionString/ExecuteStep.ts @@ -18,9 +18,15 @@ export class ExecuteStep extends AzureWizardExecuteStep { public priority: number = 100; public async execute(context: UpdateCSWizardContext): Promise { + if (context.isRecoveryCurrent?.() === false) { + return; + } const resourceType = context.storageZone ?? (context.isEmulator ? ConnectionType.Emulators : ConnectionType.Clusters); const connection = await ConnectionStorageService.get(context.storageId, resourceType); + if (context.isRecoveryCurrent?.() === false) { + return; + } if (!connection || !connection.secrets?.connectionString) { ext.outputChannel.error( @@ -86,6 +92,9 @@ export class ExecuteStep extends AzureWizardExecuteStep { } await ConnectionStorageService.save(resourceType, connection, true); + if (context.isRecoveryCurrent?.() === false) { + return; + } context.connectionStringSaved = true; if (clearedEntraMethod) { diff --git a/src/commands/updateConnectionString/UpdateCSWizardContext.ts b/src/commands/updateConnectionString/UpdateCSWizardContext.ts index 81fe2af6e..ba54a2dac 100644 --- a/src/commands/updateConnectionString/UpdateCSWizardContext.ts +++ b/src/commands/updateConnectionString/UpdateCSWizardContext.ts @@ -16,4 +16,5 @@ export interface UpdateCSWizardContext extends IActionContext { originalConnectionString: string; newConnectionString?: string; connectionStringSaved?: boolean; + isRecoveryCurrent?: () => boolean; } diff --git a/src/commands/updateConnectionString/updateConnectionString.test.ts b/src/commands/updateConnectionString/updateConnectionString.test.ts index d28dc9029..8cf9fdd1c 100644 --- a/src/commands/updateConnectionString/updateConnectionString.test.ts +++ b/src/commands/updateConnectionString/updateConnectionString.test.ts @@ -85,7 +85,11 @@ vi.mock('../../services/connectionStorageService', async (importOriginal) => ({ ConnectionStorageService: { get: vi.fn(), save: vi.fn() }, })); vi.mock('../../documentdb/ClustersClient', () => ({ - ClustersClient: { connectInteractive: vi.fn(), deleteClient: vi.fn(), exists: vi.fn() }, + addEstablishedConnectionContext: vi.fn(), + ClustersClient: { + connectInteractive: vi.fn(), deleteClient: vi.fn(), exists: vi.fn(), + getEpoch: vi.fn(() => 0), getLatchReason: vi.fn(), getExistingClient: vi.fn(), + }, })); vi.mock('../../services/connectionReachabilityService', () => ({ ConnectionReachabilityService: { ensureReachable: vi.fn() }, diff --git a/src/commands/updateConnectionString/updateConnectionString.ts b/src/commands/updateConnectionString/updateConnectionString.ts index cfb7f9d25..de04cfedf 100644 --- a/src/commands/updateConnectionString/updateConnectionString.ts +++ b/src/commands/updateConnectionString/updateConnectionString.ts @@ -37,6 +37,10 @@ export async function updateConnectionString(context: IActionContext, node: Docu throw new Error(l10n.t('No node selected.')); } const recoveringRejectedDestination = node.lastConnectionFailureReason === 'entraDestinationRejected'; + const clusterId = node.cluster.clusterId; + let epoch = ClustersClient.getEpoch(clusterId); + const recoveringRejectedCredentials = ClustersClient.getLatchReason(clusterId) === 'credentialsRejected'; + const isCurrent = (): boolean => ClustersClient.getEpoch(clusterId) === epoch; // Extract the connection string but hide the username and password @@ -46,6 +50,9 @@ export async function updateConnectionString(context: IActionContext, node: Docu const resourceType = resolveStorageZone(node.cluster); const connection = await ConnectionStorageService.get(node.storageId, resourceType); + if (!isCurrent()) { + return; + } const connectionString = connection?.secrets?.connectionString || ''; context.valuesToMask.push(connectionString); @@ -63,6 +70,7 @@ export async function updateConnectionString(context: IActionContext, node: Docu storageZone: resolveStorageZone(node.cluster), storageId: node.storageId, connectionStringSaved: false, + isRecoveryCurrent: isCurrent, }; const wizard = new AzureWizard(wizardContext, { @@ -72,11 +80,25 @@ export async function updateConnectionString(context: IActionContext, node: Docu }); await wizard.prompt(); + if (!isCurrent()) { + return; + } await wizard.execute(); + if (!isCurrent()) { + return; + } - if (recoveringRejectedDestination && wizardContext.connectionStringSaved) { - await ClustersClient.deleteClient(node.cluster.clusterId); - CredentialCache.deleteCredentials(node.cluster.clusterId); + if ((recoveringRejectedDestination || recoveringRejectedCredentials) && wizardContext.connectionStringSaved) { + const closing = ClustersClient.deleteClient(clusterId); + epoch = ClustersClient.getEpoch(clusterId); + await closing; + if (!isCurrent()) { + return; + } + CredentialCache.deleteCredentials(clusterId); + if (recoveringRejectedCredentials) { + ClustersClient.clearCredentialRejection(clusterId, epoch); + } ext.connectionsBranchDataProvider.resetNodeErrorState(node.id); node.lastConnectionFailureReason = undefined; node.lastConnectionOutcome = undefined; diff --git a/src/commands/updateCredentials/ExecuteStep.ts b/src/commands/updateCredentials/ExecuteStep.ts index 4e2d78552..4e185a558 100644 --- a/src/commands/updateCredentials/ExecuteStep.ts +++ b/src/commands/updateCredentials/ExecuteStep.ts @@ -27,9 +27,15 @@ export class ExecuteStep extends AzureWizardExecuteStep { + if (context.isRecoveryCurrent?.() === false) { + return; + } const resourceType = context.storageZone ?? (context.isEmulator ? ConnectionType.Emulators : ConnectionType.Clusters); const connectionCredentials = await ConnectionStorageService.get(context.storageId, resourceType); + if (context.isRecoveryCurrent?.() === false) { + return; + } if (!connectionCredentials) { ext.outputChannel.error(l10n.t('Failed to save credentials: connection not found in storage.')); @@ -101,6 +107,10 @@ export class ExecuteStep extends AzureWizardExecuteStep boolean; + credentialsSaved?: boolean; } diff --git a/src/commands/updateCredentials/updateCredentials.test.ts b/src/commands/updateCredentials/updateCredentials.test.ts index 03545615a..bb97c28df 100644 --- a/src/commands/updateCredentials/updateCredentials.test.ts +++ b/src/commands/updateCredentials/updateCredentials.test.ts @@ -46,6 +46,8 @@ vi.mock('../../documentdb/ClustersClient', () => ({ ClustersClient: { deleteClient: (...args: unknown[]): unknown => mockDeleteClient(...args), getLastFailedStartupCorrelationId: (): undefined => undefined, + getEpoch: (): number => 0, + getLatchReason: (): undefined => undefined, }, })); vi.mock('../playground/executePlaygroundCode', () => ({ diff --git a/src/commands/updateCredentials/updateCredentials.ts b/src/commands/updateCredentials/updateCredentials.ts index 301e09c7d..07ede843c 100644 --- a/src/commands/updateCredentials/updateCredentials.ts +++ b/src/commands/updateCredentials/updateCredentials.ts @@ -57,6 +57,10 @@ export async function updateCredentials(context: IActionContext, node: DocumentD if (!node) { throw new Error(l10n.t('No node selected.')); } + const clusterId = node.cluster.clusterId; + let epoch = ClustersClient.getEpoch(clusterId); + const recoveringRejection = ClustersClient.getLatchReason(clusterId) === 'credentialsRejected'; + const isCurrent = (): boolean => ClustersClient.getEpoch(clusterId) === epoch; // The failed attempt these credentials replace; the reconnect's `connect.startup` names it in // `previousFailedStartupCorrelationId`, so it shows whether the new credentials worked. const failedStartupCorrelationId = ClustersClient.getLastFailedStartupCorrelationId(node.cluster.clusterId); @@ -72,6 +76,9 @@ export async function updateCredentials(context: IActionContext, node: DocumentD const resourceType = resolveStorageZone(node.cluster); const storedItem = await ConnectionStorageService.get(node.storageId, resourceType); + if (!isCurrent()) { + return; + } // Type guard ensures we have connection properties (not a folder) const connectionCredentials = storedItem && isConnection(storedItem) ? storedItem : undefined; const connectionString = connectionCredentials?.secrets?.connectionString || ''; @@ -115,6 +122,7 @@ export async function updateCredentials(context: IActionContext, node: DocumentD storageId: node.storageId, isErrorState, reconnectAfterError: false, + isRecoveryCurrent: isCurrent, }; const wizard = new AzureWizard(wizardContext, { @@ -137,15 +145,31 @@ export async function updateCredentials(context: IActionContext, node: DocumentD }); await wizard.prompt(); + if (!isCurrent()) { + return; + } await wizard.execute(); - - await ClustersClient.deleteClient(node.cluster.clusterId); + if (!isCurrent() || (recoveringRejection && !wizardContext.credentialsSaved)) { + return; + } const updatedStoredItem = await ConnectionStorageService.get(node.storageId, resourceType); + if (!isCurrent()) { + return; + } const updatedConnection = updatedStoredItem && isConnection(updatedStoredItem) ? updatedStoredItem : undefined; + const closing = ClustersClient.deleteClient(clusterId); + epoch = ClustersClient.getEpoch(clusterId); + await closing; + if (!isCurrent()) { + return; + } const authMethod = authMethodFromString(updatedConnection?.properties.selectedAuthMethod); const username = updatedConnection?.secrets.nativeAuthConfig?.connectionUser; const password = updatedConnection?.secrets.nativeAuthConfig?.connectionPassword; + if (recoveringRejection && authMethod === AuthMethodId.MicrosoftEntraID) { + ClustersClient.discardEntraPinForDifferentTenant(clusterId, updatedConnection?.secrets.entraIdAuthConfig?.tenantId); + } if (updatedConnection && authMethod && !(authMethod === AuthMethodId.NativeAuth && (!username || !password))) { const connectionString = new DocumentDBConnectionString(updatedConnection.secrets.connectionString); @@ -162,6 +186,9 @@ export async function updateCredentials(context: IActionContext, node: DocumentD // Clear stale credentials so the tree can prompt from storage. CredentialCache.deleteCredentials(node.cluster.clusterId); } + if (recoveringRejection && updatedConnection) { + ClustersClient.clearCredentialRejection(clusterId, epoch); + } shutdownEvaluator(node.cluster.clusterId); diff --git a/src/documentdb/ClustersClient.test.ts b/src/documentdb/ClustersClient.test.ts index 09436fc69..09908c6c3 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -541,6 +541,27 @@ describe('regular connection startup diagnostics', () => { expect(MongoClient).toHaveBeenCalledOnce(); }); + it('does not publish an explicitly selected account when Disconnect wins the startup race', async (): Promise => { + const client = await ClustersClient.connectInteractive(clusterId); + ClustersClient.reportFailure(client.binding, new MongoServerError({ code: 18 })); + const connection = pauseNextConnect(); + const startup = ClustersClient.startAfterSignIn( + clusterId, + ClustersClient.getEpoch(clusterId), + CredentialCache.getCredentials(clusterId)!, + { connectionString: 'mongodb://private-host:27017', options: {}, + verifiedIdentity: { ...verifiedIdentity, accountId: 'other-account' } }, + ); + await connection.started; + ClustersClient.latch(clusterId, 'userDisconnected'); + connection.resolve(); + + await expect(startup).resolves.toBeUndefined(); + expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); + expect(ClustersClient.getLastVerifiedIdentity(clusterId)).toEqual(verifiedIdentity); + await expect(ClustersClient.getClient(clusterId)).rejects.toMatchObject({ reason: 'userDisconnected' }); + }); + it('uses the resolved binding, preserves nonterminal errors and returns terminal unavailability without replay', async () => { const old = await ClustersClient.connectInteractive(clusterId); poolEvents.emit('topologyClosed'); diff --git a/src/documentdb/ClustersClient.ts b/src/documentdb/ClustersClient.ts index f64979c97..290bbd936 100644 --- a/src/documentdb/ClustersClient.ts +++ b/src/documentdb/ClustersClient.ts @@ -44,7 +44,7 @@ import { ext } from '../extensionVariables'; import { meterSilentCatch } from '../utils/accumulatingTelemetry'; import { type EmulatorConfiguration } from '../utils/emulatorConfiguration'; import { nonNullValue } from '../utils/nonNull'; -import { type VerifiedEntraIdentity } from './auth/AuthHandler'; +import { type AuthHandlerResponse, type VerifiedEntraIdentity } from './auth/AuthHandler'; import { AuthMethodId } from './auth/AuthMethod'; import { createAuthHandler } from './auth/createAuthHandler'; import { EntraSignInRequiredError } from './auth/entraErrors/entraCallbackErrors'; @@ -279,6 +279,14 @@ export class ClustersClient { return ClustersClient._lastVerifiedIdentities.get(clusterId); } + /** A saved, explicit tenant change must not silently use the previous tenant's pin. */ + public static discardEntraPinForDifferentTenant(clusterId: string, tenantId: string | undefined): void { + const identity = ClustersClient.getEntraPin(clusterId); + if (identity && identity.tenantId !== tenantId) { + ClustersClient._lastVerifiedIdentities.delete(clusterId); + } + } + private static getEntraPin(clusterId: string): VerifiedEntraIdentity | undefined { const identity = ClustersClient.getLastVerifiedIdentity(clusterId); return identity?.kind === 'entra' ? identity : undefined; @@ -424,6 +432,7 @@ export class ClustersClient { epoch: number, allowInteractive: boolean, expectedFingerprint?: string, + recoveredAuth?: AuthHandlerResponse, ): Promise { this.connectionCorrelationId = startupId; let originalFailure: { error: unknown } | undefined; @@ -457,7 +466,7 @@ export class ClustersClient { }; try { - await this.initializeClient(startup, epoch, allowInteractive); + await this.initializeClient(startup, epoch, allowInteractive, recoveredAuth); this.finishClientStartup(startup, 'succeeded'); } catch (error) { const canceled = error instanceof UserCancelledError; @@ -512,7 +521,12 @@ export class ClustersClient { ); } - private async initializeClient(startup: ClientStartup, epoch: number, allowInteractive: boolean): Promise { + private async initializeClient( + startup: ClientStartup, + epoch: number, + allowInteractive: boolean, + recoveredAuth?: AuthHandlerResponse, + ): Promise { const cachedCredentials = CredentialCache.getCredentials(this.clusterId); if (!cachedCredentials) { startup.credentialsMissing = true; @@ -545,7 +559,7 @@ export class ClustersClient { // Configure auth and get connection options this.advanceClientStartup(startup, 'stage02ConfiguringAuth'); - const { connectionString, options, verifiedIdentity } = await authHandler.configureAuth(startup.costTimings, { + const { connectionString, options, verifiedIdentity } = recoveredAuth ?? await authHandler.configureAuth(startup.costTimings, { startupCorrelationId: startup.id, surface: 'extension', startupProperties: startup.telemetry.properties, @@ -592,6 +606,9 @@ export class ClustersClient { }, startupTelemetry: startup.telemetry, }); + if (recoveredAuth && epoch !== ClustersClient.getEpoch(this.clusterId)) { + throw new UserCancelledError('signInAgain'); + } this._srvResolution = prepared.summary; await this.connect( startup, @@ -601,6 +618,9 @@ export class ClustersClient { credentials.emulatorConfiguration, connectionString, ); + if (recoveredAuth && epoch !== ClustersClient.getEpoch(this.clusterId)) { + throw new UserCancelledError('signInAgain'); + } // Start metadata collection and store the promise this._clusterMetadataPromise = getClusterMetadata(this._mongoClient, hosts); @@ -749,6 +769,43 @@ export class ClustersClient { return ClustersClient.acquireClient(clusterId, abortSignal, onStartup, trigger, true, false); } + /** Publish only after explicit sign-in and database startup succeed. The prior pin stays intact until then. */ + public static async startAfterSignIn( + clusterId: string, + epoch: number, + credentials: CachedClusterCredentials, + auth: AuthHandlerResponse, + ): Promise { + const reason = ClustersClient.getLatchReason(clusterId); + if (epoch !== ClustersClient.getEpoch(clusterId) || + CredentialCache.getCredentials(clusterId) !== credentials || + credentials.authMechanism !== AuthMethodId.MicrosoftEntraID || + (reason && reason !== 'credentialsRejected')) { + return undefined; + } + if (reason && !ClustersClient.clearCredentialRejection(clusterId, epoch)) { + return undefined; + } + void ClustersClient.deleteClient(clusterId).catch(() => { + ext.outputChannel.debug('[ClustersClient] failed to close a client during sign-in recovery'); + }); + const startupEpoch = ClustersClient.getEpoch(clusterId); + try { + const { promise } = ClustersClient.getOrStartClient(clusterId, startupEpoch, 'treeConnect', false, false, undefined, auth); + const client = await promise; + return startupEpoch === ClustersClient.getEpoch(clusterId) ? client : undefined; + } catch (error) { + if (startupEpoch !== ClustersClient.getEpoch(clusterId)) { + return undefined; + } + if (reason === 'credentialsRejected' || + classifyConnectionFailure(error, AuthMethodId.MicrosoftEntraID).kind === 'credentialsRejected') { + ClustersClient.latch(clusterId, 'credentialsRejected'); + } + throw error; + } + } + private static async acquireClient( clusterId: string, abortSignal: AbortSignal | undefined, @@ -822,6 +879,7 @@ export class ClustersClient { allowInteractive: boolean, background: boolean, expectedFingerprint?: string, + recoveredAuth?: AuthHandlerResponse, ): PendingStartup { const existing = ClustersClient._pendingStartups.get(clusterId); if (existing?.epoch === epoch) { @@ -847,7 +905,7 @@ export class ClustersClient { const id = randomUUID(); // Register before initialization or a caller's onStartup callback can re-enter getClient. const promise = Promise.resolve().then(() => - ClustersClient.establishClient(clusterId, epoch, id, trigger, allowInteractive, expectedFingerprint), + ClustersClient.establishClient(clusterId, epoch, id, trigger, allowInteractive, expectedFingerprint, recoveredAuth), ); const pending = { id, epoch, promise }; ClustersClient._pendingStartups.set(clusterId, pending); @@ -867,10 +925,11 @@ export class ClustersClient { trigger: ClientStartupTrigger, allowInteractive: boolean, expectedFingerprint?: string, + recoveredAuth?: AuthHandlerResponse, ): Promise { const client = new ClustersClient(clusterId); try { - await client.initClient(id, trigger, epoch, allowInteractive, expectedFingerprint); + await client.initClient(id, trigger, epoch, allowInteractive, expectedFingerprint, recoveredAuth); if (client._closed) { throw new MongoNotConnectedError(l10n.t('The connection is unavailable.')); } diff --git a/src/documentdb/ClustersExtension.ts b/src/documentdb/ClustersExtension.ts index 5141727e1..cd3b99150 100644 --- a/src/documentdb/ClustersExtension.ts +++ b/src/documentdb/ClustersExtension.ts @@ -83,6 +83,7 @@ import { refreshView } from '../commands/refreshView/refreshView'; import { removeConnection } from '../commands/removeConnection/removeConnection'; import { removeDiscoveryRegistry } from '../commands/removeDiscoveryRegistry/removeDiscoveryRegistry'; import { retryAuthentication } from '../commands/retryAuthentication/retryAuthentication'; +import { signInAgain } from '../commands/signInAgain/signInAgain'; import { revealView } from '../commands/revealView/revealView'; import { clearSchemaCache } from '../commands/schemaStore/clearSchemaCache'; import { showSchemaStoreStats } from '../commands/schemaStore/showSchemaStoreStats'; @@ -1008,6 +1009,10 @@ export class ClustersExtension implements vscode.Disposable { 'vscode-documentdb.command.internal.retry', withTreeNodeCommandCorrelation(retryAuthentication), ); + registerCommandWithTreeNodeUnwrapping( + 'vscode-documentdb.command.signInAgain', + withTreeNodeCommandCorrelation(signInAgain), + ); registerCommandWithTreeNodeUnwrapping( 'vscode-documentdb.command.internal.revealView', withTreeNodeCommandCorrelation(revealView), diff --git a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts index b767942c3..671f5a530 100644 --- a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts +++ b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts @@ -79,6 +79,7 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { public async configureAuth( timings?: ConnectionStartupTimings, traceContext?: AuthTraceContext, + acquireRecoverySession?: (request: Parameters[0]) => ReturnType, ): Promise { const authCorrelationId = randomUUID(); const { connectionString, clusterId } = this.clusterCredentials; @@ -140,12 +141,12 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { throw new EntraSignInRequiredError('providerChanged'); } try { - const session = await getEntraSession({ + const session = await (acquireRecoverySession ?? getEntraSession)({ providerId: pin?.providerId ?? signInEnvironment.providerId, resource, tenantId, account: pin ? { id: pin.accountId, label: pin.accountLabel } : undefined, - mode: interactive ? 'interactive' : 'silent', + mode: acquireRecoverySession ? 'forceNew' : interactive ? 'interactive' : 'silent', }); return { session, signInEnvironment }; } finally { @@ -177,7 +178,7 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { } throw new Error(l10n.t('Failed to obtain Entra ID token.')); } - if (pin && session.account.id !== pin.accountId) { + if (pin && !acquireRecoverySession && session.account.id !== pin.accountId) { throw new EntraIdentityMismatchError(); } } catch (error) { diff --git a/src/documentdb/connectionFailures.ts b/src/documentdb/connectionFailures.ts index 2966504a4..740711801 100644 --- a/src/documentdb/connectionFailures.ts +++ b/src/documentdb/connectionFailures.ts @@ -75,6 +75,9 @@ export function classifyConnectionFailure(error: unknown, authMethod?: AuthMetho return { kind: 'identityChanged', generation: 'evict' }; case 'credentialsMissing': return { kind: 'credentialsMissing', generation: 'none' }; + case 'credentialsRejected': + case 'signInRequired': + return { kind: candidate.reason, generation: 'none', note: 'alreadyUnavailable' }; default: return { ...OTHER, note: 'alreadyUnavailable' }; } diff --git a/src/plugins/service-atlas-mongodb/discovery-tree/AtlasClusterItem.test.ts b/src/plugins/service-atlas-mongodb/discovery-tree/AtlasClusterItem.test.ts index a8340f9dc..36abd6522 100644 --- a/src/plugins/service-atlas-mongodb/discovery-tree/AtlasClusterItem.test.ts +++ b/src/plugins/service-atlas-mongodb/discovery-tree/AtlasClusterItem.test.ts @@ -108,9 +108,12 @@ vi.mock('../../../documentdb/CredentialCache', () => ({ })); vi.mock('../../../documentdb/ClustersClient', () => ({ + addEstablishedConnectionContext: vi.fn(), ClustersClient: { connectInteractive: vi.fn(), deleteClient: vi.fn(), + getEpoch: vi.fn(() => 0), + getLatchReason: vi.fn(), }, })); diff --git a/src/plugins/service-atlas-mongodb/discovery-tree/AtlasClusterItem.ts b/src/plugins/service-atlas-mongodb/discovery-tree/AtlasClusterItem.ts index b315dd7c2..8b6ee7b5d 100644 --- a/src/plugins/service-atlas-mongodb/discovery-tree/AtlasClusterItem.ts +++ b/src/plugins/service-atlas-mongodb/discovery-tree/AtlasClusterItem.ts @@ -183,6 +183,7 @@ export class AtlasClusterItem extends ClusterItemBase { */ protected async authenticateAndConnect(): Promise { const result = await callWithTelemetryAndErrorHandling('connect', async (context: IActionContext) => { + const epoch = ClustersClient.getEpoch(this.cluster.clusterId); const connectionStartTime = monotonicNow(); context.telemetry.properties.view = Views.DiscoveryView; context.telemetry.properties.discoveryProviderId = DISCOVERY_PROVIDER_ID; @@ -277,8 +278,7 @@ export class AtlasClusterItem extends ClusterItemBase { await this.showConnectionFailure(context, error); // Clean up failed connection - await ClustersClient.deleteClient(this.cluster.clusterId); - CredentialCache.deleteCredentials(this.cluster.clusterId); + await this.finishFailedStartup(context, error, epoch); return null; } diff --git a/src/plugins/service-azure-mongo-ru/discovery-tree/documentdb/MongoRUResourceItem.ts b/src/plugins/service-azure-mongo-ru/discovery-tree/documentdb/MongoRUResourceItem.ts index c3087cc89..1244b4b17 100644 --- a/src/plugins/service-azure-mongo-ru/discovery-tree/documentdb/MongoRUResourceItem.ts +++ b/src/plugins/service-azure-mongo-ru/discovery-tree/documentdb/MongoRUResourceItem.ts @@ -82,12 +82,17 @@ export class MongoRUResourceItem extends ClusterItemBase { return credentials; } + public override readReplacementKey(context: IActionContext): Promise { + return this.readCredentials(context); + } + /** * Authenticates and connects to the MongoDB cluster. * @returns An instance of ClustersClient if successful; otherwise, null. */ protected async authenticateAndConnect(): Promise { const result = await callWithTelemetryAndErrorHandling('connect', async (context: IActionContext) => { + const epoch = ClustersClient.getEpoch(this.cluster.clusterId); const connectionStartTime = Date.now(); context.telemetry.properties.view = Views.DiscoveryView; context.telemetry.properties.discoveryProviderId = DISCOVERY_PROVIDER_ID; @@ -161,8 +166,7 @@ export class MongoRUResourceItem extends ClusterItemBase { }); // Clean up failed connection - await ClustersClient.deleteClient(this.cluster.clusterId); - CredentialCache.deleteCredentials(this.cluster.clusterId); + await this.finishFailedStartup(context, error, epoch); return null; } diff --git a/src/plugins/service-azure-mongo-vcore/discovery-tree/documentdb/DocumentDBResourceItem.ts b/src/plugins/service-azure-mongo-vcore/discovery-tree/documentdb/DocumentDBResourceItem.ts index a50d347c6..8c68af0f6 100644 --- a/src/plugins/service-azure-mongo-vcore/discovery-tree/documentdb/DocumentDBResourceItem.ts +++ b/src/plugins/service-azure-mongo-vcore/discovery-tree/documentdb/DocumentDBResourceItem.ts @@ -102,6 +102,7 @@ export class DocumentDBResourceItem extends ClusterItemBase { */ protected async authenticateAndConnect(): Promise { const result = await callWithTelemetryAndErrorHandling('connect', async (context: IActionContext) => { + const epoch = ClustersClient.getEpoch(this.cluster.clusterId); const connectionStartTime = Date.now(); context.telemetry.properties.view = Views.DiscoveryView; context.telemetry.properties.discoveryProviderId = DISCOVERY_PROVIDER_ID; @@ -220,8 +221,7 @@ export class DocumentDBResourceItem extends ClusterItemBase { }); // Clean up failed connection - await ClustersClient.deleteClient(this.cluster.clusterId); - CredentialCache.deleteCredentials(this.cluster.clusterId); + await this.finishFailedStartup(context, error, epoch); return null; } diff --git a/src/plugins/service-azure-vm/discovery-tree/vm/AzureVMResourceItem.ts b/src/plugins/service-azure-vm/discovery-tree/vm/AzureVMResourceItem.ts index d38c83d0b..9b266cb45 100644 --- a/src/plugins/service-azure-vm/discovery-tree/vm/AzureVMResourceItem.ts +++ b/src/plugins/service-azure-vm/discovery-tree/vm/AzureVMResourceItem.ts @@ -254,6 +254,7 @@ export class AzureVMResourceItem extends ClusterItemBase { */ protected async authenticateAndConnect(): Promise { const result = await callWithTelemetryAndErrorHandling('connect', async (context: IActionContext) => { + const epoch = ClustersClient.getEpoch(this.cluster.clusterId); context.telemetry.properties.discoveryProviderId = DISCOVERY_PROVIDER_ID; context.telemetry.properties.view = Views.DiscoveryView; if (this.journeyCorrelationId) { @@ -330,8 +331,7 @@ export class AzureVMResourceItem extends ClusterItemBase { error, context, }); - await ClustersClient.deleteClient(this.cluster.clusterId); - CredentialCache.deleteCredentials(this.cluster.clusterId); + await this.finishFailedStartup(context, error, epoch); return null; } diff --git a/src/plugins/service-kubernetes/discovery-tree/documentdb/KubernetesResourceItem.test.ts b/src/plugins/service-kubernetes/discovery-tree/documentdb/KubernetesResourceItem.test.ts index 4e6c066a9..36dc654f5 100644 --- a/src/plugins/service-kubernetes/discovery-tree/documentdb/KubernetesResourceItem.test.ts +++ b/src/plugins/service-kubernetes/discovery-tree/documentdb/KubernetesResourceItem.test.ts @@ -126,10 +126,13 @@ vi.mock('../../../../documentdb/CredentialCache', () => ({ })); vi.mock('../../../../documentdb/ClustersClient', () => ({ + addEstablishedConnectionContext: vi.fn(), ClustersClient: { exists: vi.fn().mockReturnValue(false), connectInteractive: (...args: unknown[]) => mockGetClient(...args), deleteClient: vi.fn(), + getEpoch: vi.fn(() => 0), + getLatchReason: vi.fn(), }, })); diff --git a/src/plugins/service-kubernetes/discovery-tree/documentdb/KubernetesResourceItem.ts b/src/plugins/service-kubernetes/discovery-tree/documentdb/KubernetesResourceItem.ts index e117c9270..1ddf1100d 100644 --- a/src/plugins/service-kubernetes/discovery-tree/documentdb/KubernetesResourceItem.ts +++ b/src/plugins/service-kubernetes/discovery-tree/documentdb/KubernetesResourceItem.ts @@ -257,6 +257,8 @@ export class KubernetesResourceItem extends ClusterItemBase { const result = await callWithTelemetryAndErrorHandling('connect', async (context: IActionContext) => { + const { ClustersClient } = await import('../../../../documentdb/ClustersClient'); + const epoch = ClustersClient.getEpoch(this.cluster.clusterId); this.populateTelemetry(context); context.telemetry.properties.connectionInitiatedFrom = 'discoveryView'; @@ -367,9 +369,7 @@ export class KubernetesResourceItem extends ClusterItemBase return this.failedChildrenCache.get(element.id); } + // Capture the established generation before expansion. A classified failure can evict it + // before the getChildren event is reported. + const clusterId = (element as { cluster?: { clusterId?: string } }).cluster?.clusterId; + if (clusterId) { + addEstablishedConnectionContext(context.telemetry, clusterId); + } // 2. Fetch the children of the current element const children = await this.fetchChildrenWithDiagnostics(element, context, childrenFetchFunc); context.telemetry.measurements.childrenCount = children?.length ?? 0; diff --git a/src/tree/azure-resources-view/documentdb/VCoreResourceItem.ts b/src/tree/azure-resources-view/documentdb/VCoreResourceItem.ts index ee2a224aa..a14655e1f 100644 --- a/src/tree/azure-resources-view/documentdb/VCoreResourceItem.ts +++ b/src/tree/azure-resources-view/documentdb/VCoreResourceItem.ts @@ -94,6 +94,7 @@ export class VCoreResourceItem extends ClusterItemBase { */ protected async authenticateAndConnect(): Promise { const result = await callWithTelemetryAndErrorHandling('connect', async (context: IActionContext) => { + const epoch = ClustersClient.getEpoch(this.cluster.clusterId); context.telemetry.properties.view = Views.AzureResourcesView; context.telemetry.properties.branch = 'documentdb'; context.telemetry.properties.connectionInitiatedFrom = Views.AzureResourcesView; @@ -203,8 +204,7 @@ export class VCoreResourceItem extends ClusterItemBase { }); // Clean up failed connection - await ClustersClient.deleteClient(this.cluster.clusterId); - CredentialCache.deleteCredentials(this.cluster.clusterId); + await this.finishFailedStartup(context, error, epoch); return null; } diff --git a/src/tree/azure-resources-view/mongo-ru/RUCoreResourceItem.ts b/src/tree/azure-resources-view/mongo-ru/RUCoreResourceItem.ts index 5f62ee492..6eca8c5d7 100644 --- a/src/tree/azure-resources-view/mongo-ru/RUCoreResourceItem.ts +++ b/src/tree/azure-resources-view/mongo-ru/RUCoreResourceItem.ts @@ -78,6 +78,10 @@ export class RUResourceItem extends ClusterItemBase { return credentials; } + public override readReplacementKey(context: IActionContext): Promise { + return this.readCredentials(context); + } + /** * Authenticates and connects to the Azure Cosmos DB for MongoDB (RU) cluster. * No authentication prompt as we're accessing the cluster with the default credentials. @@ -118,6 +122,7 @@ export class RUResourceItem extends ClusterItemBase { }), ); + const epoch = ClustersClient.getEpoch(this.cluster.clusterId); try { const clustersClient = await this.getClientWithProgress(this.cluster.clusterId); @@ -150,8 +155,7 @@ export class RUResourceItem extends ClusterItemBase { }); // Clean up failed connection - await ClustersClient.deleteClient(this.cluster.clusterId); - CredentialCache.deleteCredentials(this.cluster.clusterId); + await this.finishFailedStartup(context, error, epoch); return null; } diff --git a/src/tree/connections-view/DocumentDBClusterItem.test.ts b/src/tree/connections-view/DocumentDBClusterItem.test.ts index 98eec549f..35aed1f64 100644 --- a/src/tree/connections-view/DocumentDBClusterItem.test.ts +++ b/src/tree/connections-view/DocumentDBClusterItem.test.ts @@ -88,10 +88,11 @@ vi.mock('../../services/connectionStorageService', async (importOriginal) => ({ ConnectionStorageService: { get: vi.fn(), save: vi.fn() }, })); vi.mock('../../documentdb/ClustersClient', () => ({ - ClustersClient: { connectInteractive: vi.fn(), deleteClient: vi.fn(), exists: vi.fn() }, + addEstablishedConnectionContext: vi.fn(), + ClustersClient: { connectInteractive: vi.fn(), deleteClient: vi.fn(), exists: vi.fn(), getEpoch: vi.fn(() => 0), getLatchReason: vi.fn() }, })); vi.mock('../../documentdb/CredentialCache', () => ({ - CredentialCache: { hasCredentials: vi.fn(), setAuthCredentials: vi.fn(), deleteCredentials: vi.fn() }, + CredentialCache: { hasCredentials: vi.fn(), setAuthCredentials: vi.fn(), deleteCredentials: vi.fn(), getCredentials: vi.fn() }, })); vi.mock('../../services/connectionReachabilityService', () => ({ ConnectionReachabilityService: { ensureReachable: vi.fn() }, @@ -315,6 +316,16 @@ describe('connect request telemetry', () => { expect(connectEvent()).toMatchObject({ connectionResult: 'success', connectionCorrelationId: 'attempt' }); }); + + it('does not drop startup settings for a transient connection error', async (): Promise => { + vi.mocked(ClustersClient.connectInteractive).mockRejectedValue( + Object.assign(new Error('connection refused'), { code: 'ECONNREFUSED' }), + ); + await expect(makeItem().connect()).resolves.toBeNull(); + expect(ClustersClient.deleteClient).toHaveBeenCalledExactlyOnceWith('stable-id'); + expect(CredentialCache.deleteCredentials).not.toHaveBeenCalled(); + expect(connectEvent()).toMatchObject({ connectionFailureKind: 'transient' }); + }); }); describe('DocumentDBClusterItem credential reachability', (): void => { diff --git a/src/tree/connections-view/DocumentDBClusterItem.ts b/src/tree/connections-view/DocumentDBClusterItem.ts index 37ee132ca..639b853f0 100644 --- a/src/tree/connections-view/DocumentDBClusterItem.ts +++ b/src/tree/connections-view/DocumentDBClusterItem.ts @@ -262,6 +262,8 @@ export class DocumentDBClusterItem extends ClusterItemBase { return result ?? null; } - protected override async getClientWithProgress(clusterId: string): Promise { + protected override async getClientWithProgress( + clusterId: string, + onReuse?: (client: ClustersClient | undefined) => void, + ): Promise { const result = await callWithTelemetryAndErrorHandling('connect', async (context: IActionContext) => { context.errorHandling.rethrow = true; context.errorHandling.suppressDisplay = true; @@ -391,7 +394,7 @@ class QuickStartClusterItem extends ClusterItemBase { if (connectionString) { maskSensitiveValuesInTelemetry(context, new DocumentDBConnectionString(connectionString)); } - return super.getClientWithProgress(clusterId); + return super.getClientWithProgress(clusterId, onReuse); }); return nonNullValue(result, 'connected client', 'QuickStartClusterItem.getClientWithProgress'); } diff --git a/src/tree/documentdb/ClusterItemBase.test.ts b/src/tree/documentdb/ClusterItemBase.test.ts index 01e8663a4..e9b29b340 100644 --- a/src/tree/documentdb/ClusterItemBase.test.ts +++ b/src/tree/documentdb/ClusterItemBase.test.ts @@ -12,7 +12,10 @@ import { } from '@microsoft/vscode-azext-utils'; import * as vscode from 'vscode'; import { EntraDestinationRejectedError } from '../../documentdb/auth/oidcAllowedHosts'; +import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; import { ClustersClient, type DatabaseItemModel } from '../../documentdb/ClustersClient'; +import { ConnectionUnavailableError } from '../../documentdb/ConnectionUnavailableError'; +import { CredentialCache } from '../../documentdb/CredentialCache'; import { ShellCommandIds } from '../../documentdb/shell/constants'; import { type Experience } from '../../DocumentDBExperiences'; import { containsRetryNode, RETRY_NODE_ID_SUFFIX } from '../api/retryNode'; @@ -67,11 +70,17 @@ const mockGetSetting = vi.fn().mockReturnValue(false); vi.mock('../../documentdb/CredentialCache', () => ({ CredentialCache: { hasCredentials: (...args: unknown[]) => mockHasCredentials(...args), + getCredentials: vi.fn(), + deleteCredentials: vi.fn(), }, })); vi.mock('../../documentdb/ClustersClient', () => ({ - ClustersClient: { connectInteractive: vi.fn(), exists: vi.fn().mockReturnValue(false), getExistingClient: vi.fn() }, + addEstablishedConnectionContext: vi.fn(), + ClustersClient: { + connectInteractive: vi.fn(), exists: vi.fn().mockReturnValue(false), getExistingClient: vi.fn(), + getLatchReason: vi.fn(), getEpoch: vi.fn(() => 0), getLastVerifiedIdentity: vi.fn(), reportFailure: vi.fn(), + }, })); vi.mock('../../extensionVariables', () => ({ @@ -436,6 +445,36 @@ describe('ClusterItemBase.getChildren — cached client connection failure handl ); }); + it('renders the Entra action for an already-latched rejection without reporting a new failure', async (): Promise => { + ClustersClientMock.getLatchReason.mockReturnValueOnce('credentialsRejected'); + ClustersClientMock.connectInteractive.mockRejectedValueOnce(new ConnectionUnavailableError('credentialsRejected')); + const credentials = { authMechanism: AuthMethodId.MicrosoftEntraID } as ReturnType; + vi.mocked(CredentialCache.getCredentials).mockReturnValue(credentials); + ClustersClientMock.getLastVerifiedIdentity.mockReturnValueOnce({ + kind: 'entra', providerId: 'microsoft', accountLabel: 'test', accountId: 'id', + }); + const item = new TestClusterItem(makeCluster(), null); + + expect((await item.getChildren()).map(({ id }) => id)).toEqual([ + 'cluster-1/sign-in-again', 'cluster-1/diagnose', 'cluster-1/open-shell', 'cluster-1/retry', + ]); + expect(ClustersClientMock.reportFailure).not.toHaveBeenCalled(); + expect(CredentialCache.deleteCredentials).not.toHaveBeenCalled(); + vi.mocked(CredentialCache.getCredentials).mockReset(); + }); + + it('reports the binding that executed listDatabases, not the current cache entry', async (): Promise => { + const error = new Error('deprecated generation'); + const binding = { clusterId: 'cluster-1', fingerprint: 'old', generation: 1 }; + const client = { ...makeClient(vi.fn().mockRejectedValue(error)), binding } as ClustersClient; + ClustersClientMock.connectInteractive.mockResolvedValueOnce(client); + ClustersClientMock.reportFailure.mockReturnValueOnce(undefined); + + expect(await new TestClusterItem(makeCluster(), null).getChildren()).toEqual([]); + expect(ClustersClientMock.reportFailure).toHaveBeenCalledExactlyOnceWith(binding, error); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + }); + it('returns a retry node when reusing the cached client fails (without listing databases)', async () => { (ClustersClientMock.connectInteractive as Mock).mockRejectedValue(new Error('server down')); diff --git a/src/tree/documentdb/ClusterItemBase.ts b/src/tree/documentdb/ClusterItemBase.ts index 7aeab3a49..525488e94 100644 --- a/src/tree/documentdb/ClusterItemBase.ts +++ b/src/tree/documentdb/ClusterItemBase.ts @@ -14,15 +14,20 @@ import * as l10n from '@vscode/l10n'; import * as vscode from 'vscode'; import { type IconPath } from 'vscode'; import { type Experience } from '../../DocumentDBExperiences'; -import { ClustersClient, type DatabaseItemModel } from '../../documentdb/ClustersClient'; +import { + addEstablishedConnectionContext, + ClustersClient, + type DatabaseItemModel, +} from '../../documentdb/ClustersClient'; import { CredentialCache } from '../../documentdb/CredentialCache'; import { type EntraIdAuthConfig, type ManagedIdentityAuthConfig, type NativeAuthConfig, } from '../../documentdb/auth/AuthConfig'; -import { type AuthMethodId } from '../../documentdb/auth/AuthMethod'; +import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; import { isEntraDestinationRejectedError } from '../../documentdb/auth/oidcAllowedHosts'; +import { classifyConnectionFailure, type ConnectionFailure } from '../../documentdb/connectionFailures'; import { ShellCommandIds } from '../../documentdb/shell/constants'; import { showClusterConnectFailure } from '../../documentdb/showClusterConnectFailure'; import { ext } from '../../extensionVariables'; @@ -103,6 +108,7 @@ export abstract class ClusterItemBase { context.errorHandling.suppressDisplay = true; + context.telemetry.maskEntireErrorMessage = true; + addEstablishedConnectionContext(context.telemetry, this.cluster.clusterId); context.telemetry.properties.connectionResult = 'failed'; context.telemetry.properties.experience = this.experience.api; context.telemetry.properties.failurePhase = 'cachedClientConnect'; @@ -248,13 +258,20 @@ export abstract class ClusterItemBase { + protected async getClientWithProgress( + clusterId: string, + onReuse?: (client: ClustersClient | undefined) => void, + ): Promise { const abortController = new AbortController(); const clientPromise = ClustersClient.connectInteractive( clusterId, abortController.signal, (id) => { this.lastConnectionCorrelationId = id; + if (onReuse) { + const client = ClustersClient.getExistingClient(clusterId); + onReuse(client?.connectionCorrelationId === id ? client : undefined); + } }, 'treeConnect', ); @@ -285,6 +302,45 @@ export abstract class ClusterItemBase { + const { clusterId } = this.cluster; + const failure = this.classifyTreeFailure(error); + context.telemetry.properties.connectionFailureKind = failure.kind; + addEstablishedConnectionContext(context.telemetry, clusterId); + if (ClustersClient.getEpoch(clusterId) !== epoch || failure.note === 'cancelled') { + return; + } + this.lastConnectionFailureKind = failure.kind; + if (ClustersClient.getLatchReason(clusterId)) { + return; + } + const retainedEntraSettings = failure.kind === 'credentialsRejected' && this.canSignInAgain(); + if (failure.kind === 'other' || (failure.kind === 'credentialsRejected' && !retainedEntraSettings)) { + CredentialCache.deleteCredentials(clusterId); + } + if (retainedEntraSettings || (failure.kind === 'credentialsRejected' && this.readReplacementKey)) { + ClustersClient.latch(clusterId, 'credentialsRejected'); + } + await ClustersClient.deleteClient(clusterId); + } + + /** Only the two Azure RU item types can replace a rejected database key from ARM. */ + public readReplacementKey?(context: IActionContext): Promise; + + private classifyTreeFailure(error: unknown): ConnectionFailure { + const method = CredentialCache.getCredentials(this.cluster.clusterId)?.authMechanism ?? AuthMethodId.NativeAuth; + return classifyConnectionFailure(error, method); + } + + private canSignInAgain(): boolean { + const { clusterId } = this.cluster; + const credentials = CredentialCache.getCredentials(clusterId); + const identity = ClustersClient.getLastVerifiedIdentity(clusterId); + return credentials?.authMechanism === AuthMethodId.MicrosoftEntraID && identity?.kind === 'entra' && + identity.tenantId === credentials.entraIdConfig?.tenantId; + } + /** * Builds the FAILURE-TYPE error-recovery nodes owned by the element layer. * @@ -303,6 +359,17 @@ export abstract class ClusterItemBase { + const { clusterId, name } = this.cluster; + const failure = failedClient + ? classifyConnectionFailure(error, failedClient.authMethod) + : this.classifyTreeFailure(error); + const destinationRejected = isEntraDestinationRejectedError(error); + let children: TreeElement[] = []; + const telemetry = callWithTelemetryAndErrorHandling('connect', async (context) => { + context.errorHandling.suppressDisplay = true; + context.telemetry.maskEntireErrorMessage = true; + context.telemetry.properties.connectionResult = failure.note === 'cancelled' ? 'cancelled' : 'failed'; + context.telemetry.properties.source = 'treeExpansion'; + context.telemetry.properties.experience = this.experience.api; + context.telemetry.properties.failurePhase = phase; + if (failedClient?.binding) { + addEstablishedConnectionContext(context.telemetry, failedClient); + const kind = ClustersClient.reportFailure(failedClient.binding, error); + if (!kind && failure.note !== 'cancelled') { + return; + } + this.lastConnectionFailureKind = kind; + } else { + if (acquisitionEpoch !== undefined && ClustersClient.getEpoch(clusterId) !== acquisitionEpoch && + failure.note !== 'cancelled' && failure.note !== 'alreadyUnavailable') { + return; + } + addEstablishedConnectionContext(context.telemetry, clusterId); + this.lastConnectionFailureKind = failure.kind; + if (this.lastConnectionCorrelationId) { + context.telemetry.properties.connectionCorrelationId = this.lastConnectionCorrelationId; + } + // A failed replacement startup has no published generation of its own. + if (failure.kind === 'credentialsRejected' && !failure.note && + (this.canSignInAgain() || this.readReplacementKey) && !ClustersClient.getLatchReason(clusterId)) { + ClustersClient.latch(clusterId, 'credentialsRejected'); + } + } + context.telemetry.properties.connectionFailureKind = failure.kind; + if (failure.note === 'cancelled') { + this.lastConnectionOutcome = 'canceled'; + throw error; + } + this.lastConnectionOutcome = 'failed'; + this.lastConnectionFailureReason = destinationRejected ? 'entraDestinationRejected' : undefined; + children = this.createErrorRecoveryChildren(); + if (destinationRejected) { + await showClusterConnectFailure({ clusterId, clusterName: name, error, context }); + } else { + const renderingEpoch = ClustersClient.getEpoch(clusterId); + const explanation = await ErrorExplanationService.explain({ clusterId, error }); + if (ClustersClient.getEpoch(clusterId) !== renderingEpoch) { + children = []; + return; + } + context.telemetry.properties.explanationProviderId = explanation?.providerId ?? 'none'; + const heading = explanation?.message ?? (phase === 'listDatabases' + ? vscode.l10n.t('Failed to load databases for "{0}"', name) + : vscode.l10n.t('Failed to connect to "{0}"', name)); + const detail = failure.note === 'alreadyUnavailable' && this.lastConnectionFailureKind === 'signInRequired' + ? vscode.l10n.t('Sign in again to continue using this connection.') + : error instanceof Error ? error.message : String(error); + void vscode.window.showErrorMessage(heading, { modal: true, detail }); + } + throw error; + }); + await telemetry; + return children; + } + /** * Authenticates and connects to the cluster to list all available databases. * Here, the MongoDB client is created and cached for future use. @@ -342,100 +483,29 @@ export abstract class ClusterItemBase { - context.telemetry.properties.connectionResult = 'cancelled'; - context.telemetry.properties.source = 'treeExpansion'; - context.telemetry.properties.experience = this.experience.api; - throw error; - }); - - return []; - } - - // Reusing a cached client can still fail (server down, stale credentials, dropped - // tunnel, TLS/auth renegotiation, …). If we let the rejection propagate out of - // getChildren(), the tree expansion would end with no children and — crucially — - // no retry affordance, leaving the user stuck. Mirror the `!clustersClient` and - // listDatabases branches: record telemetry, surface a modal, and return a retry - // node. We intentionally keep the cached credentials so the retry can re-attempt - // the connection without forcing the user to re-enter credentials (the failure may - // be transient). - const errorMessage = error instanceof Error ? error.message : String(error); - const entraRejected = isEntraDestinationRejectedError(error); - const explanation = entraRejected - ? undefined - : await ErrorExplanationService.explain({ - clusterId: this.cluster.clusterId, - error, - }); - - const telemetryPromise = callWithTelemetryAndErrorHandling('connect', async (telemetryContext) => { - telemetryContext.errorHandling.suppressDisplay = true; - telemetryContext.telemetry.properties.connectionResult = 'failed'; - telemetryContext.telemetry.properties.source = 'treeExpansion'; - telemetryContext.telemetry.properties.experience = this.experience.api; - telemetryContext.telemetry.properties.failurePhase = 'cachedClientConnect'; - telemetryContext.telemetry.properties.explanationProviderId = explanation?.providerId ?? 'none'; - // The connection being reused, so the failure joins its destination. - const reusedConnectionId = ClustersClient.getExistingClient( - this.cluster.clusterId, - )?.connectionCorrelationId; - if (reusedConnectionId) { - telemetryContext.telemetry.properties.connectionCorrelationId = reusedConnectionId; - } - if (entraRejected) { - await showClusterConnectFailure({ - clusterId: this.cluster.clusterId, - clusterName: this.cluster.name, - error, - context: telemetryContext, - }); - } - throw error; - }); - if (entraRejected) { - await telemetryPromise; + if (!ClustersClient.getLatchReason(clusterId)) { + await this.beforeCachedClientConnect(); } - - ext.outputChannel.appendLine( - l10n.t('Failed to reuse the active connection for "{cluster}": {error}', { - cluster: this.cluster.name, - error: errorMessage, - }), - ); - - if (!entraRejected) { - void vscode.window.showErrorMessage( - explanation?.message ?? vscode.l10n.t('Failed to connect to "{0}"', this.cluster.name), - { - modal: true, - detail: errorMessage, - }, - ); - } - - return this.createErrorRecoveryChildren(); + acquisitionEpoch = ClustersClient.getEpoch(clusterId); + clustersClient = await this.getClientWithProgress(clusterId, (client) => { reusedClient = client; }); + } catch (error) { + return this.renderExpansionFailure(error, 'cachedClientConnect', reusedClient, acquisitionEpoch); } } else { // Call to the abstract method to authenticate and connect to the cluster @@ -463,45 +533,7 @@ export abstract class ClusterItemBase { - telemetryContext.errorHandling.suppressDisplay = true; - telemetryContext.telemetry.properties.connectionResult = 'failed'; - telemetryContext.telemetry.properties.source = 'treeExpansion'; - telemetryContext.telemetry.properties.experience = this.experience.api; - telemetryContext.telemetry.properties.failurePhase = 'listDatabases'; - telemetryContext.telemetry.properties.explanationProviderId = explanation?.providerId ?? 'none'; - // The connection that worked but was refused the listing, so the failure joins its destination. - if (connectedClient.connectionCorrelationId) { - telemetryContext.telemetry.properties.connectionCorrelationId = - connectedClient.connectionCorrelationId; - } - throw error; - }); - - ext.outputChannel.appendLine( - l10n.t('Failed to list databases for "{cluster}": {error}', { - cluster: this.cluster.name, - error: errorMessage, - }), - ); - - void vscode.window.showErrorMessage( - explanation?.message ?? vscode.l10n.t('Failed to load databases for "{0}"', this.cluster.name), - { modal: true, detail: errorMessage }, - ); - - return this.createErrorRecoveryChildren(); + return this.renderExpansionFailure(error, 'listDatabases', connectedClient); } // A deep link that opens the dashboard itself suppresses the automatic open; that is not a skip. From 814debb3dc07739eba33cb51e68b14bfe33d0e8a Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 14:14:16 +0000 Subject: [PATCH 06/29] docs: record WI-5 verification and the OP-3 candidate Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../features/connection-lifecycle/iterations/01-dev-plan.md | 6 ++++++ 1 file changed, 6 insertions(+) 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 a8dbe8a1e..e4b5fb2b9 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 @@ -1300,6 +1300,12 @@ shim (0005). rejected settings. Only the matching explicit recovery can clear the rejection, and only if its epoch is current. The operator preferred the simpler option and asked to record [decision 0015](../decisions.md#0015-use-the-existing-latch-to-block-startup-after-authentication-rejection). +- **OP-3 candidate:** Host and tree recovery, Retry and **Sign in again** are implemented + for [draft PR4 (#1117)](https://github.com/microsoft/vscode-documentdb/pull/1117). Case 1 passed: + the host batch passed 222 tests, the tree batch passed 367, and a final 127-test run covered + the Native discovery Retry correction and the core recovery paths. These counts overlap. + OP-3 requires a real Entra sign-out on the dev host and a fresh-socket callback. PR4 pre-review + and handoff checks remain; WI-6 does not start before OP-3 is cleared. --- From cac13fb701378a88270545607be64102fc397f2e Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 15:57:27 +0000 Subject: [PATCH 07/29] fix: show one primary action for Entra tree recovery (WI-5) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../features/connection-lifecycle/README.md | 2 +- .../iterations/01-dev-plan.md | 10 ++-- src/tree/documentdb/ClusterItemBase.test.ts | 50 ++++++++++++------- src/tree/documentdb/ClusterItemBase.ts | 22 ++++---- 4 files changed, 52 insertions(+), 32 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/README.md b/docs/ai-and-plans/features/connection-lifecycle/README.md index f32fb1728..b35c648cf 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/README.md +++ b/docs/ai-and-plans/features/connection-lifecycle/README.md @@ -51,7 +51,7 @@ Evidence, telemetry and source pointers: [research-findings.md](./research-findi and offers one action. - After a database rejects a verified Entra identity, discard the client but keep its in-memory connection settings for explicit **Sign in again**. Do not retain the rejected token or retry - silently. + silently. When the tree offers **Sign in again**, it does not also offer **Retry**. - **One teardown** serves Disconnect, Remove Connection and identity-changing credential updates. - Disconnect uses the existing task-conflict guard: if a copy or export is using the cluster, leave the task and connection running. The user can retry after the task finishes or is stopped. 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 e4b5fb2b9..5e55abc92 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 @@ -1206,11 +1206,12 @@ shim (0005). - Route both catch paths in `getChildren` (cached-client reuse and `listDatabases`) through `reportFailure`. Keep the modal-plus-actions presentation. - Change `createErrorRecoveryChildren` to: - - **Sign in again** (when the kind is `signInRequired`), or **Update credentials** (the - provider-owned action that exists today); + - **Sign in again** when the kind is `signInRequired` or `credentialsRejected` and the + Entra identity and settings are available, or **Update credentials** (the provider-owned + action that exists today); - then Diagnose; - then Open shell; - - then **Retry last**. + - then **Retry last**, except when **Sign in again** is offered in its place. - Check that order against the skill text, and update the skill in WI-10 if it differs. - Call `addEstablishedConnectionContext` on the failure events of `connect`, `getchildren` and the tree. - **Keep credentials on recoverable failures (F-20).** In every provider item's `authenticateAndConnect` @@ -1306,6 +1307,9 @@ shim (0005). the Native discovery Retry correction and the core recovery paths. These counts overlap. OP-3 requires a real Entra sign-out on the dev host and a fresh-socket callback. PR4 pre-review and handoff checks remain; WI-6 does not start before OP-3 is cleared. +- **OP-3 UI clarification:** The operator accepted showing **Sign in again** instead of **Retry** + when Entra sign-in is the next useful step. Diagnose and Open shell remain. This follows decision + 0001's single sign-in action and preserves the original Retry behavior for transient failures. --- diff --git a/src/tree/documentdb/ClusterItemBase.test.ts b/src/tree/documentdb/ClusterItemBase.test.ts index e9b29b340..63c506d27 100644 --- a/src/tree/documentdb/ClusterItemBase.test.ts +++ b/src/tree/documentdb/ClusterItemBase.test.ts @@ -445,23 +445,39 @@ describe('ClusterItemBase.getChildren — cached client connection failure handl ); }); - it('renders the Entra action for an already-latched rejection without reporting a new failure', async (): Promise => { - ClustersClientMock.getLatchReason.mockReturnValueOnce('credentialsRejected'); - ClustersClientMock.connectInteractive.mockRejectedValueOnce(new ConnectionUnavailableError('credentialsRejected')); - const credentials = { authMechanism: AuthMethodId.MicrosoftEntraID } as ReturnType; - vi.mocked(CredentialCache.getCredentials).mockReturnValue(credentials); - ClustersClientMock.getLastVerifiedIdentity.mockReturnValueOnce({ - kind: 'entra', providerId: 'microsoft', accountLabel: 'test', accountId: 'id', - }); - const item = new TestClusterItem(makeCluster(), null); - - expect((await item.getChildren()).map(({ id }) => id)).toEqual([ - 'cluster-1/sign-in-again', 'cluster-1/diagnose', 'cluster-1/open-shell', 'cluster-1/retry', - ]); - expect(ClustersClientMock.reportFailure).not.toHaveBeenCalled(); - expect(CredentialCache.deleteCredentials).not.toHaveBeenCalled(); - vi.mocked(CredentialCache.getCredentials).mockReset(); - }); + it.each(['signInRequired', 'credentialsRejected'] as const)( + 'offers Sign in again instead of Retry for %s and keeps the failed-expansion marker', + async (reason): Promise => { + if (reason === 'credentialsRejected') { + ClustersClientMock.getLatchReason.mockReturnValueOnce(reason); + } + ClustersClientMock.connectInteractive.mockRejectedValueOnce(new ConnectionUnavailableError(reason)); + vi.mocked(CredentialCache.getCredentials).mockReturnValue({ + clusterId: 'cluster-1', + connectionString: 'mongodb://example.test', + authMechanism: AuthMethodId.MicrosoftEntraID, + }); + ClustersClientMock.getLastVerifiedIdentity.mockReturnValueOnce({ + kind: 'entra', + providerId: 'microsoft', + accountLabel: 'test', + accountId: 'id', + }); + const item = new TestClusterItem(makeCluster(), null); + + const children = await item.getChildren(); + + expect(children.map(({ id }) => id)).toEqual([ + 'cluster-1/sign-in-again', + 'cluster-1/diagnose', + 'cluster-1/open-shell', + ]); + expect(item.hasRetryNode(children)).toBe(true); + expect(ClustersClientMock.reportFailure).not.toHaveBeenCalled(); + expect(CredentialCache.deleteCredentials).not.toHaveBeenCalled(); + vi.mocked(CredentialCache.getCredentials).mockReset(); + }, + ); it('reports the binding that executed listDatabases, not the current cache entry', async (): Promise => { const error = new Error('deprecated generation'); diff --git a/src/tree/documentdb/ClusterItemBase.ts b/src/tree/documentdb/ClusterItemBase.ts index 525488e94..ae0c8be40 100644 --- a/src/tree/documentdb/ClusterItemBase.ts +++ b/src/tree/documentdb/ClusterItemBase.ts @@ -344,23 +344,25 @@ export abstract class ClusterItemBase child.id === `${this.id}/sign-in-again`) === true; } /** From 40a8d54d76615554fa188e37f679062379af9d31 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 16:22:37 +0000 Subject: [PATCH 08/29] fix: restore draft CI checks for connection recovery (WI-5) Repair the lifecycle test fixtures and type-only import, then update the generated localization and formatting reported by CI. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../connection-lifecycle/decisions.md | 32 ++++---- .../iterations/01-dev-plan.md | 7 +- l10n/bundle.l10n.json | 12 ++- .../diagnoseConnection.test.ts | 3 + .../retryAuthentication.test.ts | 18 +++-- .../retryAuthentication.ts | 31 ++++++-- src/commands/signInAgain/signInAgain.test.ts | 42 ++++++++--- src/commands/signInAgain/signInAgain.ts | 36 ++++++--- .../updateConnectionString.test.ts | 8 +- .../updateCredentials/updateCredentials.ts | 5 +- src/documentdb/ClustersClient.test.ts | 15 ++-- src/documentdb/ClustersClient.ts | 44 ++++++++--- src/documentdb/ClustersExtension.ts | 2 +- src/documentdb/connectionFailures.ts | 4 +- .../azureResourceAuthentication.test.ts | 15 +++- .../DocumentDBClusterItem.test.ts | 15 +++- .../LocalQuickStartItem.credentials.test.ts | 3 + src/tree/documentdb/ClusterItemBase.test.ts | 11 ++- src/tree/documentdb/ClusterItemBase.ts | 73 +++++++++++++------ 19 files changed, 271 insertions(+), 105 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/decisions.md b/docs/ai-and-plans/features/connection-lifecycle/decisions.md index 2f6b7a190..9e5712c39 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/decisions.md +++ b/docs/ai-and-plans/features/connection-lifecycle/decisions.md @@ -10,22 +10,22 @@ created: 2026-11-19 > Why connections stay usable across token expiry and idle drops, and how open surfaces behave > when credentials or the identity change. Evidence: [research-findings.md](./research-findings.md). -| # | Decision | Status | Changed from the proposal? | Date | PR | -| ---- | ---------------------------------------------------------------------------------------------------------- | --------------------------- | ------------------------------------------------------ | ---------- | --- | -| 0001 | Entra tokens are renewed silently in every OIDC callback; the callback never prompts | Accepted | Operator accepted the explanation (2026-11-19) | 2026-11-19 | — | -| 0002 | Keep one cached client per cluster; surfaces resolve it per operation with identity + generation | Accepted (modified by 0010) | Operator position: per-operation clients cost too much | 2026-11-19 | — | -| 0003 | An open surface never moves to a different identity; it becomes disconnected, keeps its state and says why | Accepted | Operator requirement | 2026-11-19 | — | -| 0004 | Disconnect lets the user choose: close all affected tabs, or keep them open and disabled | Accepted | Operator position; the default is still open (Q2) | 2026-11-19 | — | -| 0005 | Fix stale ARM credentials by upgrading azureauth to v6 (#990), not with a local shim | Accepted | Operator: open to updating dependencies | 2026-11-19 | — | -| 0006 | Deliver through `feature/connection-lifecycle` with stacked sub-PRs, ship once | Accepted (amended) | Operator removed the intermediate merge wait | 2026-11-19 | — | -| 0007 | The Disconnect choice is a VS Code modal with nothing remembered; a setting can set the default | Accepted | Operator: modal cannot pre-select; no remembering | 2026-11-19 | — | -| 0008 | Upgrade the azext stack as high as viable without breaking workflows, using Azure Resources as reference | Accepted | Operator: replaces the "minimal versions" proposal | 2026-11-19 | — | -| 0009 | Kubernetes tunnel recovery, cluster ID case handling and wider network-resilience testing move to #1105 | Accepted | Operator: keep 1.2.0 focused; schedule after release | 2026-11-19 | — | -| 0010 | Rely on the server to reject expired tokens; replacing a client for the same identity is transparent | Accepted | Operator: no rotation, no out-of-date notices | 2026-11-19 | — | -| 0011 | Disconnect keeps the cached credentials and the verified identity; only Remove drops them | Accepted | Operator: reverses the #1059 proposal (plan Q3) | 2026-11-19 | — | -| 0012 | Keep the lifecycle design minimal: no state machine, one epoch, no prompts in getClient, one-step teardown | Accepted | Operator: approved every proposed simplification | 2026-11-19 | — | -| 0013 | Correct the minimal design where it lost edits, identity or recovery: latch before save, epoch checks | Accepted (modifies 0012) | Operator: "update the plan" after the omissions review | 2026-11-19 | — | -| 0014 | Keep in-memory connection settings after a rejection for a verified Entra identity | Accepted | Operator selected A to make sign-in recovery smoother | 2026-11-23 | Yes; WI-5 previously said to delete the entry | +| # | Decision | Status | Changed from the proposal? | Date | PR | +| ---- | ---------------------------------------------------------------------------------------------------------- | --------------------------- | ----------------------------------------------------------- | ---------- | ---------------------------------------------------------------- | +| 0001 | Entra tokens are renewed silently in every OIDC callback; the callback never prompts | Accepted | Operator accepted the explanation (2026-11-19) | 2026-11-19 | — | +| 0002 | Keep one cached client per cluster; surfaces resolve it per operation with identity + generation | Accepted (modified by 0010) | Operator position: per-operation clients cost too much | 2026-11-19 | — | +| 0003 | An open surface never moves to a different identity; it becomes disconnected, keeps its state and says why | Accepted | Operator requirement | 2026-11-19 | — | +| 0004 | Disconnect lets the user choose: close all affected tabs, or keep them open and disabled | Accepted | Operator position; the default is still open (Q2) | 2026-11-19 | — | +| 0005 | Fix stale ARM credentials by upgrading azureauth to v6 (#990), not with a local shim | Accepted | Operator: open to updating dependencies | 2026-11-19 | — | +| 0006 | Deliver through `feature/connection-lifecycle` with stacked sub-PRs, ship once | Accepted (amended) | Operator removed the intermediate merge wait | 2026-11-19 | — | +| 0007 | The Disconnect choice is a VS Code modal with nothing remembered; a setting can set the default | Accepted | Operator: modal cannot pre-select; no remembering | 2026-11-19 | — | +| 0008 | Upgrade the azext stack as high as viable without breaking workflows, using Azure Resources as reference | Accepted | Operator: replaces the "minimal versions" proposal | 2026-11-19 | — | +| 0009 | Kubernetes tunnel recovery, cluster ID case handling and wider network-resilience testing move to #1105 | Accepted | Operator: keep 1.2.0 focused; schedule after release | 2026-11-19 | — | +| 0010 | Rely on the server to reject expired tokens; replacing a client for the same identity is transparent | Accepted | Operator: no rotation, no out-of-date notices | 2026-11-19 | — | +| 0011 | Disconnect keeps the cached credentials and the verified identity; only Remove drops them | Accepted | Operator: reverses the #1059 proposal (plan Q3) | 2026-11-19 | — | +| 0012 | Keep the lifecycle design minimal: no state machine, one epoch, no prompts in getClient, one-step teardown | Accepted | Operator: approved every proposed simplification | 2026-11-19 | — | +| 0013 | Correct the minimal design where it lost edits, identity or recovery: latch before save, epoch checks | Accepted (modifies 0012) | Operator: "update the plan" after the omissions review | 2026-11-19 | — | +| 0014 | Keep in-memory connection settings after a rejection for a verified Entra identity | Accepted | Operator selected A to make sign-in recovery smoother | 2026-11-23 | Yes; WI-5 previously said to delete the entry | | 0015 | Use the existing latch to block startup after authentication rejection | Accepted | Operator selected A; keep the approach simple and pragmatic | 2026-11-23 | Yes; expands the existing latch rather than adding a second hold | > Entries below are **semantically** immutable: append new entries rather than rewriting old ones, 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 5e55abc92..6784455de 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 @@ -1174,7 +1174,7 @@ shim (0005). | `ConnectionUnavailableError('credentialsMissing')` (F-20) | any | `credentialsMissing` | none to keep | Update credentials | | code 18 | Native, RU | `credentialsRejected` | evict; no automatic retry | Update credentials (RU: Retry re-reads the key) | | final code 18 | Entra | `credentialsRejected` | evict; no automatic retry | Sign in again with a verified Entra identity | - | `MongoNotConnectedError`, `MongoTopologyClosedError` | any | `clientClosed` | new generation on the next foreground call | none | + | `MongoNotConnectedError`, `MongoTopologyClosedError` | any | `clientClosed` | new generation on the next foreground call | none | | network errors, timeouts, server selection with no auth cause | any | `transient` | keep | Retry | | anything else | any | `other` | keep | existing behavior | @@ -1310,6 +1310,11 @@ shim (0005). - **OP-3 UI clarification:** The operator accepted showing **Sign in again** instead of **Retry** when Entra sign-in is the next useful step. Diagnose and Open shell remain. This follows decision 0001's single sign-in action and preserves the original Retry behavior for transient failures. +- **Draft PR4 CI follow-up:** The VSIX built, passed inspection, and activated in VS Code. Static + checks exposed stale localization, formatting changes, and a type-only import lint error. The + full test run found 32 failures in three suites whose mocks did not expose the new lifecycle + methods. Update those fixtures without changing their assertions or runtime recovery behavior. + OP-3 remains the live Entra sign-out and dismissal gate. --- diff --git a/l10n/bundle.l10n.json b/l10n/bundle.l10n.json index 91360cd83..79c6e5f2e 100644 --- a/l10n/bundle.l10n.json +++ b/l10n/bundle.l10n.json @@ -604,6 +604,7 @@ "Changelog": "Changelog", "Check": "Check", "Check a connection step by step and review the results.": "Check a connection step by step and review the results.", + "Check access to the Azure resource and try again.": "Check access to the Azure resource and try again.", "Check Docker again": "Check Docker again", "Check documentDB.customEnvironment.ossrdbmsEndpoint with your cloud administrator. If no override is set, report this on GitHub.": "Check documentDB.customEnvironment.ossrdbmsEndpoint with your cloud administrator. If no override is set, report this on GitHub.", "Check how database traffic should reach this cluster from the host running these checks.": "Check how database traffic should reach this cluster from the host running these checks.", @@ -823,6 +824,7 @@ "Connecting to the cluster using a managed identity…": "Connecting to the cluster using a managed identity…", "Connecting to the cluster using a Microsoft Entra account…": "Connecting to the cluster using a Microsoft Entra account…", "Connecting…": "Connecting…", + "connection": "connection", "Connection": "Connection", "connection \"{0}\"": "connection \"{0}\"", "Connection attempt failed": "Connection attempt failed", @@ -859,7 +861,6 @@ "Connection successful, but 1 check failed": "Connection successful, but 1 check failed", "Connection successful, but 1 check needs attention": "Connection successful, but 1 check needs attention", "Connection timed out": "Connection timed out", - "Connection to \"{cluster}\" was cancelled.": "Connection to \"{cluster}\" was cancelled.", "Connection updated successfully.": "Connection updated successfully.", "Connection updated. Microsoft Entra ID isn't available for the new server, so choose another method when you connect.": "Connection updated. Microsoft Entra ID isn't available for the new server, so choose another method when you connect.", "Connection works, but sign-in is required": "Connection works, but sign-in is required", @@ -950,8 +951,10 @@ "Could not reach a server": "Could not reach a server", "Could not read collections": "Could not read collections", "Could not read databases": "Could not read databases", + "Could not read the database key from Azure.": "Could not read the database key from Azure.", "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.", "Counting documents in the source collection...": "Counting documents in the source collection...", "Counting source indexes…": "Counting source indexes…", "Coverage and limits": "Coverage and limits", @@ -1405,7 +1408,6 @@ "Failed to initialize task": "Failed to initialize task", "Failed to initialize the DocumentDB survey: {0}": "Failed to initialize the DocumentDB survey: {0}", "Failed to initialize the Kubernetes client: {0}. Try reloading the window; if the problem persists, reinstall the extension.": "Failed to initialize the Kubernetes client: {0}. Try reloading the window; if the problem persists, reinstall the extension.", - "Failed to list databases for \"{cluster}\": {error}": "Failed to list databases for \"{cluster}\": {error}", "Failed to list DKO resources in namespace \"{0}\": {1}. Check that the DocumentDB Kubernetes Operator CRD is installed and that your Kubernetes credentials can list documentdb.io dbs resources.": "Failed to list DKO resources in namespace \"{0}\": {1}. Check that the DocumentDB Kubernetes Operator CRD is installed and that your Kubernetes credentials can list documentdb.io dbs resources.", "Failed to list namespaces: {0}. Check that your credentials are valid and you have the required RBAC permissions.": "Failed to list namespaces: {0}. Check that your credentials are valid and you have the required RBAC permissions.", "Failed to list services": "Failed to list services", @@ -1453,7 +1455,6 @@ "Failed to rename connection: connection not found in storage.": "Failed to rename connection: connection not found in storage.", "Failed to rename the connection.": "Failed to rename the connection.", "Failed to retrieve Azure accounts: {0}": "Failed to retrieve Azure accounts: {0}", - "Failed to reuse the active connection for \"{cluster}\": {error}": "Failed to reuse the active connection for \"{cluster}\": {error}", "Failed to save credentials for \"{cluster}\".": "Failed to save credentials for \"{cluster}\".", "Failed to save credentials: {0}": "Failed to save credentials: {0}", "Failed to save credentials: connection not found in storage.": "Failed to save credentials: connection not found in storage.", @@ -2087,6 +2088,7 @@ "No tenants selected. Tenant filtering disabled (all tenants will be shown).": "No tenants selected. Tenant filtering disabled (all tenants will be shown).", "No tenants were returned for the available Azure accounts.": "No tenants were returned for the available Azure accounts.", "no token was returned": "no token was returned", + "No verified Microsoft Entra ID connection is available to sign in again.": "No verified Microsoft Entra ID connection is available to sign in again.", "No, only copy documents": "No, only copy documents", "node-routed": "node-routed", "Node.js: {0}": "Node.js: {0}", @@ -2718,11 +2720,14 @@ "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 to": "Sign in to", "Sign in to additional accounts or authenticate with other tenants to see more options.": "Sign in to additional accounts or authenticate with other tenants to see more options.", "Sign in to additional accounts or authenticate with other tenants to see more subscriptions.": "Sign in to additional accounts or authenticate with other tenants to see more subscriptions.", "Sign in to Azure": "Sign in to Azure", + "Sign in to Azure and try Retry again.": "Sign in to Azure and try Retry again.", "Sign in to Azure in VS Code, then run the diagnosis again.": "Sign in to Azure in VS Code, then run the diagnosis again.", "Sign in to Azure to continue…": "Sign in to Azure to continue…", "Sign in to Azure to open {0}.": "Sign in to Azure to open {0}.", @@ -2971,6 +2976,7 @@ "The connection string will not include the password": "The connection string will not include the password", "The connection succeeded, but the database-list request returned no databases visible to this user.": "The connection succeeded, but the database-list request returned no databases visible to this user.", "The connection succeeded, but the server denied the database-list request used by the extension.": "The connection succeeded, but the server denied the database-list request used by the extension.", + "The connection was closed while you were signing in.": "The connection was closed while you were signing in.", "The connection works, but these checks need attention:": "The connection works, but these checks need attention:", "The container and its data volume will be permanently removed. All data, logs, and the auto-generated credentials will be lost. This cannot be undone. You can recreate a fresh instance any time with \"Set up DocumentDB Local\".": "The container and its data volume will be permanently removed. All data, logs, and the auto-generated credentials will be lost. This cannot be undone. You can recreate a fresh instance any time with \"Set up DocumentDB Local\".", "The container engine": "The container engine", diff --git a/src/commands/diagnoseConnection/diagnoseConnection.test.ts b/src/commands/diagnoseConnection/diagnoseConnection.test.ts index 024a5d509..6adbb78c4 100644 --- a/src/commands/diagnoseConnection/diagnoseConnection.test.ts +++ b/src/commands/diagnoseConnection/diagnoseConnection.test.ts @@ -49,7 +49,10 @@ vi.mock('../../documentdb/CredentialCache', () => ({ CredentialCache: { hasCredentials: vi.fn(), setCredentials: vi.fn(), setAuthCredentials: vi.fn() }, })); vi.mock('../../documentdb/ClustersClient', () => ({ + addEstablishedConnectionContext: vi.fn(), ClustersClient: { + getEpoch: vi.fn(() => 0), + getLatchReason: vi.fn(), getClient: vi.fn(), exists: vi.fn().mockReturnValue(false), getExistingClient: vi.fn(), diff --git a/src/commands/retryAuthentication/retryAuthentication.test.ts b/src/commands/retryAuthentication/retryAuthentication.test.ts index 60c81da13..7fa94f715 100644 --- a/src/commands/retryAuthentication/retryAuthentication.test.ts +++ b/src/commands/retryAuthentication/retryAuthentication.test.ts @@ -6,12 +6,13 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { UserCancelledError } from '@microsoft/vscode-azext-utils'; +import type * as vscode from 'vscode'; import { window } from 'vscode'; import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; import { ClustersClient } from '../../documentdb/ClustersClient'; import { CredentialCache } from '../../documentdb/CredentialCache'; -import { type ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; import { ext } from '../../extensionVariables'; +import { type ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; import { retryAuthentication } from './retryAuthentication'; vi.mock('../../extensionVariables', () => ({ @@ -53,7 +54,7 @@ vi.mock('../../documentdb/CredentialCache', () => ({ })); vi.mock('vscode', async (importOriginal) => ({ - ...(await importOriginal()), + ...(await importOriginal()), l10n: { t: vi.fn((value: string) => value), }, @@ -157,7 +158,9 @@ describe('retryAuthentication', () => { const node = ruNode(); const nativeAuthConfig = { connectionUser: 'test', connectionPassword: 'new-key' }; node.readReplacementKey.mockResolvedValue({ - connectionString: 'mongodb://test', availableAuthMethods: [AuthMethodId.NativeAuth], nativeAuthConfig, + connectionString: 'mongodb://test', + availableAuthMethods: [AuthMethodId.NativeAuth], + nativeAuthConfig, }); vi.mocked(ClustersClient.getLatchReason).mockReturnValueOnce('credentialsRejected'); vi.mocked(ClustersClient.clearCredentialRejection).mockReturnValueOnce(true); @@ -167,7 +170,10 @@ describe('retryAuthentication', () => { expect(CredentialCache.deleteCredentials).toHaveBeenCalledExactlyOnceWith('ru'); expect(node.readReplacementKey).toHaveBeenCalledTimes(1); expect(CredentialCache.setAuthCredentials).toHaveBeenCalledExactlyOnceWith( - 'ru', AuthMethodId.NativeAuth, 'mongodb://test', nativeAuthConfig, + 'ru', + AuthMethodId.NativeAuth, + 'mongodb://test', + nativeAuthConfig, ); expect(ext.discoveryBranchDataProvider.refresh).toHaveBeenCalledExactlyOnceWith(node); }); @@ -220,7 +226,9 @@ describe('retryAuthentication', () => { it('does not refresh an old Retry after the client was replaced while its close was pending', async (): Promise => { const node = { - id: 'connectionsView/stale', cluster: { clusterId: 'stale' }, getTreeItem, + id: 'connectionsView/stale', + cluster: { clusterId: 'stale' }, + getTreeItem, lastConnectionFailureKind: 'clientClosed' as const, }; vi.mocked(ClustersClient.getEpoch).mockReturnValueOnce(0).mockReturnValueOnce(1).mockReturnValueOnce(2); diff --git a/src/commands/retryAuthentication/retryAuthentication.ts b/src/commands/retryAuthentication/retryAuthentication.ts index 48a917026..ef9606445 100644 --- a/src/commands/retryAuthentication/retryAuthentication.ts +++ b/src/commands/retryAuthentication/retryAuthentication.ts @@ -11,11 +11,11 @@ import { addEstablishedConnectionContext, ClustersClient } from '../../documentd import { CredentialCache } from '../../documentdb/CredentialCache'; import { inferViewIdFromTreeId, Views } from '../../documentdb/Views'; import { ext } from '../../extensionVariables'; +import { type ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; +import { ConnectionSourceUnavailableError } from '../../tree/documentdb/diagnosticCredentialRead'; import { type TreeElement } from '../../tree/TreeElement'; import { type TreeElementWithContextValue } from '../../tree/TreeElementWithContextValue'; import { isTreeElementWithExplicitReload } from '../../tree/TreeElementWithExplicitReload'; -import { type ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; -import { ConnectionSourceUnavailableError } from '../../tree/documentdb/diagnosticCredentialRead'; const containsDelimited = (fullContext: string | undefined, value: string): boolean => { if (!fullContext) { @@ -117,12 +117,20 @@ export async function retryAuthentication(context: IActionContext, node: Retryab throw error; } const finding = classifyResolutionFailure(new ConnectionSourceUnavailableError('azure', error)); - const signInNeeded = finding.code === 'target.sourceInaccessible' && finding.data?.reason === 'signInRequired'; + const signInNeeded = + finding.code === 'target.sourceInaccessible' && finding.data?.reason === 'signInRequired'; context.telemetry.properties.azureKeyReadFailure = signInNeeded ? 'signInRequired' : 'other'; context.errorHandling.suppressDisplay = true; void window.showErrorMessage( - signInNeeded ? l10n.t('Azure sign-in needed') : l10n.t('Could not read the database key from Azure.'), - { modal: true, detail: signInNeeded ? l10n.t('Sign in to Azure and try Retry again.') : l10n.t('Check access to the Azure resource and try again.') }, + signInNeeded + ? l10n.t('Azure sign-in needed') + : l10n.t('Could not read the database key from Azure.'), + { + modal: true, + detail: signInNeeded + ? l10n.t('Sign in to Azure and try Retry again.') + : l10n.t('Check access to the Azure resource and try again.'), + }, ); throw error; } @@ -131,9 +139,16 @@ export async function retryAuthentication(context: IActionContext, node: Retryab } // One fresh ARM read per explicit click. A subsequent database rejection re-latches in // the tree; it cannot start another ARM read. - if (credentials.nativeAuthConfig?.connectionPassword && - ClustersClient.clearCredentialRejection(clusterId, epoch)) { - CredentialCache.setAuthCredentials(clusterId, AuthMethodId.NativeAuth, credentials.connectionString, credentials.nativeAuthConfig); + if ( + credentials.nativeAuthConfig?.connectionPassword && + ClustersClient.clearCredentialRejection(clusterId, epoch) + ) { + CredentialCache.setAuthCredentials( + clusterId, + AuthMethodId.NativeAuth, + credentials.connectionString, + credentials.nativeAuthConfig, + ); } else { return; } diff --git a/src/commands/signInAgain/signInAgain.test.ts b/src/commands/signInAgain/signInAgain.test.ts index e4a419f6c..90c25099a 100644 --- a/src/commands/signInAgain/signInAgain.test.ts +++ b/src/commands/signInAgain/signInAgain.test.ts @@ -12,7 +12,13 @@ import { ClustersClient } from '../../documentdb/ClustersClient'; import { CredentialCache } from '../../documentdb/CredentialCache'; import { signInAgain } from './signInAgain'; -const pin = { kind: 'entra', providerId: 'microsoft', accountId: 'pinned', accountLabel: 'Pinned', tenantId: 'tenant' } as const; +const pin = { + kind: 'entra', + providerId: 'microsoft', + accountId: 'pinned', + accountLabel: 'Pinned', + tenantId: 'tenant', +} as const; const clusterId = 'cluster'; vi.mock('../../documentdb/ClustersClient', () => ({ @@ -34,7 +40,10 @@ vi.mock('../../documentdb/auth/MicrosoftEntraIDAuthHandler', () => ({ acquire: typeof getEntraSession, ): Promise { const session = await acquire({ - mode: 'forceNew', providerId: pin.providerId, resource: 'scope', tenantId: pin.tenantId, + mode: 'forceNew', + providerId: pin.providerId, + resource: 'scope', + tenantId: pin.tenantId, account: { id: pin.accountId, label: pin.accountLabel }, }); return { verifiedIdentity: { ...pin, accountId: session?.account.id } }; @@ -51,8 +60,14 @@ function actionContext(): IActionContext { describe('signInAgain', () => { beforeEach(() => { vi.clearAllMocks(); - CredentialCache.setAuthCredentials(clusterId, AuthMethodId.MicrosoftEntraID, 'mongodb://test', undefined, - undefined, { tenantId: pin.tenantId }); + CredentialCache.setAuthCredentials( + clusterId, + AuthMethodId.MicrosoftEntraID, + 'mongodb://test', + undefined, + undefined, + { tenantId: pin.tenantId }, + ); }); it.each([ @@ -64,12 +79,18 @@ describe('signInAgain', () => { await signInAgain(actionContext(), { clusterId }); - expect(getEntraSession).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ - mode: 'forceNew', tenantId: pin.tenantId, providerId: pin.providerId, - account: { id: pin.accountId, label: pin.accountLabel }, - })); + expect(getEntraSession).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + mode: 'forceNew', + tenantId: pin.tenantId, + providerId: pin.providerId, + account: { id: pin.accountId, label: pin.accountLabel }, + }), + ); expect(ClustersClient.startAfterSignIn).toHaveBeenCalledExactlyOnceWith( - clusterId, 1, CredentialCache.getCredentials(clusterId), + clusterId, + 1, + CredentialCache.getCredentials(clusterId), { verifiedIdentity: expect.objectContaining({ accountId: account.id }) }, ); }); @@ -97,7 +118,8 @@ describe('signInAgain', () => { await signInAgain(actionContext(), { clusterId }); expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( - 'The connection was closed while you were signing in.', { modal: true }, + 'The connection was closed while you were signing in.', + { modal: true }, ); vi.mocked(ClustersClient.getEpoch).mockReturnValue(1); }); diff --git a/src/commands/signInAgain/signInAgain.ts b/src/commands/signInAgain/signInAgain.ts index 3890cbb57..caebaeedf 100644 --- a/src/commands/signInAgain/signInAgain.ts +++ b/src/commands/signInAgain/signInAgain.ts @@ -9,19 +9,21 @@ import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; import { EntraIdentityMismatchError } from '../../documentdb/auth/entraErrors/entraCallbackErrors'; import { getEntraSession } from '../../documentdb/auth/entraSession'; import { MicrosoftEntraIDAuthHandler } from '../../documentdb/auth/MicrosoftEntraIDAuthHandler'; -import { classifyConnectionFailure } from '../../documentdb/connectionFailures'; import { addEstablishedConnectionContext, ClustersClient } from '../../documentdb/ClustersClient'; +import { classifyConnectionFailure } from '../../documentdb/connectionFailures'; import { CredentialCache } from '../../documentdb/CredentialCache'; import { showClusterConnectFailure } from '../../documentdb/showClusterConnectFailure'; import { type ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; import { refreshAuthenticationNode } from '../retryAuthentication/retryAuthentication'; function isSignInDismissal(error: unknown): boolean { - return error instanceof UserCancelledError || + return ( + error instanceof UserCancelledError || (error instanceof Error && (error.name === 'Canceled' || error.message === 'User did not consent to login.' || - ('errorCode' in error && error.errorCode === 'user_cancelled'))); + ('errorCode' in error && error.errorCode === 'user_cancelled'))) + ); } export async function signInAgain( @@ -40,9 +42,11 @@ export async function signInAgain( } const identity = ClustersClient.getLastVerifiedIdentity(clusterId); const credentials = CredentialCache.getCredentials(clusterId); - if (identity?.kind !== 'entra' || + if ( + identity?.kind !== 'entra' || credentials?.authMechanism !== AuthMethodId.MicrosoftEntraID || - identity.tenantId !== credentials.entraIdConfig?.tenantId) { + identity.tenantId !== credentials.entraIdConfig?.tenantId + ) { throw new Error(vscode.l10n.t('No verified Microsoft Entra ID connection is available to sign in again.')); } @@ -59,7 +63,10 @@ export async function signInAgain( let starting = false; try { - const handler = new MicrosoftEntraIDAuthHandler(credentials, { interactive: false, pinnedEntraIdentity: identity }); + const handler = new MicrosoftEntraIDAuthHandler(credentials, { + interactive: false, + pinnedEntraIdentity: identity, + }); const auth = await handler.configureAuth(undefined, undefined, async (request) => { if (!isCurrent()) { throw new UserCancelledError('signInAgain'); @@ -71,8 +78,10 @@ export async function signInAgain( if (session.account.id !== identity.accountId) { // 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 (session.account.label === identity.accountLabel || - (identity.providerId !== 'microsoft' && identity.providerId !== 'microsoft-sovereign-cloud')) { + if ( + session.account.label === identity.accountLabel || + (identity.providerId !== 'microsoft' && identity.providerId !== 'microsoft-sovereign-cloud') + ) { throw new EntraIdentityMismatchError(); } } @@ -90,7 +99,11 @@ export async function signInAgain( reportClosed(); return; } - if (ClustersClient.getExistingClient(clusterId) === client && !ClustersClient.getLatchReason(clusterId) && node) { + if ( + ClustersClient.getExistingClient(clusterId) === client && + !ClustersClient.getLatchReason(clusterId) && + node + ) { refreshAuthenticationNode(node); } } catch (error) { @@ -101,7 +114,10 @@ export async function signInAgain( if (isSignInDismissal(error)) { throw new UserCancelledError('signInAgain'); } - context.telemetry.properties.connectionFailureKind = classifyConnectionFailure(error, AuthMethodId.MicrosoftEntraID).kind; + context.telemetry.properties.connectionFailureKind = classifyConnectionFailure( + error, + AuthMethodId.MicrosoftEntraID, + ).kind; await showClusterConnectFailure({ clusterId, clusterName: node?.cluster.name ?? vscode.l10n.t('connection'), diff --git a/src/commands/updateConnectionString/updateConnectionString.test.ts b/src/commands/updateConnectionString/updateConnectionString.test.ts index 8cf9fdd1c..e92706332 100644 --- a/src/commands/updateConnectionString/updateConnectionString.test.ts +++ b/src/commands/updateConnectionString/updateConnectionString.test.ts @@ -87,8 +87,12 @@ vi.mock('../../services/connectionStorageService', async (importOriginal) => ({ vi.mock('../../documentdb/ClustersClient', () => ({ addEstablishedConnectionContext: vi.fn(), ClustersClient: { - connectInteractive: vi.fn(), deleteClient: vi.fn(), exists: vi.fn(), - getEpoch: vi.fn(() => 0), getLatchReason: vi.fn(), getExistingClient: vi.fn(), + connectInteractive: vi.fn(), + deleteClient: vi.fn(), + exists: vi.fn(), + getEpoch: vi.fn(() => 0), + getLatchReason: vi.fn(), + getExistingClient: vi.fn(), }, })); vi.mock('../../services/connectionReachabilityService', () => ({ diff --git a/src/commands/updateCredentials/updateCredentials.ts b/src/commands/updateCredentials/updateCredentials.ts index 07ede843c..8ebc1c3fe 100644 --- a/src/commands/updateCredentials/updateCredentials.ts +++ b/src/commands/updateCredentials/updateCredentials.ts @@ -168,7 +168,10 @@ export async function updateCredentials(context: IActionContext, node: DocumentD const username = updatedConnection?.secrets.nativeAuthConfig?.connectionUser; const password = updatedConnection?.secrets.nativeAuthConfig?.connectionPassword; if (recoveringRejection && authMethod === AuthMethodId.MicrosoftEntraID) { - ClustersClient.discardEntraPinForDifferentTenant(clusterId, updatedConnection?.secrets.entraIdAuthConfig?.tenantId); + ClustersClient.discardEntraPinForDifferentTenant( + clusterId, + updatedConnection?.secrets.entraIdAuthConfig?.tenantId, + ); } if (updatedConnection && authMethod && !(authMethod === AuthMethodId.NativeAuth && (!username || !password))) { const connectionString = new DocumentDBConnectionString(updatedConnection.secrets.connectionString); diff --git a/src/documentdb/ClustersClient.test.ts b/src/documentdb/ClustersClient.test.ts index 09908c6c3..b7b2c69bd 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -517,9 +517,11 @@ describe('regular connection startup diagnostics', () => { expect(CredentialCache.getCredentials(clusterId)).toBe(settings); expect(ClustersClient.getLastVerifiedIdentity(clusterId)).toBe(identity); await expect(ClustersClient.getClient(clusterId)).rejects.toMatchObject({ reason: 'credentialsRejected' }); - await expect(ClustersClient.getClient(clusterId, undefined, undefined, 'treeChildren', { - background: true, - })).rejects.toMatchObject({ reason: 'credentialsRejected' }); + await expect( + ClustersClient.getClient(clusterId, undefined, undefined, 'treeChildren', { + background: true, + }), + ).rejects.toMatchObject({ reason: 'credentialsRejected' }); expect(MongoClient).toHaveBeenCalledOnce(); expect(ClustersClient.clearCredentialRejection(clusterId, ClustersClient.getEpoch(clusterId))).toBe(true); @@ -549,8 +551,11 @@ describe('regular connection startup diagnostics', () => { clusterId, ClustersClient.getEpoch(clusterId), CredentialCache.getCredentials(clusterId)!, - { connectionString: 'mongodb://private-host:27017', options: {}, - verifiedIdentity: { ...verifiedIdentity, accountId: 'other-account' } }, + { + connectionString: 'mongodb://private-host:27017', + options: {}, + verifiedIdentity: { ...verifiedIdentity, accountId: 'other-account' }, + }, ); await connection.started; ClustersClient.latch(clusterId, 'userDisconnected'); diff --git a/src/documentdb/ClustersClient.ts b/src/documentdb/ClustersClient.ts index 290bbd936..d0a0a534a 100644 --- a/src/documentdb/ClustersClient.ts +++ b/src/documentdb/ClustersClient.ts @@ -559,11 +559,13 @@ export class ClustersClient { // Configure auth and get connection options this.advanceClientStartup(startup, 'stage02ConfiguringAuth'); - const { connectionString, options, verifiedIdentity } = recoveredAuth ?? await authHandler.configureAuth(startup.costTimings, { - startupCorrelationId: startup.id, - surface: 'extension', - startupProperties: startup.telemetry.properties, - }); + const { connectionString, options, verifiedIdentity } = + recoveredAuth ?? + (await authHandler.configureAuth(startup.costTimings, { + startupCorrelationId: startup.id, + surface: 'extension', + startupProperties: startup.telemetry.properties, + })); this.advanceClientStartup(startup, 'stage03PreparingClient'); this.#verifiedIdentity = getVerifiedIdentity(authMethod, credentials, connectionString, verifiedIdentity); @@ -777,10 +779,12 @@ export class ClustersClient { auth: AuthHandlerResponse, ): Promise { const reason = ClustersClient.getLatchReason(clusterId); - if (epoch !== ClustersClient.getEpoch(clusterId) || + if ( + epoch !== ClustersClient.getEpoch(clusterId) || CredentialCache.getCredentials(clusterId) !== credentials || credentials.authMechanism !== AuthMethodId.MicrosoftEntraID || - (reason && reason !== 'credentialsRejected')) { + (reason && reason !== 'credentialsRejected') + ) { return undefined; } if (reason && !ClustersClient.clearCredentialRejection(clusterId, epoch)) { @@ -791,15 +795,25 @@ export class ClustersClient { }); const startupEpoch = ClustersClient.getEpoch(clusterId); try { - const { promise } = ClustersClient.getOrStartClient(clusterId, startupEpoch, 'treeConnect', false, false, undefined, auth); + const { promise } = ClustersClient.getOrStartClient( + clusterId, + startupEpoch, + 'treeConnect', + false, + false, + undefined, + auth, + ); const client = await promise; return startupEpoch === ClustersClient.getEpoch(clusterId) ? client : undefined; } catch (error) { if (startupEpoch !== ClustersClient.getEpoch(clusterId)) { return undefined; } - if (reason === 'credentialsRejected' || - classifyConnectionFailure(error, AuthMethodId.MicrosoftEntraID).kind === 'credentialsRejected') { + if ( + reason === 'credentialsRejected' || + classifyConnectionFailure(error, AuthMethodId.MicrosoftEntraID).kind === 'credentialsRejected' + ) { ClustersClient.latch(clusterId, 'credentialsRejected'); } throw error; @@ -905,7 +919,15 @@ export class ClustersClient { const id = randomUUID(); // Register before initialization or a caller's onStartup callback can re-enter getClient. const promise = Promise.resolve().then(() => - ClustersClient.establishClient(clusterId, epoch, id, trigger, allowInteractive, expectedFingerprint, recoveredAuth), + ClustersClient.establishClient( + clusterId, + epoch, + id, + trigger, + allowInteractive, + expectedFingerprint, + recoveredAuth, + ), ); const pending = { id, epoch, promise }; ClustersClient._pendingStartups.set(clusterId, pending); diff --git a/src/documentdb/ClustersExtension.ts b/src/documentdb/ClustersExtension.ts index cd3b99150..91e5f41b3 100644 --- a/src/documentdb/ClustersExtension.ts +++ b/src/documentdb/ClustersExtension.ts @@ -83,11 +83,11 @@ import { refreshView } from '../commands/refreshView/refreshView'; import { removeConnection } from '../commands/removeConnection/removeConnection'; import { removeDiscoveryRegistry } from '../commands/removeDiscoveryRegistry/removeDiscoveryRegistry'; import { retryAuthentication } from '../commands/retryAuthentication/retryAuthentication'; -import { signInAgain } from '../commands/signInAgain/signInAgain'; import { revealView } from '../commands/revealView/revealView'; import { clearSchemaCache } from '../commands/schemaStore/clearSchemaCache'; import { showSchemaStoreStats } from '../commands/schemaStore/showSchemaStoreStats'; import { showWorkerStats } from '../commands/showWorkerStats/showWorkerStats'; +import { signInAgain } from '../commands/signInAgain/signInAgain'; import { updateConnectionString } from '../commands/updateConnectionString/updateConnectionString'; import { updateCredentials } from '../commands/updateCredentials/updateCredentials'; import { isVCoreAndRURolloutEnabled } from '../extension'; diff --git a/src/documentdb/connectionFailures.ts b/src/documentdb/connectionFailures.ts index 740711801..c51df8b30 100644 --- a/src/documentdb/connectionFailures.ts +++ b/src/documentdb/connectionFailures.ts @@ -144,7 +144,9 @@ export function classifyConnectionFailure(error: unknown, authMethod?: AuthMetho } if (agreed) { mixed ||= - result.kind !== agreed.kind || result.generation !== agreed.generation || result.note !== agreed.note; + result.kind !== agreed.kind || + result.generation !== agreed.generation || + result.note !== agreed.note; } else { agreed = result; } diff --git a/src/tree/azure-resources-view/documentdb/azureResourceAuthentication.test.ts b/src/tree/azure-resources-view/documentdb/azureResourceAuthentication.test.ts index 93db00959..312715fbf 100644 --- a/src/tree/azure-resources-view/documentdb/azureResourceAuthentication.test.ts +++ b/src/tree/azure-resources-view/documentdb/azureResourceAuthentication.test.ts @@ -71,10 +71,21 @@ vi.mock('../../../utils/azureClients', () => ({ createMongoClustersManagementClient: vi.fn(() => ({ mongoClusters: { get: getCluster } })), })); vi.mock('../../../documentdb/ClustersClient', () => ({ - ClustersClient: { connectInteractive: vi.fn(), deleteClient: vi.fn() }, + addEstablishedConnectionContext: vi.fn(), + ClustersClient: { + getEpoch: vi.fn(() => 0), + getLatchReason: vi.fn(), + connectInteractive: vi.fn(), + deleteClient: vi.fn(), + }, })); vi.mock('../../../documentdb/CredentialCache', () => ({ - CredentialCache: { hasCredentials: vi.fn(), setAuthCredentials: vi.fn(), deleteCredentials: vi.fn() }, + CredentialCache: { + getCredentials: vi.fn(), + hasCredentials: vi.fn(), + setAuthCredentials: vi.fn(), + deleteCredentials: vi.fn(), + }, })); vi.mock('../../../extensionVariables', () => ({ ext: { diff --git a/src/tree/connections-view/DocumentDBClusterItem.test.ts b/src/tree/connections-view/DocumentDBClusterItem.test.ts index 35aed1f64..74027545f 100644 --- a/src/tree/connections-view/DocumentDBClusterItem.test.ts +++ b/src/tree/connections-view/DocumentDBClusterItem.test.ts @@ -89,10 +89,21 @@ vi.mock('../../services/connectionStorageService', async (importOriginal) => ({ })); vi.mock('../../documentdb/ClustersClient', () => ({ addEstablishedConnectionContext: vi.fn(), - ClustersClient: { connectInteractive: vi.fn(), deleteClient: vi.fn(), exists: vi.fn(), getEpoch: vi.fn(() => 0), getLatchReason: vi.fn() }, + ClustersClient: { + connectInteractive: vi.fn(), + deleteClient: vi.fn(), + exists: vi.fn(), + getEpoch: vi.fn(() => 0), + getLatchReason: vi.fn(), + }, })); vi.mock('../../documentdb/CredentialCache', () => ({ - CredentialCache: { hasCredentials: vi.fn(), setAuthCredentials: vi.fn(), deleteCredentials: vi.fn(), getCredentials: vi.fn() }, + CredentialCache: { + hasCredentials: vi.fn(), + setAuthCredentials: vi.fn(), + deleteCredentials: vi.fn(), + getCredentials: vi.fn(), + }, })); vi.mock('../../services/connectionReachabilityService', () => ({ ConnectionReachabilityService: { ensureReachable: vi.fn() }, diff --git a/src/tree/connections-view/LocalQuickStart/LocalQuickStartItem.credentials.test.ts b/src/tree/connections-view/LocalQuickStart/LocalQuickStartItem.credentials.test.ts index f45687f83..55745158a 100644 --- a/src/tree/connections-view/LocalQuickStart/LocalQuickStartItem.credentials.test.ts +++ b/src/tree/connections-view/LocalQuickStart/LocalQuickStartItem.credentials.test.ts @@ -77,7 +77,10 @@ vi.mock('../../../services/SettingsService', () => ({ const mockGetClient = vi.fn(); vi.mock('../../../documentdb/ClustersClient', () => ({ + addEstablishedConnectionContext: vi.fn(), ClustersClient: { + getEpoch: vi.fn(() => 0), + getLatchReason: vi.fn(), exists: vi.fn().mockReturnValue(false), connectInteractive: (...args: unknown[]) => mockGetClient(...args), }, diff --git a/src/tree/documentdb/ClusterItemBase.test.ts b/src/tree/documentdb/ClusterItemBase.test.ts index 63c506d27..7de34e605 100644 --- a/src/tree/documentdb/ClusterItemBase.test.ts +++ b/src/tree/documentdb/ClusterItemBase.test.ts @@ -11,8 +11,8 @@ import { type IActionContext, } from '@microsoft/vscode-azext-utils'; import * as vscode from 'vscode'; -import { EntraDestinationRejectedError } from '../../documentdb/auth/oidcAllowedHosts'; import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; +import { EntraDestinationRejectedError } from '../../documentdb/auth/oidcAllowedHosts'; import { ClustersClient, type DatabaseItemModel } from '../../documentdb/ClustersClient'; import { ConnectionUnavailableError } from '../../documentdb/ConnectionUnavailableError'; import { CredentialCache } from '../../documentdb/CredentialCache'; @@ -78,8 +78,13 @@ vi.mock('../../documentdb/CredentialCache', () => ({ vi.mock('../../documentdb/ClustersClient', () => ({ addEstablishedConnectionContext: vi.fn(), ClustersClient: { - connectInteractive: vi.fn(), exists: vi.fn().mockReturnValue(false), getExistingClient: vi.fn(), - getLatchReason: vi.fn(), getEpoch: vi.fn(() => 0), getLastVerifiedIdentity: vi.fn(), reportFailure: vi.fn(), + connectInteractive: vi.fn(), + exists: vi.fn().mockReturnValue(false), + getExistingClient: vi.fn(), + getLatchReason: vi.fn(), + getEpoch: vi.fn(() => 0), + getLastVerifiedIdentity: vi.fn(), + reportFailure: vi.fn(), }, })); diff --git a/src/tree/documentdb/ClusterItemBase.ts b/src/tree/documentdb/ClusterItemBase.ts index ae0c8be40..cad28218c 100644 --- a/src/tree/documentdb/ClusterItemBase.ts +++ b/src/tree/documentdb/ClusterItemBase.ts @@ -4,10 +4,10 @@ *--------------------------------------------------------------------------------------------*/ import { - UserCancelledError, callWithTelemetryAndErrorHandling, createContextValue, createGenericElement, + UserCancelledError, type IActionContext, } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; @@ -158,7 +158,10 @@ export abstract class ClusterItemBase { reusedClient = client; }); + clustersClient = await this.getClientWithProgress(clusterId, (client) => { + reusedClient = client; + }); } catch (error) { return this.renderExpansionFailure(error, 'cachedClientConnect', reusedClient, acquisitionEpoch); } @@ -585,7 +608,9 @@ export abstract class ClusterItemBase child.id === `${this.id}/sign-in-again`) === true; + return ( + containsRetryNode(children) || children?.some((child) => child.id === `${this.id}/sign-in-again`) === true + ); } /** From 20dcde1be4b835b6d9b40971de37f64e3dca4162 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 17:06:52 +0000 Subject: [PATCH 09/29] docs: defer prompt Microsoft sign-out handling until after 1.2.0 Record the partial OP-3 evidence and track prompt sign-out handling in #1119 without changing the existing gate. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../features/connection-lifecycle/README.md | 6 +++-- .../iterations/01-dev-plan.md | 24 ++++++++++++++++++- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/README.md b/docs/ai-and-plans/features/connection-lifecycle/README.md index b35c648cf..e6598d6f6 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/README.md +++ b/docs/ai-and-plans/features/connection-lifecycle/README.md @@ -18,8 +18,10 @@ code: - [#1059](https://github.com/microsoft/vscode-documentdb/issues/1059) - [#566](https://github.com/microsoft/vscode-documentdb/issues/566) - [#990](https://github.com/microsoft/vscode-documentdb/issues/990) -- follow-up after 1.2.0: [#1105](https://github.com/microsoft/vscode-documentdb/issues/1105) (Kubernetes tunnels, network resilience) and - [#1106](https://github.com/microsoft/vscode-documentdb/issues/1106) (out-of-date results) +- follow-ups after 1.2.0: [#1105](https://github.com/microsoft/vscode-documentdb/issues/1105) + (Kubernetes tunnels, network resilience), [#1106](https://github.com/microsoft/vscode-documentdb/issues/1106) + (out-of-date results), and [#1119](https://github.com/microsoft/vscode-documentdb/issues/1119) + (prompt handling of Microsoft account sign-out) **Branch:** `feature/connection-lifecycle`, with stacked sub-PRs from `dev/tnaum/*`. Implementation does not wait for intermediate merges; the operator handles approvals and merges (decision 0006). 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 6784455de..5a816c517 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 @@ -135,7 +135,7 @@ Every PR names the issues it may resolve, using the table below, and says for ea Keep it factual and short. Never include tokens, account names, cluster names or connection strings. Record the comment's link in the WI's Progress block. -- **Work moved to a follow-up issue** (#1105, #1106): when a PR hands work over, comment on the +- **Work moved to a follow-up issue** (#1105, #1106, #1119): when a PR hands work over, comment on the follow-up in the same way, so it can be planned from that comment alone. | Issue | Title (short) | PRs | Expected | @@ -148,6 +148,7 @@ Every PR names the issues it may resolve, using the table below, and says for ea | #1091 | Dashboard health check: pause, back off, stop | 6 (WI-8) | Partial unless WI-8 also does the visibility pause and backoff | | #1105 | Follow-up: Kubernetes tunnels, network resilience | — | Not resolved; comment when a PR moves work there | | #1106 | Follow-up: indicate possibly out-of-date results | — | Not resolved; comment when a PR moves work there | +| #1119 | Follow-up: handle Microsoft sign-out promptly | — | Not in 1.2.0 | ### Skills to load per work item @@ -339,6 +340,12 @@ Moved to [#1106](https://github.com/microsoft/vscode-documentdb/issues/1106) (de "results may be out of date" indication. That covers the return from the disconnected state, long idle, and writes made from another view or another client. +Prompt handling of Microsoft account sign-out is deferred to +[#1119](https://github.com/microsoft/vscode-documentdb/issues/1119), after 1.2.0. Under decisions +0001 and 0012, signing out of VS Code does not close an established database client. The client +can keep authenticating with a cached token while the server accepts it. When the driver requests +a new token and the pinned session is gone, recovery remains explicit through **Sign in again**. + Generic idle and network-drop recovery **stays in scope**: closed-client and transient classification, the cancelled-reuse fix, closed-client replacement and OT-4. It is #1102's "recover on the next operation without a restart". The no-regression rules in WI-5 and WI-6 keep tunneled connections @@ -1315,6 +1322,21 @@ shim (0005). full test run found 32 failures in three suites whose mocks did not expose the new lifecycle methods. Update those fixtures without changing their assertions or runtime recovery behavior. OP-3 remains the live Entra sign-out and dismissal gate. +- **OP-3 partial live run (2026-11-23):** A CI-built PR4 VSIX loaded databases and the dashboard. + After sign-out, idle sockets closed and fresh sockets became ready under the same client startup. + No post-sign-out OIDC callback appears in the supplied excerpt, and sign-in recovery and dismissal + were not reached. The run is inconclusive; OP-3 remains open. On resume, close the dashboard, + wait until the cached token is no longer accepted, and explicitly refresh the cluster node + without restarting the extension host. Collapse and re-expand can show cached children. +- **Sign-out scope review (2026-11-23):** Claude Opus 5.5 recommended keeping the approved + 1.2.0 scope (80% confidence). Prompt sign-out handling would need account-specific session + checks, coordination with active tasks, and separate handling for Shell and Playground + clients. Track it in [#1119](https://github.com/microsoft/vscode-documentdb/issues/1119). + OP-3 and its required evidence are unchanged. +- **Future operator VSIX builds:** Give each new test candidate a distinct extension version in + the root `package.json` and corresponding root lockfile entries. Verify the version in the + packaged manifest, and give the operator that version, the commit, and the CI artifact link. + Do not rebuild an unchanged candidate just to label the partial run. --- From a557fb642ed18c1629eed8980a5ef5e6da56578c Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 17:14:24 +0000 Subject: [PATCH 10/29] fix: keep VS Code UI imports out of the database worker Separate the shared auth IDs from host-only UI metadata so workers can load OIDC options in Node. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/documentdb/auth/AuthMethod.ts | 21 ++----------------- src/documentdb/auth/AuthMethodId.ts | 21 +++++++++++++++++++ .../auth/entraErrors/entraCallbackErrors.ts | 2 +- src/documentdb/auth/oidcClientOptions.test.ts | 4 ++++ 4 files changed, 28 insertions(+), 20 deletions(-) create mode 100644 src/documentdb/auth/AuthMethodId.ts diff --git a/src/documentdb/auth/AuthMethod.ts b/src/documentdb/auth/AuthMethod.ts index e0c92b178..d32b7bc9d 100644 --- a/src/documentdb/auth/AuthMethod.ts +++ b/src/documentdb/auth/AuthMethod.ts @@ -5,26 +5,9 @@ import * as vscode from 'vscode'; import { getIconPath } from '../../utils/icons'; +import { AuthMethodId } from './AuthMethodId'; -/** - * Authentication method identifiers - */ -export enum AuthMethodId { - /** The regular, typical username+password and connection string authentication. */ - NativeAuth = 'NativeAuth', - /** Microsoft Entra ID (Azure AD) authentication. */ - MicrosoftEntraID = 'MicrosoftEntraID', - /** - * Microsoft Entra ID using the managed identity of the Azure resource hosting VS Code. - * - * Note: unlike the other values, this one has no counterpart in the ARM `authConfig.allowedModes` - * vocabulary, so it is never produced by pass-through of service metadata. It is synthesized by - * an explicit rule in `clusterHelpers.ts`. - */ - ManagedIdentity = 'ManagedIdentity', - /** Anonymous connection without a username, password, or Entra ID. */ - NoAuth = 'NoAuth', -} +export { AuthMethodId }; /** * Authentication method metadata diff --git a/src/documentdb/auth/AuthMethodId.ts b/src/documentdb/auth/AuthMethodId.ts new file mode 100644 index 000000000..d43a37ec5 --- /dev/null +++ b/src/documentdb/auth/AuthMethodId.ts @@ -0,0 +1,21 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +export enum AuthMethodId { + /** The regular, typical username+password and connection string authentication. */ + NativeAuth = 'NativeAuth', + /** Microsoft Entra ID (Azure AD) authentication. */ + MicrosoftEntraID = 'MicrosoftEntraID', + /** + * Microsoft Entra ID using the managed identity of the Azure resource hosting VS Code. + * + * Note: unlike the other values, this one has no counterpart in the ARM `authConfig.allowedModes` + * vocabulary, so it is never produced by pass-through of service metadata. It is synthesized by + * an explicit rule in `clusterHelpers.ts`. + */ + ManagedIdentity = 'ManagedIdentity', + /** Anonymous connection without a username, password, or Entra ID. */ + NoAuth = 'NoAuth', +} diff --git a/src/documentdb/auth/entraErrors/entraCallbackErrors.ts b/src/documentdb/auth/entraErrors/entraCallbackErrors.ts index 016651b1b..ef0df558b 100644 --- a/src/documentdb/auth/entraErrors/entraCallbackErrors.ts +++ b/src/documentdb/auth/entraErrors/entraCallbackErrors.ts @@ -4,7 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import * as l10n from '@vscode/l10n'; -import { AuthMethodId } from '../AuthMethod'; +import { AuthMethodId } from '../AuthMethodId'; export class EntraSignInRequiredError extends Error { constructor(public readonly reason: 'noSession' | 'providerChanged') { diff --git a/src/documentdb/auth/oidcClientOptions.test.ts b/src/documentdb/auth/oidcClientOptions.test.ts index 552f02746..da5736391 100644 --- a/src/documentdb/auth/oidcClientOptions.test.ts +++ b/src/documentdb/auth/oidcClientOptions.test.ts @@ -14,6 +14,10 @@ import { createOidcDestinationPolicy, } from './oidcClientOptions'; +vi.mock('vscode', () => { + throw new Error('Node workers must be able to load OIDC options without the VS Code host module.'); +}); + const host = 'cluster.mongocluster.cosmos.azure.com'; const connectionString = `mongodb://${host}/`; const patterns = ['*.mongocluster.cosmos.azure.com']; From 34929b54038f24e073bed646d78658cb35e438e0 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 17:14:24 +0000 Subject: [PATCH 11/29] feat: show sanitized extension-host connection stats (WI-5) Expose a read-only snapshot for operators without changing the existing OP-3 candidate. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iterations/01-dev-plan.md | 8 +++ package.json | 6 +++ package.nls.json | 1 + .../showConnectionStats.ts | 36 +++++++++++++ src/documentdb/ClustersClient.test.ts | 53 +++++++++++++++++++ src/documentdb/ClustersClient.ts | 49 ++++++++++++++++- src/documentdb/ClustersExtension.ts | 5 ++ 7 files changed, 156 insertions(+), 2 deletions(-) create mode 100644 src/commands/showConnectionStats/showConnectionStats.ts 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 5a816c517..09687d174 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 @@ -1337,6 +1337,14 @@ shim (0005). the root `package.json` and corresponding root lockfile entries. Verify the version in the packaged manifest, and give the operator that version, the commit, and the CI artifact link. Do not rebuild an unchanged candidate just to label the partial run. +- **Connection stats add-on:** Add a read-only **Show Connection Stats** command alongside + **Show Worker Stats**, as a separate WI-5 commit. The extension-host snapshot shows client + generation, age, auth method, startup correlation, pending or held state, and whether socket + events are traced. It contains no cluster or account identifiers and makes no service calls. + Leave socket counts out rather than guessing. Keep the published OP-3 candidate unchanged. +- **Worker startup regression:** PR4's shared OIDC code imported the VS Code UI auth-method + module into the Node worker path. Keep the shared auth IDs independent of VS Code. Verify + the next packaged candidate starts both Shell and Playground; the tree OP-3 gate is unchanged. --- diff --git a/package.json b/package.json index 452852242..5a096fdb1 100644 --- a/package.json +++ b/package.json @@ -935,6 +935,12 @@ "command": "vscode-documentdb.command.showSchemaStoreStats", "title": "Show Schema Store Stats" }, + { + "//": "[Diagnostics] Show Connection Stats", + "category": "DocumentDB", + "command": "vscode-documentdb.command.showConnectionStats", + "title": "%diagnostics.showConnectionStats%" + }, { "//": "[Diagnostics] Show Worker Stats", "category": "DocumentDB", diff --git a/package.nls.json b/package.nls.json index 88f95c3c7..b30f91418 100644 --- a/package.nls.json +++ b/package.nls.json @@ -1,4 +1,5 @@ { + "diagnostics.showConnectionStats": "Show Connection Stats", "survey.containerTitle": "DocumentDB Feedback", "survey.viewTitle": "Share Your Experience", "survey.giveFeedbackTitle": "Give Feedback", diff --git a/src/commands/showConnectionStats/showConnectionStats.ts b/src/commands/showConnectionStats/showConnectionStats.ts new file mode 100644 index 000000000..8e7f08364 --- /dev/null +++ b/src/commands/showConnectionStats/showConnectionStats.ts @@ -0,0 +1,36 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { type IActionContext } from '@microsoft/vscode-azext-utils'; +import { ClustersClient } from '../../documentdb/ClustersClient'; +import { ext } from '../../extensionVariables'; + +export function showConnectionStats(_context: IActionContext): void { + const snapshot = ClustersClient.getDiagnosticsSnapshot(); + ext.outputChannel.appendLog(`[Connection Stats] Extension-host cache entries: ${String(snapshot.length)}`); + ext.outputChannel.appendLog( + 'Each cached client can own multiple sockets. Socket counts are not tracked here. For Shell and Playground, use Show Worker Stats.', + ); + for (const [index, { client, pending, held, lastFailedStartupId }] of snapshot.entries()) { + ext.outputChannel.appendLog(` Connection ${String(index + 1)}:`); + ext.outputChannel.appendLog( + client + ? ` Client: ${client.state} generation=${String(client.generation)} ageMs=${String(client.ageMs)} auth=${client.authMethod ?? 'unknown'} startup=${client.startupId ?? 'none'} socketTrace=${String(client.socketTrace)}` + : ' Client: none', + ); + if (pending) { + ext.outputChannel.appendLog( + ` Pending: ${pending.superseded ? 'superseded' : 'current'} startup=${pending.startupId}`, + ); + } + if (held) { + ext.outputChannel.appendLog(` Held: ${held}`); + } + if (lastFailedStartupId) { + ext.outputChannel.appendLog(` Last failed startup: ${lastFailedStartupId}`); + } + } + ext.outputChannel.show(); +} diff --git a/src/documentdb/ClustersClient.test.ts b/src/documentdb/ClustersClient.test.ts index b7b2c69bd..2965fc986 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -239,6 +239,59 @@ describe('regular connection startup diagnostics', () => { expect(second.createdAt).toBeGreaterThan(first.createdAt); }); + it('reports read-only client diagnostics without connection or identity details', async (): Promise => { + const client = await ClustersClient.connectInteractive(clusterId); + vi.advanceTimersByTime(2_000); + + const snapshot = ClustersClient.getDiagnosticsSnapshot(); + const entry = snapshot.find(({ client: row }) => row?.startupId === client.connectionCorrelationId); + + expect(entry?.client).toEqual({ + generation: client.generation, + ageMs: 2_000, + authMethod: AuthMethodId.MicrosoftEntraID, + startupId: client.connectionCorrelationId, + state: 'cached', + socketTrace: true, + }); + const output = JSON.stringify(snapshot); + for (const value of [ + clusterId, + client.fingerprint, + verifiedIdentity.accountId, + verifiedIdentity.accountLabel, + verifiedIdentity.tenantId, + 'private-host', + ]) { + expect(output).not.toContain(value); + } + expect(await ClustersClient.getClient(clusterId)).toBe(client); + expect(mockConnect).toHaveBeenCalledOnce(); + expect(mockClose).not.toHaveBeenCalled(); + }); + + it('shows a superseded startup and a hold even without a cached client', async (): Promise => { + const handshake = pauseNextConnect(); + const onStartup = vi.fn<(id: string) => void>(); + const opening = ClustersClient.connectInteractive(clusterId, undefined, onStartup); + await handshake.started; + const startupId = onStartup.mock.calls[0][0]; + const findPending = () => + ClustersClient.getDiagnosticsSnapshot().find(({ pending }) => pending?.startupId === startupId); + expect(findPending()).toMatchObject({ client: undefined, pending: { superseded: false } }); + + ClustersClient.latch(clusterId, 'userDisconnected'); + expect(findPending()).toMatchObject({ + client: undefined, + pending: { superseded: true }, + held: 'userDisconnected', + }); + + handshake.resolve(); + await expect(opening).rejects.toMatchObject({ reason: 'userDisconnected' }); + ClustersClient.unlatch(clusterId); + }); + it('never hydrates unpinned Entra silently, even after a native connection', async () => { const expectNoSession = async (): Promise => { await expect( diff --git a/src/documentdb/ClustersClient.ts b/src/documentdb/ClustersClient.ts index d0a0a534a..a578629e3 100644 --- a/src/documentdb/ClustersClient.ts +++ b/src/documentdb/ClustersClient.ts @@ -45,7 +45,7 @@ import { meterSilentCatch } from '../utils/accumulatingTelemetry'; import { type EmulatorConfiguration } from '../utils/emulatorConfiguration'; import { nonNullValue } from '../utils/nonNull'; import { type AuthHandlerResponse, type VerifiedEntraIdentity } from './auth/AuthHandler'; -import { AuthMethodId } from './auth/AuthMethod'; +import { AuthMethodId, isSupportedAuthMethod } from './auth/AuthMethod'; import { createAuthHandler } from './auth/createAuthHandler'; import { EntraSignInRequiredError } from './auth/entraErrors/entraCallbackErrors'; import { getAzureHostSuffix } from './auth/oidcAllowedHosts'; @@ -89,6 +89,20 @@ export interface ConnectionBinding { readonly generation: number; } +interface ConnectionStatsEntry { + readonly client?: { + readonly generation: number; + readonly ageMs: number; + readonly authMethod?: AuthMethodId; + readonly startupId?: string; + readonly state: 'cached' | 'closed' | 'replaceOnNextForeground' | 'replaceOnRecovery'; + readonly socketTrace: boolean; + }; + readonly pending?: { readonly startupId: string; readonly superseded: boolean }; + readonly held?: ConnectionUnavailableReason; + readonly lastFailedStartupId?: string; +} + export type VerifiedIdentity = VerifiedEntraIdentity | Exclude; export interface CollectionItemModel { @@ -363,6 +377,37 @@ export class ClustersClient { return ClustersClient._lastFailedStartups.get(clusterId); } + public static getDiagnosticsSnapshot(): readonly ConnectionStatsEntry[] { + const now = Date.now(); + const clusterIds = new Set([ + ...ClustersClient._clients.keys(), + ...ClustersClient._pendingStartups.keys(), + ...ClustersClient._latches.keys(), + ...ClustersClient._lastFailedStartups.keys(), + ]); + return Array.from(clusterIds, (clusterId): ConnectionStatsEntry => { + const client = ClustersClient._clients.get(clusterId); + const pending = ClustersClient._pendingStartups.get(clusterId); + const authMethod = client?.authMethod; + return { + client: client && { + generation: client.generation, + ageMs: Math.max(0, now - client.createdAt), + authMethod: isSupportedAuthMethod(authMethod) ? authMethod : undefined, + startupId: client.connectionCorrelationId, + state: client._replacement ?? (client._closed ? 'closed' : 'cached'), + socketTrace: client._interactiveEntraStartupId !== undefined, + }, + pending: pending && { + startupId: pending.id, + superseded: pending.epoch !== ClustersClient.getEpoch(clusterId), + }, + held: ClustersClient.getLatchReason(clusterId), + lastFailedStartupId: ClustersClient.getLastFailedStartupCorrelationId(clusterId), + }; + }); + } + /** * Private constructor - use getClient() instead. * Connections/Clients are being cached and reused. @@ -1057,7 +1102,7 @@ export class ClustersClient { } /** - * Returns an existing client synchronously if it is already in the connection pool. + * Returns an existing client synchronously if it is already in the client cache. * Returns `undefined` if the client is not yet connected. This is useful for * accessing cached data (e.g., cached collection/database listings) without * triggering a connection or blocking on async operations. diff --git a/src/documentdb/ClustersExtension.ts b/src/documentdb/ClustersExtension.ts index 91e5f41b3..23a91d37a 100644 --- a/src/documentdb/ClustersExtension.ts +++ b/src/documentdb/ClustersExtension.ts @@ -86,6 +86,7 @@ import { retryAuthentication } from '../commands/retryAuthentication/retryAuthen import { revealView } from '../commands/revealView/revealView'; import { clearSchemaCache } from '../commands/schemaStore/clearSchemaCache'; import { showSchemaStoreStats } from '../commands/schemaStore/showSchemaStoreStats'; +import { showConnectionStats } from '../commands/showConnectionStats/showConnectionStats'; import { showWorkerStats } from '../commands/showWorkerStats/showWorkerStats'; import { signInAgain } from '../commands/signInAgain/signInAgain'; import { updateConnectionString } from '../commands/updateConnectionString/updateConnectionString'; @@ -624,6 +625,10 @@ export class ClustersExtension implements vscode.Disposable { withCommandCorrelation(showSchemaStoreStats), ); + registerCommand( + 'vscode-documentdb.command.showConnectionStats', + withCommandCorrelation(showConnectionStats), + ); registerCommand('vscode-documentdb.command.showWorkerStats', withCommandCorrelation(showWorkerStats)); //// General Commands: From 886490748b52f0f494c967aa0a307bd1d3bb5735 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 18:02:21 +0000 Subject: [PATCH 12/29] feat: show Entra token expiry in connection stats (WI-5) Show the declared expiry of the last token supplied to the driver without retaining the token or changing renewal. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iterations/01-dev-plan.md | 3 ++ .../showConnectionStats.ts | 4 ++ src/documentdb/ClustersClient.test.ts | 40 +++++++++++++++++++ src/documentdb/ClustersClient.ts | 22 ++++++++++ 4 files changed, 69 insertions(+) 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 09687d174..4faf363ab 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 @@ -1341,6 +1341,9 @@ shim (0005). **Show Worker Stats**, as a separate WI-5 commit. The extension-host snapshot shows client generation, age, auth method, startup correlation, pending or held state, and whether socket events are traced. It contains no cluster or account identifiers and makes no service calls. + For Entra it can show the UTC expiry declared by the last token supplied to the driver, or + `unknown`. This local diagnostic retains no token and does not predict server acceptance or + force renewal. Leave socket counts out rather than guessing. Keep the published OP-3 candidate unchanged. - **Worker startup regression:** PR4's shared OIDC code imported the VS Code UI auth-method module into the Node worker path. Keep the shared auth IDs independent of VS Code. Verify diff --git a/src/commands/showConnectionStats/showConnectionStats.ts b/src/commands/showConnectionStats/showConnectionStats.ts index 8e7f08364..3a7907d75 100644 --- a/src/commands/showConnectionStats/showConnectionStats.ts +++ b/src/commands/showConnectionStats/showConnectionStats.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import { type IActionContext } from '@microsoft/vscode-azext-utils'; +import { AuthMethodId } from '../../documentdb/auth/AuthMethodId'; import { ClustersClient } from '../../documentdb/ClustersClient'; import { ext } from '../../extensionVariables'; @@ -20,6 +21,9 @@ export function showConnectionStats(_context: IActionContext): void { ? ` Client: ${client.state} generation=${String(client.generation)} ageMs=${String(client.ageMs)} auth=${client.authMethod ?? 'unknown'} startup=${client.startupId ?? 'none'} socketTrace=${String(client.socketTrace)}` : ' Client: none', ); + if (client?.authMethod === AuthMethodId.MicrosoftEntraID) { + ext.outputChannel.appendLog(` lastEntraTokenExpiresAt=${client.lastEntraTokenExpiresAt ?? 'unknown'}`); + } if (pending) { ext.outputChannel.appendLog( ` Pending: ${pending.superseded ? 'superseded' : 'current'} startup=${pending.startupId}`, diff --git a/src/documentdb/ClustersClient.test.ts b/src/documentdb/ClustersClient.test.ts index 2965fc986..84fb391cf 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -253,6 +253,7 @@ describe('regular connection startup diagnostics', () => { startupId: client.connectionCorrelationId, state: 'cached', socketTrace: true, + lastEntraTokenExpiresAt: undefined, }); const output = JSON.stringify(snapshot); for (const value of [ @@ -270,6 +271,45 @@ describe('regular connection startup diagnostics', () => { expect(mockClose).not.toHaveBeenCalled(); }); + it('reports only the expiry of the last Entra token supplied to the driver', async (): Promise => { + const firstExpiry = 1_800_000_000; + const renewedExpiry = firstExpiry + 3600; + const tokenAt = (exp: number): string => + `test.${Buffer.from(JSON.stringify({ exp })).toString('base64url')}.signature`; + const first = { accessToken: tokenAt(firstExpiry) }; + const renewed = { accessToken: tokenAt(renewedExpiry) }; + const missingSession = new EntraSignInRequiredError('noSession'); + const callback = vi + .fn() + .mockResolvedValueOnce(first) + .mockRejectedValueOnce(missingSession) + .mockResolvedValueOnce(renewed) + .mockResolvedValueOnce({ accessToken: 'opaque-test-token' }); + vi.mocked(MicrosoftEntraIDAuthHandler.prototype.configureAuth).mockResolvedValueOnce({ + connectionString: 'mongodb://private-host:27017', + options: { authMechanismProperties: { OIDC_CALLBACK: callback } }, + verifiedIdentity, + }); + const client = await ClustersClient.connectInteractive(clusterId); + const driverCallback = vi.mocked(MongoClient).mock.calls[0][1]?.authMechanismProperties?.OIDC_CALLBACK; + const params: Mongodb.OIDCCallbackParams = { version: 1, timeoutContext: new AbortController().signal }; + const expiry = (): string | undefined => + ClustersClient.getDiagnosticsSnapshot() + .find(({ client: row }) => row?.startupId === client.connectionCorrelationId) + ?.client?.lastEntraTokenExpiresAt; + + expect(expiry()).toBeUndefined(); + await expect(driverCallback!(params)).resolves.toBe(first); + expect(expiry()).toBe(new Date(firstExpiry * 1000).toISOString()); + expect(JSON.stringify(ClustersClient.getDiagnosticsSnapshot())).not.toContain(first.accessToken); + await expect(driverCallback!(params)).rejects.toBe(missingSession); + expect(expiry()).toBe(new Date(firstExpiry * 1000).toISOString()); + await expect(driverCallback!(params)).resolves.toBe(renewed); + expect(expiry()).toBe(new Date(renewedExpiry * 1000).toISOString()); + await driverCallback!(params); + expect(expiry()).toBeUndefined(); + }); + it('shows a superseded startup and a hold even without a cached client', async (): Promise => { const handshake = pauseNextConnect(); const onStartup = vi.fn<(id: string) => void>(); diff --git a/src/documentdb/ClustersClient.ts b/src/documentdb/ClustersClient.ts index a578629e3..c11d1d7c5 100644 --- a/src/documentdb/ClustersClient.ts +++ b/src/documentdb/ClustersClient.ts @@ -36,6 +36,7 @@ import { type InsertManyResult, type ListDatabasesResult, type MongoClientOptions, + type OIDCResponse, type WithId, type WithoutId, } from 'mongodb'; @@ -49,6 +50,7 @@ import { AuthMethodId, isSupportedAuthMethod } from './auth/AuthMethod'; import { createAuthHandler } from './auth/createAuthHandler'; import { EntraSignInRequiredError } from './auth/entraErrors/entraCallbackErrors'; import { getAzureHostSuffix } from './auth/oidcAllowedHosts'; +import { readJwtTimes } from './auth/tokenExpiry'; import { QueryInsightsApis, type ExplainVerbosity } from './client/QueryInsightsApis'; import { classifyConnectionFailure, type ConnectionFailure } from './connectionFailures'; import { computeConnectionFingerprint, type ConnectionPrincipal } from './connectionFingerprint'; @@ -97,6 +99,7 @@ interface ConnectionStatsEntry { readonly startupId?: string; readonly state: 'cached' | 'closed' | 'replaceOnNextForeground' | 'replaceOnRecovery'; readonly socketTrace: boolean; + readonly lastEntraTokenExpiresAt?: string; }; readonly pending?: { readonly startupId: string; readonly superseded: boolean }; readonly held?: ConnectionUnavailableReason; @@ -350,6 +353,7 @@ export class ClustersClient { private _closed = false; private _replacement?: 'replaceOnNextForeground' | 'replaceOnRecovery'; private _interactiveEntraStartupId?: string; + private _lastEntraTokenExpiresAt?: string; private _llmEnhancedFeatureApis: llmEnhancedFeatureApis | null = null; private _queryInsightsApis: QueryInsightsApis | null = null; private _clusterMetadataPromise: Promise | null = null; @@ -397,6 +401,7 @@ export class ClustersClient { startupId: client.connectionCorrelationId, state: client._replacement ?? (client._closed ? 'closed' : 'cached'), socketTrace: client._interactiveEntraStartupId !== undefined, + lastEntraTokenExpiresAt: client._lastEntraTokenExpiresAt, }, pending: pending && { startupId: pending.id, @@ -718,6 +723,23 @@ export class ClustersClient { emulatorConfiguration?: EmulatorConfiguration, originalConnectionString: string = connectionString, ): Promise { + const authProperties = options.authMechanismProperties; + const callback = authProperties?.OIDC_CALLBACK; + if (interactiveEntra && callback) { + options = { + ...options, + authMechanismProperties: { + ...authProperties, + OIDC_CALLBACK: async (params): Promise => { + const response = await callback(params); + const { expSec } = readJwtTimes(response.accessToken); + this._lastEntraTokenExpiresAt = + expSec === undefined ? undefined : (new Date(expSec * 1000).toJSON() ?? undefined); + return response; + }, + }, + }; + } this._mongoClient = new MongoClient(connectionString, options); this._mongoClient.once('topologyClosed', (): void => { this._closed = true; From 917e2e1cf8d07b949b6bc60ef3839909185adf74 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 18:05:49 +0000 Subject: [PATCH 13/29] feat: show time remaining on the Entra token (WI-5) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../showConnectionStats.test.ts | 48 +++++++++++++++++++ .../showConnectionStats.ts | 22 ++++++++- 2 files changed, 69 insertions(+), 1 deletion(-) create mode 100644 src/commands/showConnectionStats/showConnectionStats.test.ts diff --git a/src/commands/showConnectionStats/showConnectionStats.test.ts b/src/commands/showConnectionStats/showConnectionStats.test.ts new file mode 100644 index 000000000..fe1a2161f --- /dev/null +++ b/src/commands/showConnectionStats/showConnectionStats.test.ts @@ -0,0 +1,48 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { type IActionContext } from '@microsoft/vscode-azext-utils'; +import { afterEach, expect, it, vi } from 'vitest'; +import { AuthMethodId } from '../../documentdb/auth/AuthMethodId'; +import { ClustersClient } from '../../documentdb/ClustersClient'; +import { ext } from '../../extensionVariables'; +import { showConnectionStats } from './showConnectionStats'; + +vi.mock('../../documentdb/ClustersClient', () => ({ + ClustersClient: { getDiagnosticsSnapshot: vi.fn() }, +})); + +vi.mock('../../extensionVariables', () => ({ + ext: { outputChannel: { appendLog: vi.fn(), show: vi.fn() } }, +})); + +afterEach(() => { + vi.useRealTimers(); +}); + +it.each([ + ['2026-11-24T19:02:03.000Z', '2026-11-24T19:02:03.000Z (in 25:02:03)'], + ['2026-11-23T18:00:00.001Z', '2026-11-23T18:00:00.001Z (in 00:00:01)'], + ['2026-11-23T18:00:00.000Z', '2026-11-23T18:00:00.000Z (expired)'], + [undefined, 'unknown'], +])('prints the UTC expiry with remaining time or status for %s', (expiry, expected): void => { + vi.useFakeTimers({ now: new Date('2026-11-23T18:00:00.000Z') }); + vi.mocked(ClustersClient.getDiagnosticsSnapshot).mockReturnValueOnce([ + { + client: { + generation: 1, + ageMs: 1000, + authMethod: AuthMethodId.MicrosoftEntraID, + state: 'cached', + socketTrace: true, + lastEntraTokenExpiresAt: expiry, + }, + }, + ]); + + showConnectionStats({} as IActionContext); + + expect(ext.outputChannel.appendLog).toHaveBeenCalledWith(` lastEntraTokenExpiresAt=${expected}`); +}); diff --git a/src/commands/showConnectionStats/showConnectionStats.ts b/src/commands/showConnectionStats/showConnectionStats.ts index 3a7907d75..2685115f3 100644 --- a/src/commands/showConnectionStats/showConnectionStats.ts +++ b/src/commands/showConnectionStats/showConnectionStats.ts @@ -8,8 +8,26 @@ import { AuthMethodId } from '../../documentdb/auth/AuthMethodId'; import { ClustersClient } from '../../documentdb/ClustersClient'; import { ext } from '../../extensionVariables'; +function formatEntraExpiry(expiresAt: string | undefined, now: number): string { + if (expiresAt === undefined) { + return 'unknown'; + } + + const remainingMs = Date.parse(expiresAt) - now; + if (remainingMs <= 0) { + return `${expiresAt} (expired)`; + } + + const seconds = Math.ceil(remainingMs / 1000); + const remaining = [Math.floor(seconds / 3600), Math.floor(seconds / 60) % 60, seconds % 60] + .map((part) => String(part).padStart(2, '0')) + .join(':'); + return `${expiresAt} (in ${remaining})`; +} + export function showConnectionStats(_context: IActionContext): void { const snapshot = ClustersClient.getDiagnosticsSnapshot(); + const now = Date.now(); ext.outputChannel.appendLog(`[Connection Stats] Extension-host cache entries: ${String(snapshot.length)}`); ext.outputChannel.appendLog( 'Each cached client can own multiple sockets. Socket counts are not tracked here. For Shell and Playground, use Show Worker Stats.', @@ -22,7 +40,9 @@ export function showConnectionStats(_context: IActionContext): void { : ' Client: none', ); if (client?.authMethod === AuthMethodId.MicrosoftEntraID) { - ext.outputChannel.appendLog(` lastEntraTokenExpiresAt=${client.lastEntraTokenExpiresAt ?? 'unknown'}`); + ext.outputChannel.appendLog( + ` lastEntraTokenExpiresAt=${formatEntraExpiry(client.lastEntraTokenExpiresAt, now)}`, + ); } if (pending) { ext.outputChannel.appendLog( From 98d72dd4817f7da36f722edebc1c158a3f70c32d Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 18:05:49 +0000 Subject: [PATCH 14/29] chore: identify the next OP-3 test build as 1.1.1-alpha.1 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../connection-lifecycle/iterations/01-dev-plan.md | 9 +++++---- package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index 4faf363ab..c167d80ab 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 @@ -1341,10 +1341,11 @@ shim (0005). **Show Worker Stats**, as a separate WI-5 commit. The extension-host snapshot shows client generation, age, auth method, startup correlation, pending or held state, and whether socket events are traced. It contains no cluster or account identifiers and makes no service calls. - For Entra it can show the UTC expiry declared by the last token supplied to the driver, or - `unknown`. This local diagnostic retains no token and does not predict server acceptance or - force renewal. - Leave socket counts out rather than guessing. Keep the published OP-3 candidate unchanged. + For Entra it shows the UTC expiry declared by the last token supplied to the driver, with + the remaining time at capture (`hh:mm:ss`), `expired`, or `unknown`. This local diagnostic + retains no token and does not predict server acceptance or force renewal. + Leave socket counts out rather than guessing. The operator requested restarting OP-3 on + the next CI-built candidate, `1.1.1-alpha.1`, which includes the diagnostics and worker fix. - **Worker startup regression:** PR4's shared OIDC code imported the VS Code UI auth-method module into the Node worker path. Keep the shared auth IDs independent of VS Code. Verify the next packaged candidate starts both Shell and Playground; the tree OP-3 gate is unchanged. diff --git a/package-lock.json b/package-lock.json index 919b04803..a2ea6de7a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "vscode-documentdb", - "version": "1.1.1-alpha.0", + "version": "1.1.1-alpha.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "vscode-documentdb", - "version": "1.1.1-alpha.0", + "version": "1.1.1-alpha.1", "license": "SEE LICENSE IN LICENSE.md", "workspaces": [ "packages/*" diff --git a/package.json b/package.json index 5a096fdb1..eec16dff8 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "vscode-documentdb", - "version": "1.1.1-alpha.0", + "version": "1.1.1-alpha.1", "releaseNotesUrl": "https://github.com/microsoft/vscode-documentdb/discussions/1089", "aiKey": "0c6ae279ed8443289764825290e4f9e2-1a736e7c-1324-4338-be46-fc2a58ae4d14-7255", "publisher": "ms-azuretools", From ee19ba44e65d5582b9f0f4c0f3fe535e8e4fd7b6 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 19:09:28 +0000 Subject: [PATCH 15/29] fix: clarify the tree sign-in recovery action (WI-5) Record the OP-3 pass and use Retry sign-in as the primary Entra recovery action without changing its command or position. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../features/connection-lifecycle/README.md | 4 ++-- .../connection-lifecycle/iterations/01-dev-plan.md | 12 ++++++++++-- l10n/bundle.l10n.json | 2 +- src/tree/documentdb/ClusterItemBase.test.ts | 3 ++- src/tree/documentdb/ClusterItemBase.ts | 2 +- 5 files changed, 16 insertions(+), 7 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/README.md b/docs/ai-and-plans/features/connection-lifecycle/README.md index e6598d6f6..25a97a0d5 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/README.md +++ b/docs/ai-and-plans/features/connection-lifecycle/README.md @@ -52,8 +52,8 @@ Evidence, telemetry and source pointers: [research-findings.md](./research-findi - **Never change identity under an open surface.** It becomes disconnected, keeps its state, says why and offers one action. - After a database rejects a verified Entra identity, discard the client but keep its in-memory - connection settings for explicit **Sign in again**. Do not retain the rejected token or retry - silently. When the tree offers **Sign in again**, it does not also offer **Retry**. + connection settings for explicit sign-in. Do not retain the rejected token or retry silently. + When the tree offers **Retry sign-in**, it does not also offer **Retry**. - **One teardown** serves Disconnect, Remove Connection and identity-changing credential updates. - Disconnect uses the existing task-conflict guard: if a copy or export is using the cluster, leave the task and connection running. The user can retry after the task finishes or is stopped. 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 c167d80ab..02e3cca12 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 @@ -1213,12 +1213,12 @@ shim (0005). - Route both catch paths in `getChildren` (cached-client reuse and `listDatabases`) through `reportFailure`. Keep the modal-plus-actions presentation. - Change `createErrorRecoveryChildren` to: - - **Sign in again** when the kind is `signInRequired` or `credentialsRejected` and the + - **Retry sign-in** when the kind is `signInRequired` or `credentialsRejected` and the Entra identity and settings are available, or **Update credentials** (the provider-owned action that exists today); - then Diagnose; - then Open shell; - - then **Retry last**, except when **Sign in again** is offered in its place. + - then **Retry last**, except when **Retry sign-in** is offered in its place. - Check that order against the skill text, and update the skill in WI-10 if it differs. - Call `addEstablishedConnectionContext` on the failure events of `connect`, `getchildren` and the tree. - **Keep credentials on recoverable failures (F-20).** In every provider item's `authenticateAndConnect` @@ -1328,6 +1328,14 @@ shim (0005). were not reached. The run is inconclusive; OP-3 remains open. On resume, close the dashboard, wait until the cached token is no longer accepted, and explicitly refresh the cluster node without restarting the extension host. Collapse and re-expand can show cached children. +- **OP-3 resumed on the older VSIX (2026-11-23):** A refresh opened a new socket on the + same client. OIDC callback invocation 2 threw, and the database listing failed. + The operator confirmed that the initial failure showed an error modal, not a sign-in + prompt. Closing the modal revealed the recovery action. They confirmed dismissing the + actual Microsoft sign-in prompt as requested and that the recovery actions remained. + A later explicit sign-in restored the database list. **OP-3 passed** on the older CI VSIX. + The operator approved renaming the tree action to **Retry sign-in**, first before Diagnose + and Open shell, without a separate Retry row. Command ID and recovery behavior are unchanged. - **Sign-out scope review (2026-11-23):** Claude Opus 5.5 recommended keeping the approved 1.2.0 scope (80% confidence). Prompt sign-out handling would need account-specific session checks, coordination with active tasks, and separate handling for Shell and Playground diff --git a/l10n/bundle.l10n.json b/l10n/bundle.l10n.json index 79c6e5f2e..de81ca768 100644 --- a/l10n/bundle.l10n.json +++ b/l10n/bundle.l10n.json @@ -2510,6 +2510,7 @@ "Retry loading tenants": "Retry loading tenants", "Retry setup": "Retry setup", "Retry setup…": "Retry setup…", + "Retry sign-in": "Retry sign-in", "Retry TS Plugin Setup": "Retry TS Plugin Setup", "Retry with longer timeouts": "Retry with longer timeouts", "Retry without diagnostic timeouts": "Retry without diagnostic timeouts", @@ -2720,7 +2721,6 @@ "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 to": "Sign in to", diff --git a/src/tree/documentdb/ClusterItemBase.test.ts b/src/tree/documentdb/ClusterItemBase.test.ts index 7de34e605..5b9b649b0 100644 --- a/src/tree/documentdb/ClusterItemBase.test.ts +++ b/src/tree/documentdb/ClusterItemBase.test.ts @@ -451,7 +451,7 @@ describe('ClusterItemBase.getChildren — cached client connection failure handl }); it.each(['signInRequired', 'credentialsRejected'] as const)( - 'offers Sign in again instead of Retry for %s and keeps the failed-expansion marker', + 'offers Retry sign-in instead of Retry for %s and keeps the failed-expansion marker', async (reason): Promise => { if (reason === 'credentialsRejected') { ClustersClientMock.getLatchReason.mockReturnValueOnce(reason); @@ -477,6 +477,7 @@ describe('ClusterItemBase.getChildren — cached client connection failure handl 'cluster-1/diagnose', 'cluster-1/open-shell', ]); + expect(children[0]).toMatchObject({ label: 'Retry sign-in' }); expect(item.hasRetryNode(children)).toBe(true); expect(ClustersClientMock.reportFailure).not.toHaveBeenCalled(); expect(CredentialCache.deleteCredentials).not.toHaveBeenCalled(); diff --git a/src/tree/documentdb/ClusterItemBase.ts b/src/tree/documentdb/ClusterItemBase.ts index cad28218c..086d9f8a7 100644 --- a/src/tree/documentdb/ClusterItemBase.ts +++ b/src/tree/documentdb/ClusterItemBase.ts @@ -373,7 +373,7 @@ export abstract class ClusterItemBase Date: Mon, 23 Nov 2026 19:09:28 +0000 Subject: [PATCH 16/29] style: format connection diagnostics tests for CI Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/documentdb/ClustersClient.test.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/documentdb/ClustersClient.test.ts b/src/documentdb/ClustersClient.test.ts index 84fb391cf..0106bbb11 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -294,9 +294,9 @@ describe('regular connection startup diagnostics', () => { const driverCallback = vi.mocked(MongoClient).mock.calls[0][1]?.authMechanismProperties?.OIDC_CALLBACK; const params: Mongodb.OIDCCallbackParams = { version: 1, timeoutContext: new AbortController().signal }; const expiry = (): string | undefined => - ClustersClient.getDiagnosticsSnapshot() - .find(({ client: row }) => row?.startupId === client.connectionCorrelationId) - ?.client?.lastEntraTokenExpiresAt; + ClustersClient.getDiagnosticsSnapshot().find( + ({ client: row }) => row?.startupId === client.connectionCorrelationId, + )?.client?.lastEntraTokenExpiresAt; expect(expiry()).toBeUndefined(); await expect(driverCallback!(params)).resolves.toBe(first); From 87ab0ed1f2959e4874f73a6f08afa97c84761df7 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 19:38:17 +0000 Subject: [PATCH 17/29] fix: respect client recovery when reconnecting and retrying (WI-5) Hold current verified Entra replacement rejections and leave a healthy replacement alone when an old Retry action is clicked. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../retryAuthentication.test.ts | 16 ++++++++++++++++ .../retryAuthentication/retryAuthentication.ts | 5 ++++- src/documentdb/ClustersClient.test.ts | 13 +++++++++++++ src/documentdb/ClustersClient.ts | 14 ++++++++++++++ 4 files changed, 47 insertions(+), 1 deletion(-) diff --git a/src/commands/retryAuthentication/retryAuthentication.test.ts b/src/commands/retryAuthentication/retryAuthentication.test.ts index 7fa94f715..9b6b96455 100644 --- a/src/commands/retryAuthentication/retryAuthentication.test.ts +++ b/src/commands/retryAuthentication/retryAuthentication.test.ts @@ -41,6 +41,7 @@ vi.mock('../../documentdb/ClustersClient', () => ({ ClustersClient: { getEpoch: vi.fn(() => 0), getLatchReason: vi.fn(), + hasReusableClient: vi.fn(), clearCredentialRejection: vi.fn(), deleteClient: vi.fn(), getLastFailedStartupCorrelationId: vi.fn((clusterId: string) => @@ -224,6 +225,21 @@ describe('retryAuthentication', () => { expect(ext.discoveryBranchDataProvider.refresh).not.toHaveBeenCalled(); }); + it('refreshes without closing a healthy client that replaced the one that failed', async (): Promise => { + const node = { + id: 'connectionsView/stale', + cluster: { clusterId: 'stale' }, + getTreeItem, + lastConnectionFailureKind: 'clientClosed' as const, + }; + vi.mocked(ClustersClient.hasReusableClient).mockReturnValueOnce(true); + + await retryAuthentication(actionContext as never, node); + + expect(ClustersClient.deleteClient).not.toHaveBeenCalled(); + expect(ext.connectionsBranchDataProvider.refresh).toHaveBeenCalledExactlyOnceWith(node); + }); + it('does not refresh an old Retry after the client was replaced while its close was pending', async (): Promise => { const node = { id: 'connectionsView/stale', diff --git a/src/commands/retryAuthentication/retryAuthentication.ts b/src/commands/retryAuthentication/retryAuthentication.ts index ef9606445..56f7a92ca 100644 --- a/src/commands/retryAuthentication/retryAuthentication.ts +++ b/src/commands/retryAuthentication/retryAuthentication.ts @@ -152,7 +152,10 @@ export async function retryAuthentication(context: IActionContext, node: Retryab } else { return; } - } else if (kind === 'signInRequired' || kind === 'credentialsRejected' || kind === 'clientClosed') { + } else if ( + (kind === 'signInRequired' || kind === 'credentialsRejected' || kind === 'clientClosed') && + !ClustersClient.hasReusableClient(clusterId) + ) { const closing = ClustersClient.deleteClient(clusterId); epoch = ClustersClient.getEpoch(clusterId); await closing; diff --git a/src/documentdb/ClustersClient.test.ts b/src/documentdb/ClustersClient.test.ts index 0106bbb11..3fe3353a3 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -573,6 +573,19 @@ describe('regular connection startup diagnostics', () => { await expect(background()).resolves.toBe(replacement); }); + it('holds a rejected Entra replacement without retrying its cached settings', async (): Promise => { + await ClustersClient.connectInteractive(clusterId); + const credentials = CredentialCache.getCredentials(clusterId); + poolEvents.emit('topologyClosed'); + mockConnect.mockRejectedValueOnce(new MongoServerError({ code: 18 })); + + await expect(ClustersClient.getClient(clusterId)).rejects.toMatchObject({ reason: 'credentialsRejected' }); + await expect(ClustersClient.getClient(clusterId)).rejects.toMatchObject({ reason: 'credentialsRejected' }); + expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); + expect(CredentialCache.getCredentials(clusterId)).toBe(credentials); + expect(MongoClient).toHaveBeenCalledTimes(2); + }); + it('holds a sign-in miss for explicit recovery and does not let a pending replacement bypass it', async () => { const client = await ClustersClient.connectInteractive(clusterId); const pin = ClustersClient.getLastVerifiedIdentity(clusterId); diff --git a/src/documentdb/ClustersClient.ts b/src/documentdb/ClustersClient.ts index c11d1d7c5..bba86d893 100644 --- a/src/documentdb/ClustersClient.ts +++ b/src/documentdb/ClustersClient.ts @@ -1025,6 +1025,16 @@ export class ClustersClient { } catch (error) { if (!(error instanceof UserCancelledError) && epoch === ClustersClient.getEpoch(clusterId)) { ClustersClient._lastFailedStartups.set(clusterId, id); + const previous = ClustersClient._clients.get(clusterId); + if ( + previous?.authMethod === AuthMethodId.MicrosoftEntraID && + previous.fingerprint === expectedFingerprint + ) { + const failure = classifyConnectionFailure(error, previous.authMethod); + if (failure.kind === 'credentialsRejected' && failure.generation === 'evict') { + ClustersClient.reportFailure(previous.binding, error); + } + } } client._closed = true; void client._mongoClient?.close().catch(() => { @@ -1063,6 +1073,10 @@ export class ClustersClient { return !this._closed && this._replacement === undefined; } + public static hasReusableClient(clusterId: string): boolean { + return ClustersClient._clients.get(clusterId)?.canReuse() ?? false; + } + /** Reports an operation's failure against the generation that actually ran it. */ public static reportFailure(binding: ConnectionBinding, error: unknown): ConnectionFailure['kind'] | undefined { const { clusterId, fingerprint, generation } = binding; From 1500634d11d947c29583b993dbe9d54d2ffea615 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 19:38:17 +0000 Subject: [PATCH 18/29] fix: keep stale and inert recovery rows out of the cluster tree (WI-5) Drop listings from a different identity, keep actionable repairs, and detect failures without mistaking a database name for a recovery row. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/tree/documentdb/ClusterItemBase.test.ts | 40 +++++++++++++++++++++ src/tree/documentdb/ClusterItemBase.ts | 32 +++++++++++++---- 2 files changed, 66 insertions(+), 6 deletions(-) diff --git a/src/tree/documentdb/ClusterItemBase.test.ts b/src/tree/documentdb/ClusterItemBase.test.ts index 5b9b649b0..eea7db86e 100644 --- a/src/tree/documentdb/ClusterItemBase.test.ts +++ b/src/tree/documentdb/ClusterItemBase.test.ts @@ -17,6 +17,7 @@ import { ClustersClient, type DatabaseItemModel } from '../../documentdb/Cluster import { ConnectionUnavailableError } from '../../documentdb/ConnectionUnavailableError'; import { CredentialCache } from '../../documentdb/CredentialCache'; import { ShellCommandIds } from '../../documentdb/shell/constants'; +import { Views } from '../../documentdb/Views'; import { type Experience } from '../../DocumentDBExperiences'; import { containsRetryNode, RETRY_NODE_ID_SUFFIX } from '../api/retryNode'; import { BaseExtendedTreeDataProvider } from '../BaseExtendedTreeDataProvider'; @@ -485,6 +486,45 @@ describe('ClusterItemBase.getChildren — cached client connection failure handl }, ); + it('does not publish a database listing from a different identity', async (): Promise => { + const binding = { clusterId: 'cluster-1', fingerprint: 'old', generation: 1 }; + const client = { + ...makeClient(vi.fn().mockResolvedValue([{ name: 'old-database' }])), + binding, + } as ClustersClient; + const replacement = { ...client, fingerprint: 'new' } as ClustersClient; + ClustersClientMock.connectInteractive.mockResolvedValueOnce(client); + ClustersClientMock.getExistingClient.mockReturnValueOnce(replacement); + + expect(await new TestClusterItem(makeCluster(), null).getChildren()).toEqual([]); + expect(vscode.commands.executeCommand).not.toHaveBeenCalled(); + }); + + it.each(['diagnose', 'sign-in-again'])('does not mistake a database named %s for a recovery action', (name): void => { + const item = new TestClusterItem(makeCluster(), null); + const child = { + id: `cluster-1/${name}`, + contextValue: 'treeItem_documentdbdatabase', + getTreeItem: (): vscode.TreeItem => ({ label: name }), + }; + + expect(item.hasRetryNode([child])).toBe(false); + }); + + it('keeps actionable recovery children without an inert Retry for stored credentials', async (): Promise => { + ClustersClientMock.getLatchReason.mockReturnValue('credentialsRejected'); + ClustersClientMock.connectInteractive.mockRejectedValueOnce(new ConnectionUnavailableError('credentialsRejected')); + const item = new TestClusterItem({ ...makeCluster(), viewId: Views.ConnectionsView }, null); + try { + const children = await item.getChildren(); + + expect(children.map(({ id }) => id)).toEqual(['cluster-1/diagnose', 'cluster-1/open-shell']); + expect(item.hasRetryNode(children)).toBe(true); + } finally { + ClustersClientMock.getLatchReason.mockReset(); + } + }); + it('reports the binding that executed listDatabases, not the current cache entry', async (): Promise => { const error = new Error('deprecated generation'); const binding = { clusterId: 'cluster-1', fingerprint: 'old', generation: 1 }; diff --git a/src/tree/documentdb/ClusterItemBase.ts b/src/tree/documentdb/ClusterItemBase.ts index 086d9f8a7..f9c7e5bde 100644 --- a/src/tree/documentdb/ClusterItemBase.ts +++ b/src/tree/documentdb/ClusterItemBase.ts @@ -30,6 +30,7 @@ import { isEntraDestinationRejectedError } from '../../documentdb/auth/oidcAllow import { classifyConnectionFailure, type ConnectionFailure } from '../../documentdb/connectionFailures'; import { ShellCommandIds } from '../../documentdb/shell/constants'; import { showClusterConnectFailure } from '../../documentdb/showClusterConnectFailure'; +import { Views } from '../../documentdb/Views'; import { ext } from '../../extensionVariables'; import { SettingsService } from '../../services/SettingsService'; import { ErrorExplanationService } from '../../services/errorExplanationService'; @@ -37,7 +38,7 @@ import { settingsKeys } from '../../settingsKeys'; import { regionToDisplayName } from '../../utils/regionToDisplayName'; import { withDelayedProgress } from '../../utils/withProgress'; import { type TreeElement } from '../TreeElement'; -import { type TreeElementWithContextValue } from '../TreeElementWithContextValue'; +import { isTreeElementWithContextValue, type TreeElementWithContextValue } from '../TreeElementWithContextValue'; import { type TreeElementWithExperience } from '../TreeElementWithExperience'; import { type TreeElementWithRetryChildren } from '../TreeElementWithRetryChildren'; import { createGenericElementWithContext } from '../api/createGenericElementWithContext'; @@ -350,8 +351,8 @@ export abstract class ClusterItemBase + !ClustersClient.getLatchReason(clusterId) && + (!binding || ClustersClient.getExistingClient(clusterId)?.fingerprint === binding.fingerprint); + if (!isCurrentIdentity()) { + return []; + } // A deep link that opens the dashboard itself suppresses the automatic open; that is not a skip. if (!wasConnected && !isAutoOpenDashboardSuppressed(this.cluster.clusterId)) { @@ -567,6 +578,9 @@ export abstract class ClusterItemBase child.id === `${this.id}/sign-in-again`) === true + containsRetryNode(children) || + children?.some( + (child) => + child.id === `${this.id}/diagnose` && + isTreeElementWithContextValue(child) && + child.contextValue === 'error', + ) === true ); } From 64d6f3ffdc87ddc8ef41ed767dbcd7ccadd6a2a7 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 19:39:26 +0000 Subject: [PATCH 19/29] fix: preserve ordinary edits across recovery state changes (WI-5) Scope the wizard epoch fence to rejected-connection recovery and report storage saves accurately without clearing a newer latch. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../updateConnectionString/ExecuteStep.ts | 2 +- .../updateConnectionString.test.ts | 17 ++++++++ .../updateConnectionString.ts | 15 +++---- src/commands/updateCredentials/ExecuteStep.ts | 2 +- .../updateCredentials.test.ts | 41 +++++++++++++++++-- .../updateCredentials/updateCredentials.ts | 15 +++---- 6 files changed, 72 insertions(+), 20 deletions(-) diff --git a/src/commands/updateConnectionString/ExecuteStep.ts b/src/commands/updateConnectionString/ExecuteStep.ts index 948097962..e195ddb64 100644 --- a/src/commands/updateConnectionString/ExecuteStep.ts +++ b/src/commands/updateConnectionString/ExecuteStep.ts @@ -92,10 +92,10 @@ export class ExecuteStep extends AzureWizardExecuteStep { } await ConnectionStorageService.save(resourceType, connection, true); + context.connectionStringSaved = true; if (context.isRecoveryCurrent?.() === false) { return; } - context.connectionStringSaved = true; if (clearedEntraMethod) { void window.showInformationMessage( diff --git a/src/commands/updateConnectionString/updateConnectionString.test.ts b/src/commands/updateConnectionString/updateConnectionString.test.ts index e92706332..db65fdedc 100644 --- a/src/commands/updateConnectionString/updateConnectionString.test.ts +++ b/src/commands/updateConnectionString/updateConnectionString.test.ts @@ -290,4 +290,21 @@ describe('updateConnectionString rejected-destination recovery', () => { expect(item.lastConnectionOutcome).toBe('connected'); expect(refresh).toHaveBeenCalledOnce(); }); + + it('saves an ordinary edit when the epoch changes while the input is open', async (): Promise => { + const refresh = vi.spyOn(provider, 'refresh'); + item.lastConnectionOutcome = 'connected'; + showInputBox.mockImplementationOnce(async (): Promise => { + vi.mocked(ClustersClient.getEpoch).mockReturnValue(1); + return approvedUri; + }); + + await updateConnectionString(makeContext(), item); + + expect(storedConnection.secrets.connectionString).toBe(approvedUri); + expect(capturedContexts[0].connectionStringSaved).toBe(true); + expect(ClustersClient.deleteClient).not.toHaveBeenCalled(); + expect(deleteCredentials).not.toHaveBeenCalled(); + expect(refresh).toHaveBeenCalledOnce(); + }); }); diff --git a/src/commands/updateConnectionString/updateConnectionString.ts b/src/commands/updateConnectionString/updateConnectionString.ts index de04cfedf..39e22d8c5 100644 --- a/src/commands/updateConnectionString/updateConnectionString.ts +++ b/src/commands/updateConnectionString/updateConnectionString.ts @@ -40,7 +40,8 @@ export async function updateConnectionString(context: IActionContext, node: Docu const clusterId = node.cluster.clusterId; let epoch = ClustersClient.getEpoch(clusterId); const recoveringRejectedCredentials = ClustersClient.getLatchReason(clusterId) === 'credentialsRejected'; - const isCurrent = (): boolean => ClustersClient.getEpoch(clusterId) === epoch; + const recovering = recoveringRejectedDestination || recoveringRejectedCredentials; + const isRecoveryCurrent = recovering ? (): boolean => ClustersClient.getEpoch(clusterId) === epoch : undefined; // Extract the connection string but hide the username and password @@ -50,7 +51,7 @@ export async function updateConnectionString(context: IActionContext, node: Docu const resourceType = resolveStorageZone(node.cluster); const connection = await ConnectionStorageService.get(node.storageId, resourceType); - if (!isCurrent()) { + if (isRecoveryCurrent?.() === false) { return; } const connectionString = connection?.secrets?.connectionString || ''; @@ -70,7 +71,7 @@ export async function updateConnectionString(context: IActionContext, node: Docu storageZone: resolveStorageZone(node.cluster), storageId: node.storageId, connectionStringSaved: false, - isRecoveryCurrent: isCurrent, + isRecoveryCurrent, }; const wizard = new AzureWizard(wizardContext, { @@ -80,19 +81,19 @@ export async function updateConnectionString(context: IActionContext, node: Docu }); await wizard.prompt(); - if (!isCurrent()) { + if (isRecoveryCurrent?.() === false) { return; } await wizard.execute(); - if (!isCurrent()) { + if (isRecoveryCurrent?.() === false) { return; } - if ((recoveringRejectedDestination || recoveringRejectedCredentials) && wizardContext.connectionStringSaved) { + if (recovering && wizardContext.connectionStringSaved) { const closing = ClustersClient.deleteClient(clusterId); epoch = ClustersClient.getEpoch(clusterId); await closing; - if (!isCurrent()) { + if (isRecoveryCurrent?.() === false) { return; } CredentialCache.deleteCredentials(clusterId); diff --git a/src/commands/updateCredentials/ExecuteStep.ts b/src/commands/updateCredentials/ExecuteStep.ts index 4e185a558..d37c7ac03 100644 --- a/src/commands/updateCredentials/ExecuteStep.ts +++ b/src/commands/updateCredentials/ExecuteStep.ts @@ -107,10 +107,10 @@ export class ExecuteStep extends AzureWizardExecuteStep Promise>().mockResolvedValue(undefined); const mockGet = vi.fn(); +const mockSave = vi.fn(); +const mockGetEpoch = vi.fn(() => 0); const mockDeleteClient = vi.fn(); const mockDeleteCredentials = vi.spyOn(CredentialCache, 'deleteCredentials'); const mockShutdownEvaluator = vi.fn(); @@ -26,27 +30,30 @@ const mockGetRegisteredShellTerminals = vi.fn(); vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ ...(await importOriginal<{ AzureWizard: typeof AzureWizard }>()), AzureWizard: class { - constructor(context: UpdateCredentialsWizardContext) { + constructor(private readonly context: UpdateCredentialsWizardContext) { capturedContexts.push(context); } public prompt(): Promise { return Promise.resolve(); } public execute(): Promise { - return Promise.resolve(); + return mockExecute(this.context); } }, })); vi.mock('../../services/connectionStorageService', async (importOriginal) => ({ ...(await importOriginal()), - ConnectionStorageService: { get: (...args: unknown[]): unknown => mockGet(...args) }, + ConnectionStorageService: { + get: (...args: unknown[]): unknown => mockGet(...args), + save: (...args: unknown[]): unknown => mockSave(...args), + }, })); vi.mock('../../documentdb/ClustersClient', () => ({ ClustersClient: { deleteClient: (...args: unknown[]): unknown => mockDeleteClient(...args), getLastFailedStartupCorrelationId: (): undefined => undefined, - getEpoch: (): number => 0, + getEpoch: (): number => mockGetEpoch(), getLatchReason: (): undefined => undefined, }, })); @@ -57,6 +64,7 @@ vi.mock('../../documentdb/shell/ShellTerminalLinkProvider', () => ({ getRegisteredShellTerminals: (): unknown => mockGetRegisteredShellTerminals(), })); vi.mock('../refreshView/refreshView', () => ({ refreshView: vi.fn() })); +vi.mock('../../utils/dialogs/showConfirmation', () => ({ showConfirmationAsInSettings: vi.fn() })); vi.mock('../../extensionVariables', () => ({ ext: { connectionsBranchDataProvider: { hasNodeErrorState: vi.fn(() => false) } }, })); @@ -64,6 +72,7 @@ vi.mock('../../extensionVariables', () => ({ beforeEach(() => { CredentialCache.deleteCredentials('stable-cluster-id'); vi.clearAllMocks(); + mockGetEpoch.mockReturnValue(0); mockGetRegisteredShellTerminals.mockReturnValue([]); capturedContexts.length = 0; }); @@ -210,6 +219,30 @@ describe('updateCredentials post-wizard updates', () => { ); }); + it('updates runtime credentials when the epoch changes during an ordinary save', async (): Promise => { + let storedConnection = originalConnection; + const newCredentials = { connectionUser: 'old-user', connectionPassword: 'new-password' }; + mockGet.mockImplementation(async () => structuredClone(storedConnection)); + mockExecute.mockImplementationOnce(async (wizardContext): Promise => { + wizardContext.nativeAuthConfig = newCredentials; + await new ExecuteStep().execute(wizardContext); + }); + mockSave.mockImplementationOnce( + async (_zone: storageModule.StorageZone, item: storageModule.ConnectionItem): Promise => { + storedConnection = structuredClone(item); + mockGetEpoch.mockReturnValue(1); + }, + ); + + await updateCredentials(context, node); + + expect(storedConnection.secrets.nativeAuthConfig).toEqual(newCredentials); + expect(CredentialCache.getCredentials(node.cluster.clusterId)?.nativeAuthConfig).toEqual(newCredentials); + expect(capturedContexts[0].credentialsSaved).toBe(true); + expect(mockDeleteClient).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId); + expect(mockShutdownEvaluator).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId); + }); + it.each<{ authMethod: AuthMethodId; secrets: Partial }>([ { authMethod: AuthMethodId.NativeAuth, diff --git a/src/commands/updateCredentials/updateCredentials.ts b/src/commands/updateCredentials/updateCredentials.ts index 8ebc1c3fe..e132a6f0e 100644 --- a/src/commands/updateCredentials/updateCredentials.ts +++ b/src/commands/updateCredentials/updateCredentials.ts @@ -60,7 +60,7 @@ export async function updateCredentials(context: IActionContext, node: DocumentD const clusterId = node.cluster.clusterId; let epoch = ClustersClient.getEpoch(clusterId); const recoveringRejection = ClustersClient.getLatchReason(clusterId) === 'credentialsRejected'; - const isCurrent = (): boolean => ClustersClient.getEpoch(clusterId) === epoch; + const isRecoveryCurrent = recoveringRejection ? (): boolean => ClustersClient.getEpoch(clusterId) === epoch : undefined; // The failed attempt these credentials replace; the reconnect's `connect.startup` names it in // `previousFailedStartupCorrelationId`, so it shows whether the new credentials worked. const failedStartupCorrelationId = ClustersClient.getLastFailedStartupCorrelationId(node.cluster.clusterId); @@ -76,7 +76,7 @@ export async function updateCredentials(context: IActionContext, node: DocumentD const resourceType = resolveStorageZone(node.cluster); const storedItem = await ConnectionStorageService.get(node.storageId, resourceType); - if (!isCurrent()) { + if (isRecoveryCurrent?.() === false) { return; } // Type guard ensures we have connection properties (not a folder) @@ -122,7 +122,7 @@ export async function updateCredentials(context: IActionContext, node: DocumentD storageId: node.storageId, isErrorState, reconnectAfterError: false, - isRecoveryCurrent: isCurrent, + isRecoveryCurrent, }; const wizard = new AzureWizard(wizardContext, { @@ -145,23 +145,24 @@ export async function updateCredentials(context: IActionContext, node: DocumentD }); await wizard.prompt(); - if (!isCurrent()) { + if (isRecoveryCurrent?.() === false) { return; } await wizard.execute(); - if (!isCurrent() || (recoveringRejection && !wizardContext.credentialsSaved)) { + if (isRecoveryCurrent?.() === false || (recoveringRejection && !wizardContext.credentialsSaved)) { return; } const updatedStoredItem = await ConnectionStorageService.get(node.storageId, resourceType); - if (!isCurrent()) { + if (isRecoveryCurrent?.() === false) { return; } const updatedConnection = updatedStoredItem && isConnection(updatedStoredItem) ? updatedStoredItem : undefined; const closing = ClustersClient.deleteClient(clusterId); epoch = ClustersClient.getEpoch(clusterId); await closing; - if (!isCurrent()) { + // Do not publish cached credentials over a lifecycle change during close. + if (ClustersClient.getEpoch(clusterId) !== epoch) { return; } const authMethod = authMethodFromString(updatedConnection?.properties.selectedAuthMethod); From dcee13654af77d420d0ca7977107f9cf1726a817 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 19:50:39 +0000 Subject: [PATCH 20/29] fix: close lint and type-check gaps in PR4 review fixes Use the existing view ID string comparison convention and the storage read-back type in the credential regression fixture. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../updateCredentials.test.ts | 2 +- .../updateCredentials/updateCredentials.ts | 4 ++- src/tree/documentdb/ClusterItemBase.test.ts | 25 +++++++++++-------- src/tree/documentdb/ClusterItemBase.ts | 4 +-- 4 files changed, 21 insertions(+), 14 deletions(-) diff --git a/src/commands/updateCredentials/updateCredentials.test.ts b/src/commands/updateCredentials/updateCredentials.test.ts index d7e63022e..b82ec629c 100644 --- a/src/commands/updateCredentials/updateCredentials.test.ts +++ b/src/commands/updateCredentials/updateCredentials.test.ts @@ -220,7 +220,7 @@ describe('updateCredentials post-wizard updates', () => { }); it('updates runtime credentials when the epoch changes during an ordinary save', async (): Promise => { - let storedConnection = originalConnection; + let storedConnection: storageModule.ConnectionItem = originalConnection; const newCredentials = { connectionUser: 'old-user', connectionPassword: 'new-password' }; mockGet.mockImplementation(async () => structuredClone(storedConnection)); mockExecute.mockImplementationOnce(async (wizardContext): Promise => { diff --git a/src/commands/updateCredentials/updateCredentials.ts b/src/commands/updateCredentials/updateCredentials.ts index e132a6f0e..8e5e6fcfa 100644 --- a/src/commands/updateCredentials/updateCredentials.ts +++ b/src/commands/updateCredentials/updateCredentials.ts @@ -60,7 +60,9 @@ export async function updateCredentials(context: IActionContext, node: DocumentD const clusterId = node.cluster.clusterId; let epoch = ClustersClient.getEpoch(clusterId); const recoveringRejection = ClustersClient.getLatchReason(clusterId) === 'credentialsRejected'; - const isRecoveryCurrent = recoveringRejection ? (): boolean => ClustersClient.getEpoch(clusterId) === epoch : undefined; + const isRecoveryCurrent = recoveringRejection + ? (): boolean => ClustersClient.getEpoch(clusterId) === epoch + : undefined; // The failed attempt these credentials replace; the reconnect's `connect.startup` names it in // `previousFailedStartupCorrelationId`, so it shows whether the new credentials worked. const failedStartupCorrelationId = ClustersClient.getLastFailedStartupCorrelationId(node.cluster.clusterId); diff --git a/src/tree/documentdb/ClusterItemBase.test.ts b/src/tree/documentdb/ClusterItemBase.test.ts index eea7db86e..da35ebb9a 100644 --- a/src/tree/documentdb/ClusterItemBase.test.ts +++ b/src/tree/documentdb/ClusterItemBase.test.ts @@ -500,20 +500,25 @@ describe('ClusterItemBase.getChildren — cached client connection failure handl expect(vscode.commands.executeCommand).not.toHaveBeenCalled(); }); - it.each(['diagnose', 'sign-in-again'])('does not mistake a database named %s for a recovery action', (name): void => { - const item = new TestClusterItem(makeCluster(), null); - const child = { - id: `cluster-1/${name}`, - contextValue: 'treeItem_documentdbdatabase', - getTreeItem: (): vscode.TreeItem => ({ label: name }), - }; + it.each(['diagnose', 'sign-in-again'])( + 'does not mistake a database named %s for a recovery action', + (name): void => { + const item = new TestClusterItem(makeCluster(), null); + const child = { + id: `cluster-1/${name}`, + contextValue: 'treeItem_documentdbdatabase', + getTreeItem: (): vscode.TreeItem => ({ label: name }), + }; - expect(item.hasRetryNode([child])).toBe(false); - }); + expect(item.hasRetryNode([child])).toBe(false); + }, + ); it('keeps actionable recovery children without an inert Retry for stored credentials', async (): Promise => { ClustersClientMock.getLatchReason.mockReturnValue('credentialsRejected'); - ClustersClientMock.connectInteractive.mockRejectedValueOnce(new ConnectionUnavailableError('credentialsRejected')); + ClustersClientMock.connectInteractive.mockRejectedValueOnce( + new ConnectionUnavailableError('credentialsRejected'), + ); const item = new TestClusterItem({ ...makeCluster(), viewId: Views.ConnectionsView }, null); try { const children = await item.getChildren(); diff --git a/src/tree/documentdb/ClusterItemBase.ts b/src/tree/documentdb/ClusterItemBase.ts index f9c7e5bde..bdd2a8950 100644 --- a/src/tree/documentdb/ClusterItemBase.ts +++ b/src/tree/documentdb/ClusterItemBase.ts @@ -20,6 +20,7 @@ import { type DatabaseItemModel, } from '../../documentdb/ClustersClient'; import { CredentialCache } from '../../documentdb/CredentialCache'; +import { Views } from '../../documentdb/Views'; import { type EntraIdAuthConfig, type ManagedIdentityAuthConfig, @@ -30,7 +31,6 @@ import { isEntraDestinationRejectedError } from '../../documentdb/auth/oidcAllow import { classifyConnectionFailure, type ConnectionFailure } from '../../documentdb/connectionFailures'; import { ShellCommandIds } from '../../documentdb/shell/constants'; import { showClusterConnectFailure } from '../../documentdb/showClusterConnectFailure'; -import { Views } from '../../documentdb/Views'; import { ext } from '../../extensionVariables'; import { SettingsService } from '../../services/SettingsService'; import { ErrorExplanationService } from '../../services/errorExplanationService'; @@ -369,7 +369,7 @@ export abstract class ClusterItemBase Date: Mon, 23 Nov 2026 19:50:39 +0000 Subject: [PATCH 21/29] docs: record PR4 review dispositions and verified handoff checks Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iterations/01-dev-plan.md | 4 ++ .../01-pr4-connection-recovery-review.md | 58 +++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr4-connection-recovery-review.md diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index 02e3cca12..93f7d4c37 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 @@ -1357,6 +1357,10 @@ shim (0005). - **Worker startup regression:** PR4's shared OIDC code imported the VS Code UI auth-method module into the Node worker path. Keep the shared auth IDs independent of VS Code. Verify the next packaged candidate starts both Shell and Playground; the tree OP-3 gate is unchanged. +- **PR4 handoff verification:** OP-3 passed, author-approved pre-review fixes are in + [the review record](./01-pr4-connection-recovery-review.md), and local Case 2 passed + (9,796 runtime tests passed, one skipped). Keep PR4 in draft until the separate live + packaged Shell and Playground smoke passes. WI-6 host work may proceed on this base. --- diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr4-connection-recovery-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr4-connection-recovery-review.md new file mode 100644 index 000000000..79b0160a5 --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr4-connection-recovery-review.md @@ -0,0 +1,58 @@ +--- +feature: connection-lifecycle +kind: review +status: active +created: 2026-11-23 +--- + +# PR4 pre-review: connection failure recovery + +[PR #1117](https://github.com/microsoft/vscode-documentdb/pull/1117), reviewed locally at +`69112da71` against PR3's `a301f6561`. GPT-6.2-Sol performed the initial review; Claude +Opus 5.5 validated the findings and performed an independent sweep. No published GitHub +reviews were present. The review findings below reflect the reviewed revision; the +operator's dispositions and verification are recorded separately. + +| ID | Severity | Validation | Finding and recommended disposition | +| --- | -------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| F1 | Medium | Partial, 75% | A rejected replacement outside the tree can try the same Entra settings again; the tree already covers its own path. Reproduce first, then latch only a current, verified Entra replacement with a terminal rejection. Leave first-startup and Native/RU behavior alone. [Startup](../../../../../src/documentdb/ClustersClient.ts#L1010) | +| F2 | Medium | Valid, 85%; predates PR4 | An explicit tenant edit can leave the old tenant pin after a sign-in failure. Keep the existing WI-7 requirement to replace or clear the pin on a saved tenant change; do not pull the broader credential-update transaction into PR4. [Update credentials](../../../../../src/commands/updateCredentials/updateCredentials.ts#L171) | +| F3 | Medium | Valid, 80% | An old Retry row can close a healthy replacement already published before the click. Fence the destructive step to the failed client; refresh without closing a newer client. [Retry](../../../../../src/commands/retryAuthentication/retryAuthentication.ts#L155) | +| F4 | Medium | Plausible race, 65% | A late successful database listing could render old rows after another account becomes current. Reproduce first. Discard a result when the identity differs or a latch is set, using the existing stale-result path; a same-identity replacement alone should not discard it. [Expansion](../../../../../src/tree/documentdb/ClusterItemBase.ts#L559) | +| F5 | Medium | Valid, 85% | For a latched stored Native connection, Retry does nothing; Update credentials is the repair. Hide only a Retry row with no action, while retaining Diagnose and Open shell and preserving error detection. Keep working RU and Native Discovery Retry paths. [Recovery rows](../../../../../src/tree/documentdb/ClusterItemBase.ts#L360) | +| N1 | Medium | Valid, 90%; WI-6 integration | The operation wrapper lacks auth context for startup rejection. Cover it when WI-6 first wires the wrapper to routers; the host must return the typed unavailable reason instead of a generic error. [Operation wrapper](../../../../../src/documentdb/runWithClient.ts#L48) | +| N2 | Medium | Potential regression, 70% | The new recovery fence applies to ordinary edits, and a return after storage has saved can leave storage and cached settings out of sync. Reproduce first; keep any PR4 repair scoped to the new regression. Leave the broader save, latch, and teardown transaction in WI-7. [Credentials save](../../../../../src/commands/updateCredentials/ExecuteStep.ts#L110) and [connection string save](../../../../../src/commands/updateConnectionString/ExecuteStep.ts#L95). | +| N3 | Medium | Valid, 90% | A real database named `sign-in-again` can match the recovery row's ID. Require the reserved error context as well as the ID, and test that the real database remains visible as healthy. [Error detection](../../../../../src/tree/documentdb/ClusterItemBase.ts#L610) | + +## Author decisions + +The operator approved scoped PR4 fixes for F1, F3–F5 and N2–N3, with reproduction +before changing F1, F4 or N2. They asked to avoid nonessential edge cases and keep the +implementation simple. F2 stays in WI-7; N1 stays in WI-6. + +The focused regressions reproduced F1, F3, F4, F5 and N3. All 132 tests in the three +affected suites passed after `87ab0ed1f` (F1, F3) and `1500634d1` (F4, F5, N3). +The stale-tree guard checks identity, not generation, so a same-identity replacement does +not by itself discard a result. + +N2 was reproduced in both edit commands: a connection-string edit was skipped, and a +credential write succeeded without updating the runtime cache. `64d6f3ffd` limits the +wizard epoch check to recovery edits and records a completed storage save accurately. +An obsolete recovery still cannot evict newer state or clear its latch. All 62 focused +tests passed across six suites. Reconciling an already in-flight recovery save that lands +after teardown stays in WI-7, with F2. + +## Handoff verification + +OP-3 passed on the older CI VSIX. The current review proposals do not change the tested +sign-out, dismissal, or explicit sign-in sequence. The local `1.1.1-alpha.1` VSIX packaged +successfully; its shared Shell/Playground worker booted in plain Node and acknowledged +shutdown. A live Shell and Playground smoke test is separate. + +Final local Case 2 passed: localization generation and check, formatting, lint, build, +strict workspace test type-check, the full runtime suite (**432 files; 9,796 passed, one +skipped**), and VSIX packaging. The initial label test was corrected to assert the +label on the existing plain-object tree fixture. The review-fix run also caught an +enum-to-string lint error and a storage fixture type mismatch; both were fixed +without changing recovery behavior or weakening any assertions. PR4 remains a draft +until the live packaged Shell and Playground smoke test is recorded. From ed21d7c16ccbf1cf8d9ffc854d787ab324308dcf Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Tue, 24 Nov 2026 06:52:28 +0000 Subject: [PATCH 22/29] docs: record operator acceptance of the PR4 worker smoke Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../connection-lifecycle/iterations/01-dev-plan.md | 6 ++++-- .../iterations/01-pr4-connection-recovery-review.md | 8 +++++--- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index 93f7d4c37..70658a552 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 @@ -1359,8 +1359,10 @@ shim (0005). the next packaged candidate starts both Shell and Playground; the tree OP-3 gate is unchanged. - **PR4 handoff verification:** OP-3 passed, author-approved pre-review fixes are in [the review record](./01-pr4-connection-recovery-review.md), and local Case 2 passed - (9,796 runtime tests passed, one skipped). Keep PR4 in draft until the separate live - packaged Shell and Playground smoke passes. WI-6 host work may proceed on this base. + (9,796 runtime tests passed, one skipped). Full CI passed on `d422d065b`. + The operator confirmed both Shell and Playground on the CI-built `1.1.1-alpha.1` VSIX + on 2026-11-24. The worker smoke gate is cleared, and PR4 can move to operator review. + WI-6 continues on this base without waiting for PR4 to merge. --- diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr4-connection-recovery-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr4-connection-recovery-review.md index 79b0160a5..1296406c2 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr4-connection-recovery-review.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr4-connection-recovery-review.md @@ -47,12 +47,14 @@ after teardown stays in WI-7, with F2. OP-3 passed on the older CI VSIX. The current review proposals do not change the tested sign-out, dismissal, or explicit sign-in sequence. The local `1.1.1-alpha.1` VSIX packaged successfully; its shared Shell/Playground worker booted in plain Node and acknowledged -shutdown. A live Shell and Playground smoke test is separate. +shutdown. On 2026-11-24, the operator confirmed that both Shell and Playground work +on the requested CI-built `1.1.1-alpha.1` VSIX. The live smoke gate is cleared. Final local Case 2 passed: localization generation and check, formatting, lint, build, strict workspace test type-check, the full runtime suite (**432 files; 9,796 passed, one skipped**), and VSIX packaging. The initial label test was corrected to assert the label on the existing plain-object tree fixture. The review-fix run also caught an enum-to-string lint error and a storage fixture type mismatch; both were fixed -without changing recovery behavior or weakening any assertions. PR4 remains a draft -until the live packaged Shell and Playground smoke test is recorded. +without changing recovery behavior or weakening any assertions. Full CI also passed +on code head `d422d065b`. The operator confirmation is a documentation-only follow-up; +it does not change the tested build or require repeating OP-3. From 27345af20f8e226e71837841ed092e463ba9025f Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Tue, 24 Nov 2026 11:07:27 +0000 Subject: [PATCH 23/29] fix: explain Entra provider drift before retrying sign-in (R1) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/commands/signInAgain/signInAgain.test.ts | 47 ++++++++++++++++---- src/commands/signInAgain/signInAgain.ts | 14 +++++- 2 files changed, 52 insertions(+), 9 deletions(-) diff --git a/src/commands/signInAgain/signInAgain.test.ts b/src/commands/signInAgain/signInAgain.test.ts index 90c25099a..a8f814de5 100644 --- a/src/commands/signInAgain/signInAgain.test.ts +++ b/src/commands/signInAgain/signInAgain.test.ts @@ -7,9 +7,11 @@ 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 { getEntraSession } from '../../documentdb/auth/entraSession'; import { ClustersClient } from '../../documentdb/ClustersClient'; import { CredentialCache } from '../../documentdb/CredentialCache'; +import { showClusterConnectFailure } from '../../documentdb/showClusterConnectFailure'; import { signInAgain } from './signInAgain'; const pin = { @@ -20,6 +22,7 @@ const pin = { tenantId: 'tenant', } as const; const clusterId = 'cluster'; +const mocks = vi.hoisted(() => ({ configureAuth: vi.fn() })); vi.mock('../../documentdb/ClustersClient', () => ({ addEstablishedConnectionContext: vi.fn(), @@ -39,14 +42,7 @@ vi.mock('../../documentdb/auth/MicrosoftEntraIDAuthHandler', () => ({ _trace: undefined, acquire: typeof getEntraSession, ): Promise { - const session = await acquire({ - mode: 'forceNew', - providerId: pin.providerId, - resource: 'scope', - tenantId: pin.tenantId, - account: { id: pin.accountId, label: pin.accountLabel }, - }); - return { verifiedIdentity: { ...pin, accountId: session?.account.id } }; + return await mocks.configureAuth(_timings, _trace, acquire); } }, })); @@ -60,6 +56,22 @@ function actionContext(): IActionContext { describe('signInAgain', () => { beforeEach(() => { vi.clearAllMocks(); + mocks.configureAuth.mockImplementation( + async ( + _timings: undefined, + _trace: undefined, + acquire: typeof getEntraSession, + ): Promise => { + const session = await acquire({ + mode: 'forceNew', + providerId: pin.providerId, + resource: 'scope', + tenantId: pin.tenantId, + account: { id: pin.accountId, label: pin.accountLabel }, + }); + return { verifiedIdentity: { ...pin, accountId: session?.account.id } }; + }, + ); CredentialCache.setAuthCredentials( clusterId, AuthMethodId.MicrosoftEntraID, @@ -123,4 +135,23 @@ describe('signInAgain', () => { ); vi.mocked(ClustersClient.getEpoch).mockReturnValue(1); }); + + it('explains how to restore the pinned provider before opening an authorization prompt', async (): Promise => { + const error = new EntraSignInRequiredError('providerChanged'); + mocks.configureAuth.mockRejectedValueOnce(error); + + await expect(signInAgain(actionContext(), { clusterId })).rejects.toBe(error); + + expect(getEntraSession).not.toHaveBeenCalled(); + expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); + expect(showClusterConnectFailure).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( + 'The Azure cloud or sign-in provider changed.', + { + modal: true, + detail: + '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.', + }, + ); + }); }); diff --git a/src/commands/signInAgain/signInAgain.ts b/src/commands/signInAgain/signInAgain.ts index caebaeedf..ca454fd94 100644 --- a/src/commands/signInAgain/signInAgain.ts +++ b/src/commands/signInAgain/signInAgain.ts @@ -6,7 +6,10 @@ import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext-utils'; import * as vscode from 'vscode'; import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; -import { EntraIdentityMismatchError } from '../../documentdb/auth/entraErrors/entraCallbackErrors'; +import { + EntraIdentityMismatchError, + EntraSignInRequiredError, +} from '../../documentdb/auth/entraErrors/entraCallbackErrors'; import { getEntraSession } from '../../documentdb/auth/entraSession'; import { MicrosoftEntraIDAuthHandler } from '../../documentdb/auth/MicrosoftEntraIDAuthHandler'; import { addEstablishedConnectionContext, ClustersClient } from '../../documentdb/ClustersClient'; @@ -118,6 +121,15 @@ export async function signInAgain( error, 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.', + ), + }); + throw error; + } await showClusterConnectFailure({ clusterId, clusterName: node?.cluster.name ?? vscode.l10n.t('connection'), From f3407187a0e92e7b6ef88168c203470fa1a6deb7 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Tue, 24 Nov 2026 11:07:27 +0000 Subject: [PATCH 24/29] fix: preserve actionable managed identity guidance (R4) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../auth/ManagedIdentityAuthHandler.test.ts | 19 +++++++++++ .../auth/MicrosoftEntraIDAuthHandler.test.ts | 6 +++- .../auth/entraErrors/entraCallbackErrors.ts | 7 +++- src/documentdb/auth/managedIdentityErrors.ts | 3 ++ src/documentdb/auth/managedIdentityTenant.ts | 4 +-- .../auth/managedIdentityTokenProvider.ts | 12 +++++-- .../showClusterConnectFailure.test.ts | 32 +++++++++++++++++++ 7 files changed, 76 insertions(+), 7 deletions(-) diff --git a/src/documentdb/auth/ManagedIdentityAuthHandler.test.ts b/src/documentdb/auth/ManagedIdentityAuthHandler.test.ts index 503004071..89f0ed29c 100644 --- a/src/documentdb/auth/ManagedIdentityAuthHandler.test.ts +++ b/src/documentdb/auth/ManagedIdentityAuthHandler.test.ts @@ -16,6 +16,7 @@ import { buildAuthConnectionTarget } from './authConnectionTarget'; import { AuthMethodId } from './AuthMethod'; import * as tokenResources from './documentdbTokenResource'; import { TokenCallbackError } from './entraErrors/entraCallbackErrors'; +import { ManagedIdentityGuidanceError } from './managedIdentityErrors'; import { EntraErrorExplainer } from './entraErrors/EntraErrorExplainer'; import { getRecentEntraTokenFailure, @@ -373,6 +374,24 @@ describe('ManagedIdentityAuthHandler', () => { }); }); + it('preserves the actionable managed identity message in the typed callback wrapper', async (): Promise => { + const message = + 'This machine has more than one managed identity, so the right one cannot be chosen automatically. Reconnect and enter the client ID you want to use.'; + const accessToken = 'private-access-token'; + const cause = Object.freeze(Object.assign(new ManagedIdentityGuidanceError(message), { accessToken })); + getManagedIdentityAccessToken.mockRejectedValueOnce(cause); + const { options } = await new ManagedIdentityAuthHandler(buildCredentials()).configureAuth(); + + const callback = invokeOidcCallback(options); + await expect(callback).rejects.toMatchObject({ + name: 'TokenCallbackError', + message, + authMethod: AuthMethodId.ManagedIdentity, + cause, + }); + await expect(callback).rejects.not.toThrow(accessToken); + }); + it('does not record token resource resolution errors as token-acquisition failures', async (): Promise => { const error = new tokenResources.TokenResourceResolutionError( 'Set the cloud resource.', diff --git a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts index b223c2417..31061882a 100644 --- a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts +++ b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts @@ -614,7 +614,11 @@ describe('MicrosoftEntraIDAuthHandler', () => { timeoutContext: new AbortController().signal, }); await expect(result).rejects.toBeInstanceOf(TokenCallbackError); - await expect(result).rejects.toMatchObject({ authMethod: AuthMethodId.MicrosoftEntraID, cause }); + await expect(result).rejects.toMatchObject({ + message: 'Failed to obtain a Microsoft Entra ID token.', + authMethod: AuthMethodId.MicrosoftEntraID, + cause, + }); expect(onCallbackTokenObserved).toHaveBeenCalledOnce(); const observed = onCallbackTokenObserved.mock.lastCall?.[0]; expect(observed?.outcome).toBe('failed'); diff --git a/src/documentdb/auth/entraErrors/entraCallbackErrors.ts b/src/documentdb/auth/entraErrors/entraCallbackErrors.ts index ef0df558b..9bbf609ba 100644 --- a/src/documentdb/auth/entraErrors/entraCallbackErrors.ts +++ b/src/documentdb/auth/entraErrors/entraCallbackErrors.ts @@ -5,6 +5,7 @@ import * as l10n from '@vscode/l10n'; import { AuthMethodId } from '../AuthMethodId'; +import { ManagedIdentityGuidanceError } from '../managedIdentityErrors'; export class EntraSignInRequiredError extends Error { constructor(public readonly reason: 'noSession' | 'providerChanged') { @@ -27,7 +28,11 @@ export class TokenCallbackError extends Error { cause: unknown, public readonly authMethod: TokenCallbackAuthMethod = AuthMethodId.MicrosoftEntraID, ) { - super(l10n.t('Failed to obtain a Microsoft Entra ID token.'), { cause }); + const message = + authMethod === AuthMethodId.ManagedIdentity && cause instanceof ManagedIdentityGuidanceError + ? cause.message + : l10n.t('Failed to obtain a Microsoft Entra ID token.'); + super(message, { cause }); this.name = 'TokenCallbackError'; } } diff --git a/src/documentdb/auth/managedIdentityErrors.ts b/src/documentdb/auth/managedIdentityErrors.ts index ce799e620..699eb8c77 100644 --- a/src/documentdb/auth/managedIdentityErrors.ts +++ b/src/documentdb/auth/managedIdentityErrors.ts @@ -5,6 +5,9 @@ import * as l10n from '@vscode/l10n'; +/** Marks localized recovery guidance, not an SDK error message. */ +export class ManagedIdentityGuidanceError extends Error {} + /** * Coarse classification of a managed identity token failure. * diff --git a/src/documentdb/auth/managedIdentityTenant.ts b/src/documentdb/auth/managedIdentityTenant.ts index 98ad06d2d..a1a0750e8 100644 --- a/src/documentdb/auth/managedIdentityTenant.ts +++ b/src/documentdb/auth/managedIdentityTenant.ts @@ -4,7 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import { traceAuthFlow, type AuthTraceContext } from '../../utils/authTrace'; -import { describeManagedIdentityTenantMismatch } from './managedIdentityErrors'; +import { describeManagedIdentityTenantMismatch, ManagedIdentityGuidanceError } from './managedIdentityErrors'; import { reportManagedIdentityFailureReason } from './managedIdentityTelemetry'; /** @@ -87,5 +87,5 @@ export function verifyManagedIdentityTenant( traceContext, ); reportManagedIdentityFailureReason('tenantMismatch', clientId, correlationId, traceContext); - throw new Error(describeManagedIdentityTenantMismatch(identityTenantId, clusterTenantId)); + throw new ManagedIdentityGuidanceError(describeManagedIdentityTenantMismatch(identityTenantId, clusterTenantId)); } diff --git a/src/documentdb/auth/managedIdentityTokenProvider.ts b/src/documentdb/auth/managedIdentityTokenProvider.ts index 908f1ddbc..d50f90771 100644 --- a/src/documentdb/auth/managedIdentityTokenProvider.ts +++ b/src/documentdb/auth/managedIdentityTokenProvider.ts @@ -6,7 +6,11 @@ import { type TokenCredential } from '@azure/identity'; import { randomUUID } from 'crypto'; import { traceAuthFlow, traceAuthOperation, type AuthTraceContext } from '../../utils/authTrace'; -import { classifyManagedIdentityError, describeManagedIdentityError } from './managedIdentityErrors'; +import { + classifyManagedIdentityError, + describeManagedIdentityError, + ManagedIdentityGuidanceError, +} from './managedIdentityErrors'; import { reportManagedIdentityTokenFailure } from './managedIdentityTelemetry'; import { verifyManagedIdentityTenant } from './managedIdentityTenant'; @@ -50,14 +54,16 @@ export async function getManagedIdentityAccessToken( traceContext, ); } catch (error) { + const reason = classifyManagedIdentityError(error); traceAuthFlow( 'managedIdentity.tokenFailure', - { reason: classifyManagedIdentityError(error) }, + { reason }, tokenCorrelationId, traceContext, ); reportManagedIdentityTokenFailure(error, clientId, tokenCorrelationId, traceContext); - throw new Error(describeManagedIdentityError(error, clientId)); + const message = describeManagedIdentityError(error, clientId); + throw reason === 'other' ? new Error(message) : new ManagedIdentityGuidanceError(message); } if (!token) { diff --git a/src/documentdb/showClusterConnectFailure.test.ts b/src/documentdb/showClusterConnectFailure.test.ts index 2fbed1b08..19c74108c 100644 --- a/src/documentdb/showClusterConnectFailure.test.ts +++ b/src/documentdb/showClusterConnectFailure.test.ts @@ -8,6 +8,9 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { type IActionContext } from '@microsoft/vscode-azext-utils'; import { Links } from '../constants'; import { ErrorExplanationService } from '../services/errorExplanationService'; +import { AuthMethodId } from './auth/AuthMethod'; +import { TokenCallbackError } from './auth/entraErrors/entraCallbackErrors'; +import { ManagedIdentityGuidanceError } from './auth/managedIdentityErrors'; import { EntraDestinationRejectedError, evaluateEntraDestination } from './auth/oidcAllowedHosts'; import { showClusterConnectFailure } from './showClusterConnectFailure'; @@ -188,6 +191,35 @@ describe('showClusterConnectFailure', () => { }); }); + it('shows an actionable managed identity wrapper message without displaying SDK fields', async () => { + const context = createMockContext(); + const message = + 'This machine has more than one managed identity, so the right one cannot be chosen automatically. Reconnect and enter the client ID you want to use.'; + const accessToken = 'private-access-token'; + const cause = Object.assign(new ManagedIdentityGuidanceError(message), { accessToken }); + const error = new TokenCallbackError(cause, AuthMethodId.ManagedIdentity); + vi.mocked(ErrorExplanationService.explain).mockResolvedValue(undefined); + + await showClusterConnectFailure({ + clusterId: 'stable-id', + clusterName: 'Test Cluster', + error, + context, + }); + + expect(showErrorMessage).toHaveBeenCalledWith('Failed to connect to "Test Cluster"', { + modal: true, + detail: `Revisit connection details and try again.\n\nError: ${message}`, + }); + expect(JSON.stringify(showErrorMessage.mock.calls)).not.toContain(accessToken); + expect(error).toMatchObject({ + name: 'TokenCallbackError', + message, + authMethod: AuthMethodId.ManagedIdentity, + cause, + }); + }); + it('stringifies non-Error failures without changing the diagnostics input', async () => { const context = createMockContext(); vi.mocked(ErrorExplanationService.explain).mockResolvedValue(undefined); From 195243c52efe43d8de0ce2d7d220b28c9934aec5 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Tue, 24 Nov 2026 11:07:27 +0000 Subject: [PATCH 25/29] fix: recover rejected Quick Start credentials through Retry (R6) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../retryAuthentication.test.ts | 21 +++++++++++++++++++ .../retryAuthentication.ts | 12 ++++++----- .../localQuickStart/quickStartTypes.ts | 5 +++++ .../LocalQuickStart/quickStartTreeIdentity.ts | 12 +++-------- src/tree/documentdb/ClusterItemBase.test.ts | 16 ++++++++++++++ src/tree/documentdb/ClusterItemBase.ts | 9 +++++++- 6 files changed, 60 insertions(+), 15 deletions(-) diff --git a/src/commands/retryAuthentication/retryAuthentication.test.ts b/src/commands/retryAuthentication/retryAuthentication.test.ts index 9b6b96455..bee8b911e 100644 --- a/src/commands/retryAuthentication/retryAuthentication.test.ts +++ b/src/commands/retryAuthentication/retryAuthentication.test.ts @@ -12,6 +12,7 @@ import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; import { ClustersClient } from '../../documentdb/ClustersClient'; import { CredentialCache } from '../../documentdb/CredentialCache'; import { ext } from '../../extensionVariables'; +import { clusterId as quickStartClusterId, DEFAULT_ALIAS } from '../../services/localQuickStart/quickStartTypes'; import { type ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; import { retryAuthentication } from './retryAuthentication'; @@ -214,6 +215,26 @@ describe('retryAuthentication', () => { }, ); + it.each([true, false])('reloads Quick Start with an empty cache only if the rejection can be cleared (%s)', async (cleared): Promise => { + const clusterId = quickStartClusterId(DEFAULT_ALIAS); + const node = { id: 'connectionsView/localQuickStart/instance', cluster: { clusterId }, getTreeItem }; + vi.mocked(ClustersClient.getEpoch).mockReturnValueOnce(7); + vi.mocked(ClustersClient.getLatchReason).mockReturnValueOnce('credentialsRejected'); + vi.mocked(CredentialCache.getCredentials).mockReturnValueOnce(undefined); + vi.mocked(ClustersClient.clearCredentialRejection).mockReturnValueOnce(cleared); + + await retryAuthentication(actionContext as never, node); + + expect(ClustersClient.clearCredentialRejection).toHaveBeenCalledExactlyOnceWith(clusterId, 7); + if (cleared) { + expect(CredentialCache.deleteCredentials).toHaveBeenCalledExactlyOnceWith(clusterId); + expect(ext.connectionsBranchDataProvider.refresh).toHaveBeenCalledExactlyOnceWith(node); + } else { + expect(CredentialCache.deleteCredentials).not.toHaveBeenCalled(); + expect(ext.connectionsBranchDataProvider.refresh).not.toHaveBeenCalled(); + } + }); + it('abandons a successful key read if the epoch changed', async (): Promise => { const node = ruNode(); node.readReplacementKey.mockResolvedValue({ connectionString: 'mongodb://test', availableAuthMethods: [] }); diff --git a/src/commands/retryAuthentication/retryAuthentication.ts b/src/commands/retryAuthentication/retryAuthentication.ts index 56f7a92ca..2c1a44bc4 100644 --- a/src/commands/retryAuthentication/retryAuthentication.ts +++ b/src/commands/retryAuthentication/retryAuthentication.ts @@ -11,6 +11,7 @@ import { addEstablishedConnectionContext, ClustersClient } from '../../documentd import { CredentialCache } from '../../documentdb/CredentialCache'; import { inferViewIdFromTreeId, Views } from '../../documentdb/Views'; import { ext } from '../../extensionVariables'; +import { isQuickStartClusterId } from '../../services/localQuickStart/quickStartTypes'; import { type ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; import { ConnectionSourceUnavailableError } from '../../tree/documentdb/diagnosticCredentialRead'; import { type TreeElement } from '../../tree/TreeElement'; @@ -90,12 +91,13 @@ export async function retryAuthentication(context: IActionContext, node: Retryab if (!node.readReplacementKey) { const view = getViewId(node); const credentials = CredentialCache.getCredentials(clusterId); - // Native discovery nodes have no saved-credential editor. Retry through the - // existing provider flow, but never with the rejected cached credentials. + const quickStart = view === Views.ConnectionsView && isQuickStartClusterId(clusterId); + const nativeDiscovery = + (view === Views.DiscoveryView || view === Views.AzureResourcesView) && + credentials !== undefined && + (credentials.authMechanism ?? AuthMethodId.NativeAuth) === AuthMethodId.NativeAuth; if ( - (view !== Views.DiscoveryView && view !== Views.AzureResourcesView) || - !credentials || - (credentials.authMechanism ?? AuthMethodId.NativeAuth) !== AuthMethodId.NativeAuth || + (!quickStart && !nativeDiscovery) || !ClustersClient.clearCredentialRejection(clusterId, epoch) ) { return; diff --git a/src/services/localQuickStart/quickStartTypes.ts b/src/services/localQuickStart/quickStartTypes.ts index c727cc34b..14c5d3dc0 100644 --- a/src/services/localQuickStart/quickStartTypes.ts +++ b/src/services/localQuickStart/quickStartTypes.ts @@ -130,6 +130,11 @@ export function clusterId(alias: string): string { return `quickstart-${alias}`; } +/** Whether the stable cluster ID belongs to the supported managed instance. */ +export function isQuickStartClusterId(id: string): boolean { + return id === clusterId(DEFAULT_ALIAS); +} + /** Reduced lifecycle state set for the POC (design §6, decision D8). */ export enum InstanceState { NotInstalled = 'NotInstalled', diff --git a/src/tree/connections-view/LocalQuickStart/quickStartTreeIdentity.ts b/src/tree/connections-view/LocalQuickStart/quickStartTreeIdentity.ts index 30de44751..642eab353 100644 --- a/src/tree/connections-view/LocalQuickStart/quickStartTreeIdentity.ts +++ b/src/tree/connections-view/LocalQuickStart/quickStartTreeIdentity.ts @@ -5,10 +5,9 @@ import { Views } from '../../../documentdb/Views'; import { QuickStartService } from '../../../services/localQuickStart/QuickStartService'; -import { - clusterId as buildQuickStartClusterId, - DEFAULT_ALIAS, -} from '../../../services/localQuickStart/quickStartTypes'; +import { isQuickStartClusterId } from '../../../services/localQuickStart/quickStartTypes'; + +export { isQuickStartClusterId }; /** Builds the tree ID of the Quick Start root node. */ export function buildQuickStartTreeId(parentId: string = Views.ConnectionsView): string { @@ -20,11 +19,6 @@ export function buildQuickStartInstanceTreeId(parentId: string = Views.Connectio return `${buildQuickStartTreeId(parentId)}/instance`; } -/** Whether the stable cluster ID belongs to the currently supported managed instance. */ -export function isQuickStartClusterId(clusterId: string): boolean { - return clusterId === buildQuickStartClusterId(DEFAULT_ALIAS); -} - /** * Resolves the current managed instance's stable cluster ID to its synthetic tree ID. * diff --git a/src/tree/documentdb/ClusterItemBase.test.ts b/src/tree/documentdb/ClusterItemBase.test.ts index da35ebb9a..d81f7d653 100644 --- a/src/tree/documentdb/ClusterItemBase.test.ts +++ b/src/tree/documentdb/ClusterItemBase.test.ts @@ -530,6 +530,22 @@ describe('ClusterItemBase.getChildren — cached client connection failure handl } }); + it('keeps Retry for a synthetic Connections view item without a credential editor', async (): Promise => { + ClustersClientMock.getLatchReason.mockReturnValue('credentialsRejected'); + ClustersClientMock.connectInteractive.mockRejectedValueOnce(new ConnectionUnavailableError('credentialsRejected')); + const item = new TestClusterItem({ ...makeCluster(), viewId: Views.ConnectionsView }, null); + item.contextValue = 'treeItem_quickStartInstance'; + try { + expect((await item.getChildren()).map(({ id }) => id)).toEqual([ + 'cluster-1/diagnose', + 'cluster-1/open-shell', + 'cluster-1/retry', + ]); + } finally { + ClustersClientMock.getLatchReason.mockReset(); + } + }); + it('reports the binding that executed listDatabases, not the current cache entry', async (): Promise => { const error = new Error('deprecated generation'); const binding = { clusterId: 'cluster-1', fingerprint: 'old', generation: 1 }; diff --git a/src/tree/documentdb/ClusterItemBase.ts b/src/tree/documentdb/ClusterItemBase.ts index bdd2a8950..fb8f65f1b 100644 --- a/src/tree/documentdb/ClusterItemBase.ts +++ b/src/tree/documentdb/ClusterItemBase.ts @@ -348,6 +348,13 @@ export abstract class ClusterItemBase Date: Tue, 24 Nov 2026 11:07:28 +0000 Subject: [PATCH 26/29] fix: report foreground database and index expansion failures (R9) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/tree/documentdb/DatabaseItem.test.ts | 14 ++++++++++++++ src/tree/documentdb/DatabaseItem.ts | 5 ++++- src/tree/documentdb/IndexesItem.test.ts | 18 ++++++++++++++++++ src/tree/documentdb/IndexesItem.ts | 7 ++++++- 4 files changed, 42 insertions(+), 2 deletions(-) diff --git a/src/tree/documentdb/DatabaseItem.test.ts b/src/tree/documentdb/DatabaseItem.test.ts index 896a2524c..b57d029a6 100644 --- a/src/tree/documentdb/DatabaseItem.test.ts +++ b/src/tree/documentdb/DatabaseItem.test.ts @@ -35,6 +35,7 @@ vi.mock('../../utils/accumulatingTelemetry', () => ({ vi.mock('../../documentdb/ClustersClient', () => ({ ClustersClient: { getClient: vi.fn(), + reportFailure: vi.fn(), }, })); @@ -65,12 +66,25 @@ describe('DatabaseItem - async collection count loading', () => { estimateDocumentCountMock = vi.fn().mockResolvedValue(0); (ClustersClient.getClient as Mock).mockResolvedValue({ + binding: { clusterId: cluster.clusterId, fingerprint: 'identity', generation: 1 }, listCollections: listCollectionsMock, countCollections: countCollectionsMock, estimateDocumentCount: estimateDocumentCountMock, }); }); + it('reports the failed list against its own binding and preserves the error', async (): Promise => { + const error = new Error('List collections failed'); + listCollectionsMock.mockRejectedValueOnce(error); + + await expect(new DatabaseItem(cluster, databaseInfo).getChildren()).rejects.toBe(error); + expect(ClustersClient.reportFailure).toHaveBeenCalledExactlyOnceWith( + { clusterId: cluster.clusterId, fingerprint: 'identity', generation: 1 }, + error, + ); + expect(listCollectionsMock).toHaveBeenCalledOnce(); + }); + function flushAsync(): Promise { return new Promise((resolve) => setImmediate(resolve)); } diff --git a/src/tree/documentdb/DatabaseItem.ts b/src/tree/documentdb/DatabaseItem.ts index b9cef919f..90f33a7c3 100644 --- a/src/tree/documentdb/DatabaseItem.ts +++ b/src/tree/documentdb/DatabaseItem.ts @@ -76,7 +76,10 @@ export class DatabaseItem implements TreeElement, TreeElementWithExperience, Tre undefined, 'treeChildren', ); - const collections = await client.listCollections(this.databaseInfo.name); + const collections = await client.listCollections(this.databaseInfo.name).catch((error: unknown) => { + ClustersClient.reportFailure(client.binding, error); + throw error; + }); // Update the collection count from the full list we just fetched. This // is the exact value, so mark it authoritative: a still-running diff --git a/src/tree/documentdb/IndexesItem.test.ts b/src/tree/documentdb/IndexesItem.test.ts index 3d67ef096..e99b1433a 100644 --- a/src/tree/documentdb/IndexesItem.test.ts +++ b/src/tree/documentdb/IndexesItem.test.ts @@ -35,6 +35,7 @@ vi.mock('../../utils/accumulatingTelemetry', () => ({ vi.mock('../../documentdb/ClustersClient', () => ({ ClustersClient: { getClient: vi.fn(), + reportFailure: vi.fn(), }, getIndexExclusionReason: vi.fn(() => undefined), })); @@ -122,11 +123,28 @@ describe('IndexesItem - async index loading', () => { listSearchIndexesMock = vi.fn().mockRejectedValue(new Error('not supported')); (ClustersClient.getClient as Mock).mockResolvedValue({ + binding: { clusterId: cluster.clusterId, fingerprint: 'identity', generation: 1 }, listIndexes: listIndexesMock, listSearchIndexesForAtlas: listSearchIndexesMock, }); }); + it('reports only foreground index failures and preserves the original error', async (): Promise => { + const error = new Error('List indexes failed'); + listIndexesMock.mockRejectedValue(error); + const item = new IndexesItem(cluster, databaseInfo, collectionInfo); + item.loadIndexCount(); + await flushAsync(); + expect(ClustersClient.reportFailure).not.toHaveBeenCalled(); + + await expect(item.getChildren()).rejects.toBe(error); + expect(ClustersClient.reportFailure).toHaveBeenCalledExactlyOnceWith( + { clusterId: cluster.clusterId, fingerprint: 'identity', generation: 1 }, + error, + ); + expect(listIndexesMock).toHaveBeenCalledTimes(2); + }); + function flushAsync(): Promise { return new Promise((resolve) => setImmediate(resolve)); } diff --git a/src/tree/documentdb/IndexesItem.ts b/src/tree/documentdb/IndexesItem.ts index 885ef817e..4c1d52ff7 100644 --- a/src/tree/documentdb/IndexesItem.ts +++ b/src/tree/documentdb/IndexesItem.ts @@ -115,7 +115,12 @@ export class IndexesItem implements TreeElement, TreeElementWithExperience, Tree const client: ClustersClient = options ? await ClustersClient.getClient(this.cluster.clusterId, undefined, undefined, 'treeChildren', options) : await ClustersClient.getClient(this.cluster.clusterId, undefined, undefined, 'treeChildren'); - const indexes = await client.listIndexes(this.databaseInfo.name, this.collectionInfo.name); + const indexes = await client.listIndexes(this.databaseInfo.name, this.collectionInfo.name).catch((error: unknown) => { + if (!options?.background) { + ClustersClient.reportFailure(client.binding, error); + } + throw error; + }); // Try to get search indexes, but silently fail if not supported by the platform try { From 228be9f90d3717b18ab0a6ddcbbf472740683a81 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Tue, 24 Nov 2026 11:08:39 +0000 Subject: [PATCH 27/29] fix: explain how to repair rejected tree connections (R8) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/tree/documentdb/ClusterItemBase.test.ts | 33 ++++++++++++++++++++- src/tree/documentdb/ClusterItemBase.ts | 27 +++++++++++++---- 2 files changed, 53 insertions(+), 7 deletions(-) diff --git a/src/tree/documentdb/ClusterItemBase.test.ts b/src/tree/documentdb/ClusterItemBase.test.ts index d81f7d653..d05767356 100644 --- a/src/tree/documentdb/ClusterItemBase.test.ts +++ b/src/tree/documentdb/ClusterItemBase.test.ts @@ -463,7 +463,7 @@ describe('ClusterItemBase.getChildren — cached client connection failure handl connectionString: 'mongodb://example.test', authMechanism: AuthMethodId.MicrosoftEntraID, }); - ClustersClientMock.getLastVerifiedIdentity.mockReturnValueOnce({ + ClustersClientMock.getLastVerifiedIdentity.mockReturnValue({ kind: 'entra', providerId: 'microsoft', accountLabel: 'test', @@ -479,10 +479,17 @@ describe('ClusterItemBase.getChildren — cached client connection failure handl 'cluster-1/open-shell', ]); expect(children[0]).toMatchObject({ label: 'Retry sign-in' }); + if (reason === 'credentialsRejected') { + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith(expect.any(String), { + modal: true, + detail: 'The database rejected the credentials. Choose Retry sign-in to continue.', + }); + } expect(item.hasRetryNode(children)).toBe(true); expect(ClustersClientMock.reportFailure).not.toHaveBeenCalled(); expect(CredentialCache.deleteCredentials).not.toHaveBeenCalled(); vi.mocked(CredentialCache.getCredentials).mockReset(); + ClustersClientMock.getLastVerifiedIdentity.mockReset(); }, ); @@ -524,6 +531,10 @@ describe('ClusterItemBase.getChildren — cached client connection failure handl const children = await item.getChildren(); expect(children.map(({ id }) => id)).toEqual(['cluster-1/diagnose', 'cluster-1/open-shell']); + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith(expect.any(String), { + modal: true, + detail: 'The database rejected the credentials. Choose Update credentials to continue.', + }); expect(item.hasRetryNode(children)).toBe(true); } finally { ClustersClientMock.getLatchReason.mockReset(); @@ -541,6 +552,26 @@ describe('ClusterItemBase.getChildren — cached client connection failure handl 'cluster-1/open-shell', 'cluster-1/retry', ]); + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith(expect.any(String), { + modal: true, + detail: 'The database rejected the credentials. Choose Retry to reload them.', + }); + } finally { + ClustersClientMock.getLatchReason.mockReset(); + } + }); + + it('explains how to reload a rejected Azure key', async (): Promise => { + ClustersClientMock.getLatchReason.mockReturnValue('credentialsRejected'); + ClustersClientMock.connectInteractive.mockRejectedValueOnce(new ConnectionUnavailableError('credentialsRejected')); + const item = new TestClusterItem({ ...makeCluster(), viewId: Views.AzureResourcesView }, null); + item.readReplacementKey = vi.fn(); + try { + await item.getChildren(); + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith(expect.any(String), { + modal: true, + detail: 'The database rejected the key. Choose Retry to read the key from Azure again.', + }); } finally { ClustersClientMock.getLatchReason.mockReset(); } diff --git a/src/tree/documentdb/ClusterItemBase.ts b/src/tree/documentdb/ClusterItemBase.ts index fb8f65f1b..686511c3f 100644 --- a/src/tree/documentdb/ClusterItemBase.ts +++ b/src/tree/documentdb/ClusterItemBase.ts @@ -355,6 +355,19 @@ export abstract class ClusterItemBase Date: Tue, 24 Nov 2026 11:18:26 +0000 Subject: [PATCH 28/29] chore: regenerate localization and format PR4 review fixes Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- l10n/bundle.l10n.json | 6 +++ .../retryAuthentication.test.ts | 39 ++++++++++--------- .../retryAuthentication.ts | 5 +-- src/commands/signInAgain/signInAgain.test.ts | 9 +---- .../auth/ManagedIdentityAuthHandler.test.ts | 2 +- .../auth/managedIdentityTokenProvider.ts | 7 +--- src/tree/documentdb/ClusterItemBase.test.ts | 8 +++- src/tree/documentdb/IndexesItem.ts | 14 ++++--- 8 files changed, 46 insertions(+), 44 deletions(-) diff --git a/l10n/bundle.l10n.json b/l10n/bundle.l10n.json index de81ca768..3d79e848e 100644 --- a/l10n/bundle.l10n.json +++ b/l10n/bundle.l10n.json @@ -2497,6 +2497,7 @@ "Resource not found.": "Resource not found.", "Resource: {0} ({1})": "Resource: {0} ({1})", "Restarting…": "Restarting…", + "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.": "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.", "Restore certificate verification and configure a trusted CA and matching server host name.": "Restore certificate verification and configure a trusted CA and matching server host name.", "Result": "Result", "Result: {0}": "Result: {0}", @@ -2929,6 +2930,7 @@ "The active Docker context is unavailable. Select or repair a valid context, then check again.": "The active Docker context is unavailable. Select or repair a valid context, then check again.", "The authentication database is {0}, rather than admin or $external. This may be intentional.": "The authentication database is {0}, rather than admin or $external. This may be intentional.", "The authentication database is neither admin nor $external. This may be intentional.": "The authentication database is neither admin nor $external. This may be intentional.", + "The Azure cloud or sign-in provider changed.": "The Azure cloud or sign-in provider changed.", "The Azure cloud selected for sign-in does not match the cluster cloud.": "The Azure cloud selected for sign-in does not match the cluster cloud.", "The Azure resource {0} was not found in subscription {1}. Check the link, and whether the resource still exists.": "The Azure resource {0} was not found in subscription {1}. Check the link, and whether the resource still exists.", "The Azure resource reports that in-region high availability is disabled.": "The Azure resource reports that in-region high availability is disabled.", @@ -3001,6 +3003,10 @@ "The custom cloud choice is not configured. Please configure the setting `{0}.{1}`.": "The custom cloud choice is not configured. Please configure the setting `{0}.{1}`.", "The database \"{0}\" already exists in the DocumentDB cluster \"{1}\".": "The database \"{0}\" already exists in the DocumentDB cluster \"{1}\".", "The database did not sort data in memory.\n\nResults came back in the right order naturally, either from the index or because no sort was requested.": "The database did not sort data in memory.\n\nResults came back in the right order naturally, either from the index or because no sort was requested.", + "The database rejected the credentials. Choose Retry sign-in to continue.": "The database rejected the credentials. Choose Retry sign-in to continue.", + "The database rejected the credentials. Choose Retry to reload them.": "The database rejected the credentials. Choose Retry to reload them.", + "The database rejected the credentials. Choose Update credentials to continue.": "The database rejected the credentials. Choose Update credentials to continue.", + "The database rejected the key. Choose Retry to read the key from Azure again.": "The database rejected the key. Choose Retry to read the key from Azure again.", "The database retrieved your documents through a multikey index.\n\nAn index on an array field was used. Each array element creates a separate index entry, so the database examined more index keys than documents. This is expected for array indexes but adds overhead.": "The database retrieved your documents through a multikey index.\n\nAn index on an array field was used. Each array element creates a separate index entry, so the database examined more index keys than documents. This is expected for array indexes but adds overhead.", "The database retrieved your documents using a collection scan.\n\nEvery document was read sequentially because no supporting index was available. This is the slowest retrieval method for filtered queries.": "The database retrieved your documents using a collection scan.\n\nEvery document was read sequentially because no supporting index was available. This is the slowest retrieval method for filtered queries.", "The database retrieved your documents using a covered query.\n\nAll the data your query needs was already stored in the index. The database did not need to load the actual documents, making this the most efficient retrieval method.": "The database retrieved your documents using a covered query.\n\nAll the data your query needs was already stored in the index. The database did not need to load the actual documents, making this the most efficient retrieval method.", diff --git a/src/commands/retryAuthentication/retryAuthentication.test.ts b/src/commands/retryAuthentication/retryAuthentication.test.ts index bee8b911e..f72d270ba 100644 --- a/src/commands/retryAuthentication/retryAuthentication.test.ts +++ b/src/commands/retryAuthentication/retryAuthentication.test.ts @@ -12,7 +12,7 @@ import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; import { ClustersClient } from '../../documentdb/ClustersClient'; import { CredentialCache } from '../../documentdb/CredentialCache'; import { ext } from '../../extensionVariables'; -import { clusterId as quickStartClusterId, DEFAULT_ALIAS } from '../../services/localQuickStart/quickStartTypes'; +import { DEFAULT_ALIAS, clusterId as quickStartClusterId } from '../../services/localQuickStart/quickStartTypes'; import { type ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; import { retryAuthentication } from './retryAuthentication'; @@ -215,25 +215,28 @@ describe('retryAuthentication', () => { }, ); - it.each([true, false])('reloads Quick Start with an empty cache only if the rejection can be cleared (%s)', async (cleared): Promise => { - const clusterId = quickStartClusterId(DEFAULT_ALIAS); - const node = { id: 'connectionsView/localQuickStart/instance', cluster: { clusterId }, getTreeItem }; - vi.mocked(ClustersClient.getEpoch).mockReturnValueOnce(7); - vi.mocked(ClustersClient.getLatchReason).mockReturnValueOnce('credentialsRejected'); - vi.mocked(CredentialCache.getCredentials).mockReturnValueOnce(undefined); - vi.mocked(ClustersClient.clearCredentialRejection).mockReturnValueOnce(cleared); + it.each([true, false])( + 'reloads Quick Start with an empty cache only if the rejection can be cleared (%s)', + async (cleared): Promise => { + const clusterId = quickStartClusterId(DEFAULT_ALIAS); + const node = { id: 'connectionsView/localQuickStart/instance', cluster: { clusterId }, getTreeItem }; + vi.mocked(ClustersClient.getEpoch).mockReturnValueOnce(7); + vi.mocked(ClustersClient.getLatchReason).mockReturnValueOnce('credentialsRejected'); + vi.mocked(CredentialCache.getCredentials).mockReturnValueOnce(undefined); + vi.mocked(ClustersClient.clearCredentialRejection).mockReturnValueOnce(cleared); - await retryAuthentication(actionContext as never, node); + await retryAuthentication(actionContext as never, node); - expect(ClustersClient.clearCredentialRejection).toHaveBeenCalledExactlyOnceWith(clusterId, 7); - if (cleared) { - expect(CredentialCache.deleteCredentials).toHaveBeenCalledExactlyOnceWith(clusterId); - expect(ext.connectionsBranchDataProvider.refresh).toHaveBeenCalledExactlyOnceWith(node); - } else { - expect(CredentialCache.deleteCredentials).not.toHaveBeenCalled(); - expect(ext.connectionsBranchDataProvider.refresh).not.toHaveBeenCalled(); - } - }); + expect(ClustersClient.clearCredentialRejection).toHaveBeenCalledExactlyOnceWith(clusterId, 7); + if (cleared) { + expect(CredentialCache.deleteCredentials).toHaveBeenCalledExactlyOnceWith(clusterId); + expect(ext.connectionsBranchDataProvider.refresh).toHaveBeenCalledExactlyOnceWith(node); + } else { + expect(CredentialCache.deleteCredentials).not.toHaveBeenCalled(); + expect(ext.connectionsBranchDataProvider.refresh).not.toHaveBeenCalled(); + } + }, + ); it('abandons a successful key read if the epoch changed', async (): Promise => { const node = ruNode(); diff --git a/src/commands/retryAuthentication/retryAuthentication.ts b/src/commands/retryAuthentication/retryAuthentication.ts index 2c1a44bc4..db35cc0db 100644 --- a/src/commands/retryAuthentication/retryAuthentication.ts +++ b/src/commands/retryAuthentication/retryAuthentication.ts @@ -96,10 +96,7 @@ export async function retryAuthentication(context: IActionContext, node: Retryab (view === Views.DiscoveryView || view === Views.AzureResourcesView) && credentials !== undefined && (credentials.authMechanism ?? AuthMethodId.NativeAuth) === AuthMethodId.NativeAuth; - if ( - (!quickStart && !nativeDiscovery) || - !ClustersClient.clearCredentialRejection(clusterId, epoch) - ) { + if ((!quickStart && !nativeDiscovery) || !ClustersClient.clearCredentialRejection(clusterId, epoch)) { return; } CredentialCache.deleteCredentials(clusterId); diff --git a/src/commands/signInAgain/signInAgain.test.ts b/src/commands/signInAgain/signInAgain.test.ts index a8f814de5..3b1170c6c 100644 --- a/src/commands/signInAgain/signInAgain.test.ts +++ b/src/commands/signInAgain/signInAgain.test.ts @@ -57,11 +57,7 @@ describe('signInAgain', () => { beforeEach(() => { vi.clearAllMocks(); mocks.configureAuth.mockImplementation( - async ( - _timings: undefined, - _trace: undefined, - acquire: typeof getEntraSession, - ): Promise => { + async (_timings: undefined, _trace: undefined, acquire: typeof getEntraSession): Promise => { const session = await acquire({ mode: 'forceNew', providerId: pin.providerId, @@ -149,8 +145,7 @@ describe('signInAgain', () => { 'The Azure cloud or sign-in provider changed.', { modal: true, - detail: - '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.', + detail: '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.', }, ); }); diff --git a/src/documentdb/auth/ManagedIdentityAuthHandler.test.ts b/src/documentdb/auth/ManagedIdentityAuthHandler.test.ts index 89f0ed29c..149f145db 100644 --- a/src/documentdb/auth/ManagedIdentityAuthHandler.test.ts +++ b/src/documentdb/auth/ManagedIdentityAuthHandler.test.ts @@ -16,7 +16,6 @@ import { buildAuthConnectionTarget } from './authConnectionTarget'; import { AuthMethodId } from './AuthMethod'; import * as tokenResources from './documentdbTokenResource'; import { TokenCallbackError } from './entraErrors/entraCallbackErrors'; -import { ManagedIdentityGuidanceError } from './managedIdentityErrors'; import { EntraErrorExplainer } from './entraErrors/EntraErrorExplainer'; import { getRecentEntraTokenFailure, @@ -24,6 +23,7 @@ import { resetEntraTokenFailuresForTests, } from './entraErrors/entraTokenFailures'; import { ManagedIdentityAuthHandler } from './ManagedIdentityAuthHandler'; +import { ManagedIdentityGuidanceError } from './managedIdentityErrors'; import { EntraDestinationRejectedError } from './oidcAllowedHosts'; import { expiresInSecondsFromTimestamp } from './tokenExpiry'; diff --git a/src/documentdb/auth/managedIdentityTokenProvider.ts b/src/documentdb/auth/managedIdentityTokenProvider.ts index d50f90771..f06b2b9cc 100644 --- a/src/documentdb/auth/managedIdentityTokenProvider.ts +++ b/src/documentdb/auth/managedIdentityTokenProvider.ts @@ -55,12 +55,7 @@ export async function getManagedIdentityAccessToken( ); } catch (error) { const reason = classifyManagedIdentityError(error); - traceAuthFlow( - 'managedIdentity.tokenFailure', - { reason }, - tokenCorrelationId, - traceContext, - ); + traceAuthFlow('managedIdentity.tokenFailure', { reason }, tokenCorrelationId, traceContext); reportManagedIdentityTokenFailure(error, clientId, tokenCorrelationId, traceContext); const message = describeManagedIdentityError(error, clientId); throw reason === 'other' ? new Error(message) : new ManagedIdentityGuidanceError(message); diff --git a/src/tree/documentdb/ClusterItemBase.test.ts b/src/tree/documentdb/ClusterItemBase.test.ts index d05767356..104160095 100644 --- a/src/tree/documentdb/ClusterItemBase.test.ts +++ b/src/tree/documentdb/ClusterItemBase.test.ts @@ -543,7 +543,9 @@ describe('ClusterItemBase.getChildren — cached client connection failure handl it('keeps Retry for a synthetic Connections view item without a credential editor', async (): Promise => { ClustersClientMock.getLatchReason.mockReturnValue('credentialsRejected'); - ClustersClientMock.connectInteractive.mockRejectedValueOnce(new ConnectionUnavailableError('credentialsRejected')); + ClustersClientMock.connectInteractive.mockRejectedValueOnce( + new ConnectionUnavailableError('credentialsRejected'), + ); const item = new TestClusterItem({ ...makeCluster(), viewId: Views.ConnectionsView }, null); item.contextValue = 'treeItem_quickStartInstance'; try { @@ -563,7 +565,9 @@ describe('ClusterItemBase.getChildren — cached client connection failure handl it('explains how to reload a rejected Azure key', async (): Promise => { ClustersClientMock.getLatchReason.mockReturnValue('credentialsRejected'); - ClustersClientMock.connectInteractive.mockRejectedValueOnce(new ConnectionUnavailableError('credentialsRejected')); + ClustersClientMock.connectInteractive.mockRejectedValueOnce( + new ConnectionUnavailableError('credentialsRejected'), + ); const item = new TestClusterItem({ ...makeCluster(), viewId: Views.AzureResourcesView }, null); item.readReplacementKey = vi.fn(); try { diff --git a/src/tree/documentdb/IndexesItem.ts b/src/tree/documentdb/IndexesItem.ts index 4c1d52ff7..a75cd4f89 100644 --- a/src/tree/documentdb/IndexesItem.ts +++ b/src/tree/documentdb/IndexesItem.ts @@ -115,12 +115,14 @@ export class IndexesItem implements TreeElement, TreeElementWithExperience, Tree const client: ClustersClient = options ? await ClustersClient.getClient(this.cluster.clusterId, undefined, undefined, 'treeChildren', options) : await ClustersClient.getClient(this.cluster.clusterId, undefined, undefined, 'treeChildren'); - const indexes = await client.listIndexes(this.databaseInfo.name, this.collectionInfo.name).catch((error: unknown) => { - if (!options?.background) { - ClustersClient.reportFailure(client.binding, error); - } - throw error; - }); + const indexes = await client + .listIndexes(this.databaseInfo.name, this.collectionInfo.name) + .catch((error: unknown) => { + if (!options?.background) { + ClustersClient.reportFailure(client.binding, error); + } + throw error; + }); // Try to get search indexes, but silently fail if not supported by the platform try { From b9099d855692b036ab51a180b11c49b3c99ae6a9 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Tue, 24 Nov 2026 11:18:26 +0000 Subject: [PATCH 29/29] docs: record PR4 inline review dispositions and verification Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../01-pr4-connection-recovery-review.md | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr4-connection-recovery-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr4-connection-recovery-review.md index 1296406c2..f4ba08728 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr4-connection-recovery-review.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr4-connection-recovery-review.md @@ -42,6 +42,23 @@ An obsolete recovery still cannot evict newer state or clear its latch. All 62 f tests passed across six suites. Reconciling an already in-flight recovery save that lands after teardown stays in WI-7, with F2. +## Copilot review follow-up + +Claude Opus 5.5 validated the nine inline findings against `ca841a7c8`. The confirmed medium +findings are addressed in dedicated commits. The operator approved reporting child expansion +failures in this PR without adding child recovery actions or replaying the request. + +| Finding | Disposition | +| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| [R1](https://github.com/microsoft/vscode-documentdb/pull/1117#discussion_r4677891992) | `27345af20` explains how to restore the pinned Azure cloud or provider before retrying sign-in. | +| [R2](https://github.com/microsoft/vscode-documentdb/pull/1117#discussion_r4677892084) | Preserve the approved F1 scope: no new Native/RU or first-startup latch policy. | +| [R3](https://github.com/microsoft/vscode-documentdb/pull/1117#discussion_r4677892154) | Keep retrying the silent lookup on a later foreground request so signing back in through VS Code Accounts can restore the session. Track in [#1119](https://github.com/microsoft/vscode-documentdb/issues/1119#issuecomment-7127895057). | +| [R4](https://github.com/microsoft/vscode-documentdb/pull/1117#discussion_r4677892272) | `f3407187a` preserves localized Managed Identity guidance in the typed callback error without copying unrecognized SDK text into the message. | +| [R5](https://github.com/microsoft/vscode-documentdb/pull/1117#discussion_r4677892358), [R7](https://github.com/microsoft/vscode-documentdb/pull/1117#discussion_r4677892494) | Defer the two low-severity telemetry gaps to [#1123](https://github.com/microsoft/vscode-documentdb/issues/1123). | +| [R6](https://github.com/microsoft/vscode-documentdb/pull/1117#discussion_r4677892428) | `195243c52` lets Quick Start Retry clear only its current rejection and reload its service-owned credentials. | +| [R8](https://github.com/microsoft/vscode-documentdb/pull/1117#discussion_r4677892557) | `228be9f90` explains the rejection and points to the appropriate existing tree action. | +| [R9](https://github.com/microsoft/vscode-documentdb/pull/1117#discussion_r4677892633) | `b1b446e6d` reports foreground database and index listing failures against the binding that ran them and rethrows the original error. Optional navigation to the owning cluster is tracked in [#1124](https://github.com/microsoft/vscode-documentdb/issues/1124). | + ## Handoff verification OP-3 passed on the older CI VSIX. The current review proposals do not change the tested @@ -58,3 +75,8 @@ enum-to-string lint error and a storage fixture type mismatch; both were fixed without changing recovery behavior or weakening any assertions. Full CI also passed on code head `d422d065b`. The operator confirmation is a documentation-only follow-up; it does not change the tested build or require repeating OP-3. + +After the Copilot fixes, local Case 2 passed again: localization generation and check, +formatting, lint, build, strict workspace test type-check, the full runtime suite +(432 files; 9,805 tests passed, one skipped), and VSIX packaging. The earlier OP-3 and +worker smoke results stand; no repeat live test was required for these fixes.