diff --git a/docs/ai-and-plans/features/connection-lifecycle/README.md b/docs/ai-and-plans/features/connection-lifecycle/README.md index 87b66ed56..25a97a0d5 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). @@ -49,6 +51,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. 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. @@ -79,6 +84,8 @@ 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. +- 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 dcbef7f08..9e5712c39 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/decisions.md +++ b/docs/ai-and-plans/features/connection-lifecycle/decisions.md @@ -10,21 +10,23 @@ 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 | — | +| # | 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, > and record reversals as a new entry plus a status change above. Heading text is frozen once @@ -399,3 +401,26 @@ 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. + +## 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 9db2e2406..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 @@ -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 @@ -414,6 +421,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 @@ -1171,8 +1180,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 | @@ -1204,16 +1213,19 @@ 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); + - **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**. + - 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` 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 +1284,86 @@ 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. +- **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). +- **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. +- **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. +- **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. +- **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 + 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. +- **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. + 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. +- **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). 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. + --- ## 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. 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..f4ba08728 --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr4-connection-recovery-review.md @@ -0,0 +1,82 @@ +--- +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. + +## 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 +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. 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. 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. diff --git a/l10n/bundle.l10n.json b/l10n/bundle.l10n.json index 91360cd83..3d79e848e 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}", @@ -2495,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}", @@ -2508,6 +2511,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", @@ -2719,10 +2723,12 @@ "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 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}.", @@ -2924,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.", @@ -2971,6 +2978,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", @@ -2995,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/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 452852242..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", @@ -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/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 e0c080d82..f72d270ba 100644 --- a/src/commands/retryAuthentication/retryAuthentication.test.ts +++ b/src/commands/retryAuthentication/retryAuthentication.test.ts @@ -5,7 +5,15 @@ 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 { ext } from '../../extensionVariables'; +import { DEFAULT_ALIAS, clusterId as quickStartClusterId } from '../../services/localQuickStart/quickStartTypes'; +import { type ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; import { retryAuthentication } from './retryAuthentication'; vi.mock('../../extensionVariables', () => ({ @@ -30,17 +38,29 @@ vi.mock('../../extensionVariables', () => ({ })); vi.mock('../../documentdb/ClustersClient', () => ({ + addEstablishedConnectionContext: vi.fn(), ClustersClient: { + getEpoch: vi.fn(() => 0), + getLatchReason: vi.fn(), + hasReusableClient: 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 +144,156 @@ 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.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: [] }); + 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('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', + 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..db35cc0db 100644 --- a/src/commands/retryAuthentication/retryAuthentication.ts +++ b/src/commands/retryAuthentication/retryAuthentication.ts @@ -3,11 +3,17 @@ * 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 { isQuickStartClusterId } from '../../services/localQuickStart/quickStartTypes'; +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'; @@ -19,7 +25,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 +75,99 @@ 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); + const quickStart = view === Views.ConnectionsView && isQuickStartClusterId(clusterId); + const nativeDiscovery = + (view === Views.DiscoveryView || view === Views.AzureResourcesView) && + credentials !== undefined && + (credentials.authMechanism ?? AuthMethodId.NativeAuth) === AuthMethodId.NativeAuth; + if ((!quickStart && !nativeDiscovery) || !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') && + !ClustersClient.hasReusableClient(clusterId) + ) { + 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/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 new file mode 100644 index 000000000..2685115f3 --- /dev/null +++ b/src/commands/showConnectionStats/showConnectionStats.ts @@ -0,0 +1,60 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { 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.', + ); + 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 (client?.authMethod === AuthMethodId.MicrosoftEntraID) { + ext.outputChannel.appendLog( + ` lastEntraTokenExpiresAt=${formatEntraExpiry(client.lastEntraTokenExpiresAt, now)}`, + ); + } + 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/commands/signInAgain/signInAgain.test.ts b/src/commands/signInAgain/signInAgain.test.ts new file mode 100644 index 000000000..3b1170c6c --- /dev/null +++ b/src/commands/signInAgain/signInAgain.test.ts @@ -0,0 +1,152 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { 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 = { + kind: 'entra', + providerId: 'microsoft', + accountId: 'pinned', + accountLabel: 'Pinned', + tenantId: 'tenant', +} as const; +const clusterId = 'cluster'; +const mocks = vi.hoisted(() => ({ configureAuth: vi.fn() })); + +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 { + return await mocks.configureAuth(_timings, _trace, acquire); + } + }, +})); +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(); + 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, + '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); + }); + + 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 new file mode 100644 index 000000000..ca454fd94 --- /dev/null +++ b/src/commands/signInAgain/signInAgain.ts @@ -0,0 +1,142 @@ +/*--------------------------------------------------------------------------------------------- + * 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, + EntraSignInRequiredError, +} from '../../documentdb/auth/entraErrors/entraCallbackErrors'; +import { getEntraSession } from '../../documentdb/auth/entraSession'; +import { MicrosoftEntraIDAuthHandler } from '../../documentdb/auth/MicrosoftEntraIDAuthHandler'; +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 || + (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; + 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'), + 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..e195ddb64 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( @@ -87,6 +93,9 @@ export class ExecuteStep extends AzureWizardExecuteStep { await ConnectionStorageService.save(resourceType, connection, true); context.connectionStringSaved = true; + if (context.isRecoveryCurrent?.() === false) { + return; + } if (clearedEntraMethod) { void window.showInformationMessage( 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..db65fdedc 100644 --- a/src/commands/updateConnectionString/updateConnectionString.test.ts +++ b/src/commands/updateConnectionString/updateConnectionString.test.ts @@ -85,7 +85,15 @@ 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() }, @@ -282,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 cfb7f9d25..39e22d8c5 100644 --- a/src/commands/updateConnectionString/updateConnectionString.ts +++ b/src/commands/updateConnectionString/updateConnectionString.ts @@ -37,6 +37,11 @@ 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 recovering = recoveringRejectedDestination || recoveringRejectedCredentials; + const isRecoveryCurrent = recovering ? (): boolean => ClustersClient.getEpoch(clusterId) === epoch : undefined; // Extract the connection string but hide the username and password @@ -46,6 +51,9 @@ export async function updateConnectionString(context: IActionContext, node: Docu const resourceType = resolveStorageZone(node.cluster); const connection = await ConnectionStorageService.get(node.storageId, resourceType); + if (isRecoveryCurrent?.() === false) { + return; + } const connectionString = connection?.secrets?.connectionString || ''; context.valuesToMask.push(connectionString); @@ -63,6 +71,7 @@ export async function updateConnectionString(context: IActionContext, node: Docu storageZone: resolveStorageZone(node.cluster), storageId: node.storageId, connectionStringSaved: false, + isRecoveryCurrent, }; const wizard = new AzureWizard(wizardContext, { @@ -72,11 +81,25 @@ export async function updateConnectionString(context: IActionContext, node: Docu }); await wizard.prompt(); + if (isRecoveryCurrent?.() === false) { + return; + } await wizard.execute(); + if (isRecoveryCurrent?.() === false) { + return; + } - if (recoveringRejectedDestination && wizardContext.connectionStringSaved) { - await ClustersClient.deleteClient(node.cluster.clusterId); - CredentialCache.deleteCredentials(node.cluster.clusterId); + if (recovering && wizardContext.connectionStringSaved) { + const closing = ClustersClient.deleteClient(clusterId); + epoch = ClustersClient.getEpoch(clusterId); + await closing; + if (isRecoveryCurrent?.() === false) { + 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..d37c7ac03 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..b82ec629c 100644 --- a/src/commands/updateCredentials/updateCredentials.test.ts +++ b/src/commands/updateCredentials/updateCredentials.test.ts @@ -13,11 +13,15 @@ import { API } from '../../DocumentDBExperiences'; import type * as storageModule from '../../services/connectionStorageService'; import { ItemType } from '../../services/connectionStorageService'; import { type DocumentDBClusterItem } from '../../tree/connections-view/DocumentDBClusterItem'; +import { ExecuteStep } from './ExecuteStep'; import { updateCredentials } from './updateCredentials'; import { type UpdateCredentialsWizardContext } from './UpdateCredentialsWizardContext'; const capturedContexts: UpdateCredentialsWizardContext[] = []; +const mockExecute = vi.fn<(context: UpdateCredentialsWizardContext) => 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,26 +30,31 @@ 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 => mockGetEpoch(), + getLatchReason: (): undefined => undefined, }, })); vi.mock('../playground/executePlaygroundCode', () => ({ @@ -55,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) } }, })); @@ -62,6 +72,7 @@ vi.mock('../../extensionVariables', () => ({ beforeEach(() => { CredentialCache.deleteCredentials('stable-cluster-id'); vi.clearAllMocks(); + mockGetEpoch.mockReturnValue(0); mockGetRegisteredShellTerminals.mockReturnValue([]); capturedContexts.length = 0; }); @@ -208,6 +219,30 @@ describe('updateCredentials post-wizard updates', () => { ); }); + it('updates runtime credentials when the epoch changes during an ordinary save', async (): Promise => { + let storedConnection: storageModule.ConnectionItem = 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 301e09c7d..8e5e6fcfa 100644 --- a/src/commands/updateCredentials/updateCredentials.ts +++ b/src/commands/updateCredentials/updateCredentials.ts @@ -57,6 +57,12 @@ 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 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); @@ -72,6 +78,9 @@ export async function updateCredentials(context: IActionContext, node: DocumentD const resourceType = resolveStorageZone(node.cluster); const storedItem = await ConnectionStorageService.get(node.storageId, resourceType); + if (isRecoveryCurrent?.() === false) { + 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 +124,7 @@ export async function updateCredentials(context: IActionContext, node: DocumentD storageId: node.storageId, isErrorState, reconnectAfterError: false, + isRecoveryCurrent, }; const wizard = new AzureWizard(wizardContext, { @@ -137,15 +147,35 @@ export async function updateCredentials(context: IActionContext, node: DocumentD }); await wizard.prompt(); + if (isRecoveryCurrent?.() === false) { + return; + } await wizard.execute(); - - await ClustersClient.deleteClient(node.cluster.clusterId); + if (isRecoveryCurrent?.() === false || (recoveringRejection && !wizardContext.credentialsSaved)) { + return; + } const updatedStoredItem = await ConnectionStorageService.get(node.storageId, resourceType); + if (isRecoveryCurrent?.() === false) { + return; + } const updatedConnection = updatedStoredItem && isConnection(updatedStoredItem) ? updatedStoredItem : undefined; + const closing = ClustersClient.deleteClient(clusterId); + epoch = ClustersClient.getEpoch(clusterId); + await closing; + // Do not publish cached credentials over a lifecycle change during close. + if (ClustersClient.getEpoch(clusterId) !== epoch) { + 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 +192,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 1c5f97c3f..3fe3353a3 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'; @@ -233,6 +239,99 @@ 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, + lastEntraTokenExpiresAt: undefined, + }); + 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('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>(); + 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( @@ -320,7 +419,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 +487,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 +538,167 @@ 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 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); + 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('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'); + 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..bba86d893 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'; @@ -44,12 +45,14 @@ 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 { AuthMethodId } from './auth/AuthMethod'; +import { type AuthHandlerResponse, type VerifiedEntraIdentity } from './auth/AuthHandler'; +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'; import { ConnectionUnavailableError, type ConnectionUnavailableReason } from './ConnectionUnavailableError'; import { CredentialCache, type CachedClusterCredentials } from './CredentialCache'; @@ -88,6 +91,21 @@ 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 lastEntraTokenExpiresAt?: string; + }; + readonly pending?: { readonly startupId: string; readonly superseded: boolean }; + readonly held?: ConnectionUnavailableReason; + readonly lastFailedStartupId?: string; +} + export type VerifiedIdentity = VerifiedEntraIdentity | Exclude; export interface CollectionItemModel { @@ -278,6 +296,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; @@ -307,6 +333,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,7 +351,9 @@ export class ClustersClient { private _createdAt: number; private _mongoClient: MongoClient; 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; @@ -342,6 +381,38 @@ 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, + lastEntraTokenExpiresAt: client._lastEntraTokenExpiresAt, + }, + 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. @@ -411,6 +482,7 @@ export class ClustersClient { epoch: number, allowInteractive: boolean, expectedFingerprint?: string, + recoveredAuth?: AuthHandlerResponse, ): Promise { this.connectionCorrelationId = startupId; let originalFailure: { error: unknown } | undefined; @@ -444,7 +516,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; @@ -499,7 +571,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; @@ -532,11 +609,13 @@ export class ClustersClient { // Configure auth and get connection options this.advanceClientStartup(startup, 'stage02ConfiguringAuth'); - const { connectionString, options, verifiedIdentity } = 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); @@ -579,6 +658,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, @@ -588,6 +670,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); @@ -638,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; @@ -736,6 +838,55 @@ 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, @@ -758,7 +909,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 +924,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 +941,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) { @@ -806,6 +960,7 @@ export class ClustersClient { allowInteractive: boolean, background: boolean, expectedFingerprint?: string, + recoveredAuth?: AuthHandlerResponse, ): PendingStartup { const existing = ClustersClient._pendingStartups.get(clusterId); if (existing?.epoch === epoch) { @@ -817,7 +972,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 && @@ -830,7 +986,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), + ClustersClient.establishClient( + clusterId, + epoch, + id, + trigger, + allowInteractive, + expectedFingerprint, + recoveredAuth, + ), ); const pending = { id, epoch, promise }; ClustersClient._pendingStartups.set(clusterId, pending); @@ -850,13 +1014,27 @@ 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.')); + } } 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(() => { @@ -873,6 +1051,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 +1059,62 @@ 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; + } + + 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; + 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. * @@ -907,7 +1138,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 5141727e1..23a91d37a 100644 --- a/src/documentdb/ClustersExtension.ts +++ b/src/documentdb/ClustersExtension.ts @@ -86,7 +86,9 @@ 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'; import { updateCredentials } from '../commands/updateCredentials/updateCredentials'; import { isVCoreAndRURolloutEnabled } from '../extension'; @@ -623,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: @@ -1008,6 +1014,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/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/ManagedIdentityAuthHandler.test.ts b/src/documentdb/auth/ManagedIdentityAuthHandler.test.ts index e5a8bb7c4..149f145db 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, @@ -22,6 +23,7 @@ import { resetEntraTokenFailuresForTests, } from './entraErrors/entraTokenFailures'; import { ManagedIdentityAuthHandler } from './ManagedIdentityAuthHandler'; +import { ManagedIdentityGuidanceError } from './managedIdentityErrors'; import { EntraDestinationRejectedError } from './oidcAllowedHosts'; import { expiresInSecondsFromTimestamp } from './tokenExpiry'; @@ -341,16 +343,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 +360,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({ @@ -378,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.', @@ -416,11 +430,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 +615,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 +674,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.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/MicrosoftEntraIDAuthHandler.ts b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts index cda5b17d7..671f5a530 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'; @@ -78,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; @@ -139,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 { @@ -176,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) { @@ -227,6 +229,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 +266,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 +274,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/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..9bbf609ba 100644 --- a/src/documentdb/auth/entraErrors/entraCallbackErrors.ts +++ b/src/documentdb/auth/entraErrors/entraCallbackErrors.ts @@ -4,7 +4,8 @@ *--------------------------------------------------------------------------------------------*/ import * as l10n from '@vscode/l10n'; -import { AuthMethodId } from '../AuthMethod'; +import { AuthMethodId } from '../AuthMethodId'; +import { ManagedIdentityGuidanceError } from '../managedIdentityErrors'; export class EntraSignInRequiredError extends Error { constructor(public readonly reason: 'noSession' | 'providerChanged') { @@ -20,11 +21,18 @@ export class EntraIdentityMismatchError extends Error { } } -export class TokenCallbackError extends Error { - public readonly authMethod = AuthMethodId.MicrosoftEntraID; +type TokenCallbackAuthMethod = AuthMethodId.MicrosoftEntraID | AuthMethodId.ManagedIdentity; - constructor(cause: unknown) { - super(l10n.t('Failed to obtain a Microsoft Entra ID token.'), { cause }); +export class TokenCallbackError extends Error { + constructor( + cause: unknown, + public readonly authMethod: TokenCallbackAuthMethod = AuthMethodId.MicrosoftEntraID, + ) { + 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..f06b2b9cc 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,11 @@ export async function getManagedIdentityAccessToken( traceContext, ); } catch (error) { - traceAuthFlow( - 'managedIdentity.tokenFailure', - { reason: classifyManagedIdentityError(error) }, - tokenCorrelationId, - traceContext, - ); + const reason = classifyManagedIdentityError(error); + traceAuthFlow('managedIdentity.tokenFailure', { 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/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']; 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/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..c51df8b30 --- /dev/null +++ b/src/documentdb/connectionFailures.ts @@ -0,0 +1,164 @@ +/*--------------------------------------------------------------------------------------------- + * 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' }; + case 'credentialsRejected': + case 'signInRequired': + return { kind: candidate.reason, generation: 'none', note: 'alreadyUnavailable' }; + 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; +} 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; + } +} 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); 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/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/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..74027545f 100644 --- a/src/tree/connections-view/DocumentDBClusterItem.test.ts +++ b/src/tree/connections-view/DocumentDBClusterItem.test.ts @@ -88,10 +88,22 @@ 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 +327,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 ({ 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/connections-view/LocalQuickStart/LocalQuickStartItem.ts b/src/tree/connections-view/LocalQuickStart/LocalQuickStartItem.ts index 9adb985a8..df481e783 100644 --- a/src/tree/connections-view/LocalQuickStart/LocalQuickStartItem.ts +++ b/src/tree/connections-view/LocalQuickStart/LocalQuickStartItem.ts @@ -382,7 +382,10 @@ class QuickStartClusterItem 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/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 01e8663a4..104160095 100644 --- a/src/tree/documentdb/ClusterItemBase.test.ts +++ b/src/tree/documentdb/ClusterItemBase.test.ts @@ -11,9 +11,13 @@ import { type IActionContext, } from '@microsoft/vscode-azext-utils'; import * as vscode from 'vscode'; +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'; 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'; @@ -67,11 +71,22 @@ 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 +451,148 @@ describe('ClusterItemBase.getChildren — cached client connection failure handl ); }); + it.each(['signInRequired', 'credentialsRejected'] as const)( + '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); + } + ClustersClientMock.connectInteractive.mockRejectedValueOnce(new ConnectionUnavailableError(reason)); + vi.mocked(CredentialCache.getCredentials).mockReturnValue({ + clusterId: 'cluster-1', + connectionString: 'mongodb://example.test', + authMechanism: AuthMethodId.MicrosoftEntraID, + }); + ClustersClientMock.getLastVerifiedIdentity.mockReturnValue({ + 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(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(); + }, + ); + + 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(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(); + } + }); + + 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', + ]); + 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(); + } + }); + + 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..686511c3f 100644 --- a/src/tree/documentdb/ClusterItemBase.ts +++ b/src/tree/documentdb/ClusterItemBase.ts @@ -4,25 +4,31 @@ *--------------------------------------------------------------------------------------------*/ import { - UserCancelledError, callWithTelemetryAndErrorHandling, createContextValue, createGenericElement, + UserCancelledError, type IActionContext, } from '@microsoft/vscode-azext-utils'; 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 { Views } from '../../documentdb/Views'; 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'; @@ -32,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'; @@ -103,6 +109,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 +262,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,24 +306,104 @@ 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 + ); + } + + private hasStoredCredentialEditor(): boolean { + return ( + this.cluster.viewId === String(Views.ConnectionsView) && + this.contextValue.split(';').includes(CLUSTER_ITEM_CONTEXT_VALUE) + ); + } + + private describeCredentialRejection(): string { + if (this.canSignInAgain()) { + return vscode.l10n.t('The database rejected the credentials. Choose Retry sign-in to continue.'); + } + if (this.readReplacementKey) { + return vscode.l10n.t('The database rejected the key. Choose Retry to read the key from Azure again.'); + } + if (this.hasStoredCredentialEditor()) { + return vscode.l10n.t('The database rejected the credentials. Choose Update credentials to continue.'); + } + return vscode.l10n.t('The database rejected the credentials. Choose Retry to reload them.'); + } + /** * Builds the FAILURE-TYPE error-recovery nodes owned by the element layer. * - * Always includes the canonical "retry" node (see {@link createRetryNode}), a diagnosis - * action that opens diagnostics without connecting, and an "open shell" node. `hasRetryNode` - * and the provider detect the error state via the retry node. The shell is offered for every + * Includes diagnosis and "open shell", plus any applicable Retry action. `hasRetryNode` + * lets the provider detect the error state even without Retry. The shell is offered for every * failure, including sign-in failures, so experts can investigate with the shell's own * connection and error output. View-specific recovery actions (e.g. "update credentials") are * added separately by the provider via `errorRecoveryActions`. * * Error-recovery nodes in this tree are produced by two layers: - * - The ELEMENT layer (this class) owns FAILURE-TYPE nodes: "retry", "diagnose" and + * - The ELEMENT layer (this class) owns FAILURE-TYPE nodes: "sign in again" or "retry", "diagnose" and * "open shell", for any failure. * - The PROVIDER layer (a BranchDataProvider) owns VIEW-SPECIFIC nodes (e.g. "update * credentials") via `errorRecoveryActions`, gated by the failing element's contextValue. */ private createErrorRecoveryChildren(): TreeElement[] { + const needsSignIn = + (this.lastConnectionFailureKind === 'signInRequired' || + this.lastConnectionFailureKind === 'credentialsRejected') && + this.canSignInAgain(); + const rejectedStoredCredentials = + this.hasStoredCredentialEditor() && + ClustersClient.getLatchReason(this.cluster.clusterId) === 'credentialsRejected'; return [ + ...(needsSignIn + ? [ + createGenericElementWithContext({ + contextValue: 'error', + id: `${this.id}/sign-in-again`, + label: vscode.l10n.t('Retry sign-in'), + iconPath: new vscode.ThemeIcon('sign-in'), + commandId: 'vscode-documentdb.command.signInAgain', + commandArgs: [this], + }), + ] + : []), createGenericElementWithContext({ contextValue: 'error', id: `${this.id}/diagnose`, @@ -319,10 +420,99 @@ 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)); + let detail = error instanceof Error ? error.message : String(error); + if (failure.note === 'alreadyUnavailable') { + if (failure.kind === 'signInRequired') { + detail = vscode.l10n.t('Sign in again to continue using this connection.'); + } else if (failure.kind === 'credentialsRejected') { + detail = this.describeCredentialRejection(); + } + } + 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 +532,31 @@ export abstract class ClusterItemBase { - context.telemetry.properties.connectionResult = 'cancelled'; - context.telemetry.properties.source = 'treeExpansion'; - context.telemetry.properties.experience = this.experience.api; - throw error; - }); - - return []; + if (!ClustersClient.getLatchReason(clusterId)) { + await this.beforeCachedClientConnect(); } - - // 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; + acquisitionEpoch = ClustersClient.getEpoch(clusterId); + clustersClient = await this.getClientWithProgress(clusterId, (client) => { + reusedClient = client; }); - if (entraRejected) { - await telemetryPromise; - } - - 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(); + } catch (error) { + return this.renderExpansionFailure(error, 'cachedClientConnect', reusedClient, acquisitionEpoch); } } else { // Call to the abstract method to authenticate and connect to the cluster @@ -463,45 +584,14 @@ 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); + } + const binding = connectedClient.binding; + const isCurrentIdentity = (): boolean => + !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. @@ -510,6 +600,9 @@ export abstract class ClusterItemBase + child.id === `${this.id}/diagnose` && + isTreeElementWithContextValue(child) && + child.contextValue === 'error', + ) === true + ); } /** 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..a75cd4f89 100644 --- a/src/tree/documentdb/IndexesItem.ts +++ b/src/tree/documentdb/IndexesItem.ts @@ -115,7 +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); + 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 {