From e22a39b8d6b1fd690c90a48a77adb52567e1ef49 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 19 Nov 2026 10:20:14 +0000 Subject: [PATCH 001/380] wip: initial plan --- docs/ai-and-plans/README.md | 1 + .../features/connection-lifecycle/README.md | 74 +++ .../connection-lifecycle/decisions.md | 168 +++++++ .../iterations/01-implementation-plan.md | 475 ++++++++++++++++++ .../connection-lifecycle/research-findings.md | 269 ++++++++++ 5 files changed, 987 insertions(+) create mode 100644 docs/ai-and-plans/features/connection-lifecycle/README.md create mode 100644 docs/ai-and-plans/features/connection-lifecycle/decisions.md create mode 100644 docs/ai-and-plans/features/connection-lifecycle/iterations/01-implementation-plan.md create mode 100644 docs/ai-and-plans/features/connection-lifecycle/research-findings.md diff --git a/docs/ai-and-plans/README.md b/docs/ai-and-plans/README.md index 3f3395ebf..a691f8b48 100644 --- a/docs/ai-and-plans/README.md +++ b/docs/ai-and-plans/README.md @@ -52,6 +52,7 @@ treat `status: historical` or `status: superseded` as current. | [sovereign-clouds](./features/sovereign-clouds/README.md) | Entra sign-in in Azure Government and China: per-cloud token audience, Entra error classifier | implemented; sovereign checks pending | | [Diagnose connection](./features/connectivity-troubleshooter/README.md) | Read-only connection diagnosis, a server summary and readable Markdown diagnostics (#100) | implemented; handover blocked on operator | | [deep-links](./features/deep-links/README.md) | `vscode://` links: action routing, `/connect`, `/local`, `/connect/azure` for Azure portal links | active; iteration 3 implemented | +| [connection-lifecycle](./features/connection-lifecycle/README.md) | Connections that survive token expiry and idle drops; reconnect, disconnect and identity-bound tabs | planned (#1102) | Everything else is a single file at this root, such as: diff --git a/docs/ai-and-plans/features/connection-lifecycle/README.md b/docs/ai-and-plans/features/connection-lifecycle/README.md new file mode 100644 index 000000000..863d9401f --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/README.md @@ -0,0 +1,74 @@ +--- +feature: connection-lifecycle +kind: notes +status: active +created: 2026-11-19 +code: + - src/documentdb/ClustersClient.ts + - src/documentdb/ClusterSession.ts + - src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts + - src/tree/documentdb/ClusterItemBase.ts +--- + +# Connection lifecycle + +**Status:** planned (iteration 1) · **Issues:** + +- [#1102](https://github.com/microsoft/vscode-documentdb/issues/1102) +- [#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) + +**Branch:** `feature/connection-lifecycle`, with sub-PRs from `dev/tnaum/*` (decision 0006) + +> How database connections stay usable across Entra token expiry, idle drops and credential +> changes, and what open surfaces do when the user must act or the identity changes. + +## Problem + +After an hour or more, connections stop working, and only restarting VS Code helps. There are three +defects: + +1. Interactive Entra ID returns a captured token from the OIDC callback forever. +2. Azure Discovery holds subscriptions whose ARM token is frozen, and the ARM 401 challenge crashes. +3. Nothing evicts or recreates a failed client, Retry reuses it, and Collection View tabs hold the + old instance. + +Evidence, telemetry and source pointers: [research-findings.md](./research-findings.md). + +## Intent + +- **Recover silently** from token expiry and idle drops. Prompt only on a user click, and never from + a token callback. +- **Keep one client per cluster.** Surfaces resolve it per operation and check its identity + fingerprint and generation. +- **Never change identity under an open surface.** It becomes disconnected, keeps its state, says why + and offers one action. +- **One teardown** serves Disconnect, Remove Connection and identity-changing credential updates. + +## Documents + +| Document | Kind | +| ------------------------------------------------------------------------------ | --------- | +| [research-findings.md](./research-findings.md) | research | +| [decisions.md](./decisions.md) | decisions | +| [iterations/01-implementation-plan.md](./iterations/01-implementation-plan.md) | plan | + +## Decisions index + +See [decisions.md](./decisions.md): + +- 0001 silent renewal, never prompt from the callback; +- 0002 a cached client with identity and generation; +- 0003 no silent identity change; +- 0004 the Disconnect tab choice; +- 0005 azureauth v6; +- 0006 delivery through a feature branch, shipped once. + +## Timeline + +| Date | Event | +| ---------- | --------------------------------------------------------------------------- | +| 2026-11-18 | Investigation: code read, telemetry attribution, vscode-cosmosdb comparison | +| 2026-11-19 | Operator decisions 0001–0005; implementation plan (iteration 1) | +| 2026-11-19 | Decision 0006: delivery model (feature branch, sub-PRs, one release) | diff --git a/docs/ai-and-plans/features/connection-lifecycle/decisions.md b/docs/ai-and-plans/features/connection-lifecycle/decisions.md new file mode 100644 index 000000000..cb81d73c2 --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/decisions.md @@ -0,0 +1,168 @@ +--- +feature: connection-lifecycle +kind: decisions +status: active +created: 2026-11-19 +--- + +# Connection lifecycle: decisions + +> 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 | 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 sub-PRs, avoid PRs on top of open PRs, ship once | Accepted | Operator chose this over one big PR and GitHub stacks | 2026-11-19 | — | + +> 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 +> written; a retitle means a new decision. + +**Status vocabulary:** `Proposed` · `Open` · `Accepted` · `Accepted (modified)` · `Deferred` · +`Superseded by D#` · `Rejected` + +--- + +## 0001. Entra tokens are renewed silently in every OIDC callback; the callback never prompts + +**Accepted** by the operator on 2026-11-19. + +The OIDC callback calls `getSession` with `silent: true` and pins the account and tenant that the +connection started with. VS Code's MSAL refreshes the access token from its refresh token, so the +normal case is silent. The driver already calls the callback again after a code 18 rejection +(`automated_callback_workflow.js`), so a callback that returns a fresh token is enough to recover. + +When silent renewal is impossible, the operation fails with a typed "sign-in required" error, and +the UI offers a single **Sign in again** action. Silent renewal is impossible when: + +- the refresh token has expired or been revoked; +- a Conditional Access sign-in frequency policy, an MFA challenge or a CAE event requires the user; +- the account was signed out of, or removed from, VS Code. + +The action calls `getSession` with `createIfNone` for the same account and tenant, then reconnects. + +Rejected: + +- **`createIfNone: true` inside the callback.** This is what vscode-cosmosdb does as a last resort, + and it is behind their open P1 microsoft/vscode-cosmosdb#3110 (repeated prompts, even after + dismissal). It is rejected for four reasons: + - The callback also runs for background work: pool reconnects, dashboard polling, tree refresh + and completions. Prompts would appear with no user action. + - The driver gives `OIDC_CALLBACK` a hard 60 s timeout, and an MFA sign-in can take longer. + - The callback runs under a driver lock, so every operation queues behind the modal. + - The prompt lets the user pick another account, which changes the identity behind open tabs + (see 0003). +- **Proactive refresh timers.** Unnecessary, because the driver's code 18 retry together with + silent acquisition covers expiry. + +## 0002. Keep one cached client per cluster; surfaces resolve it per operation with identity + generation + +**Accepted** by the operator on 2026-11-19 ("keeping versions or username/clusterid hash would be +sufficient/better"). + +`ClustersClient._clients` keeps one `MongoClient` per `clusterId`. Each client records: + +- an **identity fingerprint**: the existing `getConnectionAuthIdentity` plus the signed-in Entra + account; +- a **generation** that increases every time the client is replaced. + +Surfaces hold `{ clusterId, fingerprint, generation }` and resolve the client per operation: + +- same fingerprint and generation: proceed; +- same fingerprint, new generation: reconnect transparently, and re-run reads from the first page + because cursors are lost; +- different fingerprint, or no client: disconnected (0003). + +Rejected: + +- **A new client for each operation** (vscode-cosmosdb). Creating a client costs about 1.1 s (p50) + and 4.3 s (p90) for Native, and about 2.0 s and 9.0 s for Entra. It also loses cursors (pagination), + server sessions and monitoring. This fits Cosmos's stateless HTTP; it does not fit a `MongoClient`. +- **Caching by `clusterId` + identity.** Two clients for one cluster could coexist, and tabs opened + under the old credentials would keep working after Update Credentials. That is the permission + risk 0003 removes, and it also leaks pools. + +## 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): + +> we need to be careful about ensuring that a connection is tied to the user name, otherwise.. a +> user could change credentials and the user name, then the tabs would get a new permissions +> possibly, this is risky. so basically, when a user disconnects/updates credentials, we might need +> to "disconnect" the open tabs, like have valid disconnected state with discoverable info why no +> 'actions' are now allowed + +- Triggers: + - Disconnect; + - Remove Connection; + - Update Credentials or Update Connection String, when the fingerprint changes; + - sign-out or removal of the bound Entra account (`onDidChangeSessions`); + - silent renewal that is impossible (reason "Sign-in expired"). +- A disconnected surface disables every action that talks to the server. It keeps the query text, + filter, sort, projection, page position and unsaved document edits. It shows the reason and the + matching action: Reconnect, Sign in again, or Close. +- A password change for the **same** user keeps the fingerprint. Tabs continue on the new client, + because the permissions follow the user. +- Today, Document View, the index and Query Insights routers, and the Cluster Dashboard already + resolve a client per operation **without** an identity check. They would quietly continue under + the new identity, so they are in scope. + +## 0004. Disconnect lets the user choose: close all affected tabs, or keep them open and disabled + +**Accepted** in principle by the operator on 2026-11-19 ("we could give an option to the user: +close all, or keep open but disabled"). The default, and whether the choice is remembered, are +still open (plan Q2). The proposal is to keep tabs open and disabled by default, and to remember the +choice in `globalState`, the same way the Atlas and Kubernetes view modes are remembered. + +## 0005. Fix stale ARM credentials by upgrading azureauth to v6 (#990), not with a local shim + +**Accepted.** The operator is open to updating dependencies, and the upgrade is already planned for +1.2.0 in #990. + +azureauth v6 calls `getSessionFromVSCode(..., { silent: true })` for every `getToken`. It also +satisfies the request-object contract that azureutils 4.2's `BearerChallengePolicy` already expects. + +Rejected: + +- **A local wrapper in `AzureSubscriptionProviderWithFilters`.** It would duplicate upstream v6 + logic, and it would be thrown away when #990 lands. +- **Staying on 5.1.1, the latest stable.** It still captures the token. + +## 0006. Deliver through `feature/connection-lifecycle` with sub-PRs, avoid PRs on top of open PRs, ship once + +**Accepted** by the operator on 2026-11-19. Source: operator input during planning. + +> I'm for 'one big PR', I had some bad experience with stacked PRs and the need of moving updates up +> the chain before being able to recover and in the end, I had to merge them individually anyway. so +> maybe a 'feature' branch for this and then PRs against it, sometimes on top of other PRs, but +> without the 'stack' feature from github. [...] it won't be a partial release, it all will go out +> at once. + +After the evaluation, the operator chose the feature-branch model and asked to reduce PRs opened on +top of other open PRs: "not required, just welcomed". + +- It follows CONTRIBUTING §1.4 (large features). +- It fits the repository's enforcement: + - CI runs on PRs to `feature/**`; + - the `feature/**` ruleset requires a reviewed PR and blocks force pushes; + - only merge commits are allowed, and head branches are deleted on merge. +- Merge commits keep the original commits. A PR opened on top of another one therefore shrinks to + its own diff, and is retargeted automatically, once its base merges. That makes the exception + workable without moving updates up the chain. +- The split and the rules are in [the plan's Delivery section](./iterations/01-implementation-plan.md#delivery). + +Rejected: + +- **One big PR to `main`:** + - The diff mixes a dependency migration, host lifecycle changes, three webviews and teardown, so + review and AI pre-review get worse. + - Each push dismisses the approval. + - There are no reviewed checkpoints, and conflicts with `main` are resolved only at the end. +- **GitHub stacked PRs:** the operator's experience was that updates must move up the chain and the + PRs end up merged one by one anyway. +- **Shipping WI-1 and WI-2 early as a patch (plan Q5):** no partial release. 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 new file mode 100644 index 000000000..0f3c82754 --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-implementation-plan.md @@ -0,0 +1,475 @@ +--- +feature: connection-lifecycle +kind: plan +status: active +created: 2026-11-19 +code: + - src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts + - src/documentdb/auth/oidcClientOptions.ts + - src/documentdb/auth/connectionAuthIdentity.ts + - src/documentdb/ClustersClient.ts + - src/documentdb/ClusterSession.ts + - src/documentdb/shell/ShellSessionManager.ts + - src/documentdb/playground/PlaygroundEvaluator.ts + - src/tree/documentdb/ClusterItemBase.ts + - src/commands/retryAuthentication/retryAuthentication.ts + - src/commands/updateCredentials/updateCredentials.ts + - src/webviews/documentdb/collectionView/collectionViewRouter.ts + - src/webviews/documentdb/documentView/documentsViewRouter.ts + - src/webviews/documentdb/clusterDashboard/clusterDashboardRouter.ts + - src/plugins/api-shared/azure/AzureSubscriptionProviderWithFilters.ts + - src/connectionDiagnostics/checks/resolveTarget.ts +--- + +# Iteration 1: keep connections usable across token expiry, idle drops and credential changes + +**Issues:** + +- [#1102](https://github.com/microsoft/vscode-documentdb/issues/1102) (this plan); +- folded in: [#1059](https://github.com/microsoft/vscode-documentdb/issues/1059) (Disconnect) and + [#566](https://github.com/microsoft/vscode-documentdb/issues/566) (one teardown for Remove and + Disconnect); +- executed as a dependency: [#990](https://github.com/microsoft/vscode-documentdb/issues/990) + (azureauth v6); +- coordinated: [#1091](https://github.com/microsoft/vscode-documentdb/issues/1091) (dashboard polling). + +**Branch:** `feature/connection-lifecycle` (sub-PRs from `dev/tnaum/*`; see [Delivery](#delivery)) · +**Milestone:** 1.2.0, shipped as one release + +The analysis, evidence and source pointers are in [../research-findings.md](../research-findings.md), +and the decisions in [../decisions.md](../decisions.md). Neither is repeated here. This plan orders the +work. **It deliberately does not specify interfaces**: a dedicated agent designs them per work item, +following the decisions. Progress is recorded **inline, against each work item**, when that item is +committed. + +## Goal + +A user who leaves VS Code open for hours, with tabs and shells open, **never has to restart VS Code** +and **never loses work** (query text, filters, sort, projection, unsaved document edits). + +- Token expiry and idle drops recover silently. +- When the user really has to act (sign in again, credentials changed, they disconnected), every + affected surface shows a clear disconnected state with the reason and one action. It never quietly + continues under a different identity. + +## Mapping to #1102 acceptance criteria + +| #1102 criterion | Work items | +| ------------------------------------------------------------------------------------------------------- | ---------- | +| Entra: renew without prompting; never reuse an expired token for a new connection | WI-1, WI-2 | +| Standard auth: reconnect with the configured credential; if invalid, prompt to update, no endless retry | WI-5 | +| Interactive sign-in keeps Collection View tabs and their state, then uses the recovered connection | WI-5, WI-6 | +| Recover on the next operation without a restart; never silently replay writes | WI-5, WI-6 | +| Discovery (signing in to Azure) is separate from database authentication | WI-3 | + +## Execution order + +``` +WI-1 ─┬─> WI-2 (Entra, small, independent) + │ +WI-3 ─┤ (azureauth v6 / #990, parallel track) + │ +WI-4 ─┴─> WI-5 ─> WI-6 ─> WI-7 ─> WI-8 (lifecycle core, then Disconnect, then dashboard) + └──> WI-9 (telemetry check) ─> WI-10 (docs) +``` + +- WI-1, WI-2 and WI-3 are independent of the lifecycle core. +- WI-1 and WI-2 remove most of the user impact (defect #1). They still ship with everything else; + there is no partial release (decision [0006](../decisions.md)). + +## Delivery + +**Model (decision [0006](../decisions.md)):** a `feature/` branch with sub-PRs, following +[CONTRIBUTING §1.4](../../../../../CONTRIBUTING.md#14-large-features). + +- `feature/connection-lifecycle` is created from `main`. +- Each sub-PR comes from a `dev/tnaum/` branch and merges into the feature branch, where it + gets its own review, AI pre-review and checks. +- **One** final PR, `feature/connection-lifecycle` → `main`, ships everything in a single release. +- GitHub's stacked PRs are not used. + +**How the repository enforces this** (checked 2026-11-19): + +- `main.yml` runs on `pull_request` to `feature/**`. +- The `feature/**` ruleset: + - every change goes through a PR with one code-owner approval; + - the last push needs approval, and a new push dismisses stale approvals; + - required checks are `license/cla` and `Merge gate`; + - **force pushes and deletion are blocked**. +- Repository merge settings: **merge commits only** (squash and rebase are disabled), and head + branches are deleted on merge. + +### Rules for keeping PRs off each other + +The goal is to open few PRs on top of other unmerged PRs. It is preferred, not required. + +1. **Open a PR only when everything it depends on has merged** into the feature branch. While a + dependency is still in review, keep building on a local branch made from it. Once the dependency + merges, `git merge feature/connection-lifecycle` into the local branch, then open the PR against + the feature branch. +2. **Use parallel tracks.** Independent work items each get their own PR off the feature branch, + so they never stack (PR 1–3 below). +3. **Group work items into one PR** when they are strongly coupled and reviewable together. Keep + commits per work item inside the PR, so the inline progress notes can name them. +4. **Exception:** if waiting would block progress, a PR _may_ target another open PR's branch. Merge + commits keep the commits intact, and deleting the base branch on merge makes GitHub retarget the + PR to the feature branch automatically. To pick up later changes from the base, use + `git merge `. Never rebase or force-push after a human review (CONTRIBUTING §1.6). +5. **Sync `main` into the feature branch** through a PR, because force pushes are blocked: + - weekly, and once more right before the final PR; + - as a pure merge, with no feature work in it; + - on `l10n/bundle.l10n.json` and `package-lock.json` conflicts, take either side and + regenerate (`npm run l10n`, `npm install`). Never hand-merge them. + +### PR split + +| PR | Content | Base when opened | Opens after | +| --- | -------------------------------------------------------------------------------- | ----------------------------- | ------------------------- | +| 0 | This plan, `research-findings.md`, `decisions.md`, README and index row | feature branch (just created) | — | +| 1 | WI-1 + WI-2: Entra silent renewal, plus the shell and playground relays | feature branch | PR 0 | +| 2 | WI-3: azureauth v6 (#990) + the diagnostics `signInRequired` mapping | feature branch | PR 0 | +| 3 | WI-4: client identity and generation, the two cache fixes, telemetry helper | feature branch | PR 0 | +| 4 | WI-5: failure classifier, recovery, Sign in again, Retry, `onDidChangeSessions` | feature branch | PR 1 and PR 3 merged | +| 5 | WI-6: surface binding and the disconnected state (host and webviews) | feature branch | PR 4 merged | +| 6 | WI-7 + WI-8: teardown, Disconnect, Remove, Update Credentials, dashboard polling | feature branch | PR 5 merged | +| 7 | WI-9 + WI-10: telemetry signals and dashboards, documentation | feature branch | PR 6 merged | +| F | `feature/connection-lifecycle` → `main` | `main` | all merged, OT-1–7 passed | + +- **PR 1, PR 2 and PR 3 run in parallel** and never stack. +- PR 4 to PR 7 are sequential, because each builds on the previous one. Under rule 1, local work on + the next item may begin early, but its PR opens only after its base has merged. +- **PR 5 is the largest.** If it becomes too large to review well, split it into host (5a) and + webviews (5b). 5b opens after 5a merges, following rule 1. +- **#990 alternative:** #990 is its own issue in the 1.2.0 milestone. It can merge to `main` instead, + which keeps the busiest lockfile changes off the feature branch; it would still ship in the same + release. The default is the feature branch, so that the discovery fix and the WI-3 diagnostics + mapping are reviewed together. + +### Verification per PR + +- **Sub-PRs (draft or in progress):** Case 1, as in the copilot instructions: `npm run build`, + plus `npx vitest run `. +- **Sub-PRs marked ready for review:** Case 2 in full. That includes `l10n:check`, `lint`, + `typecheck:tests`, the full Vitest suite and `package`. The AI pre-review is committed under + `iterations/` as `01--review.md`, following the knowledge-base naming rules. +- **Final PR F** has three gates: + - Case 2; + - the CONTRIBUTING §1.4 checklist: packaged-VSIX validation means the operator acceptance tests + below; telemetry is WI-9; docs are WI-10; + - a ~1-week watch after the merge. + +--- + +## WI-1: Entra ID, renew silently on every OIDC callback (decision 0001) + +**Problem:** the callback returns the token captured at connect time +([MicrosoftEntraIDAuthHandler.ts:155-162](../../../../../src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts)). + +- The first connect stays as it is: interactive when the user asked for it (`createIfNone`), and it + records the account that signed in (`onTokenAcquired` already exposes `account`). +- **Each callback** calls `getSessionFromVSCode([scope], tenantId, { silent: true, account })`, with + the account pinned. + - Return `expiresInSeconds` from the JWT `exp` claim. Reuse the decoding in + [playgroundWorker.ts:215-230](../../../../../src/documentdb/playground/playgroundWorker.ts) and + [tokenExpiry.ts](../../../../../src/documentdb/auth/tokenExpiry.ts). + - Keep the destination policy checks that wrap the call + ([oidcClientOptions.ts:151](../../../../../src/documentdb/auth/oidcClientOptions.ts)). +- If there is no session, or a different account comes back, throw a **typed sign-in-required + error**. Never prompt from the callback. It must work with the existing `AuthInputUnavailableError` + and with the Entra failure registry. Per the comment at + [MicrosoftEntraIDAuthHandler.ts:117](../../../../../src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts), + a silent miss is not a token failure. +- Route the typed error through `ErrorExplanationService` + ([errorExplanationService.ts](../../../../../src/services/errorExplanationService.ts); see the + error-translation skill) so every surface gets the same message: "Your Microsoft sign-in for + '{cluster}' expired. Sign in again to continue." +- **Unit tests:** + - A second callback invocation returns a new token. + - A silent miss gives the typed error, and `getSession` is never called with `createIfNone`. + - A different account is reported as such. + - The destination policy is still enforced. + +## WI-2: Shell and Playground token relays use the same policy + +**Problem:** both relays call `createIfNone: true` inside the worker's token request +([ShellSessionManager.ts:450](../../../../../src/documentdb/shell/ShellSessionManager.ts), +[PlaygroundEvaluator.ts:467](../../../../../src/documentdb/playground/PlaygroundEvaluator.ts)). + +- Make the relay silent and pinned to the account in the session's D12 identity snapshot + ([sovereign-clouds decisions D12](../../sovereign-clouds/decisions.md)). +- A miss puts the shell or playground into a "sign in again" state: a printed line and an action. It + never opens a modal during a background refresh. +- Fold in the #1059 note: `PlaygroundEvaluator.buildInitMessage` + ([PlaygroundEvaluator.ts:288](../../../../../src/documentdb/playground/PlaygroundEvaluator.ts)) reads + `CredentialCache` on every run. +- **Unit tests:** extend the existing relay tests to cover the silent miss and account pinning. + +## WI-3: Azure discovery, azureauth v6 (#990, decision 0005) + +Execute #990 as written. The issue already lists the breaking APIs, call sites, dedupe rule, l10n +bundle, filter and cache behavior, and how to verify. Additions from this investigation: + +- **Version alignment:** + - azureutils 4.2.0 expects azureauth `^6.0.0-alpha.6`; the challenge contract is the cause of the + `endsWith` crash. + - Pick versions so the bundle contains a **single** azureauth copy (see #990 "Dedupe"). + - Decide together whether to move azext-utils and azureutils to v5, as vscode-cosmosdb did + (azureauth 5.1.1 + azureutils 5 + utils 5; their host owns refresh). #626 is now stale; utils is + already 4.1.0. +- **Discovery tree items keep `AzureSubscription` objects:** + - Confirm that v6 `credential.getToken` and `authentication.getSession` acquire a token on every + call, so a subscription that was stored hours ago still works. + - Discovery item pointers: [DocumentDBResourceItem.ts](../../../../../src/plugins/service-azure-mongo-vcore/discovery-tree/documentdb/DocumentDBResourceItem.ts), + [MongoRUResourceItem.ts](../../../../../src/plugins/service-azure-mongo-ru/discovery-tree/documentdb/MongoRUResourceItem.ts), + and the VM items. + - ARM client creation: [azureClients.ts](../../../../../src/utils/azureClients.ts). +- **Diagnostics:** classify ARM sign-in failures as `signInRequired`, not `other`: + - `NotSignedInError`; + - a failed challenge; + - an `interaction_required` or AADSTS sign-in error. + + The place is `classifyResolutionFailure` + ([resolveTarget.ts:52-82](../../../../../src/connectionDiagnostics/checks/resolveTarget.ts)). Keep it + bounded: an error name and status only, never messages (decision R2 in connectivity-troubleshooter). + +- **Unit test:** a stored subscription whose first token "expires" still lists clusters (mock the + session sequence). +- **Fallback:** if #990 is not merged by the time WI-6 is ready, raise it with the operator before + changing course. Decision 0005 rejected a local shim. + +## WI-4: Client identity, generation and two cache bugs (decision 0002) + +In [ClustersClient.ts](../../../../../src/documentdb/ClustersClient.ts): + +- **Identity and generation:** every client records, when it is created: + - an identity fingerprint: [getConnectionAuthIdentity](../../../../../src/documentdb/auth/connectionAuthIdentity.ts) + plus the signed-in Entra account id from WI-1; + - a per-cluster **generation**; + - its creation time. + + The fingerprint is derived from **what was used to connect**, not from the current `CredentialCache`. + +- **Fix:** cancelling a _cached_ reuse must not close the shared client. + - Pointer: the `getClient` abort handler at + [ClustersClient.ts:586-592](../../../../../src/documentdb/ClustersClient.ts). + - This is a likely trigger for "Client must be connected before running operations" + (research §3). +- **Fix:** never hand out a client whose topology was closed. + - Today `getClient` calls `connect()` on a closed client, which reconnects with the old options. + - Replace it with a new generation that uses the current credentials, keeping the same fingerprint + rule. +- **Telemetry base:** one helper adds `authMethod`, `connectionAgeMs` and `clientGeneration` to any + failure that happens after the connection was established. The surfaces in WI-5 and WI-6 call it. + Follow the telemetry-instrumentation skill; property names must not contain "error" (masking). +- **Optional test hook, development only:** a command that makes the Entra callback return an + invalid token N times and drops pooled connections. It lets WI-5 and WI-6 be checked in minutes + instead of 90. + - Declare it in `LAZY_COMMANDS` ([checks.cjs](../../../../../build/verification/activation/checks.cjs)), + as required for commands that are not registered in production. + - Use a dashed context key if it needs one. + +## WI-5: Classify failures and recover (main thread and tree) + +- **One classifier** for failures on an established client. Inputs: the driver error (code 18, code + 391, `MongoNotConnectedError` / closed topology, network codes and timeouts) and the WI-1 typed + error. Outputs: + - `signInRequired` (Entra): offer **Sign in again**. + - `credentialsRejected` (Native code 18 after a reconnect): offer **Update credentials**, and + **no automatic retry loop**. + - `clientClosed`: create a new generation with the same identity. + - `transient` (network or timeout): no eviction, because the driver recovers. Offer Retry. + + Reuse `ErrorExplanationService` for wording. + +- **Sign in again** action: + - It calls `getSession(..., { createIfNone: true, account })` for the pinned account and tenant. + - Same account: evict and create a new generation. Surfaces continue (WI-6). + - Different account: treat it as an identity change (decision 0003). + - **One** prompt per user click. Dismissing it is respected: no reprompt until the user acts again. +- **The tree's Retry must actually reconnect.** + - [retryAuthentication.ts](../../../../../src/commands/retryAuthentication/retryAuthentication.ts) + and the cached-client path in + [ClusterItemBase.ts:358-447](../../../../../src/tree/documentdb/ClusterItemBase.ts) should evict + the client when the last failure was `signInRequired`, `credentialsRejected` or `clientClosed`. + - Keep the cached credentials (#1059 open question 1: dropping the client is not the same as + forgetting the credentials). + - Add **Sign in again** to `createErrorRecoveryChildren` + ([ClusterItemBase.ts:304-326](../../../../../src/tree/documentdb/ClusterItemBase.ts)), following the + "actions only" order in the tree-cluster-architecture skill: repairs first, Retry last. +- **`vscode.authentication.onDidChangeSessions`:** when the bound Entra account disappears, mark its + clients `signInRequired`. Never sign the user out, and never remove sessions (#1059 "must NOT be + touched"). +- **Unit tests:** + - classifier table tests; + - Retry after `clientClosed` produces a new generation; + - Sign in again with the same account versus a different account; + - no reprompt after a dismissal. + +## WI-6: Bind surfaces to `{ clusterId, fingerprint, generation }` and add a disconnected state (decisions 0002, 0003) + +The largest item. Host side first, then each view. + +- **Host:** + - `ClusterSession` stops holding a `ClustersClient` + ([ClusterSession.ts:65-78, 688-725](../../../../../src/documentdb/ClusterSession.ts)). It records + the binding and resolves the client for each operation. + - Per-operation `getClient` callers that skip any check must check the fingerprint too: + - Document View ([documentsViewRouter.ts:54,91](../../../../../src/webviews/documentdb/documentView/documentsViewRouter.ts)); + - the index router; + - the Query Insights routers; + - [QueryInsightsAIService.ts](../../../../../src/services/ai/QueryInsightsAIService.ts); + - the Cluster Dashboard router. + + The full call-site list is in research §3; rerun + `grep -rn "ClustersClient.getClient(\|\.getClient()" src`. + + - Outcomes: + - same fingerprint and generation: proceed; + - same fingerprint, new generation: proceed, and re-run reads from page 1 because cursors are + lost, with a notice in the spirit of Cosmos's "results are no longer current"; + - different fingerprint, or no client: **disconnected**, with a reason. + - **Writes are never replayed.** A write with an unknown outcome is reported as failed, and the + message says the outcome is unknown. + +- **Webviews:** + - Push one connection-state channel per view over tRPC: connected, reconnecting, or disconnected + with a reason. Follow the webview-trpc-messaging and react-webview-architecture skills. + - Disconnected disables every action that talks to the server and shows a banner with the reason + and one action: Reconnect, Sign in again, Update credentials, or Close. + - It **keeps** the editor contents, filter, sort, projection, page position and unsaved document + edits. + - Views: Collection View (query, documents, indexes and Query Insights tabs), Document View + (dirty editor) and the Cluster Dashboard. + - Accessibility: announce the state change (accessibility skill; live region). +- **Long-running tasks** (copy and paste, import, export, index copy; + [DocumentDbDocumentReader.ts](../../../../../src/services/taskService/data-api/readers/DocumentDbDocumentReader.ts)): + they resolve a client for each batch. A fingerprint change fails the task with a clear reason and + never resumes under the new identity. The cancel-or-ask policy belongs to WI-7. +- **Tests:** + - router tests for the three binding outcomes; + - a Collection View scenario: disconnected banner with the query text kept; + - a Document View scenario: dirty edit kept; + - scenarios run through the L2-dev runner (`/scenarios/`, see the copilot instructions). + +## WI-7: Teardown service, Disconnect, Remove and Update Credentials (#1059, #566, decisions 0003, 0004) + +- **One teardown**, keyed by `clusterId` and matched case-insensitively. Remove = teardown + delete + + clear schema; Disconnect = teardown only. + - Follow the full #1059 checklist: client, shells, playground, webviews, tasks, in-flight token + requests (sovereign-clouds finding E4), `CredentialCache`, the Entra failure registry, and the + `SchemaStore` decision. + - Its "must NOT be touched" rules apply: VS Code auth sessions, the managed identity cache, the + ARM cache. +- **Disconnect command** on connected clusters in the Connections, Azure Resources and Discovery + views. + - Use dashed context keys (manifest rule in the copilot instructions). + - When surfaces are open, ask the user: **Close all** or **Keep open (disabled)** (decision 0004; + default and remembering per Q2). + - Close all must not throw away unsaved document edits without the usual dirty-editor confirmation. +- **Update Credentials** + ([updateCredentials.ts:142-185](../../../../../src/commands/updateCredentials/updateCredentials.ts)) + and Update Connection String compare the old and new fingerprints: + - **same:** the client is replaced and tabs continue; + - **different:** teardown with reason "credentials changed", offering the same Close/Keep choice. + + Today's D12 modal for open shells offers Disconnect as a button (#1059). + +- **Telemetry:** one event with the activation source and teardown counts. No identifiers (#1059). +- **Tests:** + - teardown per surface; + - IDs that differ only in case; + - a late token response after Disconnect is ignored; + - reconnecting uses the current credentials and cloud settings; + - Remove reuses the same teardown. + +## WI-8: Cluster Dashboard health polling + +Coordinate with #1091. The minimum for this plan: + +- the poll uses the WI-6 binding; +- after a `signInRequired`, `credentialsRejected` or disconnected outcome, polling **stops** and the + dashboard shows the WI-6 banner instead of starting a connection every 5 s. + +Visibility pause and backoff are the rest of #1091 and may ship separately. + +## WI-9: Telemetry check + +- **New signals:** + - `connection.recovered`, with its trigger (silent renewal, reconnect, sign in again); + - silent-renewal outcomes. Use counters with `accumulateTelemetry` on the hot path, or one event + per miss; + - the Disconnect event; + - the WI-4 enrichment on failures after connect. +- **Dashboards:** extend the errors recipe in the telemetry-dashboards skill (devbox worktree) + with: + - late failures after connect, by auth method; + - successful ARM challenges; + - recoveries. +- **After the pre-release:** rerun the research queries (research appendix). Expected: + - Entra-only sessions show almost no late code 18 or socket-closed failures; + - `challengeSuccess=true` appears; + - "Client must be connected" disappears. + +## WI-10: Documentation + +- User manual: + - Disconnect; + - "Sign in again"; + - what a disconnected tab means and how to resume; + - the Update Credentials note about open sessions. +- Release notes (writing-release-notes skill). +- Skills: + - tree-cluster-architecture: the connection lifecycle rule ("resolve the client per operation; + never hold a `ClustersClient`"); + - error-translation: the new categories. +- This feature's README, plus `docs/ai-and-plans/README.md`. + +--- + +## Operator acceptance tests (run on the installed VSIX at the end) + +These are the minimal checks that confirm the goal. The operator should finish them **without +restarting VS Code** and **without losing any typed text or unsaved edits**. + +**Setup:** + +- one Azure DocumentDB cluster with Entra ID enabled, and a native user on it; +- one RU account reached through Azure Discovery (account key); +- VS Code signed in to the Microsoft account that has access. + +**Test matrix:** RU with Entra ID for the database is **not supported** by the extension (key-based +only), so it is not tested. + +**Long wait:** "Wait ≥ 2 h" means leaving the window idle, for example over lunch or overnight. The +optional WI-4 test hook may shorten this during development. The release check uses a real wait at +least once. + +| # | Scenario | Steps | Pass when | +| ---- | ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| OT-1 | **Entra, long idle, work open** | Connect with Entra. Open a Collection View with filter, sort and projection, on page 2. Open a Document View with an unsaved edit. Open the Cluster Dashboard and a shell. Wait ≥ 2 h. Then refresh the tree, run the query, go to the next page, save the document, and run a command in the shell. | Everything works. No sign-in prompt, and no error that needs a click. Text and edits are kept. If page 1 is re-run, the view says why. | +| OT-2 | **Entra, silent renewal impossible** | With the OT-1 surfaces open, sign out of the account in the Accounts menu (or revoke sessions in Entra). Run the query. Dismiss the prompt if one appears. Wait 5 min. Then click **Sign in again** and pick the same account. | The action fails once and offers **Sign in again**. The tabs show "sign-in expired" with their content kept. No modal appears on its own, and nothing prompts again after a dismissal. After signing in, the tabs re-enable and the unsaved edit saves. | +| OT-3 | **Identity change is never silent** | (a) Native: with tabs open, use Update Credentials to switch to a different user. Choose "Keep open (disabled)". (b) Repeat, changing only the password of the same user. (c) Entra: in OT-2, sign in again with a _different_ account. | (a) and (c): tabs are disabled with "credentials changed", no action runs under the new identity, and Reconnect opens a new session and says so. (b): tabs continue. | +| OT-4 | **Native, idle and network drop** | Native connection with tabs open. Turn the network off for 2 min, or put the machine to sleep for ≥ 30 min, then restore it. Run a query, refresh the tree, save a document. Also try an insert while offline. | The operations work after restoring, at most after one Retry. The offline insert is reported as failed or unknown and is **not** replayed. | +| OT-5 | **RU (key), idle and key rotation** | Open the RU cluster through Discovery, with tabs open. Wait ≥ 2 h and run a query. Then regenerate the primary key in the portal and run a query again. | After the wait: it works. After rotation: one clear failure with an action. The action reconnects with the new key. No endless retry. | +| OT-6 | **Azure discovery, long idle** | Expand a subscription in vCore and RU Discovery. Wait ≥ 2 h. Expand a cluster, connect, and run **Diagnose connection**. Then sign out of Azure and run Diagnose again. | It works without refreshing the provider root. When signed out, the diagnosis says **"Azure sign-in needed"**, not "Azure details unavailable". | +| OT-7 | **Disconnect** | With a Collection View, a dirty Document View, a shell and a playground open: Disconnect and choose **Keep open (disabled)**, then use Reconnect from a tab. Repeat with **Close all**. Then use Remove Connection. | Keep open: disabled with the reason, content kept, and Reconnect resumes. Close all: the dirty editor asks before it closes. The shell prints "Disconnected". The node collapses, and the next expand connects again. Remove behaves like Disconnect plus delete. | + +**After release** (telemetry, operator with Kusto access): run the WI-9 queries on the pre-release +cohort. + +--- + +## Open questions (to settle before or during WI-5 and WI-7) + +- **Q1:** For a user-initiated action, should the interactive sign-in open **immediately**, or only + through the **Sign in again** button? The proposal is the button everywhere (decision 0001). A + first connect from the tree stays interactive, as it is today. +- **Q2:** The default for the Disconnect choice, and whether to remember it. The proposal is Keep + open (disabled), remembered in `globalState`. +- **Q3:** Should Disconnect drop the `CredentialCache` entry (#1059 proposes yes), so a password + typed only for a discovery connection must be entered again? +- **Q4:** Ask the Azure DocumentDB service team whether the server closes connections when the + token expires, and whether it ever sends code 391 `ReauthenticationRequired` (research §1). +- ~~**Q5:** Release slicing. Should WI-1 and WI-2 ship early as a patch (backport skill)? They are + small, isolated and fix the largest group (≥60 machines in 28 days).~~ **Resolved 2026-11-19:** + no. Everything ships at once from the feature branch (decision [0006](../decisions.md)). diff --git a/docs/ai-and-plans/features/connection-lifecycle/research-findings.md b/docs/ai-and-plans/features/connection-lifecycle/research-findings.md new file mode 100644 index 000000000..9ad2b779e --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/research-findings.md @@ -0,0 +1,269 @@ +--- +feature: connection-lifecycle +kind: research +status: active +created: 2026-11-19 +verified: 2026-11-19 +code: + - src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts + - src/documentdb/auth/oidcClientOptions.ts + - src/documentdb/ClustersClient.ts + - src/documentdb/ClusterSession.ts + - src/tree/documentdb/ClusterItemBase.ts + - src/commands/retryAuthentication/retryAuthentication.ts + - src/plugins/api-shared/azure/AzureSubscriptionProviderWithFilters.ts + - src/utils/azureClients.ts + - src/connectionDiagnostics/checks/resolveTarget.ts +--- + +# Why connections stop working in long-running sessions (#1102) + +> Evidence gathered on 2026-11-18/19 for [#1102](https://github.com/microsoft/vscode-documentdb/issues/1102). +> Code was read at `main` @ `1180ceb2f`: mongodb driver 7.2.0, `@microsoft/vscode-azext-azureauth` +> 4.1.1, `@microsoft/vscode-azext-azureutils` 4.2.0, `@microsoft/vscode-azext-utils` 4.1.0. +> Telemetry comes from `ddtelvscode/VSCodeExt.RawEventsVSCodeExt`, last 28 full days. "Machines" +> means distinct `VSCodeMachineId`. Line numbers are at that commit and will drift; function names +> are the stable pointer. + +## Summary + +There are three separate defects. Two are about tokens that expire. The third is about a stale +client. Together they explain "everything is disconnected, and only restarting VS Code helps". + +| # | Defect | Who | Telemetry (28 days) | Confidence | +| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- | +| 1 | The **Entra ID database token is captured once** and the OIDC callback returns it forever | Interactive Entra ID (Azure DocumentDB) | ≥60 of 153 long-running Entra machines. No failures between 30 and 60 min; the first failures appear at 60–75 min | Verified (code + telemetry) | +| 2 | The **ARM token is frozen inside the `AzureSubscription`** that discovery tree items hold, and the ARM 401 challenge handler crashes with `e.endsWith is not a function` | Azure Discovery (vCore + RU) | 27 of 350 discovery machines. **Every** ARM challenge in 28 days failed. Median onset is about 13 h | Verified (code + telemetry) | +| 3 | **No recovery path.** The cached `ClustersClient` is never evicted, Retry reuses it, and Collection View tabs hold the old instance | All auth methods | Amplifies #1. 16 machines saw "Client must be connected before running operations" in the Collection View | Code verified; the trigger for #3b is a hypothesis | + +Native (username and password) authentication is **not** affected by expiry. The driver signs every +new socket in again with SCRAM. Native failures are mostly timeouts, and a few code 18 errors that do +not depend on how long the connection has been open. + +## 1. Entra ID (interactive) database connections + +### Mechanism + +- `MicrosoftEntraIDAuthHandler.configureAuth` acquires one VS Code session (`getSessionFromVSCode`, + [MicrosoftEntraIDAuthHandler.ts:93-107](../../../../src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts)). + It then builds the OIDC callback as a closure over that session + ([MicrosoftEntraIDAuthHandler.ts:155-162](../../../../src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts)): + `Promise.resolve({ accessToken: session.accessToken, expiresInSeconds: 0 })`. +- The wrapper in [oidcClientOptions.ts:151](../../../../src/documentdb/auth/oidcClientOptions.ts) + (`buildOidcClientConfiguration`) checks the destination policy around the callback. It does not + change the token. +- The driver can recover on its own. In `node_modules/mongodb/lib/cmap/auth/mongodb_oidc/automated_callback_workflow.js:22-51`, + when the cached token gets code 18, the driver drops it and **calls the callback again**. Our + callback returns the same expired token, so the code 18 error reaches the user. +- The driver gives `OIDC_CALLBACK` a hard **60 s timeout** (`AUTOMATED_TIMEOUT_MS`, + `automated_callback_workflow.js:67-74`). The callback runs under a lock + (`callback_workflow.js`, `withLock`). +- The `MongoClient` lives in the static `ClustersClient._clients` map until it is explicitly deleted + ([ClustersClient.ts:196](../../../../src/documentdb/ClustersClient.ts)). Every new pool connection + signs in through that callback. New pool connections appear after idle sockets close, or after the + server drops sockets when the token expires. +- These paths are already correct, because they acquire a token for each callback: + - managed identity ([ManagedIdentityAuthHandler.ts:103-148](../../../../src/documentdb/auth/ManagedIdentityAuthHandler.ts)); + - the shell and playground workers, whose `tokenRequest` IPC is answered on the main thread + ([playgroundWorker.ts:189-230](../../../../src/documentdb/playground/playgroundWorker.ts) decodes + the JWT `exp` claim; [ShellSessionManager.ts:450](../../../../src/documentdb/shell/ShellSessionManager.ts); + [PlaygroundEvaluator.ts:467](../../../../src/documentdb/playground/PlaygroundEvaluator.ts)). + However, both of these use **`createIfNone: true` inside the callback**, so a token refresh in + the background can open a sign-in prompt. +- VS Code's Microsoft auth provider (MSAL) refreshes access tokens silently from its refresh token. + `getSession(..., { silent: true })` inside the callback returns a valid token without a prompt in + the normal case. + +### Telemetry + +Failures were attributed to auth methods through successful `connect.startup` events in the same +`VSCodeSessionId`, using single-auth sessions only. "Late" means at least 60 min after the last +successful startup in that session. + +| Auth | Signature | Surface | Machines late | Machines early | +| -------- | ------------------------------ | ------------------------ | ----------------- | -------------- | +| Entra ID | code 18 `AuthenticationFailed` | tree | **60** (430 rows) | 15 | +| Entra ID | `connection N to … closed` | tree | **41** | 13 | +| Entra ID | `connection N to … closed` | Collection/Document View | **40** | 5 | +| Native | code 18 | tree | 14 | 11 | +| Native | timeout | tree / webview | 26 / 18 | 9 / 7 | + +Denominators, from sessions with a successful connect: + +| Auth | Machines | Machines active ≥60 min after connect | +| -------- | -------- | ------------------------------------- | +| Native | 921 | 674 | +| Entra ID | 187 | 153 | +| No Auth | 107 | 48 | + +Age of the **first** failure in sessions that used only Entra ID: + +| Age | Sessions with code 18 | Sessions with socket closed | +| ---------- | --------------------- | --------------------------- | +| <30 min | 4 | 0 | +| 30–60 min | **0** | **0** | +| 60–75 min | 8 | 12 | +| 75–90 min | 11 | 16 | +| 90–120 min | 27 | 25 | +| 2–4 h | 28 | 36 | +| 4–8 h | 17 | 17 | +| ≥8 h | 49 | 55 | + +Failures start at 60–90 min, which matches the lifetime of an Entra access token. The socket-closed +errors start at the same time. **Hypothesis, not confirmed with the service team:** the server closes +connections when the token expires, and the following reconnects then fail with code 18. + +## 2. Azure Discovery (ARM) credentials + +### Mechanism + +1. In azureauth 4.1.1, `VSCodeAzureSubscriptionProvider.getSubscriptionsForTenant` + (`out/src/VSCodeAzureSubscriptionProvider.js:319-331, 364-391`) creates every subscription with + `authentication.getSession = () => session` and a credential that returns the token captured at + listing time. +2. Discovery tree items keep that subscription (`readonly subscription` in + [DocumentDBResourceItem.ts:45](../../../../src/plugins/service-azure-mongo-vcore/discovery-tree/documentdb/DocumentDBResourceItem.ts), + and the same in the RU and VM items). +3. ARM clients are built through `createSubscriptionContext` ([azureClients.ts](../../../../src/utils/azureClients.ts) → + azext-utils `credentialUtils.js:33-44`). The credential wraps `subscription.authentication.getSession`, + which is the frozen session. +4. After the token expires, ARM answers 401 with a challenge. The azureutils 4.2.0 `BearerChallengePolicy` + (`createAzureClient.js:76-98`) calls `createCredentialsForScopes(challengeRequest)`, which leads to + `getSessionWithScopes(requestObject)`. azureauth 4.1.1 expects a list of scope strings and calls + `scope.endsWith(...)`, which throws **`TypeError: e.endsWith is not a function`**. azureutils + 4.2.0 is built against azureauth `^6.0.0-alpha.6`. +5. Diagnostics turns this into `target.sourceInaccessible` with reason `other`, which shows as + "Azure details unavailable". The TypeError has no HTTP status and no sign-in error name + ([resolveTarget.ts:52-82](../../../../src/connectionDiagnostics/checks/resolveTarget.ts), + [readCredentialsForDiagnostics.ts](../../../../src/tree/documentdb/readCredentialsForDiagnostics.ts)). +6. Refresh or Retry on a cluster node reuses the subscription stored on the item. Only listing the + subscriptions again creates a new session. + +azureauth 5.1.1, the latest stable version, still captures the token. **v6 (alpha) fixes this:** +`AzureSubscriptionProviderBase.getToken` calls `getSessionFromVSCode(..., { silent: true })` on every +call. Upgrading is tracked in [#990](https://github.com/microsoft/vscode-documentdb/issues/990). + +### Telemetry + +- `challenge=true` occurs only together with `challengeSuccess=false` and + `challengeError="e.endsWith is not a function"`. **There is no successful challenge** in the 28 days. + Affected events include `azure-discovery.getchildren` (12 machines), `connect` from vCore discovery + (8), `getcredentials` from RU discovery (8), and `azure-mongo-ru-discovery.getchildren` (3). +- 27 of the 350 machines that used Azure discovery were affected (about 8%). Onset was a median of + about 13 h after the session's first discovery event; the 25th percentile is 96 min. + +## 3. No recovery path, and stale references + +- `ClustersClient.getClient` returns the cached instance and calls `mongoClient.connect()` + ([ClustersClient.ts:571-619](../../../../src/documentdb/ClustersClient.ts)). That call does nothing + on a live topology. On a closed topology it reconnects with the same options, so with the same + stale callback. +- No error path evicts a client on code 18, code 391 or a network failure. `deleteClient` is called + only by Update Credentials ([updateCredentials.ts:142](../../../../src/commands/updateCredentials/updateCredentials.ts)), + Update Connection String, Remove Connection and Local Quick Start cleanup. +- The tree's **Retry** ([retryAuthentication.ts](../../../../src/commands/retryAuthentication/retryAuthentication.ts)) + only resets the node's error state and refreshes it. `getChildren` then reuses the cached client + and fails again ([ClusterItemBase.ts:358-447](../../../../src/tree/documentdb/ClusterItemBase.ts)). +- Different surfaces get their client differently: + - **`ClusterSession` holds a direct client reference.** Collection View queries and the AI + services use it ([ClusterSession.ts:65-78, 688-725](../../../../src/documentdb/ClusterSession.ts); + `initNewSession` is called from [openCollectionView.ts:67](../../../../src/commands/openCollectionView/openCollectionView.ts)). + - **These resolve the client per operation**, with no identity check: + - Document View ([documentsViewRouter.ts:54,91](../../../../src/webviews/documentdb/documentView/documentsViewRouter.ts)); + - the index and Query Insights routers; + - the Cluster Dashboard. + + After an identity change, these would quietly use the new identity. + +- The Cluster Dashboard `measureRtt` polls the cached client + ([clusterDashboardRouter.ts:221-225](../../../../src/webviews/documentdb/clusterDashboard/clusterDashboardRouter.ts)). + Polling backoff is tracked in [#1091](https://github.com/microsoft/vscode-documentdb/issues/1091). +- **Possible triggers for "Client must be connected before running operations"** (16 machines): + - `updateCredentials` calls `deleteClient` while Collection View tabs still hold the closed client. + - The `getClient` abort handler closes the **shared** cached client when someone cancels a cached + reuse ([ClustersClient.ts:586-592](../../../../src/documentdb/ClustersClient.ts)). +- There is no Disconnect command. It is proposed in [#1059](https://github.com/microsoft/vscode-documentdb/issues/1059), + and its overlap with Remove Connection is [#566](https://github.com/microsoft/vscode-documentdb/issues/566). +- Under sovereign-clouds decision D12 ([decisions.md](../sovereign-clouds/decisions.md)), open + shells snapshot their identity and token audience, and Update Credentials does not touch them. That + snapshot is a precedent for the identity binding proposed here. + +## 4. Native auth, RU and others + +- **Native (SCRAM):** idle socket closes recover on their own. Late failures are timeouts, which + points to sleep, VPN or idle firewalls. The code 18 errors appear about as often early as late, + so they point to changed credentials rather than expiry. +- **RU:** the extension authenticates with account keys only. These are fetched from ARM through + `listConnectionStrings` ([ruClusterHelpers.ts](../../../../src/plugins/service-azure-mongo-ru/utils/ruClusterHelpers.ts)). + Signing in to Azure matters only for discovery, which is defect #2. A regenerated key causes + code 18 until the client is recreated, which is defect #3. +- **Managed identity:** already correct. + +## 5. How telemetry reports this today + +- `connect.startup` masks its whole error, which is by design. Failure events after the connection + has been established carry neither `authMethod` nor connection age. Attributing them needs a join + on `connectionCorrelationId` (1.1.0+) or on `VSCodeSessionId`. +- `connectionCorrelationId` is present on only about 2% of the tree failures with code 18 in the + window. +- Webview RPC failures keep the real message only in `errorcause`. +- Some code 18 messages are replaced by the secret scanner. +- Diagnostics reports the ARM challenge crash as `other` instead of `signInRequired`. +- No event records "a client that had worked failed" or "recovered". + +## 6. How vscode-cosmosdb handles this (origin/main `3b19fd92`, 2026-11-19) + +- **Data-plane Entra tokens are never captured.** `aadCredentials.getToken` calls `getSessionFromVSCode` + on every request and returns `expiresOnTimestamp: 0` (`src/cosmosdb/getCosmosClient.ts:98-124`). + This is the pattern this plan adopts. +- **Prompting:** as a last resort, they call `createIfNone: true` from inside the token callback + (`getCosmosClient.ts:151-190`). That causes the open P1 microsoft/vscode-cosmosdb#3110: the sign-in + prompt keeps coming back after the session expires, even after the user dismisses it. Users ask for + a disconnected or read-only mode. **Avoid this.** +- **Subscriptions** come from the Azure Resources host extension, which owns token refresh. Their azext + major versions match (azureauth 5.1.1, azureutils 5, utils 5). +- **No client cache:** a new `CosmosClient` is created for each operation, and tabs hold a connection + descriptor. Cosmos traffic is stateless HTTP, so this works for them. It is **not** suitable for us; + see decision [0002](./decisions.md). +- **Query Editor connection state:** a `connectionVersion` counter. A connection change disposes its + sessions, and stale results are rejected with "These query results are no longer current. Run the + query again before using them." (`panels/trpc/queryEditorConnectionState.ts`). +- **Gaps they share with us:** + - Remove does not close or notify open tabs. + - There is no `onDidChangeSessions` listener. + - There is no identity binding: `getSession` is called without `account`, so a tab can quietly use + a different account. + - The shell receives a captured token. + +## 7. Cost of creating a client (why the cache stays) + +Successful `connect.startup` durations over the last 14 days. The value is `Measures.duration`, +read as seconds: + +| Auth | Startups | p50 | p90 | +| -------- | -------- | ------- | ------ | +| Native | 2,102 | ~1.1 s | ~4.3 s | +| Entra ID | 912 | ~2.0 s | ~9.0 s | +| No Auth | 188 | ~0.07 s | ~1.8 s | + +A `MongoClient` also owns cursors (Collection View pagination uses `getMore`), server sessions and +monitoring. A per-operation client would cost seconds per action and break pagination. + +## Appendix: queries + +The queries were run in the local telemetry dashboards devbox worktree, using the +`vscode-documentdb-telemetry-dashboards` skill. They are summarized here so they can be rerun. + +- **Failure signatures:** failed events whose `errormessage` or `errorcause` matches + `Authentication failed` or `error == "18"`, `connection … closed`, `ECONNRESET`, + `Client must be connected`, or `timed out`, grouped by event. +- **Attribution by session:** + - Failures joined to successful `connect.startup` (`startupoutcome == "succeeded"`) on + `VSCodeSessionId`, with `StartTs <= FailTs`. + - Only sessions where every startup used the same `authmethod`. + - Late means `FailTs - max(StartTs) >= 60 min`. +- **Histogram of the first failure:** sessions that used only Entra ID, from + `min(FailTs) - min(StartTs)`. +- **ARM challenge:** `Properties.challenge == "true"` or a non-empty `challengeerror`. Reach is + measured against machines with any Azure discovery event (`discoveryproviderid` starting with + `azure-`). From 4fe5a72c9a7ca41abd3559a1d5cfe2589a90e9b6 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 19 Nov 2026 10:41:09 +0000 Subject: [PATCH 002/380] wip: revisiting the plan --- .../features/connection-lifecycle/README.md | 2 + .../iterations/01-implementation-plan.md | 162 +++++++++++++----- 2 files changed, 124 insertions(+), 40 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/README.md b/docs/ai-and-plans/features/connection-lifecycle/README.md index 863d9401f..d9b8aa680 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/README.md +++ b/docs/ai-and-plans/features/connection-lifecycle/README.md @@ -45,6 +45,8 @@ Evidence, telemetry and source pointers: [research-findings.md](./research-findi - **Never change identity under an open surface.** It becomes disconnected, keeps its state, says why and offers one action. - **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. ## Documents 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 0f3c82754..c07b74abb 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 @@ -135,7 +135,8 @@ The goal is to open few PRs on top of other unmerged PRs. It is preferred, not r | 7 | WI-9 + WI-10: telemetry signals and dashboards, documentation | feature branch | PR 6 merged | | F | `feature/connection-lifecycle` → `main` | `main` | all merged, OT-1–7 passed | -- **PR 1, PR 2 and PR 3 run in parallel** and never stack. +- PR 1–3 can run in parallel if PR 0 agrees how WI-1 passes the verified account, provider and + tenant to WI-4. Otherwise, land PR 1 before PR 3; do not reconstruct the identity from a later cache read. - PR 4 to PR 7 are sequential, because each builds on the previous one. Under rule 1, local work on the next item may begin early, but its PR opens only after its base has merged. - **PR 5 is the largest.** If it becomes too large to review well, split it into host (5a) and @@ -184,25 +185,36 @@ The goal is to open few PRs on top of other unmerged PRs. It is preferred, not r error-translation skill) so every surface gets the same message: "Your Microsoft sign-in for '{cluster}' expired. Sign in again to continue." - **Unit tests:** - - A second callback invocation returns a new token. + - A second callback consults the provider again and uses its result; identical token bytes are + valid while the token is still good. - A silent miss gives the typed error, and `getSession` is never called with `createIfNone`. - A different account is reported as such. - The destination policy is still enforced. +**Driver verification gate:** in a local probe at `e22a39b8d`, driver 7.2.0 tried its cached token +on a new connection even with `expiresInSeconds: 0`. Code 18 on that token triggered the callback; +a transport failure did not. Returning the JWT lifetime alone does not meet #1102. Demonstrate +that a known-expired token is not offered on a new socket, including speculative authentication. +After a callback threw, the same driver workflow reused the rejection; a fresh workflow succeeded. +Test that explicit recovery replaces the failed workflow rather than retrying it indefinitely. + ## WI-2: Shell and Playground token relays use the same policy **Problem:** both relays call `createIfNone: true` inside the worker's token request ([ShellSessionManager.ts:450](../../../../../src/documentdb/shell/ShellSessionManager.ts), [PlaygroundEvaluator.ts:467](../../../../../src/documentdb/playground/PlaygroundEvaluator.ts)). -- Make the relay silent and pinned to the account in the session's D12 identity snapshot - ([sovereign-clouds decisions D12](../../sovereign-clouds/decisions.md)). +- Extend the [D12 snapshot](../../sovereign-clouds/decisions.md): it pins the audience today, **not** + the VS Code account. Capture the verified account ID, provider/cloud and tenant on initial + acquisition. Fail closed if the provider changes or the returned account does not match. - A miss puts the shell or playground into a "sign in again" state: a printed line and an action. It never opens a modal during a background refresh. - Fold in the #1059 note: `PlaygroundEvaluator.buildInitMessage` ([PlaygroundEvaluator.ts:288](../../../../../src/documentdb/playground/PlaygroundEvaluator.ts)) reads `CredentialCache` on every run. -- **Unit tests:** extend the existing relay tests to cover the silent miss and account pinning. +- **Unit tests:** the current worker IPC drops a sign-in-required error's type. Verify that a + bounded reason reaches the host action during both init and a warm evaluation. A healthy warm + worker must not need a new cache read; build its init message only when spawning it. ## WI-3: Azure discovery, azureauth v6 (#990, decision 0005) @@ -230,7 +242,12 @@ bundle, filter and cache behavior, and how to verify. Additions from this invest The place is `classifyResolutionFailure` ([resolveTarget.ts:52-82](../../../../../src/connectionDiagnostics/checks/resolveTarget.ts)). Keep it - bounded: an error name and status only, never messages (decision R2 in connectivity-troubleshooter). + bounded: an error name and status only in the report, never messages (decision R2 in connectivity-troubleshooter). + A local probe of `6.0.0-alpha.8` through `createSubscriptionContext` confirmed that a held + subscription looks up a session again. On a silent miss the actual exception had `name: "Error"` + and no HTTP status; the current test manufactures `name: "NotSignedInError"`. Use the package's + `isNotSignedInError` guard and test the real exception. A challenge can request interactive + step-up; do not infer that ARM discovery shares the database callback's no-prompt behavior. - **Unit test:** a stored subscription whose first token "expires" still lists clusters (mock the session sequence). @@ -248,6 +265,10 @@ In [ClustersClient.ts](../../../../../src/documentdb/ClustersClient.ts): - its creation time. The fingerprint is derived from **what was used to connect**, not from the current `CredentialCache`. + The helper alone returned `native:sam` for two hosts and two auth databases. Bind the logical + deployment plus the effective principal (including auth source); for tunnels use the provider's + target, not its temporary local port. Test managed identity using the actual runtime credential + shape, a password-only change, and the same username on a different deployment or auth source. - **Fix:** cancelling a _cached_ reuse must not close the shared client. - Pointer: the `getClient` abort handler at @@ -261,6 +282,10 @@ In [ClustersClient.ts](../../../../../src/documentdb/ClustersClient.ts): - **Telemetry base:** one helper adds `authMethod`, `connectionAgeMs` and `clientGeneration` to any failure that happens after the connection was established. The surfaces in WI-5 and WI-6 call it. Follow the telemetry-instrumentation skill; property names must not contain "error" (masking). +- **Concurrent startup and teardown:** two deferred cold gets produced two clients, and a pending + connect repopulated the cache after deletion completed. Share one startup per cluster; invalidate + the generation before teardown awaits and check it before publishing or returning a client. + Test a late startup after Disconnect, an old Retry after replacement, and cancelling one of two waiters. - **Optional test hook, development only:** a command that makes the Entra callback return an invalid token N times and drops pooled connections. It lets WI-5 and WI-6 be checked in minutes instead of 90. @@ -286,19 +311,24 @@ In [ClustersClient.ts](../../../../../src/documentdb/ClustersClient.ts): - Same account: evict and create a new generation. Surfaces continue (WI-6). - Different account: treat it as an identity change (decision 0003). - **One** prompt per user click. Dismissing it is respected: no reprompt until the user acts again. + - `createIfNone` can return an existing session. Test a still-present but rejected token as well + as a missing session; prove that the explicit action obtains usable credentials in both cases. - **The tree's Retry must actually reconnect.** - [retryAuthentication.ts](../../../../../src/commands/retryAuthentication/retryAuthentication.ts) and the cached-client path in [ClusterItemBase.ts:358-447](../../../../../src/tree/documentdb/ClusterItemBase.ts) should evict the client when the last failure was `signInRequired`, `credentialsRejected` or `clientClosed`. - Keep the cached credentials (#1059 open question 1: dropping the client is not the same as - forgetting the credentials). + forgetting the credentials). Exception: for a rejected RU Discovery key, explicit recovery must + reread the primary key from ARM once, not reuse the cached key or open a password wizard. + Test an old/new key pair and distinguish an ARM sign-in failure from database rejection. - Add **Sign in again** to `createErrorRecoveryChildren` ([ClusterItemBase.ts:304-326](../../../../../src/tree/documentdb/ClusterItemBase.ts)), following the "actions only" order in the tree-cluster-architecture skill: repairs first, Retry last. - **`vscode.authentication.onDidChangeSessions`:** when the bound Entra account disappears, mark its clients `signInRequired`. Never sign the user out, and never remove sessions (#1059 "must NOT be - touched"). + touched"). The event identifies the provider, not the removed account. Silently recheck affected + bindings and ignore results from stale generations; another account's change must not disconnect this one. - **Unit tests:** - classifier table tests; - Retry after `clientClosed` produces a new generation; @@ -325,11 +355,13 @@ The largest item. Host side first, then each view. - Outcomes: - same fingerprint and generation: proceed; - - same fingerprint, new generation: proceed, and re-run reads from page 1 because cursors are - lost, with a notice in the spirit of Cosmos's "results are no longer current"; + - same fingerprint, new generation: re-run the applied query from page 1 with a notice that + results are no longer current. Pages use separate offset queries, not a cursor held between + pages. Discard old-generation responses on both host and UI; preserve unapplied editor text; - different fingerprint, or no client: **disconnected**, with a reason. - - **Writes are never replayed.** A write with an unknown outcome is reported as failed, and the - message says the outcome is unknown. + - **The extension never resubmits a write with an unknown outcome.** Report the outcome as + unknown, not as a definite failure. The driver can retry the same logical write or handle 391 + internally; test one application submission when the server accepts a write but its reply is lost. - **Webviews:** - Push one connection-state channel per view over tRPC: connected, reconnecting, or disconnected @@ -341,43 +373,60 @@ The largest item. Host side first, then each view. - Views: Collection View (query, documents, indexes and Query Insights tabs), Document View (dirty editor) and the Cluster Dashboard. - Accessibility: announce the state change (accessibility skill; live region). -- **Long-running tasks** (copy and paste, import, export, index copy; - [DocumentDbDocumentReader.ts](../../../../../src/services/taskService/data-api/readers/DocumentDbDocumentReader.ts)): - they resolve a client for each batch. A fingerprint change fails the task with a clear reason and - never resumes under the new identity. The cancel-or-ask policy belongs to WI-7. +- **Transfer scope:** copy and export may keep their current client or stream. Do not redesign + transfers to rebind per batch or resume after Disconnect. Protect active tasks from an explicit + disconnect using the existing resource-conflict check in WI-7. An unexpected connection loss + is not permission to restart a transfer under another identity. - **Tests:** - router tests for the three binding outcomes; - a Collection View scenario: disconnected banner with the query text kept; - a Document View scenario: dirty edit kept; + - inject a disconnect after typing, then deliver a stale page or document read; neither applied + results nor drafts may be overwritten, and disabled actions must issue no server calls; - scenarios run through the L2-dev runner (`/scenarios/`, see the copilot instructions). ## WI-7: Teardown service, Disconnect, Remove and Update Credentials (#1059, #566, decisions 0003, 0004) -- **One teardown**, keyed by `clusterId` and matched case-insensitively. Remove = teardown + delete + - clear schema; Disconnect = teardown only. - - Follow the full #1059 checklist: client, shells, playground, webviews, tasks, in-flight token +- **One teardown**, keyed by stable `clusterId`, with provider-specific equality. Azure case aliases + must match, but folding Kubernetes context IDs such as `Prod` and `prod` would target different + resources together. Remove = teardown + delete + clear schema; Disconnect = teardown only. + - After the task-conflict preflight below, tear down the client, shells, playground, webviews, in-flight token requests (sovereign-clouds finding E4), `CredentialCache`, the Entra failure registry, and the `SchemaStore` decision. - Its "must NOT be touched" rules apply: VS Code auth sessions, the managed identity cache, the ARM cache. - **Disconnect command** on connected clusters in the Connections, Azure Resources and Discovery views. + - **Check for active tasks first.** Reuse + [`checkCanProceedAndInformUser({ clusterId }, …)`](../../../../../src/services/taskService/resourceUsageHelper.ts) + as [Remove Connection](../../../../../src/commands/removeConnection/removeConnection.ts) already + does. If a copy or export uses this cluster, name the conflicting task and leave **both the task + and connection running**. The user can retry Disconnect after the task finishes or they stop it. + Do not offer force-disconnect or automatically cancel the task. Verify that export registers its + source and copy registers both endpoints; fill registration gaps rather than changing transfer logic. - Use dashed context keys (manifest rule in the copilot instructions). - When surfaces are open, ask the user: **Close all** or **Keep open (disabled)** (decision 0004; default and remembering per Q2). - - Close all must not throw away unsaved document edits without the usual dirty-editor confirmation. + - Document View is a plain webview panel: `dispose()` has no dirty-editor veto. For Close all, + confirm unsaved edits **before** disposing any panel or changing the connection. Cancelling leaves + every panel, draft and connection intact, including when Remove initiated teardown. - **Update Credentials** ([updateCredentials.ts:142-185](../../../../../src/commands/updateCredentials/updateCredentials.ts)) and Update Connection String compare the old and new fingerprints: - **same:** the client is replaced and tabs continue; - - **different:** teardown with reason "credentials changed", offering the same Close/Keep choice. + - **different:** before saving, run the same task and dirty-panel checks as Disconnect. If approved, + tear down with reason "credentials changed", offering the same Close/Keep choice. + - Only replace the client after the credential save succeeds; test that a failed save leaves the + old binding usable and a concurrent connect cannot publish the previous credentials after replacement. Today's D12 modal for open shells offers Disconnect as a button (#1059). - **Telemetry:** one event with the activation source and teardown counts. No identifiers (#1059). - **Tests:** - teardown per surface; - - IDs that differ only in case; + - Azure case aliases vs distinct Kubernetes context IDs; + - Disconnect blocked for copy source, copy destination and export source; an unrelated cluster + is not blocked. After the task finishes or is stopped, retrying Disconnect succeeds; - a late token response after Disconnect is ignored; - reconnecting uses the current credentials and cloud settings; - Remove reuses the same teardown. @@ -391,24 +440,46 @@ Coordinate with #1091. The minimum for this plan: dashboard shows the WI-6 banner instead of starting a connection every 5 s. Visibility pause and backoff are the rest of #1091 and may ship separately. - -## WI-9: Telemetry check - -- **New signals:** - - `connection.recovered`, with its trigger (silent renewal, reconnect, sign in again); - - silent-renewal outcomes. Use counters with `accumulateTelemetry` on the hot path, or one event - per miss; - - the Disconnect event; - - the WI-4 enrichment on failures after connect. -- **Dashboards:** extend the errors recipe in the telemetry-dashboards skill (devbox worktree) - with: - - late failures after connect, by auth method; - - successful ARM challenges; - - recoveries. -- **After the pre-release:** rerun the research queries (research appendix). Expected: - - Entra-only sessions show almost no late code 18 or socket-closed failures; - - `challengeSuccess=true` appears; - - "Client must be connected" disappears. +Existing visibility and in-flight guards do not distinguish a missing ping sample from terminal +auth failure. With fake timers, verify no client lookups on ticks or reveal after Disconnect, +that a late successful ping cannot clear the banner, and that reconnect starts only one poll loop. + +## WI-9: Measure token renewal and recovery after release + +The [existing correlation IDs](../../../telemetry-correlation-ids.md) identify a client or worker +startup and optionally link it to cluster metadata. They do **not** tell us when a token changed, +how long it was valid, or whether the database worked afterward. Reuse `startupCorrelationId` +for drill-down and `connectionCorrelationId` where already available; the headline metrics below +must be queryable without a join or a new persistent identifier. + +- **When did a refresh happen?** Emit `connection.tokenRenewal` once per completed post-startup + Entra database token lookup (host, shell or playground), not per query or dashboard tick. + Use the event timestamp, `surface`, and one bounded `renewalOutcome`: `changed`, `unchanged`, + `noSession`, `identityMismatch`, `failed`, or `unknown` when there is no prior observation. + Compare only within the same binding. Exclude initial acquisition; count a valid unchanged + token as successful reuse, **not** a refresh. `changed` means the extension received a + different token, not that it observed an MSAL network request. Count successes as well as misses. +- **What was the lifetime?** On that same event record numeric measurements, not timestamps: + `connectionAgeMs` (age of this client/worker at lookup), `previousTokenObservedAgeSeconds` + (time since the previous token was first seen, not reset by unchanged lookups), + `tokenLifetimeSeconds` (returned token's `exp - iat`) and `tokenRemainingSeconds` (`exp - now` + at lookup). Omit unavailable or invalid measurements; never substitute a worker fallback TTL + or zero for unknown. Do not retain tokens just for telemetry or send token values, hashes, raw + claims, account/tenant IDs, cluster IDs, fingerprints or hostnames. +- **Did the connection actually recover?** Emit `connection.recovered` once on the first successful + database operation after a pending recovery, with trigger (`silentRenewal`, `reconnect` or + `signInAgain`) and `connectionAgeMs`. A callback returning a token is not that success. Keep + WI-4's classified post-connect failures and WI-7's Disconnect event. Report ARM challenges + separately from database renewal and verify the final ARM request, not just token acquisition. +- **Release dashboard and acceptance:** check in runnable queries that show daily renewal outcomes + and changed-token rate (`changed / all completed lookups`), plus p50/p90 token lifetime, + remaining validity and connection age at refresh, split by version and surface. Show sample + counts and missing timing data alongside percentiles. Trend confirmed recoveries by trigger and + late auth/socket/closed-client failures against the pre-release baseline using the same exposure + denominator. No lookups or no subsequent operation is **no evidence**, not success. + Before rollout, use a fake clock and token sequence (unchanged → changed → silent miss) to + verify counts and units; include an opaque token and a database rejection after lookup. Verify + the dashboard can read the classified fields from pre-release ingestion before judging outcomes. ## WI-10: Documentation @@ -457,6 +528,17 @@ least once. **After release** (telemetry, operator with Kusto access): run the WI-9 queries on the pre-release cohort. +**Evidence required for the matrix:** exercise both idle and dropped data-plane connections for +each supported backend/auth pair. For OT-1 record a new handshake or callback after the wait +(never log tokens): a successful read on an existing socket does not prove renewal. For OT-2 +distinguish local sign-out from remote revocation; their timing is not established. For OT-5 +force a new handshake after rotation. For OT-7 also try Disconnect during a tracked copy/export: +verify it is blocked before the Close/Keep prompt and the task continues. + +For WI-9, `challengeSuccess=true` means a challenge token was obtained, not that ARM accepted the +retried request. Check the final operation too. Record the cohort query, time window and exposure +denominator; a cohort with no challenges is inconclusive, and timing alone does not establish cause. + --- ## Open questions (to settle before or during WI-5 and WI-7) From 30caf2149008020ebdee2b41e941ba1e581fb1ed Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 19 Nov 2026 12:07:46 +0000 Subject: [PATCH 003/380] wip: revisiting the plan --- .../features/connection-lifecycle/README.md | 1 + .../iterations/01-dev-plan.md | 1219 +++++++++++++++++ .../iterations/01-implementation-plan.md | 6 +- 3 files changed, 1225 insertions(+), 1 deletion(-) create mode 100644 docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md diff --git a/docs/ai-and-plans/features/connection-lifecycle/README.md b/docs/ai-and-plans/features/connection-lifecycle/README.md index d9b8aa680..2d4e2f685 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/README.md +++ b/docs/ai-and-plans/features/connection-lifecycle/README.md @@ -55,6 +55,7 @@ Evidence, telemetry and source pointers: [research-findings.md](./research-findi | [research-findings.md](./research-findings.md) | research | | [decisions.md](./decisions.md) | decisions | | [iterations/01-implementation-plan.md](./iterations/01-implementation-plan.md) | plan | +| [iterations/01-dev-plan.md](./iterations/01-dev-plan.md) | plan | ## Decisions index 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 new file mode 100644 index 000000000..c8fd92362 --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md @@ -0,0 +1,1219 @@ +--- +feature: connection-lifecycle +kind: plan +status: active +created: 2026-11-19 +code: + - src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts + - src/documentdb/auth/oidcClientOptions.ts + - src/documentdb/auth/connectionAuthIdentity.ts + - src/documentdb/auth/tokenExpiry.ts + - src/documentdb/ClustersClient.ts + - src/documentdb/ClusterSession.ts + - src/documentdb/CredentialCache.ts + - src/documentdb/shell/ShellSessionManager.ts + - src/documentdb/playground/PlaygroundEvaluator.ts + - src/documentdb/playground/playgroundWorker.ts + - src/documentdb/playground/workerTypes.ts + - src/tree/documentdb/ClusterItemBase.ts + - src/commands/retryAuthentication/retryAuthentication.ts + - src/commands/updateCredentials/updateCredentials.ts + - src/commands/removeConnection/removeConnection.ts + - src/services/taskService/resourceUsageHelper.ts + - src/webviews/documentdb/collectionView/collectionViewRouter.ts + - src/webviews/documentdb/documentView/documentsViewRouter.ts + - src/webviews/documentdb/clusterDashboard/clusterDashboardRouter.ts + - src/plugins/api-shared/azure/AzureSubscriptionProviderWithFilters.ts + - src/connectionDiagnostics/checks/resolveTarget.ts +--- + +# Iteration 1, dev plan: how to execute the connection lifecycle work + +> This is the execution guide for the approved [01-implementation-plan.md](./01-implementation-plan.md). +> That plan says **what** to build and in which PRs. This file says **how** for each work item: what to read +> first, ordered steps, the contracts that cross PRs, tests, the done criteria, and the points where the +> advisor must decide. Work-item numbers (WI-n), PR numbers and OT-n acceptance tests are the same as in +> the approved plan. Decisions are in [../decisions.md](../decisions.md), evidence in +> [../research-findings.md](../research-findings.md). Neither is repeated here. + +Written at `4fe5a72c9` (branch `tnaum-ms/issue1102`). Line numbers will drift; function names are the +stable pointers. + +## 0. How to use this document + +### Authority and deviation + +1. **Accepted decisions 0001–0006 bind you.** You cannot change them on your own. If the code shows one of + them is wrong or cannot be met, stop and raise it with the operator, giving evidence and alternatives. + The advisor cannot overrule an accepted decision. +2. **The approved plan's content binds you**, except where §3 (Tensions) names a conflict. There the advisor + decides at the named checkpoint. If that changes the intent of an accepted decision, the operator + confirms, as rule 1 requires. +3. **Everything in this dev plan is guidance.** That includes steps, file names, helper names and contract + field names. You may deviate when the advisor agrees. Record each deviation **inline, under the work + item's Progress block**, naming the alternatives you considered and why each was rejected + (knowledge-base rules, [docs/ai-and-plans/README.md](../../../README.md)). Never rewrite the plan text + to match what happened. +4. **The provisional answers in §1 are not decisions.** Implement them as written, keep them easy to change + (one constant, one setting, one branch of code), and list them in every PR description until the + operator confirms them. Once confirmed, append a decision entry to `decisions.md`. + +### Progress recording + +Each work item ends with a **Progress** block. When you commit a step, add a line there that names the +commit SHA, what landed, and anything that differed from the plan. Each checkpoint (§5) also writes its +verdict there. At the hand-over, add an `# Outcome` chapter to the end of this file: what was verified, +and just as plainly, what was not. + +### Per-PR workflow + +- **Branch:** create `dev/tnaum/` from `feature/connection-lifecycle`. Follow the approved plan's + rules for keeping PRs off each other. +- **Commits:** one or more commits per WI, never one commit that mixes two WIs. Each commit ends with the + `Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>` trailer. +- **While working, and for draft PRs:** Case 1 only: `npm run build` plus `npx vitest run `. + If you edit `packages/*/src`, run `npm run build` in that package before the root tests; root tests + import the package's `dist`. +- **Ready for review:** Case 2 in full (copilot instructions). Run `npm run l10n` before `l10n:check` + whenever a `vscode.l10n.t()` string changed. +- **AI pre-review:** run the review (CONTRIBUTING §6) and commit it as + `iterations/01-pr--review.md`, for example `01-pr1-entra-renewal-review.md`. When this folder + reaches three or more iteration-1 documents, ask the operator before promoting it to an + `iterations/01-…/` folder. Moving the files breaks links in the issues. +- **PR description:** name the WIs, the provisional answers (§1) the PR relies on, the checkpoint verdicts + it implements, and which verification case ran. + +### Skills to load per work item + +| WI | Load before starting | +| ----- | -------------------------------------------------------------------------------------------- | +| WI-1 | error-translation, telemetry-instrumentation | +| WI-2 | error-translation | +| WI-3 | flagging-fresh-dependencies (lockfile audit), error-translation | +| WI-4 | tree-cluster-architecture, telemetry-instrumentation | +| WI-5 | tree-cluster-architecture, error-translation, telemetry-instrumentation | +| WI-6 | webview-trpc-messaging, react-webview-architecture, fluentui, detecting-accessibility-issues | +| WI-7 | tree-cluster-architecture, webview-trpc-messaging, telemetry-instrumentation | +| WI-8 | webview-trpc-messaging, react-webview-architecture | +| WI-9 | telemetry-instrumentation | +| WI-10 | writing-release-notes, documentation-screenshots, previewing-docs-site, skill-creator | + +--- + +## 1. Provisional answers to the open questions + +The operator was not available on 2026-11-19. These are the recommended answers, adopted provisionally +under rule 4 above. + +| # | Question | Provisional answer | Where it lands | +| --- | ---------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------- | +| A1 | Plan Q1: how does sign-in start after a silent miss? | **Only through the Sign in again button**, everywhere. The first connect from the tree stays interactive, as it is today. One rule, and no surface has to decide whether it is in the foreground. This matches 0001. | WI-1, WI-2, WI-5, WI-6 | +| A2 | Plan Q2: Disconnect choice, default and memory | Ask every time. **Keep open (disabled)** is pre-selected the first time; after that, the last choice is pre-selected. The choice is stored under one `globalState` key (pattern: `switchAtlasViewMode.ts`). No setting. | WI-7 | +| A3 | Plan Q3: does Disconnect drop `CredentialCache`? | **Yes** (#1059 proposal). Saved connections reload from storage on the next expand. A password typed only for a discovery connection must be typed again. Implement it as a teardown option, so flipping the answer is a one-line change. | WI-7 | +| A4 | #990: which azext versions? | **Probe both, default to the minimal option:** azureauth `6.0.0-alpha.8` (already nested in the lockfile), keeping azureutils `4.2.x` and utils `4.1.x`. Choose the full v5 line only if the probe shows that the minimal option keeps two azureauth copies or needs a shim. | WI-3 (CP-W3) | +| A5 | How does Disconnect see an in-flight Export? | A small **resource lease** API on `TaskService`. Export holds the lease while it runs, and `checkCanProceedAndInformUser` reports it like a task. Export logic is not touched. | WI-7 | +| A6 | Where do the dev plan and its progress notes live? | In this file. Progress is recorded inline per WI here. The approved plan gets a one-line pointer. | — | + +--- + +## 2. Facts established while writing this plan + +These were verified at `4fe5a72c9` with mongodb driver 7.2.0. They shape the steps below. If a dependency +upgrade changes any of them, stop and re-plan the affected WI. + +- **F-1. One failed OIDC callback breaks that `MongoClient`'s Entra authentication for good.** + - Where: `node_modules/mongodb/lib/cmap/auth/mongodb_oidc/callback_workflow.js`, `withLock`. It runs + `await lock` _before_ it reassigns `lock`, so after one rejection every later callback call throws the + same rejection again. + - This is the "same workflow reused the rejection" result of the earlier probe. + - Consequence: the only way to recover after the callback throws is a **new `MongoClient`**, that is, a + new generation. It applies to every throw, including transient Entra errors. +- **F-2. The driver ignores `expiresInSeconds` in the automated workflow.** + - `token_cache.js` stores the value, but `AutomatedCallbackWorkflow.execute` never reads it. + - `CallbackWorkflow.speculativeAuth` sends the cached token on **every new socket**. + - Code 18 drops the cached token and calls the callback again. A transport failure does not. + - Code 391 goes through `reauthenticate`. + - So no `OIDCResponse` value alone can stop an expired token from being offered. +- **F-3. `getSessionFromVSCode` reads the auth provider ID that is configured _at call time_.** + - Where: azureauth 4.1.1 `getSessionFromVSCode.js` calls `getConfiguredAuthProviderId()`. + - If the user changes their sovereign-cloud setting after connecting, a callback would ask a different + provider. That breaks the identity pin. + - The deep import path `@microsoft/vscode-azext-azureauth/out/src/getSessionFromVSCode` does not exist + in v6; it moved to `dist/esm/src/utils/`. + - `vscode.authentication.getSession` supports `account` (engine `^1.109.0`). +- **F-4. Cluster ID equality differs by store.** + - `CredentialCache` and the Entra failure registry use case-insensitive maps. + - `ClustersClient._clients`, `ClusterSession._sessions` and `SchemaStore` (prefix `${clusterId}::`) match + exactly. + - Kubernetes IDs keep the context's case (`kubernetes_${source}_${context}__…`), so `Prod` and `prod` + already collide in `CredentialCache` today. +- **F-5. There is no per-cluster registry of open webview panels.** + - Only the Cluster Dashboard keeps its own `openPanels` map (`clusterDashboardController.ts`). + - Collection View and Document View open through `openAppWebview`, whose handle exposes `onDisposed`. +- **F-6. Collection View sessions.** + - `ClusterSession` sessions are keyed by a random session ID and **hold** a `ClustersClient`. + - `openCollectionView.ts` calls `closeSession` when the panel is disposed. + - Paging uses **offset queries**: `skip = querySkip + (page - 1) * pageSize`. No cursor is held between + pages. +- **F-7. The Cluster Dashboard health poll runs in the webview, not the host.** + - Where: `ClusterDashboard.tsx`, the interval effect around `refreshIntervalMs`. + - The host procedure `measureRtt` resolves the client for every tick, with trigger `clusterDashboardPoll`. +- **F-8. Worker IPC loses error types.** + - `tokenError` carries only a message, plus `errorName` for one value: destination rejection. + - `initResult` and `evalError` carry strings only. + - The playground rebuilds its init message from `CredentialCache` on **every run** + (`PlaygroundEvaluator.evaluate` → `buildInitMessage`), even when the worker is warm. +- **F-9. Task coverage.** + - Copy/paste and copy-indexes register both endpoints through `getUsedResources()`. + - **Export is not a task.** `exportDocuments.ts` calls `getClient` directly and registers nothing. +- **F-10. Remove Connection does not close the client, shells, the playground or webviews.** It deletes + storage, `CredentialCache` and `SchemaStore` data only. +- **F-11. Credential updates.** + - Update Credentials saves first, then calls `deleteClient`, then shuts down the playground. It only warns + about shells (the D12 modal). + - Update Connection String deletes the client only when recovering a rejected destination. +- **F-12. Errors lose their identity at the tRPC boundary.** + - Errors arrive rebuilt as `{ code, name, message, stack, cause }`. + - Webview RPC telemetry records the tRPC code as `error` (`src/webviews/_integration/trpc.ts`). + - So a disconnected reason must reach a webview as **structured data**, never as an error that the + webview has to recognize. +- **F-13. About 35 other `getClient` call sites are not open surfaces, but some of them are background + work.** + - One-shot user commands: create/delete database and collection, import, index commands, LLM commands, + paste. They act on the current client, so WI-6 does not bind them. + - **Background callers:** playground completions (`CollectionNameCache.ts`, an explicit background + lookup), tree count badges and prefetches. + - Today **every** startup is interactive: `initializeClient` hardcodes `{ interactive: true }`. A + background caller can therefore reconnect, or even prompt, after an eviction or a Disconnect. + - So the interaction policy and the disconnected latch must be enforced **centrally in `getClient`** + (C-6), not per caller. +- **F-15. A stopped worker respawns by itself.** + - `ShellSessionManager.evaluate` re-initializes a dead or stopped worker from the current + `CredentialCache`. `executePlaygroundCode.ts` recreates the evaluator in the same way. + - "Stop the worker" alone therefore keeps neither a shell nor a playground disconnected. Without a + latch, it silently adopts new credentials on the next command. +- **F-16. The host rebuilds worker errors as generic errors.** + - `WorkerSessionManager` turns `initResult` and `evalError` into a plain `Error`. Only + `EntraDestinationRejectedError` keeps its name. + - New IPC fields are lost unless this layer is changed too. +- **F-17. The native authentication database follows the driver's rules.** + - With no explicit `authSource`, the driver uses the URI's database path (`connection_string.js`, around + line 307). Only when there is none does it use `admin`. + - The same user on `/sales` and on `/admin` is therefore two different principals. +- **F-18. Cluster ID matching is inconsistent across stores.** + - `CredentialCache.deleteCredentials` lowercases its key (`CaseInsensitiveMap`), so deleting Kubernetes + context `prod` also deletes `Prod`. + - Task conflict matching (`hasResourceConflict` in `taskServiceResourceTracking.ts`) compares IDs + exactly, so it misses Azure case aliases. + - One equality function in the teardown cannot fix either problem. +- **F-19. Credential saves can fail without the command knowing.** The Update Credentials `ExecuteStep` + catches save failures and returns normally, so the command cannot tell whether the save happened. +- **F-14. VS Code has no API to collapse one tree node.** + - The repository uses `reveal(..., { expand: false })`, which does not collapse a node. + - Collapsing through a changed `TreeItem.id` would conflict with the `treeId`/`clusterId` rules. + +--- + +## 3. Tensions between the approved plan and the code + +| # | Tension | Decided at | Recommendation | +| --- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| T-1 | WI-1 requires that a known-expired token is never offered on a new socket. Under F-2 that is only possible with a new `MongoClient` once the issued token expires, roughly once an hour. Decision 0002 says that a new generation re-runs reads from page 1 "because cursors are lost", but under F-6 no surface holds a cursor. Applying 0002 as written would show "results are no longer current" every hour (worse for OT-1). | CP-0 | Distinguish **token rotation** (same fingerprint, planned replacement) from **recovery**. Neither re-runs a query, because paging is offset-based. Show the "results are no longer current" notice only when a surface comes back from the **disconnected** state. This clarifies the intent of 0002, so the operator confirms it as a new decision entry. **Coverage caveat:** rotation at resolution time covers host operations only. Sockets opened by driver pool maintenance (`minPoolSize`), and the shell and playground workers' own driver token caches, still offer the cached token. CP-0 must show that every path is covered, or the operator must explicitly relax the guarantee for that path. A timer-based rotation would resemble the "proactive refresh timers" that 0001 rejected, so it also needs the operator. | +| T-2 | OT-7 expects the cluster node to "collapse" after Disconnect, but VS Code cannot collapse a single node (F-14). | CP-4 | Refresh the node. A disconnected cluster returns **one** child action, "Connect", following the actions-only rule. Its handler reconnects and refreshes. Do not change `TreeItem.id`. Update OT-7's wording at hand-over. | +| T-3 | WI-7 must not fold Kubernetes context IDs, but `CredentialCache` already folds them, and task matching does not fold Azure aliases (F-4, F-18). | CP-1, CP-4 | Introduce **one canonical cluster key** in WI-4: `canonicalClusterKey(clusterId)`, lowercase for Azure IDs, exact for everything else. Key every **new** map with it (generations, pending startups, state, registry). In WI-7, apply it to the stores the teardown touches: `CredentialCache`, the Entra failure registry, `SchemaStore`, `ClustersClient._clients`, and task and lease conflict matching. Add migration-safe tests for `Prod`/`prod` and for Azure case aliases. If this grows beyond those stores, raise it with the operator. | +| T-4 | Under decision 0002, a classified failure evicts and replaces the client. A background caller such as the dashboard poll or tree count badges could therefore start a new connection every tick. | CP-2 | Only a **foreground** operation, or the rotation in T-1, replaces a generation. Background callers read the state and stop (WI-8). Add a per-cluster backoff of one replacement per 30 s, as a guard against loops. | +| T-5 | For Entra, code 18 after the driver's own fresh callback means the server rejected a _fresh_ token: the principal has no database user, or Conditional Access or CAE intervened. That is not the same as `signInRequired`. | CP-2 | Classify it as `credentialsRejected` with an Entra-specific explanation ("Your account has no access…"). Offer **Sign in again** only when the token came from a session the user can replace. Decide this with the real driver error shapes collected for CP-0. | + +--- + +## 4. Contracts that cross PRs + +The approved plan lets PR 1–3 run in parallel "if PR 0 agrees how WI-1 passes the verified account, +provider and tenant to WI-4". These contracts are that agreement. The field names are illustrative; the +semantics are binding unless a checkpoint changes them. + +- **C-1. Verified identity.** + - WI-1 produces it on the first successful Entra acquisition: + `{ kind: 'entra', providerId, accountId, accountLabel, tenantId? }`. + - `providerId` is the provider that was **actually used**, never re-read later (F-3). + - It is returned on `AuthHandlerResponse` as an optional field. + - Native, managed identity and no-auth handlers return nothing; WI-4 derives their identity from the + credentials used. + - WI-2 builds the same shape at worker spawn. + - Never logged, never sent to telemetry, never persisted. +- **C-2. Typed auth errors.** + - One error class per outcome, each with a stable `name` and a bounded `reason`: + - `EntraSignInRequiredError`, reason `noSession | providerChanged`; + - `EntraIdentityMismatchError` (a different account came back); + - `EntraTokenRefreshError` (any other failure of the lookup; the cause is kept, but it is never + rendered raw). + - Messages are localized. Classification uses the `name` (walking `cause`), never the message. + - All three are "callback threw" for F-1. + - Keep the existing `AuthInputUnavailableError` for the non-interactive startup path (diagnostics). + Either make the new errors related to it or map between them explicitly, so the Entra failure registry + still skips silent misses (comment in `MicrosoftEntraIDAuthHandler.configureAuth`). +- **C-3. Token lookup observation.** + - Every **completed** post-startup token lookup notifies an optional host-only observer, whether it + succeeded or failed: + `{ outcome: 'returned' | 'noSession' | 'identityMismatch' | 'failed', issuedAtSec?, expiresAtSec?, changed: boolean | 'unknown' }`. + - `changed` means "a different issuance": the JWT `iat` or `exp` differs from the previous token + returned in the same binding. It is `'unknown'` when either token is opaque, or when there is no + earlier observation. + - Byte equality is **not** established. Nothing about a token is retained except the previous `iat` and + `exp` numbers. + - The observer never receives the token, a hash of it or any other claim. + - WI-4 uses it for T-1 rotation; WI-9 uses it for `connection.tokenRenewal`, including the miss outcomes. +- **C-4. Binding.** + - Its form is `{ clusterId, fingerprint, generation }`. + - **`fingerprint`** is an opaque hash of the logical deployment plus the effective principal (WI-4). It + never contains a password and is never sent to telemetry. + - **`generation`** is a per-cluster number that only ever increases. It is **never reset**, not even + after teardown. A binding from before Disconnect therefore never matches a client created after + Reconnect. +- **C-5. Connection state, at two levels.** + - **Cluster state** is owned by the host and keyed by canonical cluster key. It describes the cluster's + current client: `connected { binding }`, `reconnecting`, `needsAction { reason }`, or + `disconnected { reason }` (the latch, C-6). + - **Surface state** is **derived for each registered binding**. It is what the tree, webviews, shells + and the playground show: + - `connected`; + - `reconnecting`; + - `disconnected { reason, action }`. + - A surface whose fingerprint differs from the cluster's current binding is + `disconnected(identityChanged | credentialsChanged)` **even while the cluster is `connected`**. This is + what lets the tree and new panels run as identity B while panels opened as A stay disabled. + - `reason` is one of: `signInRequired`, `credentialsRejected`, `credentialsChanged`, + `identityChanged`, `userDisconnected`, `connectionRemoved`, `unreachable`. + - `action` is one of: `reconnect`, `signInAgain`, `updateCredentials`, `close`. + - Reasons are bounded enums. The webview gets the localized text from the host. +- **C-6. Central interaction and latch policy, enforced inside `ClustersClient.getClient`.** + - **Interaction:** + - every call states `interaction: 'allowed' | 'never'`, and the default is `'never'`; + - `'allowed'` may prompt **only** when the cluster has no `lastVerifiedIdentity` (a first connect); + - once an identity is verified, reconnects are silent and pinned whatever the caller asked for; + - interactive sign-in after that happens only in the Sign in again command (A1). + - **Latch:** while a cluster is `disconnected` (Disconnect, Remove, a credentials change), `getClient` + rejects every caller with a typed `ClusterDisconnectedError`. Background callers are included. Only + the explicit Connect and Reconnect actions clear the latch. + - **Lifecycle epoch:** a per-cluster counter that increases on every latch, unlatch, eviction and + teardown. Every recovery command (Retry, Sign in again, Reconnect) captures the epoch **before** its + first `await`, and applies its result only if the epoch is unchanged (compare and swap). + +--- + +## 5. Advisor checkpoints + +Each checkpoint is a short written verdict recorded in the Progress block of the WI named. Until the +verdict exists, do not start the work it gates. + +| CP | When | Question | Evidence required | +| ----- | --------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| CP-0 | WI-1, after step 1, before the handler is changed | Which strategy for expired tokens (T-1)? Confirm F-1 and F-2 with the driver contract test. | Contract test output, plus, if available, an Azure DocumentDB handshake log after expiry (no tokens logged). If T-1 changes the intent of 0002: the operator's answer. | +| CP-W3 | WI-3, after the version probe | Which azext versions (A4)? | `npm ls @microsoft/vscode-azext-azureauth`, bundle scan for duplicate copies, size of the build-error list for each option. | +| CP-1 | Before PR 3 opens | Does C-1 work for every auth method, including the managed identity runtime shape and tunnels? | Fingerprint table tests (WI-4 step 1). | +| CP-2 | WI-5, after the classifier is drafted, before recovery is wired | The classifier table, T-4 and T-5. | Classifier table tests run on **real** driver error shapes captured by the contract test and the tree paths. | +| CP-3 | Before WI-6 webview work | Split PR 5 into 5a/5b? Is the binding-resolution API and state channel final? | Diff size of host-only work; one router converted end to end. | +| CP-4 | Before WI-7 starts | Teardown order, T-2 and T-3, the export lease (A5). | Teardown sequence diagram in the PR description. | +| CP-5 | Before PR F | Is the hand-over complete? | OT-1 to OT-7 results recorded in `# Outcome`, WI-9 queries run on pre-release ingestion. | + +--- + +## 6. PR 0: plan, research, decisions + +1. Have the operator create `feature/connection-lifecycle` from `main`, or create it yourself if you + have permission: `git push origin origin/main:refs/heads/feature/connection-lifecycle`. Deletion and + force-push are blocked afterwards, so check the base commit first. +2. The PR contains: + - `research-findings.md`, `decisions.md`, `README.md`; + - `01-implementation-plan.md` with the pointer to this file; + - **this file**; + - the index row in `docs/ai-and-plans/README.md` (already present). + The current branch `tnaum-ms/issue1102` can be the head branch; renaming it to `dev/tnaum/*` is + optional for PR 0. +3. Its description states that §4 (C-1 to C-6) is the agreement that lets PR 1–3 run in parallel, and + lists A1–A6 for the operator to confirm. +4. Verification: docs only, so none, beyond `npm run prettier` on the changed Markdown. + +**Progress:** + +--- + +## WI-1: Entra ID, silent renewal on every OIDC callback (PR 1) + +**Outcome:** + +- Each OIDC callback returns a token that is valid for the account the connection started with, looked up + silently. +- A silent miss produces a typed error that every surface explains the same way. +- A known-expired token is never offered on a new socket (by the mechanism chosen at CP-0). + +**Read first:** + +- `MicrosoftEntraIDAuthHandler.configureAuth`, and `MicrosoftEntraIDAuthHandler.test.ts`; +- `buildOidcClientConfiguration` in `oidcClientOptions.ts`; +- `documentdbTokenResource.ts`: `resolveInteractiveTokenResource` and the provider and env helpers; +- the JWT decoding in `playgroundWorker.ts` (the OIDC callback, around `tokenRequest`); +- `tokenExpiry.ts`; +- `entraErrors/entraTokenFailures.ts`; +- the error-translation skill. + +**Steps:** + +1. **Driver contract test (CP-0 evidence).** + - Add `src/documentdb/auth/driverOidcContract.test.ts`. It imports the driver's internal OIDC workflow + modules (use an ESLint disable comment, like the existing deep import) and drives them with a fake + `connection.command`. + - It asserts: + - (a) after the callback throws once, the next `fetchAccessToken` rethrows the same error (F-1); + - (b) `speculativeAuth` sends the cached token, whatever `expiresInSeconds` was (F-2); + - (c) code 18 calls the callback again and uses the new token; + - (d) a network error does not. + - Name the suite so it reads as a contract: `driver contract: mongodb OIDC workflow (7.2.0)`. If a + driver upgrade breaks it, the strategy has to be reviewed again. +2. **CP-0.** Choose the strategy for expired tokens, using T-1. The options: + - **A.** Rely on code 18. This only meets the approved plan's gate if the operator relaxes it. + - **B (recommended).** Proactive rotation. `ClustersClient` keeps the latest `expiresAtSec` it learned + through C-3. When a client is resolved, for any caller, and that time is in the past (minus a margin + of 300 s), it builds a new generation with the same fingerprint before returning. Implement the + client side of this in WI-4. WI-1 only provides C-3. + - **C.** Clear the driver's internal `TokenCache`. Rejected: it depends on driver internals. + + **Coverage, which must be shown for the chosen option (T-1 caveat):** + - (i) host operations that resolve a client; + - (ii) sockets the pool opens by itself: check the effective `minPoolSize` and `maxIdleTimeMS`, and + whether pool maintenance can open an authenticated socket with no operation pending; + - (iii) the shell and playground workers. Their own driver caches the token too; does WI-2 need a + worker-side rotation, for example recreating the worker's `MongoClient` when the relayed token + expires? + + For each path, record "covered by …" or "operator relaxed the guarantee for this path on ". + + Record the verdict, and the operator's answer if T-1 changes intent. + +3. **Session helper.** + - Add `src/documentdb/auth/entraSession.ts`. It calls `vscode.authentication.getSession` with an + **explicit** provider ID, normalizes the scopes (same rules as `getSessionFromVSCode`: `.default` + suffix plus `VSCODE_TENANT:`), and takes the `account` and mode (`interactive` = `createIfNone`, + `silent`, `forceNew`) as parameters. + - Replace the deep import in `MicrosoftEntraIDAuthHandler.ts` with it. This takes the handler off the + azureauth internal path, so PR 1 and PR 2 do not collide. + - Read the provider ID through the existing seam in `documentdbTokenResource.ts`, so that PR 2 migrates + a single place. +4. **First acquisition.** Keep it as it is (interactive when the policy says so). Then record C-1 from + `session.account` and the provider ID that was actually used, and return it on `AuthHandlerResponse`. +5. **The callback.** Replace the closure over `session` with: + - a silent lookup pinned to the provider, scopes, tenant and `account`; + - if the provider in use differs from the pinned one: `EntraSignInRequiredError('providerChanged')`; + - no session: `EntraSignInRequiredError('noSession')`; + - `session.account.id !== pinned.accountId`: `EntraIdentityMismatchError`; + - any other thrown error: `EntraTokenRefreshError` (keep the cause); + - a result of `{ accessToken, expiresInSeconds }`, where `expiresInSeconds` comes from the JWT `exp`; + - a C-3 notification for every completed lookup, including misses and failures. `changed` compares + only the previous `iat` and `exp` numbers; the previous token itself is never kept. + + Leave `buildOidcClientConfiguration` untouched; it still checks the destination policy around the call. + +6. **Shared JWT helper.** Move the JWT `exp` and `iat` decoding into `tokenExpiry.ts` as + `readJwtTimes(token)`, returning `{ iatSec?, expSec? }`. Use it in the handler and in + `playgroundWorker.ts`. An unknown `exp` stays unknown (`undefined`). The worker keeps its own fallback + TTL; WI-9 must not report that fallback as a measured value. +7. **Failure registry.** A silent miss and an identity mismatch are **not** recorded as token failures, + as the existing comment requires. An `EntraTokenRefreshError` is recorded through + `recordEntraTokenFailure`, with its `classifyEntraError` rule. +8. **Explanation.** + - Register an `ErrorExplanationService` provider (id `entraSignInRequired`) that walks the + `cause` chain, and the server-selection `reason` if the driver wraps the error, looking for C-2 + names. + - It returns: + - "Your Microsoft sign-in for '{cluster}' expired. Sign in again to continue."; + - for a mismatch: "VS Code returned a different Microsoft account for '{cluster}'…". + - Text only, no UI (skill rules). + - The cluster name comes from the request's `clusterId`. Find out how existing providers resolve a + display name; if none do, use a generic "this connection" rather than adding a lookup. +9. **Telemetry trace.** Extend the existing `traceAuthFlow` usage to the callback, with bounded values + only. WI-9 adds the counted event; do not emit it here. + +**Tests** (extend `MicrosoftEntraIDAuthHandler.test.ts`): + +- a second callback asks the provider again, pinned, with `silent: true` and **never** `createIfNone`; +- the same token bytes while the token is still valid are accepted, and C-3 reports `changed: false`; +- no session gives `EntraSignInRequiredError`; +- a different account gives `EntraIdentityMismatchError`; +- a changed configured provider gives `providerChanged`, and `getSession` is never called with the new + provider; +- the destination policy is still enforced before and after; +- `expiresInSeconds` comes from the JWT, and an opaque token leads to an unknown value, not 0; +- the registry is not touched for silent misses; +- the explanation provider recognizes a C-2 error wrapped two levels deep. + +**Done when:** + +- Case 1 is green; +- the contract test is committed; +- the CP-0 verdict is recorded; +- no `createIfNone` is reachable from the callback (a grep test or an assertion on the mock). + +**Progress:** + +--- + +## WI-2: Shell and Playground token relays (PR 1) + +**Outcome:** + +- Worker token relays follow WI-1's policy, pinned to a snapshot taken at spawn. +- A miss reaches the host as a bounded reason, and the shell or playground shows one "sign in again" line + with an action. +- A healthy warm worker never reads `CredentialCache`. + +**Read first:** + +- `ShellSessionManager`: `initialize`, `buildInitMessage`, the token relay and the shutdown paths; +- `PlaygroundEvaluator`: `evaluate`, `buildInitMessage`, the token relay and the worker lifecycle; +- `playgroundWorker.ts`: the OIDC callback and the `tokenError` handling; +- `workerTypes.ts`; +- the sovereign-clouds `decisions.md` D12 and finding E4 + (`sovereign-clouds/iterations/02-copilot-feedback-and-edge-case-review.md`); +- `ShellSessionManager.test.ts` and `PlaygroundEvaluator.test.ts`. + +**Steps:** + +1. **Snapshot and surface binding.** + - Extend the D12 session snapshot with C-1: `providerId`, `accountId` and `tenantId`. Capture them on + the **first** token relay of a newly spawned worker. + - That first relay may be interactive only while the spawn is user-initiated: opening a shell, or + running a playground on a cold worker. Track this with an explicit "initial acquisition pending" flag, + not with timing. + - Every later relay uses `entraSession.ts` in silent mode with the pinned account, and the same C-2 + errors as WI-1. + - Optional optimization (the advisor decides): if the host already has a client for the cluster with a + verified identity, seed the snapshot from it, so the initial relay is silent too. + - **The shell or playground surface keeps its own binding** (C-4 fingerprint plus C-1), and that + binding **outlives the worker** (F-15). Before an automatic respawn (`ShellSessionManager.evaluate`, + `executePlaygroundCode.ts`), check the binding and the surface latch: + - same fingerprint and not latched: respawn as today; + - a different fingerprint, or latched: do not respawn. Print the disconnected reason and the action. + - Only an explicit recovery (Sign in again, Reconnect) may respawn under a new binding. +2. **IPC.** + - Extend `tokenError` with an optional bounded `reason`. Its values are `signInRequired`, + `identityMismatch`, `destinationRejected` and `refreshFailed`. Keep the existing allow-list pattern + of `errorName`. + - The worker rebuilds an error with the matching C-2 `name`. + - Add an optional bounded `authReason` to `initResult` and `evalError`, so that the reason survives both + **init** and a **warm evaluation**. + - **Update `WorkerSessionManager`'s error reconstruction** for init and eval (F-16). Today it builds a + plain `Error` and keeps only `EntraDestinationRejectedError`. Test the whole path: worker → manager + → surface. + - Never send token values over IPC except the existing `tokenResponse`. +3. **Host behavior when the reason arrives.** + - **Shell:** print one localized line, "Microsoft sign-in expired for this shell. Run 'Sign in again' to + continue.", plus a terminal link or a non-modal notification with **Sign in again**. Never a modal + (A1). + - **Playground:** show the same as the run's error output, with an action. + - **Sign in again for a worker:** under F-1 the worker's own driver workflow is broken. After a + successful interactive acquisition **for the pinned account**, restart the worker session. The shell + keeps its terminal and prints "Reconnected". The playground respawns on the next run. + - A different account is an identity change (0003): the shell prints "Signed in as a different account; + open a new shell to use it". Do not rebind. +4. **#1059 note.** + - Call `PlaygroundEvaluator.buildInitMessage` only when a worker is spawned. + - A warm run on the same cluster reuses the stored init. + - A run against a different cluster, or a dead worker, spawns as it does today. +5. **E4.** A late token response or error from a disposed or replaced worker must change neither state nor + diagnostics. Guard by a worker or session instance ID. + +**Tests:** + +- Extend the two existing suites: + - the second relay is silent and pinned; `createIfNone` is never used after the initial acquisition; + - a changed provider fails closed; + - a mismatched account fails closed; + - the reason reaches the host during init **and** during a warm `evaluate`; + - a warm evaluation does not read `CredentialCache` (spy); + - a late relay result from a replaced worker is ignored; + - after the cluster's credentials change to another user, the next shell command does **not** respawn + silently; it prints `credentialsChanged`. A password-only change does respawn; + - a latched (disconnected) shell or playground does not respawn on the next command. +- Add a test of the worker message round trip for `reason` and `authReason`. + +**Done when:** Case 1 is green, and the PR 1 pre-review is committed. + +**Progress:** + +--- + +## WI-3: Azure discovery on azureauth v6 (#990) (PR 2) + +**Outcome:** + +- Discovery works after the ARM token expires, with no provider refresh. +- The ARM challenge works. +- Diagnostics reports "Azure sign-in needed" for ARM sign-in failures. + +**Read first:** + +- issue #990: `gh issue view 990 --comments`. It is the checklist. +- `AzureSubscriptionProviderWithFilters.ts` and `subscriptionFiltering/*`; +- `azureClients.ts`; +- `classifyResolutionFailure` in `resolveTarget.ts`, and its tests; +- the azureauth import list in #990. + +**Steps:** + +1. **Version probe (CP-W3).** In a scratch branch, try both version options from A4. + - For each, record: + - `npm ls @microsoft/vscode-azext-azureauth` (there must be exactly one copy); + - the number of `npm run build` errors; + - the bundle scan from #990 for duplicate copies and the broken ESM init pattern. + - Choose with the advisor. Run `flagging-fresh-dependencies` on the resulting lockfile. +2. **Migrate the APIs** at every call site that #990 lists: + - `getSubscriptions` → `getAvailableSubscriptions`; + - accounts and tenants; + - `signIn`; + - `onRefreshSuggested`; + - the provider class paths; + - the type-only imports. + + Keep the subscription-filter override effective, and keep the tenant filter as **one** mechanism + (#990 asks you to choose; recommended: keep the extension's `globalState` tenant filter as it is). + +3. **Shared seam.** Migrate `documentdbTokenResource.ts` (`getConfiguredAuthProviderId`, + `getConfiguredAzureEnv`). That is the single seam WI-1 reads. If PR 1 merged first, re-run the WI-1 + tests. +4. **Stored subscriptions.** Confirm that v6 `credential.getToken` and `authentication.getSession` acquire + a token on **every** call. + - Add a unit test: a stored `AzureSubscription` whose first session "expires" still lists clusters on + the second call. Use a mocked session sequence, and go through `createSubscriptionContext` the way + `azureClients.ts` does. +5. **Diagnostics.** + - In `classifyResolutionFailure`, classify these as `signInRequired`: + - the package's `isNotSignedInError` guard; + - a failed challenge; + - `interaction_required` or an AADSTS sign-in error, matched by name or code, never by free text where + a typed signal exists. + - The report stays bounded: error name and status only. + - Replace the test that manufactures `name: 'NotSignedInError'` with the **real** v6 exception shape + (`name: 'Error'`, no status) recognized by the guard. + - Do not assume ARM never prompts: a challenge can ask for step-up. +6. **l10n.** Refresh `l10n/@microsoft/vscode-azext-azureauth/bundle.l10n.json` as #990 describes, then + run `npm run l10n` and `npm run l10n:check`. + +**Done when:** + +- Case 1 is green; +- exactly one copy of azureauth is installed; +- the #990 manual checklist is recorded in Progress, with OT-6 still pending; +- the PR 2 pre-review is committed. + +**Fallback:** if PR 2 is not merged when WI-6 is ready, tell the operator (approved plan). Do not add a +shim (0005). + +**Progress:** + +--- + +## WI-4: Client identity, generation and the two cache fixes (PR 3) + +**Outcome:** + +- Every cached client carries C-4. +- Concurrent cold starts share one startup. +- Teardown and late startups cannot publish stale clients. +- Cancelling a cached reuse never closes the shared client. +- A closed topology is replaced, never reconnected with old options. + +**Read first:** + +- `ClustersClient`: `getClient`, `initClient`, `initializeClient`, `connect` and `deleteClient`; +- `ClustersClient.test.ts`; +- `connectionAuthIdentity.ts`; +- the tree-cluster-architecture skill (dual ID); +- the Kubernetes and Atlas reachability providers (how a tunnel rewrites the host). + +**Steps:** + +0. **Canonical cluster key** (T-3). Add `canonicalClusterKey(clusterId)`: lowercase for Azure-derived + IDs, exact for everything else. Find out how to tell them apart: the ID prefix, or the provider that + built it. Key every **new** map in WI-4 and WI-5 with it. WI-7 applies it to the existing stores. +1. **Fingerprint** (`src/documentdb/connectionFingerprint.ts`, pure). + - Inputs are the **credentials snapshot actually used** in `initializeClient`, the C-1 identity + (Entra), and the provider's logical target for tunnels. + - The **deployment** is the normalized seed host list of the original connection string (before + reachability rewrites it to `localhost`), or the provider's stable target ID. + - The **principal**, per auth method: + - Native: user + the **effective** authentication database, using the driver's rules (F-17): + explicit `authSource`, else the URI's database path, else `admin`; + - Entra: `providerId` + `accountId` + `tenantId`; + - managed identity: the client ID, as the runtime credential carries it, or `system-assigned`; + - no auth: `none`. + - Hash it (SHA-256, hex, truncated) into an opaque string. + - Table tests: + - a password-only change keeps the fingerprint; + - another user changes it; + - the same user on another host changes it; + - the same user with another explicit `authSource` changes it; + - the same user with **no** `authSource` and a different URI database (`/sales` against `/admin`) + changes it; + - two managed identity client IDs differ; + - a tunnel's local port change keeps it. + - Use this table as the CP-1 evidence. +2. **Generation.** + - Keep a static `Map` that only ever increases and is never cleared. + - Each `ClustersClient` instance records `generation`, `fingerprint`, `createdAt` and its credentials + snapshot. + - Expose a read-only `binding` (C-4) and `ClustersClient.getBinding(clusterId)`. +3. **One startup at a time (single flight).** + - A `_pendingStartups` map keyed by `clusterId` holds `{ promise, epoch }`. + - Every caller awaits the same startup, and each caller's own `abortSignal` rejects only **that + caller's** wait. + - The startup itself is aborted only when **all** waiters have aborted. Otherwise it continues and + publishes. + - A per-cluster `epoch` is incremented **synchronously** by `invalidate(clusterId)`. A startup publishes + only if the epoch is unchanged; otherwise it closes its own `MongoClient` and rejects with a typed + `ClientInvalidatedError`. + - `deleteClient` calls `invalidate` **before** its first `await`. + - `invalidate` also increments the C-6 lifecycle epoch. +4. **Central policy (C-6).** + - `getClient` takes `{ interaction, trigger, abortSignal }`, with `interaction` defaulting to `'never'`. + - Add a per-cluster `lastVerifiedIdentity` record (C-1 for Entra; the principal for other methods), + keyed by canonical key. It **survives eviction** and is cleared only by teardown (WI-7). + - `initializeClient` stops hardcoding `{ interactive: true }`. It is interactive only when the caller + allowed it **and** the cluster has no `lastVerifiedIdentity`. Otherwise it is silent and pinned to + that identity. + - Add the disconnected latch: a latched cluster throws `ClusterDisconnectedError` for every caller. + WI-7 sets the latch; WI-4 adds the check, the error and the tests. + - Audit every `getClient` call site (F-13), and pass `interaction: 'allowed'` only from explicit user + connect paths: tree expand, Connect, and one-shot commands on a cluster that is not yet connected. + List the audit in Progress. +5. **Cached reuse.** + - Remove the abort handler that closes the shared client (the cached branch of `getClient`). + - A cancelled waiter just rejects with `UserCancelledError`. +6. **Closed topology.** + - Track closure with the public SDAM event `topologyClosed` on the `MongoClient`, plus our own `close()` + calls. + - `getClient` on a closed client publishes a **new generation**, using the **current** `CredentialCache` + and requiring the **same fingerprint**. + - If the fingerprint differs, do not publish. Return a typed `IdentityChangedError` for WI-5 and WI-6 to + handle. + - Today's `client._mongoClient.connect()` call on the cached path goes away. +7. **Rotation (CP-0 option B, if chosen).** + - Subscribe to C-3 from the auth handler at startup, and store `tokenExpiresAtSec` on the instance. + - Expose `needsRotation(now)`, and apply it inside `getClient` for **every** caller. Rotation is not a + failure-driven replacement, so the T-4 background restriction does not apply to it. + - Cover the other paths that CP-0 lists, or record their relaxation. +8. **Telemetry helper.** + - Add `addEstablishedConnectionContext(context, clusterId | client)`. It sets `authMethod`, + `connectionCorrelationId`, and the measurements `connectionAgeMs` and `clientGeneration`. + - No property name may contain "error" (masking). + - WI-5 and WI-6 call it; add the helper and its tests only here. +9. **Development test hook** (optional, recommended). + - Add `vscode-documentdb.debug.connection.simulateExpiry`, following the survey debug commands: + - declared in `package.json`; + - registered only in development mode; + - listed in `LAZY_COMMANDS` with its reason. + - It (a) makes the next N Entra callbacks for a selected cluster behave like a silent miss, (b) marks + the token as expired for rotation, and (c) force-closes the pool to simulate an idle drop. + - Use a dashed context key if one is needed. + +**Tests** (`ClustersClient.test.ts`, plus the new fingerprint test): + +- two concurrent cold `getClient` calls create one `MongoClient`; +- cancelling one of two waiters leaves the other connected; +- a startup that finishes after `deleteClient` does not publish, and closes its client; +- a cancelled cached reuse does not close the shared client; +- `topologyClosed` followed by `getClient` gives a new generation with the same fingerprint; +- a changed principal followed by `getClient` gives `IdentityChangedError`; +- a background caller (`interaction: 'never'`) never prompts, even with no client and with credentials + cached; a verified cluster reconnects silently even when the caller allowed interaction; +- a latched cluster rejects every caller, including background ones; +- generation numbers only ever increase across delete and reconnect; +- the telemetry helper sets the bounded properties and no forbidden names. + +**Done when:** + +- Case 1 is green; +- the CP-1 verdict is recorded; +- every existing `ClustersClient` test still passes unchanged, or each change is justified in Progress. + +**Progress:** + +--- + +## WI-5: Classify failures and recover: host and tree (PR 4) + +**Outcome:** + +- One classifier and one state owner. +- The tree's Retry actually reconnects. +- **Sign in again** exists and prompts once per click. +- Account removal marks the clusters bound to it. + +**Read first:** + +- `ClusterItemBase.getChildren` and `createErrorRecoveryChildren`; +- `retryAuthentication.ts` and its test; +- the RU items: `MongoRUResourceItem.ts`, `RUCoreResourceItem.ts`, `ruClusterHelpers.ts`; +- the tree-cluster-architecture skill, "Failure Presentation: Actions Only"; +- the contract-test fixtures from WI-1. + +**Steps:** + +1. **Classifier** (`src/documentdb/connectionFailures.ts`, pure). Draft the table, then hold CP-2. + - It walks `cause`, plus `MongoServerSelectionError.reason.servers[*].error` where present. + - Initial table: + + | Signal | Auth | Kind | Generation | Offered action | + | ---------------------------------------------------------------------- | ---------- | ---------------------------- | -------------------------------------------------- | ----------------------------------------------- | + | `EntraSignInRequiredError` | Entra | `signInRequired` | replace on recovery (F-1) | Sign in again | + | `EntraIdentityMismatchError`, `IdentityChangedError` | any | `identityChanged` | evict; surfaces disconnected | Reconnect (rebind) | + | `EntraTokenRefreshError` | Entra | `transient`, workflow broken | replace on the next **foreground** operation (T-4) | Retry | + | 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 silently | none | + | network errors, timeouts, server selection with no auth cause | any | `transient` | keep | Retry | + | anything else | any | `other` | keep | existing behavior | + +2. **State owner.** + - Add `ClustersClient.reportFailure(binding, error)`, or a small `ConnectionStateService` that sits + beside it (advisor's choice). It classifies the error and ignores it if `binding.generation` is + stale. It evicts according to the table and updates the C-5 **cluster** state. Surface states are + projected per binding (WI-6). + - It fires `onDidChangeConnectionState(clusterId)`. + - A foreground helper `withClusterClient(clusterId, op, { foreground })` resolves the client (including + rotation under CP-0 option B), runs the operation, reports failures, and applies the T-4 backoff. + WI-6 extends it with bindings. +3. **Tree.** + - 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); + - then Diagnose; + - then Open shell; + - then **Retry last**. + - 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. +4. **Retry.** + - `retryAuthentication` evicts the client (`deleteClient` without clearing credentials) when the last + kind was `signInRequired`, `credentialsRejected` or `clientClosed`, and then refreshes. + - It captures the C-6 lifecycle epoch and the current binding **before** its first `await`. If either + changed in the meantime (a Disconnect, or another recovery replaced the client), it does nothing + destructive: no eviction, and no latch cleared. + - The `CredentialCache` entry is kept. + - **RU key exception:** on Retry after `credentialsRejected` for an RU Discovery or Azure Resources + item: + - drop the cached key and re-read it from ARM once (`extractCredentialsFromRUAccount`); + - an ARM sign-in failure there is reported as "Azure sign-in needed" (WI-3 classifier), not as a + database rejection; + - never open a password wizard. +5. **Sign in again** command (`vscode-documentdb.command.signInAgain`, args: a tree node or `{ clusterId }`). + - Read the pinned C-1 from the cluster's `lastVerifiedIdentity` record (WI-4). Capture the C-6 + lifecycle epoch **before** prompting. + - Call `entraSession.ts` interactively for that account and tenant. + - **Rejected-but-present session:** if the failure that led here was a server rejection of a token that + the silent lookup still returns, use `forceNewSession` for the pinned account instead of + `createIfNone`. Prove both paths in tests. + - **After the prompt, compare and swap.** If the epoch changed while the user was signing in (for + example, a Disconnect), do not evict, do not reconnect and do not clear the latch. Report "The + connection was closed while you were signing in." + - Same account: evict, start a new generation, and set the cluster state to `connected`. + - Different account: the identity changed. Surfaces bound to the old fingerprint project to + `disconnected(identityChanged)` (C-5), and the tree continues with the new identity. + - A dismissal is a `UserCancelledError`. No code path re-prompts. C-6 enforces this centrally; add a + test that background paths cannot prompt. +6. **`onDidChangeSessions`.** + - Register once, at activation. + - For events of a provider ID that some live binding pins, silently re-check each affected binding, + debounced to about 500 ms. + - A missing session sets the state to `signInRequired`. + - Results from a stale generation are ignored. Clusters bound to another account are not touched. + - Never sign the user out, and never remove a session. + +**Tests:** + +- classifier table tests on real error shapes; +- Retry after `clientClosed` creates a new generation; after `credentialsRejected` it keeps the + credentials and does not loop; +- the RU old/new key pair; an ARM sign-in failure compared with a database rejection; +- Sign in again with the same account and with a different account; the forced-new-session path; +- no re-prompt after a dismissal; +- an `onDidChangeSessions` event for another account does not affect this cluster; +- a stale-generation result is ignored; +- an old Retry that resolves after the client was replaced does not evict the new client; +- Sign in again that completes after a Disconnect does not reconnect or clear the latch; +- the T-4 backoff. + +**Done when:** + +- Case 1 is green; +- the CP-2 verdict is recorded; +- OT-2's tree part can be reproduced with the WI-4 hook. + +**Progress:** + +--- + +## WI-6: Bind surfaces and add the disconnected state (PR 5, or 5a and 5b) + +**Outcome:** + +- Collection View (all tabs), Document View and the Cluster Dashboard resolve their client per operation + through a binding. +- They show C-5 state with a banner and one action. +- They keep all user state. +- They never apply stale results. +- They never run under another identity. + +**Read first:** + +- the webview-trpc-messaging and react-webview-architecture skills; +- `collectionViewRouter.ts`, `indexesTab/indexViewRouter.ts`, `queryInsights/queryInsightsRouter.ts` + and `queryInsightsEventsRouter.ts` (it already has a tRPC subscription you can copy); +- `QueryInsightsAIService.ts` and `indexAdvisorCommands.ts`; +- `documentsViewRouter.ts` and `documentView.tsx` (the `isDirty` state); +- `clusterDashboardRouter.ts` and `ClusterDashboard.tsx`; +- `collectionViewContext.ts`; +- `openAppWebview.ts`; +- `build/verification/browser/scenarios.ts` and `fixtures.ts`. + +**CP-3 first.** + +- Convert **one** router end to end (Document View is the smallest) on the host side. +- Show the API, then decide with the advisor: + - whether to split into 5a (host: registry, binding, routers, state channel) and 5b (webviews: + banner, disabling, scenarios); + - the recommendation is to split, because 5b needs the 5a contract to be stable. + +### Host (5a) + +1. **Surface registry** (`src/documentdb/connectionSurfaces.ts`). + - `register({ clusterId, kind, binding, pushState, dispose, hasUnsavedChanges? })` returns a + disposable. + - Collection View, Document View and the Dashboard register when they open and unregister on + `onDisposed`. + - WI-7 enumerates this registry. +2. **Binding resolution.** + - `resolveBoundClient(binding, { foreground })` has three outcomes: + - (a) same fingerprint and generation: return the client; + - (b) same fingerprint, the client was replaced or closed for **recovery or rotation**: return the + current client, with no re-run (T-1, if confirmed). If T-1 is **not** confirmed, follow 0002 as + written: re-run the applied query from page 1, and discard old-generation responses; + - (c) a different fingerprint, the cluster is latched `disconnected` (C-6), or `identityChanged`: + throw a typed `SurfaceDisconnectedError(reason)`. + - Projection rule (C-5): the surface's state comes from comparing **its** binding with the cluster's + current binding, never from the cluster state alone. + - A surface **never** prompts. Under C-6 it calls `getClient` with `interaction: 'never'`. If no client + exists and the cluster is not latched, the reconnect is silent and pinned to `lastVerifiedIdentity`, + so Entra fails closed with a mismatch instead of prompting. +3. **`ClusterSession`.** + - It stops holding a `ClustersClient`, and stores the binding instead. + - `getClient()` becomes an `async` resolve. + - Update its callers: + - the Collection View router; + - the Query Insights routers; + - `QueryInsightsAIService`; + - `indexAdvisorCommands`. +4. **Routers without a session.** + - Document View, the index router and the Dashboard capture the binding when the panel opens (in the + controller's config and tRPC context), and resolve it for every operation. + - Re-run the grep from the approved plan, and list every converted call site in Progress. +5. **Writes.** + - Save document, inserts and deletes, and index create, drop, hide and unhide. + - When the request may have reached the server and the reply was lost (network error or timeout after + send), report **outcome unknown**: "The change may or may not have been applied. Refresh to check." + - Never resubmit. Leave the driver's own `retryWrites` as it is. + - Test that one application-level submission results in exactly one call to the driver. +6. **State channel and stale results.** + - Each view router gets a `connectionState` subscription, fed by the registry (C-5 surface state). It + replays the current state when a view subscribes. + - It carries a **surface epoch** that increases on every transition into `disconnected` and on every + rebind. + - Every request records `{ epoch, generation }` when it starts. + - **Before any host-side mutation**, check that the epoch is unchanged and that the generation is + acceptable under T-1 (or under 0002 as written). That covers `ClusterSession`'s + `_currentRawDocuments`, its query caches, Query Insights caches and `SchemaStore` updates. A stale + result must not change host state at all, so dropping it only at delivery is not enough. + - Check again at delivery. The UI applies the same check (5b). +7. Every router error path uses `addEstablishedConnectionContext` (WI-4). + +### Webviews (5b) + +1. **Shared UI.** + - A `useConnectionState()` hook and a `DisconnectedBanner` component. + - The banner is a Fluent `MessageBar` with intent `warning`, the host-provided reason text and **one** + action button. + - It uses `role="status"` and `aria-live="polite"`. + - Put both in the shared webview components folder. + - Run the detecting-accessibility-issues skill on them. +2. **Disabling.** + - While disconnected, every action that talks to the server is disabled: run query, paging, refresh, + save, delete, insert, index actions, Query Insights stages and AI calls. + - Editors stay **editable**. The user can keep typing. + - Responses whose epoch is older than the UI's current epoch are discarded on the UI side too. +3. **What each view keeps.** + - **Collection View:** query text, filter, sort, projection, page number and size, the selected tab, + and Query Insights results with a "stale" marker. + - **Document View:** the dirty editor content and `isDirty`. + - **Dashboard:** the last data, marked stale (WI-8 stops the polling). +4. **Actions.** + - **Reconnect** (same fingerprint): resolve again. On success, show "Reconnected. Results may be out + of date. Run the query again to refresh." The query is not run automatically. + - **Reconnect after an identity change:** an explicit rebind to the new fingerprint, then show "Now + connected as {label}" (OT-3). + - **Sign in again:** the WI-5 command. + - **Update credentials:** the existing command. + - **Close:** dispose the panel. +5. **L2-dev scenarios** (`scenarios.ts` and `fixtures.ts`): + - `collectionView/disconnected-signInRequired`: query text kept, Run disabled, no host calls when + Run is clicked; + - `documentView/disconnected-dirty`: edit kept, Save disabled; + - `clusterDashboard/disconnected`; + - a scenario that injects a disconnect after typing and then delivers a stale page response: the + applied results are not overwritten. + - Run them with the browser scenario config. Screenshots are artifacts, not baselines. + +**Transfers:** do not touch copy, paste or export (approved plan). + +**Tests:** + +- router tests for the three binding outcomes on each converted router; +- `ClusterSession` no longer stores a client (a type-level or structural test); +- the epoch drop on host and UI; +- one submission for a write whose reply is lost; +- the scenarios above. + +**Done when:** + +- Case 1 is green; +- the scenarios pass; +- OT-1 and OT-3(a) can be reproduced with the WI-4 hook; +- if split, 5a merges before 5b opens. + +**Progress:** + +--- + +## WI-7: Teardown, Disconnect, Remove and Update Credentials (PR 6) + +**Outcome:** + +- One teardown serves Disconnect, Remove and identity-changing credential updates. +- It is guarded by task conflicts and dirty editors. +- It covers every per-cluster resource. + +**Read first:** + +- `removeConnection.ts`; +- `resourceUsageHelper.ts` and `taskService.ts` (`getConflictingTasks`); +- `CopyPasteCollectionTask.ts` and `CopyIndexesTask.ts` (`getUsedResources`); +- `exportDocuments.ts`; +- `updateCredentials.ts`, including the D12 modal; +- `updateConnectionString.ts`; +- `CredentialCache.ts`, `entraTokenFailures.ts` and `SchemaStore.clearCluster`; +- the WI-6 registry; +- `switchAtlasViewMode.ts` (the `globalState` pattern). + +**CP-4 first:** the teardown order, T-2, T-3 and the export lease. + +**Steps:** + +1. **Export lease (A5).** + - Add `TaskService.acquireResourceLease(resource, label)`, which returns a disposable. + `getConflictingTasks` includes active leases. + - `exportDocuments.ts` holds the lease for the whole export. + - Test that export conflicts with Disconnect of its source, and that an unrelated cluster does not. +2. **Teardown service** (`src/documentdb/connectionTeardown.ts`). + - Two phases: `prepare(clusterId, intent)` and `commit(reservation, options)`. + - Disconnect and Remove call both, back to back. + - Update Credentials puts the save between them (step 5). + - **`prepare`**, which may prompt and may be cancelled: + 1. **Preflight:** task and lease conflicts through `checkCanProceedAndInformUser`. On a conflict, + stop and change nothing; the conflicting task is named. + 2. **Choice:** Close all or Keep open (A2), only when surfaces are registered. + 3. **Dirty check** (only for `close`): if any registered surface reports `hasUnsavedChanges`, ask for + confirmation. Cancelling leaves every panel, draft and connection intact. That includes the case + where Remove started the teardown. + 4. **Reserve, atomically:** **recheck** task and lease conflicts, because a copy or export may have + started while a prompt was open. Then take a per-cluster teardown reservation in `TaskService`. + While it is held, new tasks and leases on this cluster are refused with a clear message. + If the recheck finds a conflict, release everything and stop. + - **`commit`**, which has no prompts and cannot be cancelled: + 1. **Synchronous section, before any `await`:** set the latch and the cluster state to + `disconnected(reason)` (C-6), call `ClustersClient.invalidate` (it increments the lifecycle + epoch), increment the surface epochs, and mark in-flight token requests as abandoned (E4). + 2. **Surfaces:** + - `keepDisabled`: push the state; + - `close`: dispose the panels; + - shells: latch the surface (F-15), print "Disconnected", then stop the worker; + - playground: latch it, then stop the worker. + 3. Close the client (`deleteClient`). + 4. Clear the `CredentialCache` entry if `dropCredentials` is set (A3), the Entra failure registry, + `SchemaStore.clearCluster`, and `lastVerifiedIdentity`. + 5. Release the reservation, and refresh the tree (T-2). + - Releasing a reservation without committing must restore everything to the state before `prepare`. + - **Never touched:** VS Code auth sessions, the managed identity cache, the ARM cache. + - **Keys (T-3, F-18):** apply `canonicalClusterKey` to every store the teardown touches: + `CredentialCache`, the Entra failure registry, `SchemaStore`, `ClustersClient._clients`, and task + and lease conflict matching. Test that Kubernetes `Prod` and `prod` stay separate, and that Azure + case aliases match everywhere. +3. **Disconnect command** (`vscode-documentdb.command.disconnect`). + - Add a `connected` tag to the cluster item's `contextValue` while a client exists, and refresh it on + state changes. Use `viewItem` regex menus in the Connections, Azure Resources and Discovery views. + - The Close all / Keep open choice follows A2. Skip the prompt when no surfaces are registered. + - Add a disconnected cluster node child action, "Connect" (T-2). +4. **Remove Connection.** Teardown with reason `connectionRemoved` and `dropCredentials: true`, then delete + the stored connection and clear the schema, as today. Keep the existing confirmation. +5. **Update Credentials and Update Connection String.** + - Compute the **new** fingerprint from the wizard context before saving. + - **Make save success explicit** (F-19): the execute step must report whether the save succeeded, for + example with a flag on the wizard context. Today it catches failures and returns normally. + - **Same fingerprint:** save. Only after a confirmed success, call `invalidate` and replace the client + with a new generation; surfaces continue. + - **Different fingerprint:** + 1. `prepare` (preflight, choice, dirty check, reservation) **before** saving. + 2. Save. + 3. On a confirmed success: `commit` with reason `credentialsChanged` and `dropCredentials: false`, + so the **new** credentials stay. + 4. On a failed save: release the reservation. The old binding stays usable, and nothing was latched. + - The reservation and the `invalidate` call in `commit` make sure a concurrent connect cannot publish + the old credentials after the change. + - Add a **Disconnect** button to the D12 modal for open shells. +6. **Telemetry.** + - One `connection.disconnect` event with `source` (`command`, `remove`, `credentialsChanged`), + `surfacesChoice`, and counts of surfaces, shells and the playground, plus `blockedByTask`. + - No identifiers. + +**Tests:** + +- teardown for each surface type; +- Azure case aliases compared with distinct Kubernetes contexts; +- blocked for a copy source, a copy destination and an export source; an unrelated cluster is not + blocked; Disconnect succeeds once the task is done or stopped; +- a token response that arrives after Disconnect is ignored; +- Reconnect uses the current credentials and cloud settings; +- Remove reuses the same teardown; +- cancelling the dirty prompt changes nothing; +- a copy or export that starts while the Disconnect prompt is open blocks the commit, and nothing changes; +- a task or lease cannot start while a teardown reservation is held; +- a shell or playground left open after Disconnect does not respawn on its next command; +- a failed save keeps the old binding; +- a concurrent connect during Update Credentials does not publish the old credentials. + +**Done when:** Case 1 is green, and the OT-7 flows can be reproduced on a dev build. + +**Progress:** + +--- + +## WI-8: Cluster Dashboard health polling (PR 6) + +**Outcome:** the poll stops on a terminal state, shows the banner, and resumes with exactly one loop. + +**Steps:** + +1. `measureRtt` resolves through the WI-6 binding with `foreground: false` (T-4). It returns a + structured result, `{ ok, rttMs } | { terminal: reason }`, instead of throwing for terminal states. +2. The webview poll effect stops on `terminal` and on any `disconnected` state from the channel. It + restarts only on `connected`, guarded by one loop token, so that two loops can never run at once. +3. A late successful ping that started before the disconnect epoch cannot clear the banner (epoch check). +4. Visibility pause and backoff are the rest of #1091. Do them here only if they are trivial; otherwise + leave them to #1091. + +**Tests** (fake timers): + +- no client lookups on ticks or on reveal after Disconnect; +- a late success does not clear the banner; +- reconnecting starts exactly one loop; +- `signInRequired` and `credentialsRejected` stop the loop after one tick. + +**Progress:** + +--- + +## WI-9: Token renewal and recovery telemetry (PR 7) + +**Outcome:** the release can be judged from events that need no joins and no persistent identifiers. + +**Steps:** + +1. **`connection.tokenRenewal`.** + - Emitted from the C-3 observer (host client) and from the host side of the shell and playground relays. + - Once per completed post-startup Entra **database** token lookup. The initial acquisition is excluded. + - Properties: + - `surface` (`extension`, `shell`, `playground`); + - `renewalOutcome`: `changed`, `unchanged`, `noSession`, `identityMismatch`, `failed`, or `unknown` + when there is no earlier observation in the same binding. + - Measurements: `connectionAgeMs`, `previousTokenObservedAgeSeconds`, `tokenLifetimeSeconds` and + `tokenRemainingSeconds`. Omit any value that is unknown; never send 0 or the worker's fallback TTL. + - Never send a token, hash, claim, account, tenant, cluster ID, fingerprint or host name. +2. **`connection.recovered`.** + - The state owner (WI-5) keeps a "pending recovery" flag per cluster, with the trigger: `silentRenewal`, + `reconnect` or `signInAgain`. + - The event is emitted on the **first successful database operation** after that flag was set, with + `trigger` and `connectionAgeMs`. + - A callback returning a token does not count as recovery. +3. **ARM.** Report challenge outcomes separately from database renewal. Confirm that the final ARM request + succeeded, not just that a token was acquired. +4. **Volume.** + - Both events are background events. If the dashboards keep an event-scope exclusion list for + "active users" totals, add `connection.tokenRenewal` to it. + - Check the expected volume (about one renewal per active Entra client per hour) against the + telemetry budget. +5. **Queries.** + - Commit runnable Kusto queries in a durable `../telemetry.md` at the feature root: + - daily renewal outcomes and the changed-token rate; + - p50/p90 of lifetime, remaining validity and connection age at refresh; + - recoveries by trigger; + - late auth, socket and closed-client failures against the pre-release baseline, using the same + exposure denominator. + - Show sample counts and missing timing data next to every percentile. + - If the operator's telemetry dashboards worktree is available, port the queries there too. +6. **Fake-clock test** for the token sequence unchanged → changed → silent miss: + - check counts and units; + - include an opaque token and a database rejection after the lookup. + +**Done when:** + +- the tests are green; +- the queries have run once against pre-release ingestion (or they are marked "pending ingestion" in + `# Outcome`). + +**Progress:** + +--- + +## WI-10: Documentation (PR 7) + +1. **User manual:** + - add `docs/user-manual/connection-lifecycle.md`, or extend `connecting-to-databases.md` (choose one and + record the choice). It covers Disconnect, Sign in again, what a disconnected tab means and how to + resume, and what Update Credentials does to open sessions; + - link it from `interactive-shell.md`, `query-playground.md` and `managing-azure-discovery.md`; + - user-manual pages and release notes use **separate copies** of their images. +2. **Release notes** for 1.2.0 (writing-release-notes skill). Screenshots go through the + documentation-screenshots skill. +3. **Skills:** + - tree-cluster-architecture: "resolve the client per operation through a binding; never hold a + `ClustersClient`", the recovery-children order, and the `connected` context tag; + - error-translation: the C-2 errors and the `entraSignInRequired` provider. +4. **Feature docs:** + - feature `README.md`: status, code map and timeline; + - `decisions.md`: entries for A1–A6 once confirmed, T-1 and anything else the checkpoints decided; + - add `design.md` if the binding, state and teardown design outgrew the README. +5. **Preview** the docs site locally (previewing-docs-site skill). + +**Progress:** + +--- + +## PR F: `feature/connection-lifecycle` → `main` + +1. Sync `main` into the feature branch through a pure merge PR (approved plan rule 5). +2. Run Case 2 on the feature branch head. +3. Run OT-1 to OT-7 on the packaged VSIX, with at least one real wait of two hours or more. Record each + result, and the evidence the approved plan requires, in `# Outcome`. +4. CP-5 verdict, then open PR F. Watch telemetry for about one week after the merge (WI-9 queries). + +# Outcome + +_To be written at hand-over._ 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 c07b74abb..a2dfe14ed 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 @@ -42,6 +42,10 @@ work. **It deliberately does not specify interfaces**: a dedicated agent designs following the decisions. Progress is recorded **inline, against each work item**, when that item is committed. +**Execution detail:** [01-dev-plan.md](./01-dev-plan.md) expands each work item into steps, cross-PR +contracts, advisor checkpoints and provisional answers to the open questions. Progress is recorded inline +there. + ## Goal A user who leaves VS Code open for hours, with tabs and shells open, **never has to restart VS Code** @@ -242,7 +246,7 @@ bundle, filter and cache behavior, and how to verify. Additions from this invest The place is `classifyResolutionFailure` ([resolveTarget.ts:52-82](../../../../../src/connectionDiagnostics/checks/resolveTarget.ts)). Keep it - bounded: an error name and status only in the report, never messages (decision R2 in connectivity-troubleshooter). + bounded: an error name and status only in the report, never messages (decision R2 in connectivity-troubleshooter). A local probe of `6.0.0-alpha.8` through `createSubscriptionContext` confirmed that a held subscription looks up a session again. On a silent miss the actual exception had `name: "Error"` and no HTTP status; the current test manufactures `name: "NotSignedInError"`. Use the package's From 4ea34dcd9986c1bdcad26fe5e63c5564fd063a5f Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 19 Nov 2026 12:29:19 +0000 Subject: [PATCH 004/380] wip: revisiting the plan --- .../features/connection-lifecycle/README.md | 6 +- .../connection-lifecycle/decisions.md | 84 ++++++++++ .../iterations/01-dev-plan.md | 143 +++++++++++++----- .../iterations/01-implementation-plan.md | 10 +- 4 files changed, 205 insertions(+), 38 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/README.md b/docs/ai-and-plans/features/connection-lifecycle/README.md index 2d4e2f685..58c3629c0 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/README.md +++ b/docs/ai-and-plans/features/connection-lifecycle/README.md @@ -18,6 +18,7 @@ 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) **Branch:** `feature/connection-lifecycle`, with sub-PRs from `dev/tnaum/*` (decision 0006) @@ -66,7 +67,10 @@ See [decisions.md](./decisions.md): - 0003 no silent identity change; - 0004 the Disconnect tab choice; - 0005 azureauth v6; -- 0006 delivery through a feature branch, shipped once. +- 0006 delivery through a feature branch, shipped once; +- 0007 the Disconnect choice is a modal, not remembered, with a setting for the default; +- 0008 the azext stack is upgraded as high as viable, with Azure Resources as the reference; +- 0009 Kubernetes tunnel recovery, case handling and wider network-resilience testing move to #1105. ## Timeline diff --git a/docs/ai-and-plans/features/connection-lifecycle/decisions.md b/docs/ai-and-plans/features/connection-lifecycle/decisions.md index cb81d73c2..9c7bc2198 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/decisions.md +++ b/docs/ai-and-plans/features/connection-lifecycle/decisions.md @@ -18,6 +18,9 @@ created: 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 sub-PRs, avoid PRs on top of open PRs, ship once | Accepted | Operator chose this over one big PR and GitHub stacks | 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 | — | > 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 @@ -166,3 +169,84 @@ Rejected: - **GitHub stacked PRs:** the operator's experience was that updates must move up the chain and the PRs end up merged one by one anyway. - **Shipping WI-1 and WI-2 early as a patch (plan Q5):** no partial release. + +## 0007. The Disconnect choice is a VS Code modal with nothing remembered; a setting can set the default + +**Accepted** by the operator on 2026-11-19. It answers plan Q2, which decision 0004 left open. Source: +operator input on the dev plan's provisional answer A2. + +> this will be a modal dialog from vs code, so we can't preselect, we don't need to remember. we can add +> a setting for users to control their default if they want. + +- The Close all / Keep open (disabled) choice from 0004 is a VS Code modal. A modal has no pre-selected + button, and its built-in Cancel cancels the whole operation. +- The choice is **not remembered** between uses. +- A setting lets users pick a default: `ask` (the default) shows the modal; `closeAll` or + `keepOpenDisabled` skips it. The setting never skips the unsaved-edits confirmation. +- The choice applies to Disconnect, Remove Connection and credential updates that change identity. + +Rejected: + +- **Pre-select Keep open and remember the last choice in `globalState`** (the earlier proposal): a modal + cannot pre-select a button, and a remembered answer that silently changes what the next Disconnect does + is less predictable than an explicit setting. + +## 0008. Upgrade the azext stack as high as viable without breaking workflows, using Azure Resources as reference + +**Accepted** by the operator on 2026-11-19. Source: operator input on the dev plan's provisional +answer A4. + +> check what 'azure resoruces' extension is using, that's the same team that's behind the auzreauth +> package, and that azure resources extnesion is heavily used., I'd update / upgrade as hihgh as viable +> and not breaking our fworkflows. + +- The #990 upgrade (0005) targets the highest versions of azureauth, azureutils, utils and + `@microsoft/vscode-azureresources-api` that keep our workflows working, with one installed copy of each. +- The Azure Resources extension is the reference, because the same team owns azureauth and the extension + is heavily used. On 2026-11-19 its `main` used azureauth `^6.1.0-alpha.2`, azureutils `^4.3.0` and + utils `^4.1.0`. +- The dev plan ([iterations/01-dev-plan.md](./iterations/01-dev-plan.md), WI-3 step 1) holds the version + ladder, the evidence and the workflow checks that define "not breaking". + +Rejected: + +- **The minimal set** (azureauth `6.0.0-alpha.8` with azureutils 4.2 and utils 4.1, the earlier + proposal): it stays behind the line the azureauth owners run, and it would mean a second migration + later. It remains only as the last fallback if a higher level breaks a workflow that cannot be fixed. + +## 0009. Kubernetes tunnel recovery, cluster ID case handling and wider network-resilience testing move to #1105 + +**Accepted** by the operator on 2026-11-19. Source: operator input during dev planning. + +> I'd consider moving kubernetes fixes and the adding 'network resilience' as a new issue to work on +> once 1.2.0 ships, this would also simplify this dev plan. + +Moved to [#1105](https://github.com/microsoft/vscode-documentdb/issues/1105), to be scheduled after +1.2.0: + +- re-creating Kubernetes port-forward tunnels outside the tree. Today only `beforeCachedClientConnect` + restores a tunnel, when a tree node expands; +- tunnel ownership on Disconnect and Remove, and running the teardown when a kubeconfig source is + removed; +- provider-specific cluster ID matching, which the approved plan had put in WI-7. Today + `CredentialCache` folds case, so Kubernetes `Prod` and `prod` collide, and task conflict matching does + not fold, so it misses Azure case aliases. Both behaviors already exist today; +- Kubernetes API credential expiry (the AKS exec plugin); +- a network-resilience test matrix beyond OT-4, including a Kubernetes acceptance test. + +**Stays in iteration 1:** generic idle and network-drop recovery. That means closed-client and transient +classification, the cancelled-reuse fix, closed-client replacement and OT-4, which together are #1102's +"recover on the next operation without a restart". + +**Guard:** tunneled connections must not get worse. + +- Connection refused against a port-forward port is `transient`: the client is kept, not evicted. +- Per-operation resolution does no less than today's tree path. + +A tab whose tunnel died therefore behaves exactly as it does today. + +Rejected: + +- **Doing it in 1.2.0:** it adds a second layer (tunnels) to a release that is already the largest + connection change so far, for an authentication method that does not expire. The case-handling bugs + already exist and are rarely hit (two contexts that differ only in case). 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 c8fd92362..bf405fe2a 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 @@ -43,7 +43,7 @@ stable pointers. ### Authority and deviation -1. **Accepted decisions 0001–0006 bind you.** You cannot change them on your own. If the code shows one of +1. **Accepted decisions 0001–0008 bind you.** You cannot change them on your own. If the code shows one of them is wrong or cannot be met, stop and raise it with the operator, giving evidence and alternatives. The advisor cannot overrule an accepted decision. 2. **The approved plan's content binds you**, except where §3 (Tensions) names a conflict. There the advisor @@ -100,19 +100,19 @@ and just as plainly, what was not. --- -## 1. Provisional answers to the open questions +## 1. Answers to the open questions -The operator was not available on 2026-11-19. These are the recommended answers, adopted provisionally -under rule 4 above. +The operator was not available on 2026-11-19 at first. They answered A2, A4, A5 and A6 later the same +day; A1 and A3 are still **provisional** under rule 4 above. -| # | Question | Provisional answer | Where it lands | -| --- | ---------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------- | -| A1 | Plan Q1: how does sign-in start after a silent miss? | **Only through the Sign in again button**, everywhere. The first connect from the tree stays interactive, as it is today. One rule, and no surface has to decide whether it is in the foreground. This matches 0001. | WI-1, WI-2, WI-5, WI-6 | -| A2 | Plan Q2: Disconnect choice, default and memory | Ask every time. **Keep open (disabled)** is pre-selected the first time; after that, the last choice is pre-selected. The choice is stored under one `globalState` key (pattern: `switchAtlasViewMode.ts`). No setting. | WI-7 | -| A3 | Plan Q3: does Disconnect drop `CredentialCache`? | **Yes** (#1059 proposal). Saved connections reload from storage on the next expand. A password typed only for a discovery connection must be typed again. Implement it as a teardown option, so flipping the answer is a one-line change. | WI-7 | -| A4 | #990: which azext versions? | **Probe both, default to the minimal option:** azureauth `6.0.0-alpha.8` (already nested in the lockfile), keeping azureutils `4.2.x` and utils `4.1.x`. Choose the full v5 line only if the probe shows that the minimal option keeps two azureauth copies or needs a shim. | WI-3 (CP-W3) | -| A5 | How does Disconnect see an in-flight Export? | A small **resource lease** API on `TaskService`. Export holds the lease while it runs, and `checkCanProceedAndInformUser` reports it like a task. Export logic is not touched. | WI-7 | -| A6 | Where do the dev plan and its progress notes live? | In this file. Progress is recorded inline per WI here. The approved plan gets a one-line pointer. | — | +| # | Question | Answer | Status | Where it lands | +| --- | ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- | ---------------------- | +| A1 | Plan Q1: how does sign-in start after a silent miss? | **Only through the Sign in again button**, everywhere. The first connect from the tree stays interactive, as it is today. One rule, and no surface has to decide whether it is in the foreground. This matches 0001. | Provisional | WI-1, WI-2, WI-5, WI-6 | +| A2 | Plan Q2: Disconnect choice, default and memory | A **VS Code modal**, which has no pre-selected button and **remembers nothing**. A setting lets users choose a default: `ask` (the default) shows the modal; `closeAll` or `keepOpenDisabled` skips it. The unsaved-edits confirmation still appears when closing. See WI-7 step 3. | **Operator, 2026-11-19** (decision 0007) | WI-7 | +| A3 | Plan Q3: does Disconnect drop `CredentialCache`? | **Yes** (#1059 proposal). Saved connections reload from storage on the next expand. A password typed only for a discovery connection must be typed again. Implement it as a teardown option, so flipping the answer is a one-line change. | Provisional | WI-7 | +| A4 | #990: which azext versions? | **As high as viable without breaking our workflows**, using the Azure Resources extension (same team as azureauth, heavily used) as the reference. Ladder and findings are in WI-3 step 1: target L2, fall back to L1, then L0. | **Operator policy, 2026-11-19** (decision 0008) | WI-3 (CP-W3) | +| A5 | How does Disconnect see an in-flight Export? | **Reuse the existing mechanism.** Delete Collection, Delete Database and Remove Connection already guard through `checkCanProceedAndInformUser` (`TaskService` resource tracking). Export is the gap: it is not a task and registers nothing, so even Delete Collection does not see a running export today. Close it with a small **resource lease** that feeds the same check. Every existing guard then sees exports too, and the export logic is not touched. | Operator pointed at the existing check; lease is the recommendation | WI-7 | +| A6 | Where do the dev plan and its progress notes live? | In this file. Progress is recorded inline per WI here. The approved plan gets a one-line pointer. | **Operator, 2026-11-19** | — | --- @@ -147,6 +147,8 @@ upgrade changes any of them, stop and re-plan the affected WI. exactly. - Kubernetes IDs keep the context's case (`kubernetes_${source}_${context}__…`), so `Prod` and `prod` already collide in `CredentialCache` today. + - **Out of scope for this iteration** (decision 0009, #1105). Every store keeps its current matching; + this iteration adds no case handling. - **F-5. There is no per-cluster registry of open webview panels.** - Only the Cluster Dashboard keeps its own `openPanels` map (`clusterDashboardController.ts`). - Collection View and Document View open through `openAppWebview`, whose handle exposes `onDisposed`. @@ -205,7 +207,7 @@ upgrade changes any of them, stop and re-plan the affected WI. context `prod` also deletes `Prod`. - Task conflict matching (`hasResourceConflict` in `taskServiceResourceTracking.ts`) compares IDs exactly, so it misses Azure case aliases. - - One equality function in the teardown cannot fix either problem. + - Both problems exist today. They are **out of scope** for this iteration (decision 0009, #1105). - **F-19. Credential saves can fail without the command knowing.** The Update Credentials `ExecuteStep` catches save failures and returns normally, so the command cannot tell whether the save happened. - **F-14. VS Code has no API to collapse one tree node.** @@ -220,12 +222,30 @@ upgrade changes any of them, stop and re-plan the affected WI. | --- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | T-1 | WI-1 requires that a known-expired token is never offered on a new socket. Under F-2 that is only possible with a new `MongoClient` once the issued token expires, roughly once an hour. Decision 0002 says that a new generation re-runs reads from page 1 "because cursors are lost", but under F-6 no surface holds a cursor. Applying 0002 as written would show "results are no longer current" every hour (worse for OT-1). | CP-0 | Distinguish **token rotation** (same fingerprint, planned replacement) from **recovery**. Neither re-runs a query, because paging is offset-based. Show the "results are no longer current" notice only when a surface comes back from the **disconnected** state. This clarifies the intent of 0002, so the operator confirms it as a new decision entry. **Coverage caveat:** rotation at resolution time covers host operations only. Sockets opened by driver pool maintenance (`minPoolSize`), and the shell and playground workers' own driver token caches, still offer the cached token. CP-0 must show that every path is covered, or the operator must explicitly relax the guarantee for that path. A timer-based rotation would resemble the "proactive refresh timers" that 0001 rejected, so it also needs the operator. | | T-2 | OT-7 expects the cluster node to "collapse" after Disconnect, but VS Code cannot collapse a single node (F-14). | CP-4 | Refresh the node. A disconnected cluster returns **one** child action, "Connect", following the actions-only rule. Its handler reconnects and refreshes. Do not change `TreeItem.id`. Update OT-7's wording at hand-over. | -| T-3 | WI-7 must not fold Kubernetes context IDs, but `CredentialCache` already folds them, and task matching does not fold Azure aliases (F-4, F-18). | CP-1, CP-4 | Introduce **one canonical cluster key** in WI-4: `canonicalClusterKey(clusterId)`, lowercase for Azure IDs, exact for everything else. Key every **new** map with it (generations, pending startups, state, registry). In WI-7, apply it to the stores the teardown touches: `CredentialCache`, the Entra failure registry, `SchemaStore`, `ClustersClient._clients`, and task and lease conflict matching. Add migration-safe tests for `Prod`/`prod` and for Azure case aliases. If this grows beyond those stores, raise it with the operator. | +| T-3 | WI-7 asked for provider-specific cluster ID equality (Azure case aliases match; Kubernetes contexts such as `Prod` and `prod` stay distinct). Today's stores disagree on this (F-4, F-18). | — | **Withdrawn 2026-11-19:** moved out of this iteration (decision 0009, #1105). Each store keeps its current matching. | | T-4 | Under decision 0002, a classified failure evicts and replaces the client. A background caller such as the dashboard poll or tree count badges could therefore start a new connection every tick. | CP-2 | Only a **foreground** operation, or the rotation in T-1, replaces a generation. Background callers read the state and stop (WI-8). Add a per-cluster backoff of one replacement per 30 s, as a guard against loops. | | T-5 | For Entra, code 18 after the driver's own fresh callback means the server rejected a _fresh_ token: the principal has no database user, or Conditional Access or CAE intervened. That is not the same as `signInRequired`. | CP-2 | Classify it as `credentialsRejected` with an Entra-specific explanation ("Your account has no access…"). Offer **Sign in again** only when the token came from a session the user can replace. Decide this with the real driver error shapes collected for CP-0. | --- +## 3a. Out of scope for this iteration + +Moved to [#1105](https://github.com/microsoft/vscode-documentdb/issues/1105) on 2026-11-19 (decision +0009), to be scheduled after 1.2.0: + +- re-creating Kubernetes port-forward tunnels outside the tree (per-operation resolution, recovery); +- tunnel ownership on Disconnect and Remove, and running the teardown when a kubeconfig source is removed; +- provider-specific cluster ID matching (the withdrawn T-3; F-4, F-18); +- Kubernetes API credential expiry (AKS exec plugin); +- a wider network-resilience test matrix beyond OT-4, including a Kubernetes acceptance test. + +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 +working as they do today. + +--- + ## 4. Contracts that cross PRs The approved plan lets PR 1–3 run in parallel "if PR 0 agrees how WI-1 passes the verified account, @@ -271,7 +291,8 @@ semantics are binding unless a checkpoint changes them. after teardown. A binding from before Disconnect therefore never matches a client created after Reconnect. - **C-5. Connection state, at two levels.** - - **Cluster state** is owned by the host and keyed by canonical cluster key. It describes the cluster's + - **Cluster state** is owned by the host and keyed by `clusterId`, matched the same way as + `ClustersClient._clients` today. It describes the cluster's current client: `connected { binding }`, `reconnecting`, `needsAction { reason }`, or `disconnected { reason }` (the latch, C-6). - **Surface state** is **derived for each registered binding**. It is what the tree, webviews, shells @@ -313,7 +334,7 @@ verdict exists, do not start the work it gates. | CP-1 | Before PR 3 opens | Does C-1 work for every auth method, including the managed identity runtime shape and tunnels? | Fingerprint table tests (WI-4 step 1). | | CP-2 | WI-5, after the classifier is drafted, before recovery is wired | The classifier table, T-4 and T-5. | Classifier table tests run on **real** driver error shapes captured by the contract test and the tree paths. | | CP-3 | Before WI-6 webview work | Split PR 5 into 5a/5b? Is the binding-resolution API and state channel final? | Diff size of host-only work; one router converted end to end. | -| CP-4 | Before WI-7 starts | Teardown order, T-2 and T-3, the export lease (A5). | Teardown sequence diagram in the PR description. | +| CP-4 | Before WI-7 starts | Teardown order, T-2, the export lease (A5). | Teardown sequence diagram in the PR description. | | CP-5 | Before PR F | Is the hand-over complete? | OT-1 to OT-7 results recorded in `# Outcome`, WI-9 queries run on pre-release ingestion. | --- @@ -560,12 +581,48 @@ verdict exists, do not start the work it gates. **Steps:** -1. **Version probe (CP-W3).** In a scratch branch, try both version options from A4. - - For each, record: - - `npm ls @microsoft/vscode-azext-azureauth` (there must be exactly one copy); - - the number of `npm run build` errors; - - the bundle scan from #990 for duplicate copies and the broken ESM init pattern. - - Choose with the advisor. Run `flagging-fresh-dependencies` on the resulting lockfile. +1. **Version selection (CP-W3), under the A4 policy: as high as viable without breaking our workflows.** + - Findings on 2026-11-19: + - The **Azure Resources extension** (`vscode-azureresourcegroups` `main`, 0.13.x) uses azureauth + `^6.1.0-alpha.2`, azureutils `^4.3.0` and utils `^4.1.0`. + - azureutils `4.3.0`, `5.0.0` and `5.1.0` all require azureauth `^6.1.0-alpha.2`. + - Our azureutils `4.2.0` requires `^6.0.0-alpha.6`, which **does not** accept `6.1.0-alpha.x`. + - utils `4.1.1` and later, including `5.x`, require `@microsoft/vscode-azureresources-api` + **`^3.1.1`**. We are on `~2.5.0`; version 3 moved the package to CJS+ESM and finalized the auth + challenge API. We use it in about 30 files, mostly for `AzureSubscription` types, plus the Azure + Resources branch and workspace providers, `getAzureResourcesExtensionApi` and `unwrapArgs`. + - **utils 5.0.0's only breaking change** removes the experimentation (TAS) API, which we do not use. + The other public typings from 4.1.0 to 5.1.0 are additive (workflow telemetry, + `openReadOnlyFile`, `authentication` on subscription context). Whole-error masking in + `callWithTelemetryAndErrorHandling` is unchanged. + - azureutils `5.0.0` only bumps it to utils v5; `5.1.0` loosens the Azure client type generics. + - In our lockfile, only azureutils depends on the other azext packages, so the root manifest + controls all versions. + - The ladder (try from the top, stop at the first that passes): + + | Level | azureauth | azureutils | utils | azureresources-api | Note | + | --------------- | --------------- | ---------- | -------- | ------------------ | ---------------------------------------------------------- | + | **L2 (target)** | `6.1.0-alpha.2` | `~5.1.0` | `~5.1.0` | `~3.1.1` | Highest available; ahead of Azure Resources on utils | + | L1 | `6.1.0-alpha.2` | `~4.3.0` | `~4.3.0` | `~3.1.1` | Parity with Azure Resources | + | L0 | `6.0.0-alpha.8` | `~4.2.0` | `~4.1.0` | `~2.5.0` | Minimal; only if L1 breaks a workflow that cannot be fixed | + + - Before choosing, check the lockfile of the Azure Resources release that is published for the utils + and azureauth versions it actually resolved. + - For each level tried, record: + - `npm ls` for all four packages: exactly **one** copy each; + - the number of `npm run build` errors and what kind they are; + - the bundle scan from #990 for duplicate copies and the broken ESM init pattern; + - `flagging-fresh-dependencies` on the resulting lockfile. + - **"Not breaking our workflows" means all of these pass:** + - Azure Resources view: vCore and RU nodes, and the workspace resource provider; + - Discovery: vCore, RU and VMs, with subscription and tenant filters; + - sign-in, account changes, MFA and cloud switches; + - deep links (`/connect/azure`, with and without a tenant ID); + - every `AzureWizard` flow; + - the masking test in the telemetry-masking memory: a property containing "error" is still redacted. + - Choose with the advisor. If L2 needs more than mechanical changes in the `azureresources-api` 3 + consumers, step down to L1 and record why. + 2. **Migrate the APIs** at every call site that #990 lists: - `getSubscriptions` → `getAvailableSubscriptions`; - accounts and tenants; @@ -632,9 +689,6 @@ shim (0005). **Steps:** -0. **Canonical cluster key** (T-3). Add `canonicalClusterKey(clusterId)`: lowercase for Azure-derived - IDs, exact for everything else. Find out how to tell them apart: the ID prefix, or the provider that - built it. Key every **new** map in WI-4 and WI-5 with it. WI-7 applies it to the existing stores. 1. **Fingerprint** (`src/documentdb/connectionFingerprint.ts`, pure). - Inputs are the **credentials snapshot actually used** in `initializeClient`, the C-1 identity (Entra), and the provider's logical target for tunnels. @@ -676,7 +730,7 @@ shim (0005). 4. **Central policy (C-6).** - `getClient` takes `{ interaction, trigger, abortSignal }`, with `interaction` defaulting to `'never'`. - Add a per-cluster `lastVerifiedIdentity` record (C-1 for Entra; the principal for other methods), - keyed by canonical key. It **survives eviction** and is cleared only by teardown (WI-7). + keyed by `clusterId` like `ClustersClient._clients`. It **survives eviction** and is cleared only by teardown (WI-7). - `initializeClient` stops hardcoding `{ interactive: true }`. It is interactive only when the caller allowed it **and** the cluster has no `lastVerifiedIdentity`. Otherwise it is silent and pinned to that identity. @@ -773,6 +827,10 @@ shim (0005). | network errors, timeouts, server selection with no auth cause | any | `transient` | keep | Retry | | anything else | any | `other` | keep | existing behavior | + - **No regression for tunneled connections:** connection refused against a Kubernetes port-forward + port is `transient`. The client is **kept**, never evicted, so the tree's existing tunnel restore + (`beforeCachedClientConnect`) still recovers it. Tunnel recovery itself is #1105. + 2. **State owner.** - Add `ClustersClient.reportFailure(binding, error)`, or a small `ConnectionStateService` that sits beside it (advisor's choice). It classifies the error and ignores it if `binding.generation` is @@ -905,6 +963,10 @@ shim (0005). - A surface **never** prompts. Under C-6 it calls `getClient` with `interaction: 'never'`. If no client exists and the cluster is not latched, the reconnect is silent and pinned to `lastVerifiedIdentity`, so Entra fails closed with a mismatch instead of prompting. + - **No regression for tunneled connections** (Kubernetes `ClusterIP` through port-forward). Creating a + new generation from this path may not do less than today's tree path, and it does not re-create + tunnels. A tab whose tunnel died behaves as it does today: it fails transiently until a tree expand + restores the tunnel. Re-creating the tunnel outside the tree is #1105. 3. **`ClusterSession`.** - It stops holding a `ClustersClient`, and stores the binding instead. - `getClient()` becomes an `async` resolve. @@ -1013,7 +1075,7 @@ shim (0005). - the WI-6 registry; - `switchAtlasViewMode.ts` (the `globalState` pattern). -**CP-4 first:** the teardown order, T-2, T-3 and the export lease. +**CP-4 first:** the teardown order, T-2 and the export lease. **Steps:** @@ -1029,7 +1091,8 @@ shim (0005). - **`prepare`**, which may prompt and may be cancelled: 1. **Preflight:** task and lease conflicts through `checkCanProceedAndInformUser`. On a conflict, stop and change nothing; the conflicting task is named. - 2. **Choice:** Close all or Keep open (A2), only when surfaces are registered. + 2. **Choice:** Close all or Keep open (A2), only when surfaces are registered and the setting is + `ask`. With the setting at `closeAll` or `keepOpenDisabled`, use that value without a modal. 3. **Dirty check** (only for `close`): if any registered surface reports `hasUnsavedChanges`, ask for confirmation. Cancelling leaves every panel, draft and connection intact. That includes the case where Remove started the teardown. @@ -1052,14 +1115,27 @@ shim (0005). 5. Release the reservation, and refresh the tree (T-2). - Releasing a reservation without committing must restore everything to the state before `prepare`. - **Never touched:** VS Code auth sessions, the managed identity cache, the ARM cache. - - **Keys (T-3, F-18):** apply `canonicalClusterKey` to every store the teardown touches: - `CredentialCache`, the Entra failure registry, `SchemaStore`, `ClustersClient._clients`, and task - and lease conflict matching. Test that Kubernetes `Prod` and `prod` stay separate, and that Azure - case aliases match everywhere. + - **Keys:** every store keeps its current `clusterId` matching. Provider-specific equality is out of + scope (decision 0009, #1105). Do not add case folding or unfolding in this iteration. + - **Kubernetes tunnels:** the teardown does not stop port-forward tunnels, and does not change how + removing a kubeconfig source works (#1105). 3. **Disconnect command** (`vscode-documentdb.command.disconnect`). - Add a `connected` tag to the cluster item's `contextValue` while a client exists, and refresh it on state changes. Use `viewItem` regex menus in the Connections, Azure Resources and Discovery views. - - The Close all / Keep open choice follows A2. Skip the prompt when no surfaces are registered. + - **The choice (A2):** + - Use a modal warning: `showWarningMessage` with `{ modal: true, detail }` and the two buttons Close + all and Keep open (disabled). The built-in Cancel cancels the whole operation. + - The modal cannot pre-select a button, and nothing is remembered. + - Add a setting, proposed as `documentDB.connections.openTabsOnDisconnect`, with the enum `ask` + (default), `closeAll` and `keepOpenDisabled`. `documentDB.shell.multiLinePasteBehavior` is the + precedent for an enum with an `ask` default and `enumDescriptions`. + - Follow [settings/README.md](../../settings/README.md) for the group, `order` and the ID naming + rules. If an existing group fits better than `connections`, use it and record the final ID in + Progress. + - The same choice applies to Remove Connection and to identity-changing credential updates. + - The setting never skips the unsaved-edits confirmation: when Close all is chosen and an editor is + dirty, that confirmation still appears. + - Skip the modal when no surfaces are registered. - Add a disconnected cluster node child action, "Connect" (T-2). 4. **Remove Connection.** Teardown with reason `connectionRemoved` and `dropCredentials: true`, then delete the stored connection and clear the schema, as today. Keep the existing confirmation. @@ -1086,7 +1162,6 @@ shim (0005). **Tests:** - teardown for each surface type; -- Azure case aliases compared with distinct Kubernetes contexts; - blocked for a copy source, a copy destination and an export source; an unrelated cluster is not blocked; Disconnect succeeds once the task is done or stopped; - a token response that arrives after Disconnect is ignored; 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 a2dfe14ed..6b4893104 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 @@ -394,6 +394,9 @@ The largest item. Host side first, then each view. - **One teardown**, keyed by stable `clusterId`, with provider-specific equality. Azure case aliases must match, but folding Kubernetes context IDs such as `Prod` and `prod` would target different resources together. Remove = teardown + delete + clear schema; Disconnect = teardown only. + - **Changed 2026-11-19:** provider-specific equality and all Kubernetes tunnel work moved to + [#1105](https://github.com/microsoft/vscode-documentdb/issues/1105), after 1.2.0 (decision + [0009](../decisions.md)). The teardown keeps each store's current `clusterId` matching. - After the task-conflict preflight below, tear down the client, shells, playground, webviews, in-flight token requests (sovereign-clouds finding E4), `CredentialCache`, the Entra failure registry, and the `SchemaStore` decision. @@ -428,7 +431,7 @@ The largest item. Host side first, then each view. - **Telemetry:** one event with the activation source and teardown counts. No identifiers (#1059). - **Tests:** - teardown per surface; - - Azure case aliases vs distinct Kubernetes context IDs; + - ~~Azure case aliases vs distinct Kubernetes context IDs;~~ moved to #1105 (decision 0009); - Disconnect blocked for copy source, copy destination and export source; an unrelated cluster is not blocked. After the task finishes or is stopped, retrying Disconnect succeeds; - a late token response after Disconnect is ignored; @@ -550,8 +553,9 @@ denominator; a cohort with no challenges is inconclusive, and timing alone does - **Q1:** For a user-initiated action, should the interactive sign-in open **immediately**, or only through the **Sign in again** button? The proposal is the button everywhere (decision 0001). A first connect from the tree stays interactive, as it is today. -- **Q2:** The default for the Disconnect choice, and whether to remember it. The proposal is Keep - open (disabled), remembered in `globalState`. +- ~~**Q2:** The default for the Disconnect choice, and whether to remember it. The proposal is Keep + open (disabled), remembered in `globalState`.~~ **Resolved 2026-11-19:** a VS Code modal with nothing + remembered, plus a setting for the default (decision [0007](../decisions.md)). - **Q3:** Should Disconnect drop the `CredentialCache` entry (#1059 proposes yes), so a password typed only for a discovery connection must be entered again? - **Q4:** Ask the Azure DocumentDB service team whether the server closes connections when the From 22b8ad2a3be921d8a9809295e4ef2257cb7210d4 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 19 Nov 2026 13:50:26 +0000 Subject: [PATCH 005/380] wip: revisiting the plan --- .../features/connection-lifecycle/README.md | 6 +- .../connection-lifecycle/decisions.md | 57 ++++-- .../iterations/01-dev-plan.md | 174 ++++++++++++------ .../iterations/01-implementation-plan.md | 10 +- .../connection-lifecycle/research-findings.md | 6 +- 5 files changed, 178 insertions(+), 75 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/README.md b/docs/ai-and-plans/features/connection-lifecycle/README.md index 58c3629c0..53514f6c8 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/README.md +++ b/docs/ai-and-plans/features/connection-lifecycle/README.md @@ -18,7 +18,8 @@ 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) +- 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) **Branch:** `feature/connection-lifecycle`, with sub-PRs from `dev/tnaum/*` (decision 0006) @@ -70,7 +71,8 @@ See [decisions.md](./decisions.md): - 0006 delivery through a feature branch, shipped once; - 0007 the Disconnect choice is a modal, not remembered, with a setting for the default; - 0008 the azext stack is upgraded as high as viable, with Azure Resources as the reference; -- 0009 Kubernetes tunnel recovery, case handling and wider network-resilience testing move to #1105. +- 0009 Kubernetes tunnel recovery, case handling and wider network-resilience testing move to #1105; +- 0010 rely on the server to reject expired tokens; same-identity client replacement is transparent. ## Timeline diff --git a/docs/ai-and-plans/features/connection-lifecycle/decisions.md b/docs/ai-and-plans/features/connection-lifecycle/decisions.md index 9c7bc2198..c6f18890c 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/decisions.md +++ b/docs/ai-and-plans/features/connection-lifecycle/decisions.md @@ -10,17 +10,18 @@ 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 | 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 sub-PRs, avoid PRs on top of open PRs, ship once | Accepted | Operator chose this over one big PR and GitHub stacks | 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 | — | +| # | 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 sub-PRs, avoid PRs on top of open PRs, ship once | Accepted | Operator chose this over one big PR and GitHub stacks | 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 | — | > 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 @@ -250,3 +251,37 @@ Rejected: - **Doing it in 1.2.0:** it adds a second layer (tunnels) to a release that is already the largest connection change so far, for an authentication method that does not expire. The case-handling bugs already exist and are rarely hit (two contexts that differ only in case). + +## 0010. Rely on the server to reject expired tokens; replacing a client for the same identity is transparent + +**Accepted** by the operator on 2026-11-19. It answers T-1 in the dev plan. It modifies 0002's "re-run +reads from the first page", and drops the approved plan's WI-1 requirement that a known-expired token is +never offered on a new socket. Source: operator input at planning. + +> I wouldn't worry about this guarantee, the server will tell us, then we can act, this is easier. sure +> we can have a local check for some expirations, but that's unreliable anyway. + +> no banners about out of date, this can be another future work issue [...] this is really an edge case. + +- **Expired tokens:** + - No proactive client rotation and no local expiry checks. + - The server rejects an expired token with code 18; the driver then calls the OIDC callback again, + which renews silently (0001). + - The operator test OP-1 in the dev plan confirms what the server actually returns. If it closes the + socket instead, the failure classifier acts on that: the next foreground operation gets a new client + with a fresh token cache. +- **Replacing a client for the same identity** (recovery from a closed client, Sign in again with the same + account) is **transparent**: open views continue on the new client, with no re-run of the query and no + notice. 0002's reason for re-running, lost cursors, does not apply: Collection View pages with offset + queries. +- **No "results may be out of date" notice anywhere in this iteration,** including when a view returns + from the disconnected state. Whether to indicate stale data (after a reconnect, a long idle, or writes) + is [#1106](https://github.com/microsoft/vscode-documentdb/issues/1106). + +Rejected: + +- **Proactive rotation when the issued token expires:** it covers only host operations, not the pool's own + sockets or the shell and playground workers, unless rotation is coordinated across all of them. It + costs a reconnect about every hour, and local expiry checks are unreliable anyway. +- **Re-run page 1 with a "results are no longer current" notice** (0002 as written): it would appear after + every reconnect, for no correctness benefit. 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 bf405fe2a..b538395ac 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 @@ -65,6 +65,33 @@ commit SHA, what landed, and anything that differed from the plan. Each checkpoi verdict there. At the hand-over, add an `# Outcome` chapter to the end of this file: what was verified, and just as plainly, what was not. +### Operator tests: announce them clearly + +Some checks need the operator: a real cluster, a long wait, a real account, or the packaged VSIX. When +the work reaches one, **stop** and post a message whose first line is: + +> **⏸ OPERATOR TEST NEEDED: OP-n, ** + +followed by: + +- **why** it is needed now, and what it blocks; +- **setup:** the build to install, the cluster and account, and the settings; +- **steps**, numbered; +- **what to send back:** output-channel lines, screenshots, pass or fail per step. Never include tokens; +- **an estimated duration**, including waits. + +Do not continue past the blocked step until the operator replies. Work that does not depend on the +result may continue, but say so in the message. Record the result in the Progress block of the WI. + +| OP | When | Test | +| ---- | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | +| OP-1 | WI-1, CP-0 | Entra connection, idle past the token lifetime (60–90 min or more), then force a new connection. Does the server answer code 18 or close the socket? | +| OP-2 | WI-3, CP-W3 | The azext workflow checks on the packaged VSIX: Azure sign-in, discovery, filters, deep links, wizards, Azure Resources view. | +| OP-3 | WI-5 done | OT-2's tree part with a real sign-out: Sign in again, a dismissal, no reprompt. | +| OP-4 | WI-6 done (after 5b) | OT-1 (short form, with the WI-4 hook) and OT-3(a) and (b) on a dev build. | +| OP-5 | WI-7 done | OT-7 on a dev build, including a Disconnect during a running copy or export, and while a query or save is in flight. | +| OP-6 | Before PR F (CP-5) | OT-1 to OT-7 on the packaged VSIX, with at least one real wait of two hours or more (PR F step 3). | + ### Per-PR workflow - **Branch:** create `dev/tnaum/` from `feature/connection-lifecycle`. Follow the approved plan's @@ -218,13 +245,13 @@ upgrade changes any of them, stop and re-plan the affected WI. ## 3. Tensions between the approved plan and the code -| # | Tension | Decided at | Recommendation | -| --- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| T-1 | WI-1 requires that a known-expired token is never offered on a new socket. Under F-2 that is only possible with a new `MongoClient` once the issued token expires, roughly once an hour. Decision 0002 says that a new generation re-runs reads from page 1 "because cursors are lost", but under F-6 no surface holds a cursor. Applying 0002 as written would show "results are no longer current" every hour (worse for OT-1). | CP-0 | Distinguish **token rotation** (same fingerprint, planned replacement) from **recovery**. Neither re-runs a query, because paging is offset-based. Show the "results are no longer current" notice only when a surface comes back from the **disconnected** state. This clarifies the intent of 0002, so the operator confirms it as a new decision entry. **Coverage caveat:** rotation at resolution time covers host operations only. Sockets opened by driver pool maintenance (`minPoolSize`), and the shell and playground workers' own driver token caches, still offer the cached token. CP-0 must show that every path is covered, or the operator must explicitly relax the guarantee for that path. A timer-based rotation would resemble the "proactive refresh timers" that 0001 rejected, so it also needs the operator. | -| T-2 | OT-7 expects the cluster node to "collapse" after Disconnect, but VS Code cannot collapse a single node (F-14). | CP-4 | Refresh the node. A disconnected cluster returns **one** child action, "Connect", following the actions-only rule. Its handler reconnects and refreshes. Do not change `TreeItem.id`. Update OT-7's wording at hand-over. | -| T-3 | WI-7 asked for provider-specific cluster ID equality (Azure case aliases match; Kubernetes contexts such as `Prod` and `prod` stay distinct). Today's stores disagree on this (F-4, F-18). | — | **Withdrawn 2026-11-19:** moved out of this iteration (decision 0009, #1105). Each store keeps its current matching. | -| T-4 | Under decision 0002, a classified failure evicts and replaces the client. A background caller such as the dashboard poll or tree count badges could therefore start a new connection every tick. | CP-2 | Only a **foreground** operation, or the rotation in T-1, replaces a generation. Background callers read the state and stop (WI-8). Add a per-cluster backoff of one replacement per 30 s, as a guard against loops. | -| T-5 | For Entra, code 18 after the driver's own fresh callback means the server rejected a _fresh_ token: the principal has no database user, or Conditional Access or CAE intervened. That is not the same as `signInRequired`. | CP-2 | Classify it as `credentialsRejected` with an Entra-specific explanation ("Your account has no access…"). Offer **Sign in again** only when the token came from a session the user can replace. Decide this with the real driver error shapes collected for CP-0. | +| # | Tension | Decided at | Recommendation | +| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| T-1 | WI-1 required that a known-expired token is never offered on a new socket. Under F-2 that is only possible with a new `MongoClient` once the issued token expires. Decision 0002 says a new generation re-runs reads from page 1 "because cursors are lost", but under F-6 no surface holds a cursor. | CP-0 | **Resolved by the operator on 2026-11-19 (decision 0010).** (1) No proactive rotation and no local expiry checks: "the server will tell us, then we can act". An expired token is rejected by the server; the driver then calls the callback, which renews silently. If the server closes the socket instead, the classifier acts on that (WI-5). (2) Replacing a client for the same identity is **transparent**: no re-run and no "out of date" notice, including on return from the disconnected state. Stale-data indication is #1106. | +| T-2 | OT-7 expects the cluster node to "collapse" after Disconnect, but VS Code cannot collapse a single node (F-14). | CP-4 | Refresh the node. A disconnected cluster returns **one** child action, "Connect", following the actions-only rule. Its handler reconnects and refreshes. Do not change `TreeItem.id`. Update OT-7's wording at hand-over. | +| T-3 | WI-7 asked for provider-specific cluster ID equality (Azure case aliases match; Kubernetes contexts such as `Prod` and `prod` stay distinct). Today's stores disagree on this (F-4, F-18). | — | **Withdrawn 2026-11-19:** moved out of this iteration (decision 0009, #1105). Each store keeps its current matching. | +| T-4 | Under decision 0002, a classified failure evicts and replaces the client. A background caller such as the dashboard poll or tree count badges could therefore start a new connection every tick. | CP-2 | Only a **foreground** operation replaces a generation. Background callers read the state and stop (WI-8). Add a per-cluster backoff of one replacement per 30 s, as a guard against loops. | +| T-5 | For Entra, code 18 after the driver's own fresh callback means the server rejected a _fresh_ token: the principal has no database user, or Conditional Access or CAE intervened. That is not the same as `signInRequired`. | CP-2 | Classify it as `credentialsRejected` with an Entra-specific explanation ("Your account has no access…"). Offer **Sign in again** only when the token came from a session the user can replace. Decide this with the real driver error shapes collected for CP-0. | --- @@ -239,6 +266,10 @@ Moved to [#1105](https://github.com/microsoft/vscode-documentdb/issues/1105) on - Kubernetes API credential expiry (AKS exec plugin); - a wider network-resilience test matrix beyond OT-4, including a Kubernetes acceptance test. +Moved to [#1106](https://github.com/microsoft/vscode-documentdb/issues/1106) (decision 0010): any +"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. + 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 @@ -282,7 +313,8 @@ semantics are binding unless a checkpoint changes them. - Byte equality is **not** established. Nothing about a token is retained except the previous `iat` and `exp` numbers. - The observer never receives the token, a hash of it or any other claim. - - WI-4 uses it for T-1 rotation; WI-9 uses it for `connection.tokenRenewal`, including the miss outcomes. + - WI-9 uses it for `connection.tokenRenewal`, including the miss outcomes. A WI-5 rule may also read the + last `expiresAtSec`, if OP-1 shows that the server closes the socket (CP-0). - **C-4. Binding.** - Its form is `{ clusterId, fingerprint, generation }`. - **`fingerprint`** is an opaque hash of the logical deployment plus the effective principal (WI-4). It @@ -327,15 +359,15 @@ semantics are binding unless a checkpoint changes them. Each checkpoint is a short written verdict recorded in the Progress block of the WI named. Until the verdict exists, do not start the work it gates. -| CP | When | Question | Evidence required | -| ----- | --------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| CP-0 | WI-1, after step 1, before the handler is changed | Which strategy for expired tokens (T-1)? Confirm F-1 and F-2 with the driver contract test. | Contract test output, plus, if available, an Azure DocumentDB handshake log after expiry (no tokens logged). If T-1 changes the intent of 0002: the operator's answer. | -| CP-W3 | WI-3, after the version probe | Which azext versions (A4)? | `npm ls @microsoft/vscode-azext-azureauth`, bundle scan for duplicate copies, size of the build-error list for each option. | -| CP-1 | Before PR 3 opens | Does C-1 work for every auth method, including the managed identity runtime shape and tunnels? | Fingerprint table tests (WI-4 step 1). | -| CP-2 | WI-5, after the classifier is drafted, before recovery is wired | The classifier table, T-4 and T-5. | Classifier table tests run on **real** driver error shapes captured by the contract test and the tree paths. | -| CP-3 | Before WI-6 webview work | Split PR 5 into 5a/5b? Is the binding-resolution API and state channel final? | Diff size of host-only work; one router converted end to end. | -| CP-4 | Before WI-7 starts | Teardown order, T-2, the export lease (A5). | Teardown sequence diagram in the PR description. | -| CP-5 | Before PR F | Is the hand-over complete? | OT-1 to OT-7 results recorded in `# Outcome`, WI-9 queries run on pre-release ingestion. | +| CP | When | Question | Evidence required | +| ----- | --------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| CP-0 | WI-1, after step 1, before the handler is changed | What does the server do when an expired token reaches a new socket: does it answer code 18, or close the socket? The strategy itself is decided (0010); this only tells the WI-5 classifier what to act on. | Contract test output, and the **operator test OP-1** (§0): one real waited session, never logging tokens. | +| CP-W3 | WI-3, after the version probe | Which azext versions (A4)? | `npm ls` for each package, bundle scan for duplicate copies, build-error list per level, and the **packaged VSIX** loading and passing the WI-3 workflow checks. | +| CP-1 | Before PR 3 opens | Does C-1 work for every auth method, including the managed identity runtime shape and tunnels? | Fingerprint table tests (WI-4 step 1). | +| CP-2 | WI-5, after the classifier is drafted, before recovery is wired | The classifier table, T-4 and T-5. | Classifier table tests run on **real** driver error shapes captured by the contract test and the tree paths. | +| CP-3 | Before WI-6 webview work | Split PR 5 into 5a/5b? Is the binding-resolution API and state channel final? | Diff size of host-only work; one router converted end to end. | +| CP-4 | Before WI-7 starts | Teardown order, T-2, the export lease (A5). | Teardown sequence diagram in the PR description. | +| CP-5 | Before PR F | Is the hand-over complete? | OT-1 to OT-7 results recorded in `# Outcome`, WI-9 queries run on pre-release ingestion. | --- @@ -366,7 +398,8 @@ verdict exists, do not start the work it gates. - Each OIDC callback returns a token that is valid for the account the connection started with, looked up silently. - A silent miss produces a typed error that every surface explains the same way. -- A known-expired token is never offered on a new socket (by the mechanism chosen at CP-0). +- An expired token that the server rejects is renewed silently. The extension relies on the server's + answer, not on local expiry checks (decision 0010). **Read first:** @@ -391,25 +424,20 @@ verdict exists, do not start the work it gates. - (d) a network error does not. - Name the suite so it reads as a contract: `driver contract: mongodb OIDC workflow (7.2.0)`. If a driver upgrade breaks it, the strategy has to be reviewed again. -2. **CP-0.** Choose the strategy for expired tokens, using T-1. The options: - - **A.** Rely on code 18. This only meets the approved plan's gate if the operator relaxes it. - - **B (recommended).** Proactive rotation. `ClustersClient` keeps the latest `expiresAtSec` it learned - through C-3. When a client is resolved, for any caller, and that time is in the past (minus a margin - of 300 s), it builds a new generation with the same fingerprint before returning. Implement the - client side of this in WI-4. WI-1 only provides C-3. - - **C.** Clear the driver's internal `TokenCache`. Rejected: it depends on driver internals. - - **Coverage, which must be shown for the chosen option (T-1 caveat):** - - (i) host operations that resolve a client; - - (ii) sockets the pool opens by itself: check the effective `minPoolSize` and `maxIdleTimeMS`, and - whether pool maintenance can open an authenticated socket with no operation pending; - - (iii) the shell and playground workers. Their own driver caches the token too; does WI-2 need a - worker-side rotation, for example recreating the worker's `MongoClient` when the relayed token - expires? - - For each path, record "covered by …" or "operator relaxed the guarantee for this path on ". - - Record the verdict, and the operator's answer if T-1 changes intent. +2. **CP-0.** The strategy is **decided** (T-1, decision 0010): rely on the server. No proactive + rotation and no local expiry checks. An expired token is rejected with code 18, and the driver calls + our callback, which renews silently (step 5). + - Add **tracing** that makes this visible without logging tokens: each callback call with its + outcome (C-3), and the server error code or socket error that preceded it. + - Then **stop and hand OP-1 to the operator** (§0, operator tests). + - Act on the result: + - **code 18, then a second callback, then success:** nothing more to do; + - **socket closed or reset, with no callback:** the driver keeps its stale cached token, so retrying + on the same client cannot recover. Add a WI-5 classifier rule: on an Entra client whose last + observed token has expired (C-3), a closed connection during authentication is `clientClosed`, so + the next **foreground** operation creates a new generation with a fresh token cache (T-4 still + applies). + - Record the result and the rule, if one was added, in Progress. 3. **Session helper.** - Add `src/documentdb/auth/entraSession.ts`. It calls `vscode.authentication.getSession` with an @@ -510,7 +538,11 @@ verdict exists, do not start the work it gates. - Optional optimization (the advisor decides): if the host already has a client for the cluster with a verified identity, seed the snapshot from it, so the initial relay is silent too. - **The shell or playground surface keeps its own binding** (C-4 fingerprint plus C-1), and that - binding **outlives the worker** (F-15). Before an automatic respawn (`ShellSessionManager.evaluate`, + binding **outlives the worker** (F-15). It registers in the **same surface registry** as the + webviews (WI-6 host step 1), with kind `shell` or `playground`. It consumes the same projected state + (C-5) and the same latch (C-6), so host and workers share one lifecycle coordinator, not two state + machines. If PR 1 lands before the registry exists, keep the latch behind a small interface that + WI-6 moves into the registry. Before an automatic respawn (`ShellSessionManager.evaluate`, `executePlaygroundCode.ts`), check the binding and the surface latch: - same fingerprint and not latched: respawn as today; - a different fingerprint, or latched: do not respawn. Print the disconnected reason and the action. @@ -619,6 +651,8 @@ verdict exists, do not start the work it gates. - sign-in, account changes, MFA and cloud switches; - deep links (`/connect/azure`, with and without a tenant ID); - every `AzureWizard` flow; + - the **packaged VSIX** (`npm run package`) loads and activates, and the checks above pass on it, + not only on a dev build; - the masking test in the telemetry-masking memory: a property containing "error" is still redacted. - Choose with the advisor. If L2 needs more than mechanical changes in the `azureresources-api` 3 consumers, step down to L1 and record why. @@ -698,8 +732,17 @@ shim (0005). - Native: user + the **effective** authentication database, using the driver's rules (F-17): explicit `authSource`, else the URI's database path, else `admin`; - Entra: `providerId` + `accountId` + `tenantId`; - - managed identity: the client ID, as the runtime credential carries it, or `system-assigned`; + - managed identity: the client ID, as the runtime credential carries it, or `system-assigned`. + **Known limitation:** if an admin replaces a resource's system-assigned identity, the principal + changes but the fingerprint does not. That is not the user-driven identity switch that 0003 guards + against, so document it rather than research a principal claim; - no auth: `none`. + - **Fail closed:** when two inputs might mean the same deployment but normalization is unsure (for + example, an SRV string compared with a seed list), the fingerprints **differ**. The user then sees + "credentials changed" once and reconnects, which is acceptable. + - The Entra `providerId` is part of the fingerprint, so a provider or cloud change is an **identity + change**. Open surfaces go disconnected, and Reconnect is an explicit rebind under the current + settings. - Hash it (SHA-256, hex, truncated) into an opaque string. - Table tests: - a password-only change keeps the fingerprint; @@ -750,11 +793,7 @@ shim (0005). - If the fingerprint differs, do not publish. Return a typed `IdentityChangedError` for WI-5 and WI-6 to handle. - Today's `client._mongoClient.connect()` call on the cached path goes away. -7. **Rotation (CP-0 option B, if chosen).** - - Subscribe to C-3 from the auth handler at startup, and store `tokenExpiresAtSec` on the instance. - - Expose `needsRotation(now)`, and apply it inside `getClient` for **every** caller. Rotation is not a - failure-driven replacement, so the T-4 background restriction does not apply to it. - - Cover the other paths that CP-0 lists, or record their relaxation. +7. ~~**Rotation.**~~ Removed: no proactive rotation (decision 0010). 8. **Telemetry helper.** - Add `addEstablishedConnectionContext(context, clusterId | client)`. It sets `authMethod`, `connectionCorrelationId`, and the measurements `connectionAgeMs` and `clientGeneration`. @@ -765,8 +804,8 @@ shim (0005). - declared in `package.json`; - registered only in development mode; - listed in `LAZY_COMMANDS` with its reason. - - It (a) makes the next N Entra callbacks for a selected cluster behave like a silent miss, (b) marks - the token as expired for rotation, and (c) force-closes the pool to simulate an idle drop. + - It (a) makes the next N Entra callbacks for a selected cluster behave like a silent miss, and (b) + force-closes the pool to simulate an idle drop. - Use a dashed context key if one is needed. **Tests** (`ClustersClient.test.ts`, plus the new fingerprint test): @@ -837,8 +876,7 @@ shim (0005). stale. It evicts according to the table and updates the C-5 **cluster** state. Surface states are projected per binding (WI-6). - It fires `onDidChangeConnectionState(clusterId)`. - - A foreground helper `withClusterClient(clusterId, op, { foreground })` resolves the client (including - rotation under CP-0 option B), runs the operation, reports failures, and applies the T-4 backoff. + - A foreground helper `withClusterClient(clusterId, op, { foreground })` resolves the client, runs the operation, reports failures, and applies the T-4 backoff. WI-6 extends it with bindings. 3. **Tree.** - Route both catch paths in `getChildren` (cached-client reuse and `listDatabases`) through @@ -948,14 +986,14 @@ shim (0005). - `register({ clusterId, kind, binding, pushState, dispose, hasUnsavedChanges? })` returns a disposable. - Collection View, Document View and the Dashboard register when they open and unregister on - `onDisposed`. + `onDisposed`. Shells and the playground register too (WI-2), so there is one registry for every + surface. - WI-7 enumerates this registry. 2. **Binding resolution.** - `resolveBoundClient(binding, { foreground })` has three outcomes: - (a) same fingerprint and generation: return the client; - - (b) same fingerprint, the client was replaced or closed for **recovery or rotation**: return the - current client, with no re-run (T-1, if confirmed). If T-1 is **not** confirmed, follow 0002 as - written: re-run the applied query from page 1, and discard old-generation responses; + - (b) same fingerprint, the client was replaced or closed for **recovery**: return the current + client, transparently, with no re-run and no notice (decision 0010); - (c) a different fingerprint, the cluster is latched `disconnected` (C-6), or `identityChanged`: throw a typed `SurfaceDisconnectedError(reason)`. - Projection rule (C-5): the surface's state comes from comparing **its** binding with the cluster's @@ -983,7 +1021,9 @@ shim (0005). - Save document, inserts and deletes, and index create, drop, hide and unhide. - When the request may have reached the server and the reply was lost (network error or timeout after send), report **outcome unknown**: "The change may or may not have been applied. Refresh to check." - - Never resubmit. Leave the driver's own `retryWrites` as it is. + - The extension **never resubmits** a write. That is the guarantee, and OT-4's "not replayed" means + this. The driver's own retryable writes (`retryWrites`) stay as they are: the server deduplicates + them by design, and RU connection strings disable them. - Test that one application-level submission results in exactly one call to the driver. 6. **State channel and stale results.** - Each view router gets a `connectionState` subscription, fed by the registry (C-5 surface state). It @@ -992,7 +1032,7 @@ shim (0005). rebind. - Every request records `{ epoch, generation }` when it starts. - **Before any host-side mutation**, check that the epoch is unchanged and that the generation is - acceptable under T-1 (or under 0002 as written). That covers `ClusterSession`'s + acceptable: same fingerprint is acceptable under decision 0010. That covers `ClusterSession`'s `_currentRawDocuments`, its query caches, Query Insights caches and `SchemaStore` updates. A stale result must not change host state at all, so dropping it only at delivery is not enough. - Check again at delivery. The UI applies the same check (5b). @@ -1014,12 +1054,13 @@ shim (0005). - Responses whose epoch is older than the UI's current epoch are discarded on the UI side too. 3. **What each view keeps.** - **Collection View:** query text, filter, sort, projection, page number and size, the selected tab, - and Query Insights results with a "stale" marker. + and the Query Insights results as they were. - **Document View:** the dirty editor content and `isDirty`. - - **Dashboard:** the last data, marked stale (WI-8 stops the polling). + - **Dashboard:** the last data (WI-8 stops the polling). 4. **Actions.** - - **Reconnect** (same fingerprint): resolve again. On success, show "Reconnected. Results may be out - of date. Run the query again to refresh." The query is not run automatically. + - **Reconnect** (same fingerprint): resolve again. On success, remove the banner and re-enable the + actions; the live region announces "Reconnected". The query is not run automatically, and there is + **no** "out of date" notice (decision 0010; see #1106). - **Reconnect after an identity change:** an explicit rebind to the new fingerprint, then show "Now connected as {label}" (OT-3). - **Sign in again:** the WI-5 command. @@ -1062,6 +1103,15 @@ shim (0005). - One teardown serves Disconnect, Remove and identity-changing credential updates. - It is guarded by task conflicts and dirty editors. - It covers every per-cluster resource. +- **What it guarantees:** after `commit`, no operation **starts** under the old binding. Operations + already in flight are not admitted or tracked individually: + - `deleteClient` closes the client with `force`, so they fail; + - their failure is reported normally, and a write whose reply was lost is reported as outcome unknown + (WI-6); + - shell and playground workers are stopped; + - tasks and exports are protected by the preflight. + + This is the right level for an interactive tool; do not build per-operation admission control. **Read first:** @@ -1171,6 +1221,8 @@ shim (0005). - a copy or export that starts while the Disconnect prompt is open blocks the commit, and nothing changes; - a task or lease cannot start while a teardown reservation is held; - a shell or playground left open after Disconnect does not respawn on its next command; +- Disconnect while a query or save is in flight: the operation fails and is reported (a write as outcome + unknown), and nothing runs afterwards under the old binding; - a failed save keeps the old binding; - a concurrent connect during Update Credentials does not publish the old credentials. @@ -1286,7 +1338,11 @@ shim (0005). 1. Sync `main` into the feature branch through a pure merge PR (approved plan rule 5). 2. Run Case 2 on the feature branch head. 3. Run OT-1 to OT-7 on the packaged VSIX, with at least one real wait of two hours or more. Record each - result, and the evidence the approved plan requires, in `# Outcome`. + result, and the evidence the approved plan requires, in `# Outcome`. In addition: + - **OT-1:** check the shell separately. After the wait, its worker's own connection must renew without + a prompt; record the token relay in the output channel, never the token. + - **OT-7:** also Disconnect while a query or save is in flight. It must fail and be reported, and + nothing may run afterwards under the old connection. 4. CP-5 verdict, then open PR F. Watch telemetry for about one week after the merge (WI-9 queries). # Outcome 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 6b4893104..b785dcd0b 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 @@ -202,6 +202,11 @@ that a known-expired token is not offered on a new socket, including speculative After a callback threw, the same driver workflow reused the rejection; a fresh workflow succeeded. Test that explicit recovery replaces the failed workflow rather than retrying it indefinitely. +> **Changed 2026-11-19 (decision [0010](../decisions.md)):** the "known-expired token is not offered" +> requirement is dropped. The extension relies on the server rejecting an expired token, after which the +> driver calls the callback and renews silently. No proactive rotation, no local expiry checks. The +> operator test OP-1 in [01-dev-plan.md](./01-dev-plan.md) checks what the server actually returns. + ## WI-2: Shell and Playground token relays use the same policy **Problem:** both relays call `createIfNone: true` inside the worker's token request @@ -362,6 +367,9 @@ The largest item. Host side first, then each view. - same fingerprint, new generation: re-run the applied query from page 1 with a notice that results are no longer current. Pages use separate offset queries, not a cursor held between pages. Discard old-generation responses on both host and UI; preserve unapplied editor text; + - **Changed 2026-11-19 (decision 0010):** transparent: proceed on the current client, with no + re-run and no notice. Any "out of date" indication is + [#1106](https://github.com/microsoft/vscode-documentdb/issues/1106). - different fingerprint, or no client: **disconnected**, with a reason. - **The extension never resubmits a write with an unknown outcome.** Report the outcome as unknown, not as a definite failure. The driver can retry the same logical write or handle 391 @@ -524,7 +532,7 @@ least once. | # | Scenario | Steps | Pass when | | ---- | ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| OT-1 | **Entra, long idle, work open** | Connect with Entra. Open a Collection View with filter, sort and projection, on page 2. Open a Document View with an unsaved edit. Open the Cluster Dashboard and a shell. Wait ≥ 2 h. Then refresh the tree, run the query, go to the next page, save the document, and run a command in the shell. | Everything works. No sign-in prompt, and no error that needs a click. Text and edits are kept. If page 1 is re-run, the view says why. | +| OT-1 | **Entra, long idle, work open** | Connect with Entra. Open a Collection View with filter, sort and projection, on page 2. Open a Document View with an unsaved edit. Open the Cluster Dashboard and a shell. Wait ≥ 2 h. Then refresh the tree, run the query, go to the next page, save the document, and run a command in the shell. | Everything works. No sign-in prompt, and no error that needs a click. Text and edits are kept. (No re-run and no out-of-date notice: decision 0010.) | | OT-2 | **Entra, silent renewal impossible** | With the OT-1 surfaces open, sign out of the account in the Accounts menu (or revoke sessions in Entra). Run the query. Dismiss the prompt if one appears. Wait 5 min. Then click **Sign in again** and pick the same account. | The action fails once and offers **Sign in again**. The tabs show "sign-in expired" with their content kept. No modal appears on its own, and nothing prompts again after a dismissal. After signing in, the tabs re-enable and the unsaved edit saves. | | OT-3 | **Identity change is never silent** | (a) Native: with tabs open, use Update Credentials to switch to a different user. Choose "Keep open (disabled)". (b) Repeat, changing only the password of the same user. (c) Entra: in OT-2, sign in again with a _different_ account. | (a) and (c): tabs are disabled with "credentials changed", no action runs under the new identity, and Reconnect opens a new session and says so. (b): tabs continue. | | OT-4 | **Native, idle and network drop** | Native connection with tabs open. Turn the network off for 2 min, or put the machine to sleep for ≥ 30 min, then restore it. Run a query, refresh the tree, save a document. Also try an insert while offline. | The operations work after restoring, at most after one Retry. The offline insert is reported as failed or unknown and is **not** replayed. | diff --git a/docs/ai-and-plans/features/connection-lifecycle/research-findings.md b/docs/ai-and-plans/features/connection-lifecycle/research-findings.md index 9ad2b779e..e2e01f3b0 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/research-findings.md +++ b/docs/ai-and-plans/features/connection-lifecycle/research-findings.md @@ -246,8 +246,10 @@ read as seconds: | Entra ID | 912 | ~2.0 s | ~9.0 s | | No Auth | 188 | ~0.07 s | ~1.8 s | -A `MongoClient` also owns cursors (Collection View pagination uses `getMore`), server sessions and -monitoring. A per-operation client would cost seconds per action and break pagination. +A `MongoClient` also owns server sessions and monitoring, and the shell and playground hold cursors. +Collection View pagination does **not** hold a cursor: each page is a separate offset (`skip`) query, as +`ClusterSession.runFindQueryWithCache` shows (corrected 2026-11-19; an earlier version of this document +said it used `getMore`). A per-operation client would still cost seconds per action. ## Appendix: queries From f4d8c2b2b6a55e6e4e6c51a10a95eca80d65d331 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 19 Nov 2026 14:23:29 +0000 Subject: [PATCH 006/380] wip: complexity reduction --- .../features/connection-lifecycle/README.md | 4 +- .../connection-lifecycle/decisions.md | 69 ++ .../iterations/01-dev-plan.md | 704 +++++++++--------- .../iterations/01-implementation-plan.md | 13 +- 4 files changed, 433 insertions(+), 357 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/README.md b/docs/ai-and-plans/features/connection-lifecycle/README.md index 53514f6c8..37d5afd1e 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/README.md +++ b/docs/ai-and-plans/features/connection-lifecycle/README.md @@ -72,7 +72,9 @@ See [decisions.md](./decisions.md): - 0007 the Disconnect choice is a modal, not remembered, with a setting for the default; - 0008 the azext stack is upgraded as high as viable, with Azure Resources as the reference; - 0009 Kubernetes tunnel recovery, case handling and wider network-resilience testing move to #1105; -- 0010 rely on the server to reject expired tokens; same-identity client replacement is transparent. +- 0010 rely on the server to reject expired tokens; same-identity client replacement is transparent; +- 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. ## Timeline diff --git a/docs/ai-and-plans/features/connection-lifecycle/decisions.md b/docs/ai-and-plans/features/connection-lifecycle/decisions.md index c6f18890c..e1d956209 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/decisions.md +++ b/docs/ai-and-plans/features/connection-lifecycle/decisions.md @@ -22,6 +22,8 @@ created: 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 | — | > 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 @@ -285,3 +287,70 @@ Rejected: costs a reconnect about every hour, and local expiry checks are unreliable anyway. - **Re-run page 1 with a "results are no longer current" notice** (0002 as written): it would appear after every reconnect, for no correctness benefit. + +## 0011. Disconnect keeps the cached credentials and the verified identity; only Remove drops them + +**Accepted** by the operator on 2026-11-19. It answers plan Q3 (dev plan A3), reversing the #1059 +proposal that Disconnect drops `CredentialCache`. Source: operator input on the pre-hand-over review of +the dev plan. + +> we should not drop the credential cache, that was too premature + +- **Disconnect** closes the client, stops the shell and playground workers, latches the cluster and + handles open surfaces (0004, 0007). It keeps the `CredentialCache` entry and `lastVerifiedIdentity`. +- **Remove Connection** drops both. An identity-changing credential update keeps the new credentials and + replaces the verified identity on its next successful connect. +- Evidence from the review (the operator's reason is the quote above): `ClustersClient` can start a client only from a `CredentialCache` entry, and only the tree fills it + (dev plan F-20). Dropping it on Disconnect would leave a tab's Reconnect with nothing to connect from, + because surfaces never prompt. Keeping `lastVerifiedIdentity` makes that Reconnect silent and pinned to + the same identity. If the Entra session is gone, it fails with **Sign in again** (0001), never with a + prompt for another account. +- The same review found that the tree drops `CredentialCache` on **every** connect failure, including + network errors. The dev plan (WI-5 step 3) now keeps the entry for recoverable failures and evicts it + only when credentials were rejected. + +Rejected: + +- **Drop `CredentialCache` on Disconnect (#1059, the earlier provisional answer A3):** it needs a second + credential-loading path outside the tree for every provider (storage, ARM, Atlas, Kubernetes), and the + user must retype a password that was typed only for a discovery connection. + +## 0012. Keep the lifecycle design minimal: no state machine, one epoch, no prompts in getClient, one-step teardown + +**Accepted** by the operator on 2026-11-19, after a review of the dev plan for over-engineering. Source: +operator input. + +> the premise is simple, so I don't want to have too many managers, controllers, and reconcile tools +> processes in the plan. + +> apply all simplifications to the plan, and I approve all simplifications. + +The dev plan ([iterations/01-dev-plan.md](./iterations/01-dev-plan.md)) now follows these rules: + +- **No stored connection state.** There is no cluster state machine, no projected surface state, no state + service with change events, and no tRPC state subscription. A surface learns its state when it resolves + its binding; routers return a structured "unavailable" result. The only push is teardown calling + `disable(reason)` on each registered surface, and that registry is a plain list. +- **One staleness guard:** the per-client generation plus one per-cluster epoch. The separate startup, + lifecycle and surface epochs, the dashboard loop token and the worker instance IDs are gone. A stale + result is checked once on the host, before it changes anything; the webview ignores responses while its + banner shows. +- **`getClient` never prompts.** The `interaction` parameter and the audit of every call site are gone. + Only the tree's first connect and Sign in again may prompt. Background callers pass `background: true` + and never replace a client. +- **Teardown is two plain functions** (confirm, then commit), with a conflict recheck right before the + commit. No reservation in TaskService and no rollback. +- **No `onDidChangeSessions` listener.** This changes the approved plan's WI-5. The next operation's + silent lookup finds a signed-out account. +- **Four error classes:** `EntraSignInRequiredError`, `EntraIdentityMismatchError`, `TokenCallbackError` + for any other callback throw (all auth methods), and `ConnectionUnavailableError { reason }`. +- **The fingerprint hashes the stored connection string without its password, plus the principal.** No + normalization; any connection-string edit counts as an identity change. +- **Smaller removals:** the 30 s replacement backoff; startup abort only when every waiter aborted; + two Sign in again paths (it always uses `forceNewSession`); shells and the playground in the surface + registry; the changed-token telemetry, the remaining-validity measures and `connection.recovered` + (this changes the approved plan's WI-9); the "outcome unknown" wording for writes; checkpoints CP-1 and + CP-3, which become ordinary PR review. PR 5 stays one PR unless its diff becomes too large. + +Unchanged: everything that carries an accepted decision (0001 to 0011), the single-flight startup, the +cancelled-reuse fix, closed-client replacement, the failure classifier and the export and import lease. 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 b538395ac..95c215039 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 @@ -83,14 +83,14 @@ followed by: Do not continue past the blocked step until the operator replies. Work that does not depend on the result may continue, but say so in the message. Record the result in the Progress block of the WI. -| OP | When | Test | -| ---- | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -| OP-1 | WI-1, CP-0 | Entra connection, idle past the token lifetime (60–90 min or more), then force a new connection. Does the server answer code 18 or close the socket? | -| OP-2 | WI-3, CP-W3 | The azext workflow checks on the packaged VSIX: Azure sign-in, discovery, filters, deep links, wizards, Azure Resources view. | -| OP-3 | WI-5 done | OT-2's tree part with a real sign-out: Sign in again, a dismissal, no reprompt. | -| OP-4 | WI-6 done (after 5b) | OT-1 (short form, with the WI-4 hook) and OT-3(a) and (b) on a dev build. | -| OP-5 | WI-7 done | OT-7 on a dev build, including a Disconnect during a running copy or export, and while a query or save is in flight. | -| OP-6 | Before PR F (CP-5) | OT-1 to OT-7 on the packaged VSIX, with at least one real wait of two hours or more (PR F step 3). | +| OP | When | Test | +| ---- | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------- | +| OP-1 | WI-1, CP-0 | Entra connection, idle past the token lifetime (60–90 min or more), then force a new connection. Does the server answer code 18 or close the socket? | +| OP-2 | WI-3, CP-W3 | The azext workflow checks on the packaged VSIX: Azure sign-in, discovery, filters, deep links, wizards, Azure Resources view. | +| OP-3 | WI-5 done | OT-2's tree part with a real sign-out: Sign in again, a dismissal, no reprompt. | +| OP-4 | WI-6 done | OT-1 (short form, with the WI-4 hook) and OT-3(a) and (b) on a dev build. | +| OP-5 | WI-7 done | OT-7 on a dev build, including a Disconnect during a running copy, export or import, and while a query or save is in flight. | +| OP-6 | Before PR F (CP-5) | OT-1 to OT-7 on the packaged VSIX, with at least one real wait of two hours or more (PR F step 3). | ### Per-PR workflow @@ -129,17 +129,17 @@ result may continue, but say so in the message. Record the result in the Progres ## 1. Answers to the open questions -The operator was not available on 2026-11-19 at first. They answered A2, A4, A5 and A6 later the same -day; A1 and A3 are still **provisional** under rule 4 above. +The operator was not available on 2026-11-19 at first. They answered A2 to A6 later the same day; A1 is +still **provisional** under rule 4 above. -| # | Question | Answer | Status | Where it lands | -| --- | ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- | ---------------------- | -| A1 | Plan Q1: how does sign-in start after a silent miss? | **Only through the Sign in again button**, everywhere. The first connect from the tree stays interactive, as it is today. One rule, and no surface has to decide whether it is in the foreground. This matches 0001. | Provisional | WI-1, WI-2, WI-5, WI-6 | -| A2 | Plan Q2: Disconnect choice, default and memory | A **VS Code modal**, which has no pre-selected button and **remembers nothing**. A setting lets users choose a default: `ask` (the default) shows the modal; `closeAll` or `keepOpenDisabled` skips it. The unsaved-edits confirmation still appears when closing. See WI-7 step 3. | **Operator, 2026-11-19** (decision 0007) | WI-7 | -| A3 | Plan Q3: does Disconnect drop `CredentialCache`? | **Yes** (#1059 proposal). Saved connections reload from storage on the next expand. A password typed only for a discovery connection must be typed again. Implement it as a teardown option, so flipping the answer is a one-line change. | Provisional | WI-7 | -| A4 | #990: which azext versions? | **As high as viable without breaking our workflows**, using the Azure Resources extension (same team as azureauth, heavily used) as the reference. Ladder and findings are in WI-3 step 1: target L2, fall back to L1, then L0. | **Operator policy, 2026-11-19** (decision 0008) | WI-3 (CP-W3) | -| A5 | How does Disconnect see an in-flight Export? | **Reuse the existing mechanism.** Delete Collection, Delete Database and Remove Connection already guard through `checkCanProceedAndInformUser` (`TaskService` resource tracking). Export is the gap: it is not a task and registers nothing, so even Delete Collection does not see a running export today. Close it with a small **resource lease** that feeds the same check. Every existing guard then sees exports too, and the export logic is not touched. | Operator pointed at the existing check; lease is the recommendation | WI-7 | -| A6 | Where do the dev plan and its progress notes live? | In this file. Progress is recorded inline per WI here. The approved plan gets a one-line pointer. | **Operator, 2026-11-19** | — | +| # | Question | Answer | Status | Where it lands | +| --- | ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | ---------------------- | +| A1 | Plan Q1: how does sign-in start after a silent miss? | **Only through the Sign in again button**, everywhere. The first connect from the tree stays interactive, as it is today. One rule, and no surface has to decide whether it is in the foreground. This matches 0001. | Provisional | WI-1, WI-2, WI-5, WI-6 | +| A2 | Plan Q2: Disconnect choice, default and memory | A **VS Code modal**, which has no pre-selected button and **remembers nothing**. A setting lets users choose a default: `ask` (the default) shows the modal; `closeAll` or `keepOpenDisabled` skips it. The unsaved-edits confirmation still appears when closing. See WI-7 step 3. | **Operator, 2026-11-19** (decision 0007) | WI-7 | +| A3 | Plan Q3: does Disconnect drop `CredentialCache`? | **No** (reverses the #1059 proposal). Disconnect keeps the `CredentialCache` entry **and** `lastVerifiedIdentity`, so Connect and a tab's Reconnect work without the tree and without retyping a discovery password. Only Remove Connection drops them; an identity-changing credential update replaces them. Keep `dropCredentials` as a teardown option. | **Operator, 2026-11-19** (decision 0011) | WI-7 | +| A4 | #990: which azext versions? | **As high as viable without breaking our workflows**, using the Azure Resources extension (same team as azureauth, heavily used) as the reference. Ladder and findings are in WI-3 step 1: target L2, fall back to L1, then L0. | **Operator policy, 2026-11-19** (decision 0008) | WI-3 (CP-W3) | +| A5 | How does Disconnect see an in-flight Export? | **Reuse the existing mechanism.** Delete Collection, Delete Database and Remove Connection already guard through `checkCanProceedAndInformUser` (`TaskService` resource tracking). Export **and Import** are the gap: neither is a task and neither registers anything, so even Delete Collection does not see a running export or import today. Close it with a small **resource lease** that feeds the same check. Every existing guard then sees them too, and the export and import logic is not touched. Copy/paste and copy-indexes are already tasks that register both endpoints (F-9). | Operator pointed at the existing check; lease is the recommendation; operator added Import (2026-11-19) | WI-7 | +| A6 | Where do the dev plan and its progress notes live? | In this file. Progress is recorded inline per WI here. The approved plan gets a one-line pointer. | **Operator, 2026-11-19** | — | --- @@ -194,7 +194,9 @@ upgrade changes any of them, stop and re-plan the affected WI. (`PlaygroundEvaluator.evaluate` → `buildInitMessage`), even when the worker is warm. - **F-9. Task coverage.** - Copy/paste and copy-indexes register both endpoints through `getUsedResources()`. - - **Export is not a task.** `exportDocuments.ts` calls `getClient` directly and registers nothing. + - **Export and Import are not tasks.** `exportDocuments.ts` and `importDocuments.ts` call `getClient` + directly and register nothing. Import calls `getClient` again for every insert batch, so a latch + during an import leaves a partial import, and running it again inserts duplicates. - **F-10. Remove Connection does not close the client, shells, the playground or webviews.** It deletes storage, `CredentialCache` and `SchemaStore` data only. - **F-11. Credential updates.** @@ -214,8 +216,8 @@ upgrade changes any of them, stop and re-plan the affected WI. lookup), tree count badges and prefetches. - Today **every** startup is interactive: `initializeClient` hardcodes `{ interactive: true }`. A background caller can therefore reconnect, or even prompt, after an eviction or a Disconnect. - - So the interaction policy and the disconnected latch must be enforced **centrally in `getClient`** - (C-6), not per caller. + - So `getClient` must **never prompt**, and the latch must be enforced **inside `getClient`** (C-6), + not per caller. - **F-15. A stopped worker respawns by itself.** - `ShellSessionManager.evaluate` re-initializes a dead or stopped worker from the current `CredentialCache`. `executePlaygroundCode.ts` recreates the evaluator in the same way. @@ -229,6 +231,8 @@ upgrade changes any of them, stop and re-plan the affected WI. - With no explicit `authSource`, the driver uses the URI's database path (`connection_string.js`, around line 307). Only when there is none does it use `admin`. - The same user on `/sales` and on `/admin` is therefore two different principals. + - The fingerprint hashes the stored connection string, which carries the database path and any + `authSource`, so this needs no special handling (WI-4 step 1). - **F-18. Cluster ID matching is inconsistent across stores.** - `CredentialCache.deleteCredentials` lowercases its key (`CaseInsensitiveMap`), so deleting Kubernetes context `prod` also deletes `Prod`. @@ -237,6 +241,15 @@ upgrade changes any of them, stop and re-plan the affected WI. - Both problems exist today. They are **out of scope** for this iteration (decision 0009, #1105). - **F-19. Credential saves can fail without the command knowing.** The Update Credentials `ExecuteStep` catches save failures and returns normally, so the command cannot tell whether the save happened. +- **F-20. Only the tree fills `CredentialCache`, and the tree empties it on any connect failure.** + - `ClustersClient.initializeClient` starts only from a `CredentialCache` entry. Without one it throws + "No credentials found for id {clusterId}" and sets `startup.credentialsMissing`. + - Only the tree items' provider-specific `authenticateAndConnect` methods (and Update Credentials, + which reloads the entry from storage) fill the cache. + - Every `authenticateAndConnect` failure path calls `deleteClient` **and** + `CredentialCache.deleteCredentials`, whatever the cause: `DocumentDBClusterItem`, the Azure + Resources vCore and RU items, and the Atlas, Kubernetes, VM, vCore and RU discovery items. + - So a tree expand during a network outage leaves open surfaces with nothing to reconnect from. - **F-14. VS Code has no API to collapse one tree node.** - The repository uses `reveal(..., { expand: false })`, which does not collapse a node. - Collapsing through a changed `TreeItem.id` would conflict with the `treeId`/`clusterId` rules. @@ -250,7 +263,7 @@ upgrade changes any of them, stop and re-plan the affected WI. | T-1 | WI-1 required that a known-expired token is never offered on a new socket. Under F-2 that is only possible with a new `MongoClient` once the issued token expires. Decision 0002 says a new generation re-runs reads from page 1 "because cursors are lost", but under F-6 no surface holds a cursor. | CP-0 | **Resolved by the operator on 2026-11-19 (decision 0010).** (1) No proactive rotation and no local expiry checks: "the server will tell us, then we can act". An expired token is rejected by the server; the driver then calls the callback, which renews silently. If the server closes the socket instead, the classifier acts on that (WI-5). (2) Replacing a client for the same identity is **transparent**: no re-run and no "out of date" notice, including on return from the disconnected state. Stale-data indication is #1106. | | T-2 | OT-7 expects the cluster node to "collapse" after Disconnect, but VS Code cannot collapse a single node (F-14). | CP-4 | Refresh the node. A disconnected cluster returns **one** child action, "Connect", following the actions-only rule. Its handler reconnects and refreshes. Do not change `TreeItem.id`. Update OT-7's wording at hand-over. | | T-3 | WI-7 asked for provider-specific cluster ID equality (Azure case aliases match; Kubernetes contexts such as `Prod` and `prod` stay distinct). Today's stores disagree on this (F-4, F-18). | — | **Withdrawn 2026-11-19:** moved out of this iteration (decision 0009, #1105). Each store keeps its current matching. | -| T-4 | Under decision 0002, a classified failure evicts and replaces the client. A background caller such as the dashboard poll or tree count badges could therefore start a new connection every tick. | CP-2 | Only a **foreground** operation replaces a generation. Background callers read the state and stop (WI-8). Add a per-cluster backoff of one replacement per 30 s, as a guard against loops. | +| T-4 | Under decision 0002, a classified failure evicts and replaces the client. A background caller such as the dashboard poll or tree count badges could therefore start a new connection every tick. | CP-2 | Only a **foreground** operation replaces a generation. Background callers pass `background: true` and just fail (C-6, WI-8). No backoff: with no background replacement there is no loop to guard against (decision 0012). | | T-5 | For Entra, code 18 after the driver's own fresh callback means the server rejected a _fresh_ token: the principal has no database user, or Conditional Access or CAE intervened. That is not the same as `signInRequired`. | CP-2 | Classify it as `credentialsRejected` with an Entra-specific explanation ("Your account has no access…"). Offer **Sign in again** only when the token came from a session the user can replace. Decide this with the real driver error shapes collected for CP-0. | --- @@ -292,81 +305,76 @@ semantics are binding unless a checkpoint changes them. credentials used. - WI-2 builds the same shape at worker spawn. - Never logged, never sent to telemetry, never persisted. -- **C-2. Typed auth errors.** - - One error class per outcome, each with a stable `name` and a bounded `reason`: - - `EntraSignInRequiredError`, reason `noSession | providerChanged`; - - `EntraIdentityMismatchError` (a different account came back); - - `EntraTokenRefreshError` (any other failure of the lookup; the cause is kept, but it is never - rendered raw). - - Messages are localized. Classification uses the `name` (walking `cause`), never the message. - - All three are "callback threw" for F-1. +- **C-2. Typed errors: four classes in total.** + - `EntraSignInRequiredError`, reason `noSession | providerChanged`. + - `EntraIdentityMismatchError`: a different account came back. + - `TokenCallbackError`: wraps **any other** error thrown from an OIDC callback, for every auth method + (Entra and managed identity), with a bounded `authMethod`. The original is kept as `cause` and is + never rendered raw. + - `ConnectionUnavailableError { reason }`: the one error for a client the caller cannot use (the latch, + an identity change, missing credentials). `reason` is the C-5 enum. + - Messages are localized. Classification uses the `name` (walking `cause`), never the message. Existing + name checks that walk `cause`, such as destination rejection, keep working. + - The first three are "callback threw" for F-1. - Keep the existing `AuthInputUnavailableError` for the non-interactive startup path (diagnostics). Either make the new errors related to it or map between them explicitly, so the Entra failure registry still skips silent misses (comment in `MicrosoftEntraIDAuthHandler.configureAuth`). - **C-3. Token lookup observation.** - Every **completed** post-startup token lookup notifies an optional host-only observer, whether it - succeeded or failed: - `{ outcome: 'returned' | 'noSession' | 'identityMismatch' | 'failed', issuedAtSec?, expiresAtSec?, changed: boolean | 'unknown' }`. - - `changed` means "a different issuance": the JWT `iat` or `exp` differs from the previous token - returned in the same binding. It is `'unknown'` when either token is opaque, or when there is no - earlier observation. - - Byte equality is **not** established. Nothing about a token is retained except the previous `iat` and - `exp` numbers. - - The observer never receives the token, a hash of it or any other claim. - - WI-9 uses it for `connection.tokenRenewal`, including the miss outcomes. A WI-5 rule may also read the - last `expiresAtSec`, if OP-1 shows that the server closes the socket (CP-0). + succeeded or failed: `{ outcome: 'returned' | 'noSession' | 'identityMismatch' | 'failed', lifetimeSeconds? }`. + - `lifetimeSeconds` is the JWT `exp` minus `iat`, and is omitted when the token is opaque. + - Nothing about a token is retained between lookups. The observer never receives the token, a hash of it + or any other claim. + - WI-9 uses it for `connection.tokenRenewal`. - **C-4. Binding.** - Its form is `{ clusterId, fingerprint, generation }`. - - **`fingerprint`** is an opaque hash of the logical deployment plus the effective principal (WI-4). It - never contains a password and is never sent to telemetry. + - **`fingerprint`** is an opaque hash of the stored connection string without its password, plus the + principal (WI-4 step 1). It never contains a password and is never sent to telemetry. - **`generation`** is a per-cluster number that only ever increases. It is **never reset**, not even after teardown. A binding from before Disconnect therefore never matches a client created after Reconnect. -- **C-5. Connection state, at two levels.** - - **Cluster state** is owned by the host and keyed by `clusterId`, matched the same way as - `ClustersClient._clients` today. It describes the cluster's - current client: `connected { binding }`, `reconnecting`, `needsAction { reason }`, or - `disconnected { reason }` (the latch, C-6). - - **Surface state** is **derived for each registered binding**. It is what the tree, webviews, shells - and the playground show: - - `connected`; - - `reconnecting`; - - `disconnected { reason, action }`. - - A surface whose fingerprint differs from the cluster's current binding is - `disconnected(identityChanged | credentialsChanged)` **even while the cluster is `connected`**. This is - what lets the tree and new panels run as identity B while panels opened as A stay disabled. - - `reason` is one of: `signInRequired`, `credentialsRejected`, `credentialsChanged`, +- **C-5. Unavailable reasons, derived on demand.** + - There is **no stored connection state** and no state machine. A surface learns where it stands when it + resolves its binding (WI-6): it gets a client, or a `ConnectionUnavailableError { reason }`. A router + returns that to the webview as structured data (F-12). + - A surface whose fingerprint differs from the client the cluster would use now is unavailable with + `identityChanged` or `credentialsChanged`, **even while the tree works**. This is what lets the tree and + new panels run as identity B while panels opened as A stay disabled. + - `reason` is one of: `signInRequired`, `credentialsRejected`, `credentialsMissing`, `credentialsChanged`, `identityChanged`, `userDisconnected`, `connectionRemoved`, `unreachable`. - `action` is one of: `reconnect`, `signInAgain`, `updateCredentials`, `close`. - - Reasons are bounded enums. The webview gets the localized text from the host. -- **C-6. Central interaction and latch policy, enforced inside `ClustersClient.getClient`.** - - **Interaction:** - - every call states `interaction: 'allowed' | 'never'`, and the default is `'never'`; - - `'allowed'` may prompt **only** when the cluster has no `lastVerifiedIdentity` (a first connect); - - once an identity is verified, reconnects are silent and pinned whatever the caller asked for; - - interactive sign-in after that happens only in the Sign in again command (A1). - - **Latch:** while a cluster is `disconnected` (Disconnect, Remove, a credentials change), `getClient` - rejects every caller with a typed `ClusterDisconnectedError`. Background callers are included. Only - the explicit Connect and Reconnect actions clear the latch. - - **Lifecycle epoch:** a per-cluster counter that increases on every latch, unlatch, eviction and - teardown. Every recovery command (Retry, Sign in again, Reconnect) captures the epoch **before** its - first `await`, and applies its result only if the epoch is unchanged (compare and swap). + - Reasons are bounded enums. The webview gets the localized text and the action from the host. + - The only push is teardown: Disconnect with Keep open calls each registered surface's `disable(reason)` + (WI-6 host step 1). +- **C-6. `getClient` rules.** + - **It never prompts.** `getClient` is always silent. Only the tree's first connect + (`authenticateAndConnect`, through `ClustersClient.connectInteractive`) and the Sign in again command + may prompt (A1). Once an identity is verified (`lastVerifiedIdentity`, WI-4), a reconnect is silent and + pinned to it. + - **Background callers** (the dashboard poll, tree count badges, playground completions) pass + `background: true`. They never replace a client; they just fail (T-4). + - **Latch:** while a cluster is disconnected (Disconnect, Remove, an identity-changing credentials + update), `getClient` throws `ConnectionUnavailableError` with the latch's reason, for every caller. + Only the explicit Connect and Reconnect actions clear the 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 + its result only if it is unchanged. With the per-client generation, it is the only staleness guard. --- ## 5. Advisor checkpoints Each checkpoint is a short written verdict recorded in the Progress block of the WI named. Until the -verdict exists, do not start the work it gates. +verdict exists, do not start the work it gates. The fingerprint table (formerly CP-1) and the PR 5 split +(formerly CP-3) are ordinary PR review (decision 0012). | CP | When | Question | Evidence required | | ----- | --------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | | CP-0 | WI-1, after step 1, before the handler is changed | What does the server do when an expired token reaches a new socket: does it answer code 18, or close the socket? The strategy itself is decided (0010); this only tells the WI-5 classifier what to act on. | Contract test output, and the **operator test OP-1** (§0): one real waited session, never logging tokens. | | CP-W3 | WI-3, after the version probe | Which azext versions (A4)? | `npm ls` for each package, bundle scan for duplicate copies, build-error list per level, and the **packaged VSIX** loading and passing the WI-3 workflow checks. | -| CP-1 | Before PR 3 opens | Does C-1 work for every auth method, including the managed identity runtime shape and tunnels? | Fingerprint table tests (WI-4 step 1). | -| CP-2 | WI-5, after the classifier is drafted, before recovery is wired | The classifier table, T-4 and T-5. | Classifier table tests run on **real** driver error shapes captured by the contract test and the tree paths. | -| CP-3 | Before WI-6 webview work | Split PR 5 into 5a/5b? Is the binding-resolution API and state channel final? | Diff size of host-only work; one router converted end to end. | -| CP-4 | Before WI-7 starts | Teardown order, T-2, the export lease (A5). | Teardown sequence diagram in the PR description. | +| CP-2 | WI-5, after the classifier is drafted, before recovery is wired | The classifier table and T-5. | Classifier table tests run on **real** driver error shapes captured by the contract test and the tree paths. | +| CP-4 | Before WI-7 starts | Teardown order, T-2, the export and import lease (A5). | Teardown sequence diagram in the PR description. | | CP-5 | Before PR F | Is the hand-over complete? | OT-1 to OT-7 results recorded in `# Outcome`, WI-9 queries run on pre-release ingestion. | --- @@ -433,10 +441,9 @@ verdict exists, do not start the work it gates. - Act on the result: - **code 18, then a second callback, then success:** nothing more to do; - **socket closed or reset, with no callback:** the driver keeps its stale cached token, so retrying - on the same client cannot recover. Add a WI-5 classifier rule: on an Entra client whose last - observed token has expired (C-3), a closed connection during authentication is `clientClosed`, so - the next **foreground** operation creates a new generation with a fresh token cache (T-4 still - applies). + on the same client cannot recover. Add a WI-5 classifier rule: on an Entra client, a closed + connection during authentication is `clientClosed`, so the next **foreground** operation creates a + new generation with a fresh token cache. No local expiry check (decision 0010). - Record the result and the rule, if one was added, in Progress. 3. **Session helper.** @@ -448,17 +455,17 @@ verdict exists, do not start the work it gates. azureauth internal path, so PR 1 and PR 2 do not collide. - Read the provider ID through the existing seam in `documentdbTokenResource.ts`, so that PR 2 migrates a single place. -4. **First acquisition.** Keep it as it is (interactive when the policy says so). Then record C-1 from +4. **First acquisition.** Keep it as it is: interactive, reached only through the tree's first connect + (C-6). Then record C-1 from `session.account` and the provider ID that was actually used, and return it on `AuthHandlerResponse`. 5. **The callback.** Replace the closure over `session` with: - a silent lookup pinned to the provider, scopes, tenant and `account`; - if the provider in use differs from the pinned one: `EntraSignInRequiredError('providerChanged')`; - no session: `EntraSignInRequiredError('noSession')`; - `session.account.id !== pinned.accountId`: `EntraIdentityMismatchError`; - - any other thrown error: `EntraTokenRefreshError` (keep the cause); + - any other thrown error: `TokenCallbackError` (keep the cause); - a result of `{ accessToken, expiresInSeconds }`, where `expiresInSeconds` comes from the JWT `exp`; - - a C-3 notification for every completed lookup, including misses and failures. `changed` compares - only the previous `iat` and `exp` numbers; the previous token itself is never kept. + - a C-3 notification for every completed lookup, including misses and failures. Leave `buildOidcClientConfiguration` untouched; it still checks the destination policy around the call. @@ -467,7 +474,7 @@ verdict exists, do not start the work it gates. `playgroundWorker.ts`. An unknown `exp` stays unknown (`undefined`). The worker keeps its own fallback TTL; WI-9 must not report that fallback as a measured value. 7. **Failure registry.** A silent miss and an identity mismatch are **not** recorded as token failures, - as the existing comment requires. An `EntraTokenRefreshError` is recorded through + as the existing comment requires. A `TokenCallbackError` is recorded through `recordEntraTokenFailure`, with its `classifyEntraError` rule. 8. **Explanation.** - Register an `ErrorExplanationService` provider (id `entraSignInRequired`) that walks the @@ -485,7 +492,7 @@ verdict exists, do not start the work it gates. **Tests** (extend `MicrosoftEntraIDAuthHandler.test.ts`): - a second callback asks the provider again, pinned, with `silent: true` and **never** `createIfNone`; -- the same token bytes while the token is still valid are accepted, and C-3 reports `changed: false`; +- the same token bytes while the token is still valid are accepted; - no session gives `EntraSignInRequiredError`; - a different account gives `EntraIdentityMismatchError`; - a changed configured provider gives `providerChanged`, and `getSession` is never called with the new @@ -530,23 +537,20 @@ verdict exists, do not start the work it gates. 1. **Snapshot and surface binding.** - Extend the D12 session snapshot with C-1: `providerId`, `accountId` and `tenantId`. Capture them on the **first** token relay of a newly spawned worker. - - That first relay may be interactive only while the spawn is user-initiated: opening a shell, or - running a playground on a cold worker. Track this with an explicit "initial acquisition pending" flag, - not with timing. + - The first relay is silent and pinned when the host has a verified identity for the cluster + (`lastVerifiedIdentity`, WI-4). Only when the snapshot has no pinned account yet may it be + interactive, because opening a shell or running a playground is user-initiated. No separate + "initial acquisition pending" flag. - Every later relay uses `entraSession.ts` in silent mode with the pinned account, and the same C-2 errors as WI-1. - - Optional optimization (the advisor decides): if the host already has a client for the cluster with a - verified identity, seed the snapshot from it, so the initial relay is silent too. - - **The shell or playground surface keeps its own binding** (C-4 fingerprint plus C-1), and that - binding **outlives the worker** (F-15). It registers in the **same surface registry** as the - webviews (WI-6 host step 1), with kind `shell` or `playground`. It consumes the same projected state - (C-5) and the same latch (C-6), so host and workers share one lifecycle coordinator, not two state - machines. If PR 1 lands before the registry exists, keep the latch behind a small interface that - WI-6 moves into the registry. Before an automatic respawn (`ShellSessionManager.evaluate`, - `executePlaygroundCode.ts`), check the binding and the surface latch: + - **The shell or playground session stores its fingerprint string** (C-4) when it spawns. It does + **not** join the surface registry; teardown finds shells through `getRegisteredShellTerminals` and + the playground through its evaluator (WI-7). Before an automatic respawn + (`ShellSessionManager.evaluate`, `executePlaygroundCode.ts`), compare the fingerprint of the current + credentials with the stored one, and check the cluster latch (C-6): - same fingerprint and not latched: respawn as today; - - a different fingerprint, or latched: do not respawn. Print the disconnected reason and the action. - - Only an explicit recovery (Sign in again, Reconnect) may respawn under a new binding. + - a different fingerprint, or latched: do not respawn. Print the reason and the action. + - Only an explicit recovery (Sign in again, Reconnect) may respawn under a new fingerprint. 2. **IPC.** - Extend `tokenError` with an optional bounded `reason`. Its values are `signInRequired`, `identityMismatch`, `destinationRejected` and `refreshFailed`. Keep the existing allow-list pattern @@ -568,12 +572,19 @@ verdict exists, do not start the work it gates. keeps its terminal and prints "Reconnected". The playground respawns on the next run. - A different account is an identity change (0003): the shell prints "Signed in as a different account; open a new shell to use it". Do not rebind. + - **Any other token failure (F-1).** A `refreshFailed` reason, or any other error thrown from the + worker's OIDC callback, whatever the auth method (Entra or managed identity), leaves the worker's + `MongoClient` broken while the worker process stays alive, so the automatic respawn (F-15) never + runs. Mark the worker session as broken when such a reason arrives. The next command, or the next + playground run, stops the worker and respawns it under the **same fingerprint**, using the respawn + rule in step 1. Print one line, without a modal. 4. **#1059 note.** - Call `PlaygroundEvaluator.buildInitMessage` only when a worker is spawned. - A warm run on the same cluster reuses the stored init. - A run against a different cluster, or a dead worker, spawns as it does today. 5. **E4.** A late token response or error from a disposed or replaced worker must change neither state nor - diagnostics. Guard by a worker or session instance ID. + diagnostics. Ignore messages from a worker that is no longer the session's current worker (compare the + worker object); no extra ID. **Tests:** @@ -586,7 +597,9 @@ verdict exists, do not start the work it gates. - a late relay result from a replaced worker is ignored; - after the cluster's credentials change to another user, the next shell command does **not** respawn silently; it prints `credentialsChanged`. A password-only change does respawn; - - a latched (disconnected) shell or playground does not respawn on the next command. + - a latched (disconnected) shell or playground does not respawn on its next command; + - after a `refreshFailed` token error (Entra and managed identity), the next command respawns the + worker once under the same fingerprint, and the command after that runs on the new worker. - Add a test of the worker message round trip for `reason` and `authReason`. **Done when:** Case 1 is green, and the PR 1 pre-review is committed. @@ -712,6 +725,7 @@ shim (0005). - Teardown and late startups cannot publish stale clients. - Cancelling a cached reuse never closes the shared client. - A closed topology is replaced, never reconnected with old options. +- `getClient` never prompts (C-6). **Read first:** @@ -724,82 +738,67 @@ shim (0005). **Steps:** 1. **Fingerprint** (`src/documentdb/connectionFingerprint.ts`, pure). - - Inputs are the **credentials snapshot actually used** in `initializeClient`, the C-1 identity - (Entra), and the provider's logical target for tunnels. - - The **deployment** is the normalized seed host list of the original connection string (before - reachability rewrites it to `localhost`), or the provider's stable target ID. - - The **principal**, per auth method: - - Native: user + the **effective** authentication database, using the driver's rules (F-17): - explicit `authSource`, else the URI's database path, else `admin`; - - Entra: `providerId` + `accountId` + `tenantId`; - - managed identity: the client ID, as the runtime credential carries it, or `system-assigned`. - **Known limitation:** if an admin replaces a resource's system-assigned identity, the principal - changes but the fingerprint does not. That is not the user-driven identity switch that 0003 guards - against, so document it rather than research a principal claim; - - no auth: `none`. - - **Fail closed:** when two inputs might mean the same deployment but normalization is unsure (for - example, an SRV string compared with a seed list), the fingerprints **differ**. The user then sees - "credentials changed" once and reconnects, which is acceptable. - - The Entra `providerId` is part of the fingerprint, so a provider or cloud change is an **identity - change**. Open surfaces go disconnected, and Reconnect is an explicit rebind under the current - settings. - - Hash it (SHA-256, hex, truncated) into an opaque string. - - Table tests: - - a password-only change keeps the fingerprint; + - It hashes two inputs (SHA-256, hex, truncated) into an opaque string: + - the **stored connection string without its password**, as it was before reachability rewrote the + host to `localhost`. It carries the hosts, the database path and any `authSource`, so F-17 needs no + special handling; + - the **principal**: the native user name; Entra `providerId` + `accountId` + `tenantId` (C-1); the + managed identity client ID, or `system-assigned`; or `none`. + - **No normalization.** Any edit to the connection string counts as an identity change. That fails + closed: the user sees "credentials changed" once and reconnects. + - The Entra `providerId` is part of it, so a provider or cloud change is an identity change too. + - **Known limitation:** if an admin replaces a resource's system-assigned identity, the principal + changes but the fingerprint does not. That is not the user-driven identity switch that 0003 guards + against; document it. + - Table tests, reviewed as part of the PR: + - a password-only change keeps the fingerprint, including an RU key rotation; - another user changes it; - - the same user on another host changes it; - - the same user with another explicit `authSource` changes it; - - the same user with **no** `authSource` and a different URI database (`/sales` against `/admin`) - changes it; + - an edited connection string changes it; - two managed identity client IDs differ; - a tunnel's local port change keeps it. - - Use this table as the CP-1 evidence. 2. **Generation.** - Keep a static `Map` that only ever increases and is never cleared. - Each `ClustersClient` instance records `generation`, `fingerprint`, `createdAt` and its credentials snapshot. - Expose a read-only `binding` (C-4) and `ClustersClient.getBinding(clusterId)`. 3. **One startup at a time (single flight).** - - A `_pendingStartups` map keyed by `clusterId` holds `{ promise, epoch }`. - - Every caller awaits the same startup, and each caller's own `abortSignal` rejects only **that - caller's** wait. - - The startup itself is aborted only when **all** waiters have aborted. Otherwise it continues and - publishes. - - A per-cluster `epoch` is incremented **synchronously** by `invalidate(clusterId)`. A startup publishes - only if the epoch is unchanged; otherwise it closes its own `MongoClient` and rejects with a typed - `ClientInvalidatedError`. + - A `_pendingStartups` map keyed by `clusterId` holds the startup promise. Every caller awaits it. + - A caller's own `abortSignal` rejects only **that caller's** wait. It never aborts the startup, which + has its own timeout. + - The startup captures the C-6 epoch and publishes only if it is unchanged. Otherwise it closes its own + `MongoClient`. Its waiters then get the latch's `ConnectionUnavailableError` if the cluster is + latched, or retry once with the current credentials if it is not. - `deleteClient` calls `invalidate` **before** its first `await`. - - `invalidate` also increments the C-6 lifecycle epoch. -4. **Central policy (C-6).** - - `getClient` takes `{ interaction, trigger, abortSignal }`, with `interaction` defaulting to `'never'`. +4. **`getClient` rules (C-6).** + - `initializeClient` stops hardcoding `{ interactive: true }`; `getClient` is always silent. Its options + are `{ trigger, abortSignal, background? }`. + - The interactive first connect moves to `ClustersClient.connectInteractive(clusterId)`, called only by + the tree items' `authenticateAndConnect` and by Sign in again. No per-call-site audit is needed: every + other caller acts on a cluster that the tree has already connected. - Add a per-cluster `lastVerifiedIdentity` record (C-1 for Entra; the principal for other methods), - keyed by `clusterId` like `ClustersClient._clients`. It **survives eviction** and is cleared only by teardown (WI-7). - - `initializeClient` stops hardcoding `{ interactive: true }`. It is interactive only when the caller - allowed it **and** the cluster has no `lastVerifiedIdentity`. Otherwise it is silent and pinned to - that identity. - - Add the disconnected latch: a latched cluster throws `ClusterDisconnectedError` for every caller. - WI-7 sets the latch; WI-4 adds the check, the error and the tests. - - Audit every `getClient` call site (F-13), and pass `interaction: 'allowed'` only from explicit user - connect paths: tree expand, Connect, and one-shot commands on a cluster that is not yet connected. - List the audit in Progress. + keyed by `clusterId` like `ClustersClient._clients`. It **survives eviction and Disconnect**, and only + Remove Connection clears it (WI-7, decision 0011). A silent reconnect is pinned to it. + - Add the latch check: a latched cluster throws `ConnectionUnavailableError(reason)` for every caller. + WI-7 sets the latch. + - Missing credentials throw `ConnectionUnavailableError('credentialsMissing')` instead of today's plain + `Error`, whose message shows the raw `clusterId` (F-20). + - Pass `background: true` from the dashboard poll, tree count badges and `CollectionNameCache`. 5. **Cached reuse.** - Remove the abort handler that closes the shared client (the cached branch of `getClient`). - A cancelled waiter just rejects with `UserCancelledError`. 6. **Closed topology.** - Track closure with the public SDAM event `topologyClosed` on the `MongoClient`, plus our own `close()` calls. - - `getClient` on a closed client publishes a **new generation**, using the **current** `CredentialCache` - and requiring the **same fingerprint**. - - If the fingerprint differs, do not publish. Return a typed `IdentityChangedError` for WI-5 and WI-6 to - handle. + - A foreground `getClient` on a closed client publishes a **new generation**, using the **current** + `CredentialCache` and requiring the **same fingerprint**. A background caller fails instead. + - If the fingerprint differs, do not publish; throw `ConnectionUnavailableError('identityChanged')`. - Today's `client._mongoClient.connect()` call on the cached path goes away. -7. ~~**Rotation.**~~ Removed: no proactive rotation (decision 0010). -8. **Telemetry helper.** +7. **Telemetry helper.** - Add `addEstablishedConnectionContext(context, clusterId | client)`. It sets `authMethod`, `connectionCorrelationId`, and the measurements `connectionAgeMs` and `clientGeneration`. - No property name may contain "error" (masking). - WI-5 and WI-6 call it; add the helper and its tests only here. -9. **Development test hook** (optional, recommended). +8. **Development test hook** (optional, recommended). - Add `vscode-documentdb.debug.connection.simulateExpiry`, following the survey debug commands: - declared in `package.json`; - registered only in development mode; @@ -811,21 +810,22 @@ shim (0005). **Tests** (`ClustersClient.test.ts`, plus the new fingerprint test): - two concurrent cold `getClient` calls create one `MongoClient`; -- cancelling one of two waiters leaves the other connected; +- cancelling one of two waiters leaves the other connected; cancelling both does not abort the startup; - a startup that finishes after `deleteClient` does not publish, and closes its client; - a cancelled cached reuse does not close the shared client; -- `topologyClosed` followed by `getClient` gives a new generation with the same fingerprint; -- a changed principal followed by `getClient` gives `IdentityChangedError`; -- a background caller (`interaction: 'never'`) never prompts, even with no client and with credentials - cached; a verified cluster reconnects silently even when the caller allowed interaction; +- `topologyClosed` followed by a foreground `getClient` gives a new generation with the same fingerprint; + a background `getClient` does not replace it; +- a changed principal followed by `getClient` gives `ConnectionUnavailableError('identityChanged')`; +- `getClient` never prompts, even with no client and with credentials cached; only `connectInteractive` + may, and only when the cluster has no `lastVerifiedIdentity`; - a latched cluster rejects every caller, including background ones; +- missing credentials give `credentialsMissing`, with no `clusterId` in the message; - generation numbers only ever increase across delete and reconnect; - the telemetry helper sets the bounded properties and no forbidden names. **Done when:** - Case 1 is green; -- the CP-1 verdict is recorded; - every existing `ClustersClient` test still passes unchanged, or each change is justified in Progress. **Progress:** @@ -836,10 +836,10 @@ shim (0005). **Outcome:** -- One classifier and one state owner. +- One pure classifier. - The tree's Retry actually reconnects. - **Sign in again** exists and prompts once per click. -- Account removal marks the clusters bound to it. +- A token callback failure never leaves a broken client cached, for any auth method. **Read first:** @@ -855,30 +855,37 @@ shim (0005). - It walks `cause`, plus `MongoServerSelectionError.reason.servers[*].error` where present. - Initial table: - | Signal | Auth | Kind | Generation | Offered action | - | ---------------------------------------------------------------------- | ---------- | ---------------------------- | -------------------------------------------------- | ----------------------------------------------- | - | `EntraSignInRequiredError` | Entra | `signInRequired` | replace on recovery (F-1) | Sign in again | - | `EntraIdentityMismatchError`, `IdentityChangedError` | any | `identityChanged` | evict; surfaces disconnected | Reconnect (rebind) | - | `EntraTokenRefreshError` | Entra | `transient`, workflow broken | replace on the next **foreground** operation (T-4) | Retry | - | 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 silently | none | - | network errors, timeouts, server selection with no auth cause | any | `transient` | keep | Retry | - | anything else | any | `other` | keep | existing behavior | + | Signal | Auth | Kind | Generation | Offered action | + | ----------------------------------------------------------------------------- | ---------- | ---------------------------- | -------------------------------------------- | ----------------------------------------------- | + | `EntraSignInRequiredError` | Entra | `signInRequired` | replace on recovery (F-1) | Sign in again | + | `EntraIdentityMismatchError`, `ConnectionUnavailableError('identityChanged')` | any | `identityChanged` | evict; surfaces unavailable | Reconnect (rebind) | + | `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 | + | network errors, timeouts, server selection with no auth cause | any | `transient` | keep | Retry | + | anything else | any | `other` | keep | existing behavior | - **No regression for tunneled connections:** connection refused against a Kubernetes port-forward port is `transient`. The client is **kept**, never evicted, so the tree's existing tunnel restore (`beforeCachedClientConnect`) still recovers it. Tunnel recovery itself is #1105. -2. **State owner.** - - Add `ClustersClient.reportFailure(binding, error)`, or a small `ConnectionStateService` that sits - beside it (advisor's choice). It classifies the error and ignores it if `binding.generation` is - stale. It evicts according to the table and updates the C-5 **cluster** state. Surface states are - projected per binding (WI-6). - - It fires `onDidChangeConnectionState(clusterId)`. - - A foreground helper `withClusterClient(clusterId, op, { foreground })` resolves the client, runs the operation, reports failures, and applies the T-4 backoff. - WI-6 extends it with bindings. -3. **Tree.** +2. **Callback failures for every auth method (F-1).** + - F-1 applies to **every** throw from the OIDC callback. The managed identity callback + (`ManagedIdentityAuthHandler.configureAuth`) rethrows token-service (IMDS) failures and throttling as + they are, so today they fall to `other → keep`, and the broken client stays cached until VS Code + restarts. + - Both handlers wrap such errors in `TokenCallbackError` (C-2). Destination rejection keeps its current + handling. + - The classifier treats it as `transient`, workflow broken: `reportFailure` marks the client, and the + next **foreground** `getClient` replaces it with a new generation and the same fingerprint. +3. **Report failures.** + - Add `ClustersClient.reportFailure(binding, error)`: a function, not a service. It classifies the + error and ignores it when `binding.generation` is stale. It evicts or marks the client according to + the table, and returns the kind so the caller can choose its UI. + - It keeps no connection state and fires no events (C-5). +4. **Tree.** - Route both catch paths in `getChildren` (cached-client reuse and `listDatabases`) through `reportFailure`. Keep the modal-plus-actions presentation. - Change `createErrorRecoveryChildren` to: @@ -889,12 +896,18 @@ shim (0005). - then **Retry last**. - 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. -4. **Retry.** + - **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 + `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. +5. **Retry.** - `retryAuthentication` evicts the client (`deleteClient` without clearing credentials) when the last kind was `signInRequired`, `credentialsRejected` or `clientClosed`, and then refreshes. - - It captures the C-6 lifecycle epoch and the current binding **before** its first `await`. If either - changed in the meantime (a Disconnect, or another recovery replaced the client), it does nothing - destructive: no eviction, and no latch cleared. + - It captures the C-6 epoch **before** its first `await`. If the epoch changed in the meantime (a + Disconnect, or another recovery replaced the client), it does nothing destructive: no eviction, and + no latch cleared. - The `CredentialCache` entry is kept. - **RU key exception:** on Retry after `credentialsRejected` for an RU Discovery or Azure Resources item: @@ -902,42 +915,37 @@ shim (0005). - an ARM sign-in failure there is reported as "Azure sign-in needed" (WI-3 classifier), not as a database rejection; - never open a password wizard. -5. **Sign in again** command (`vscode-documentdb.command.signInAgain`, args: a tree node or `{ clusterId }`). - - Read the pinned C-1 from the cluster's `lastVerifiedIdentity` record (WI-4). Capture the C-6 - lifecycle epoch **before** prompting. - - Call `entraSession.ts` interactively for that account and tenant. - - **Rejected-but-present session:** if the failure that led here was a server rejection of a token that - the silent lookup still returns, use `forceNewSession` for the pinned account instead of - `createIfNone`. Prove both paths in tests. - - **After the prompt, compare and swap.** If the epoch changed while the user was signing in (for - example, a Disconnect), do not evict, do not reconnect and do not clear the latch. Report "The - connection was closed while you were signing in." - - Same account: evict, start a new generation, and set the cluster state to `connected`. - - Different account: the identity changed. Surfaces bound to the old fingerprint project to - `disconnected(identityChanged)` (C-5), and the tree continues with the new identity. - - A dismissal is a `UserCancelledError`. No code path re-prompts. C-6 enforces this centrally; add a - test that background paths cannot prompt. -6. **`onDidChangeSessions`.** - - Register once, at activation. - - For events of a provider ID that some live binding pins, silently re-check each affected binding, - debounced to about 500 ms. - - A missing session sets the state to `signInRequired`. - - Results from a stale generation are ignored. Clusters bound to another account are not touched. - - Never sign the user out, and never remove a session. +6. **Sign in again** command (`vscode-documentdb.command.signInAgain`, args: a tree node or `{ clusterId }`). + - Read the pinned C-1 from the cluster's `lastVerifiedIdentity` record (WI-4). Capture the C-6 epoch + **before** prompting. + - Call `entraSession.ts` with `forceNewSession` for that account and tenant, every time. The user + clicked, so one prompt is expected, and it also covers a session that the silent lookup still + returns but the server rejects. + - **After the prompt, check the epoch.** If it changed while the user was signing in (for example, a + Disconnect), do not evict, do not reconnect and do not clear the latch. Report "The connection was + closed while you were signing in." + - Same account: evict and start a new generation. + - Different account: the identity changed. Surfaces bound to the old fingerprint become unavailable + with `identityChanged` (C-5), and the tree continues with the new identity. + - A dismissal is a `UserCancelledError`. Nothing re-prompts, because `getClient` never prompts (C-6). + - There is no `onDidChangeSessions` listener (decision 0012). A signed-out account is found by the next + operation's silent lookup, which fails with `signInRequired`. **Tests:** - classifier table tests on real error shapes; +- a managed identity callback that throws once: the next foreground operation works on a new + generation, and a background tick does not replace the client; - Retry after `clientClosed` creates a new generation; after `credentialsRejected` it keeps the credentials and does not loop; - the RU old/new key pair; an ARM sign-in failure compared with a database rejection; -- Sign in again with the same account and with a different account; the forced-new-session path; +- Sign in again with the same account and with a different account, always with `forceNewSession`; - no re-prompt after a dismissal; -- an `onDidChangeSessions` event for another account does not affect this cluster; - a stale-generation result is ignored; - an old Retry that resolves after the client was replaced does not evict the new client; - Sign in again that completes after a Disconnect does not reconnect or clear the latch; -- the T-4 backoff. +- a tree expand that fails with a network error keeps the `CredentialCache` entry, and an open surface + then reconnects silently once the network is back; a code 18 failure still evicts it. **Done when:** @@ -949,13 +957,13 @@ shim (0005). --- -## WI-6: Bind surfaces and add the disconnected state (PR 5, or 5a and 5b) +## WI-6: Bind surfaces and add the unavailable state (PR 5) **Outcome:** - Collection View (all tabs), Document View and the Cluster Dashboard resolve their client per operation through a binding. -- They show C-5 state with a banner and one action. +- They show an unavailable state (C-5) with a banner and one action. - They keep all user state. - They never apply stale results. - They never run under another identity. @@ -964,7 +972,7 @@ shim (0005). - the webview-trpc-messaging and react-webview-architecture skills; - `collectionViewRouter.ts`, `indexesTab/indexViewRouter.ts`, `queryInsights/queryInsightsRouter.ts` - and `queryInsightsEventsRouter.ts` (it already has a tRPC subscription you can copy); + and `queryInsightsEventsRouter.ts`; - `QueryInsightsAIService.ts` and `indexAdvisorCommands.ts`; - `documentsViewRouter.ts` and `documentView.tsx` (the `isDirty` state); - `clusterDashboardRouter.ts` and `ClusterDashboard.tsx`; @@ -972,35 +980,27 @@ shim (0005). - `openAppWebview.ts`; - `build/verification/browser/scenarios.ts` and `fixtures.ts`. -**CP-3 first.** +PR 5 is one PR. Split it into host and webviews only if the diff becomes too large to review well, as the +approved plan allows; the webview half then opens after the host half merges. -- Convert **one** router end to end (Document View is the smallest) on the host side. -- Show the API, then decide with the advisor: - - whether to split into 5a (host: registry, binding, routers, state channel) and 5b (webviews: - banner, disabling, scenarios); - - the recommendation is to split, because 5b needs the 5a contract to be stable. - -### Host (5a) +### Host 1. **Surface registry** (`src/documentdb/connectionSurfaces.ts`). - - `register({ clusterId, kind, binding, pushState, dispose, hasUnsavedChanges? })` returns a - disposable. + - A plain list per `clusterId`: `register({ clusterId, kind, disable(reason), dispose, isDirty? })` + returns a disposable. - Collection View, Document View and the Dashboard register when they open and unregister on - `onDisposed`. Shells and the playground register too (WI-2), so there is one registry for every - surface. - - WI-7 enumerates this registry. + `onDisposed`. + - Only teardown reads it (WI-7). Shells and the playground do not register (WI-2). 2. **Binding resolution.** - - `resolveBoundClient(binding, { foreground })` has three outcomes: - - (a) same fingerprint and generation: return the client; - - (b) same fingerprint, the client was replaced or closed for **recovery**: return the current - client, transparently, with no re-run and no notice (decision 0010); - - (c) a different fingerprint, the cluster is latched `disconnected` (C-6), or `identityChanged`: - throw a typed `SurfaceDisconnectedError(reason)`. - - Projection rule (C-5): the surface's state comes from comparing **its** binding with the cluster's - current binding, never from the cluster state alone. - - A surface **never** prompts. Under C-6 it calls `getClient` with `interaction: 'never'`. If no client - exists and the cluster is not latched, the reconnect is silent and pinned to `lastVerifiedIdentity`, - so Entra fails closed with a mismatch instead of prompting. + - `resolveBoundClient(binding, { background? })` has two outcomes: + - **the same fingerprint:** return the cluster's current client, whatever its generation. Replacing a + client for the same identity is transparent: no re-run and no notice (decision 0010). If there is + no client and the cluster is not latched, `getClient` reconnects silently, pinned to + `lastVerifiedIdentity`; + - **a different fingerprint, or a latched cluster:** throw `ConnectionUnavailableError(reason)`. + - A surface **never** prompts (C-6). + - Router procedures catch `ConnectionUnavailableError` and return a structured + `{ unavailable: { reason, text, action } }` result instead of an error (F-12). - **No regression for tunneled connections** (Kubernetes `ClusterIP` through port-forward). Creating a new generation from this path may not do less than today's tree path, and it does not re-create tunnels. A tab whose tunnel died behaves as it does today: it fails transiently until a tree expand @@ -1019,48 +1019,42 @@ shim (0005). - Re-run the grep from the approved plan, and list every converted call site in Progress. 5. **Writes.** - Save document, inserts and deletes, and index create, drop, hide and unhide. - - When the request may have reached the server and the reply was lost (network error or timeout after - send), report **outcome unknown**: "The change may or may not have been applied. Refresh to check." - - The extension **never resubmits** a write. That is the guarantee, and OT-4's "not replayed" means - this. The driver's own retryable writes (`retryWrites`) stay as they are: the server deduplicates - them by design, and RU connection strings disable them. + - The extension **never resubmits** a write; that is OT-4's "not replayed". A failed write is reported + as it is today. The driver's own retryable writes (`retryWrites`) stay as they are: the server + deduplicates them by design, and RU connection strings disable them. - Test that one application-level submission results in exactly one call to the driver. -6. **State channel and stale results.** - - Each view router gets a `connectionState` subscription, fed by the registry (C-5 surface state). It - replays the current state when a view subscribes. - - It carries a **surface epoch** that increases on every transition into `disconnected` and on every - rebind. - - Every request records `{ epoch, generation }` when it starts. - - **Before any host-side mutation**, check that the epoch is unchanged and that the generation is - acceptable: same fingerprint is acceptable under decision 0010. That covers `ClusterSession`'s - `_currentRawDocuments`, its query caches, Query Insights caches and `SchemaStore` updates. A stale - result must not change host state at all, so dropping it only at delivery is not enough. - - Check again at delivery. The UI applies the same check (5b). +6. **Stale results.** + - Every request records the generation it started with. + - **Before any host-side mutation**, check once that the binding still resolves to the same fingerprint + and that the cluster is not latched. Otherwise drop the result. That covers `ClusterSession`'s + `_currentRawDocuments`, its query caches, the Query Insights caches and `SchemaStore` updates. A stale + result must not change host state at all. 7. Every router error path uses `addEstablishedConnectionContext` (WI-4). -### Webviews (5b) +### Webviews 1. **Shared UI.** - - A `useConnectionState()` hook and a `DisconnectedBanner` component. - - The banner is a Fluent `MessageBar` with intent `warning`, the host-provided reason text and **one** - action button. - - It uses `role="status"` and `aria-live="polite"`. - - Put both in the shared webview components folder. - - Run the detecting-accessibility-issues skill on them. + - A `DisconnectedBanner` component: a Fluent `MessageBar` with intent `warning`, the host-provided + reason text and **one** action button. It uses `role="status"` and `aria-live="polite"`. + - It shows when a procedure returns `unavailable`, or when the host's `disable(reason)` sends its one + message to the panel over the existing webview channel. + - Put it in the shared webview components folder, and run the detecting-accessibility-issues skill on + it. 2. **Disabling.** - - While disconnected, every action that talks to the server is disabled: run query, paging, refresh, - save, delete, insert, index actions, Query Insights stages and AI calls. + - While the banner shows, every action that talks to the server is disabled: run query, paging, + refresh, save, delete, insert, index actions, Query Insights stages and AI calls. - Editors stay **editable**. The user can keep typing. - - Responses whose epoch is older than the UI's current epoch are discarded on the UI side too. + - A response that arrives while the banner shows is ignored. 3. **What each view keeps.** - **Collection View:** query text, filter, sort, projection, page number and size, the selected tab, and the Query Insights results as they were. - **Document View:** the dirty editor content and `isDirty`. - **Dashboard:** the last data (WI-8 stops the polling). 4. **Actions.** - - **Reconnect** (same fingerprint): resolve again. On success, remove the banner and re-enable the - actions; the live region announces "Reconnected". The query is not run automatically, and there is - **no** "out of date" notice (decision 0010; see #1106). + - **Reconnect** (same fingerprint): clear the latch if one is set, and resolve again. On success, + remove the banner and re-enable the actions; the live region announces "Reconnected". The query is + not run automatically, and there is **no** "out of date" notice (decision 0010; see #1106). After a + Disconnect the credentials are still cached (0011), so this is silent. - **Reconnect after an identity change:** an explicit rebind to the new fingerprint, then show "Now connected as {label}" (OT-3). - **Sign in again:** the WI-5 command. @@ -1071,17 +1065,18 @@ shim (0005). Run is clicked; - `documentView/disconnected-dirty`: edit kept, Save disabled; - `clusterDashboard/disconnected`; - - a scenario that injects a disconnect after typing and then delivers a stale page response: the - applied results are not overwritten. + - a scenario that injects a disconnect after typing and then delivers a page response: the applied + results are not overwritten. - Run them with the browser scenario config. Screenshots are artifacts, not baselines. **Transfers:** do not touch copy, paste or export (approved plan). **Tests:** -- router tests for the three binding outcomes on each converted router; +- router tests for both resolution outcomes on each converted router; - `ClusterSession` no longer stores a client (a type-level or structural test); -- the epoch drop on host and UI; +- a stale result is dropped before any host-side mutation; +- the webview ignores a response that arrives while the banner shows; - one submission for a write whose reply is lost; - the scenarios above. @@ -1089,8 +1084,7 @@ shim (0005). - Case 1 is green; - the scenarios pass; -- OT-1 and OT-3(a) can be reproduced with the WI-4 hook; -- if split, 5a merges before 5b opens. +- OT-1 and OT-3(a) can be reproduced with the WI-4 hook. **Progress:** @@ -1103,13 +1097,11 @@ shim (0005). - One teardown serves Disconnect, Remove and identity-changing credential updates. - It is guarded by task conflicts and dirty editors. - It covers every per-cluster resource. -- **What it guarantees:** after `commit`, no operation **starts** under the old binding. Operations - already in flight are not admitted or tracked individually: - - `deleteClient` closes the client with `force`, so they fail; - - their failure is reported normally, and a write whose reply was lost is reported as outcome unknown - (WI-6); +- **What it guarantees:** after the commit, no operation **starts** under the old binding. Operations + already in flight are not tracked individually: + - `deleteClient` closes the client with `force`, so they fail and their failure is reported normally; - shell and playground workers are stopped; - - tasks and exports are protected by the preflight. + - tasks, exports and imports are protected by the conflict check. This is the right level for an interactive tool; do not build per-operation admission control. @@ -1118,60 +1110,59 @@ shim (0005). - `removeConnection.ts`; - `resourceUsageHelper.ts` and `taskService.ts` (`getConflictingTasks`); - `CopyPasteCollectionTask.ts` and `CopyIndexesTask.ts` (`getUsedResources`); -- `exportDocuments.ts`; +- `exportDocuments.ts` and `importDocuments.ts`; - `updateCredentials.ts`, including the D12 modal; - `updateConnectionString.ts`; - `CredentialCache.ts`, `entraTokenFailures.ts` and `SchemaStore.clearCluster`; - the WI-6 registry; - `switchAtlasViewMode.ts` (the `globalState` pattern). -**CP-4 first:** the teardown order, T-2 and the export lease. +**CP-4 first:** the teardown order, T-2 and the export and import lease. **Steps:** -1. **Export lease (A5).** +1. **Export and import lease (A5).** - Add `TaskService.acquireResourceLease(resource, label)`, which returns a disposable. `getConflictingTasks` includes active leases. - - `exportDocuments.ts` holds the lease for the whole export. - - Test that export conflicts with Disconnect of its source, and that an unrelated cluster does not. -2. **Teardown service** (`src/documentdb/connectionTeardown.ts`). - - Two phases: `prepare(clusterId, intent)` and `commit(reservation, options)`. - - Disconnect and Remove call both, back to back. - - Update Credentials puts the save between them (step 5). - - **`prepare`**, which may prompt and may be cancelled: - 1. **Preflight:** task and lease conflicts through `checkCanProceedAndInformUser`. On a conflict, - stop and change nothing; the conflicting task is named. + - `exportDocuments.ts` holds the lease for the whole export, and `importDocuments.ts` for the whole + import (from the first `getClient` to the last flushed batch), on the target collection. + - Copy/paste and copy-indexes are tasks already and need no lease (F-9). + - Test that export and import each conflict with Disconnect of their cluster and with Delete + Collection of their collection, and that an unrelated cluster does not. +2. **Teardown** (`src/documentdb/connectionTeardown.ts`): two plain functions, with no reservation and no + rollback. Disconnect and Remove call them back to back; Update Credentials puts the save between them + (step 5). + - **`confirmTeardown(clusterId, intent)`**, which may prompt and may be cancelled. It changes nothing: + 1. **Conflicts:** task and lease conflicts through `checkCanProceedAndInformUser`. On a conflict, + stop; the conflicting task is named. 2. **Choice:** Close all or Keep open (A2), only when surfaces are registered and the setting is `ask`. With the setting at `closeAll` or `keepOpenDisabled`, use that value without a modal. - 3. **Dirty check** (only for `close`): if any registered surface reports `hasUnsavedChanges`, ask for - confirmation. Cancelling leaves every panel, draft and connection intact. That includes the case - where Remove started the teardown. - 4. **Reserve, atomically:** **recheck** task and lease conflicts, because a copy or export may have - started while a prompt was open. Then take a per-cluster teardown reservation in `TaskService`. - While it is held, new tasks and leases on this cluster are refused with a clear message. - If the recheck finds a conflict, release everything and stop. - - **`commit`**, which has no prompts and cannot be cancelled: - 1. **Synchronous section, before any `await`:** set the latch and the cluster state to - `disconnected(reason)` (C-6), call `ClustersClient.invalidate` (it increments the lifecycle - epoch), increment the surface epochs, and mark in-flight token requests as abandoned (E4). - 2. **Surfaces:** - - `keepDisabled`: push the state; - - `close`: dispose the panels; - - shells: latch the surface (F-15), print "Disconnected", then stop the worker; - - playground: latch it, then stop the worker. - 3. Close the client (`deleteClient`). - 4. Clear the `CredentialCache` entry if `dropCredentials` is set (A3), the Entra failure registry, - `SchemaStore.clearCluster`, and `lastVerifiedIdentity`. - 5. Release the reservation, and refresh the tree (T-2). - - Releasing a reservation without committing must restore everything to the state before `prepare`. + 3. **Dirty check** (only for `close`): if any registered surface reports `isDirty`, ask for + confirmation. Cancelling leaves every panel, draft and connection intact, also when Remove started + the teardown. + - **`commitTeardown(clusterId, { reason, choice, dropCredentials })`**, which has no prompts: + 1. **Recheck** conflicts with `getConflictingTasks`, because a copy, export or import may have started + while a prompt was open. On a conflict, stop and inform the user; nothing has changed. + 2. **With no `await` between the recheck and this step:** set the latch (C-6) with `reason`, and call + `ClustersClient.invalidate`, which increases the epoch. + 3. **Surfaces:** for Keep open, call each registered surface's `disable(reason)`; for Close all, + dispose them. + 4. **Shells** (found through `getRegisteredShellTerminals`): print "Disconnected", then stop the + worker. **Playground:** stop the worker. The latch keeps both from respawning (F-15). + 5. Close the client (`deleteClient`). Clear the Entra failure registry and `SchemaStore.clearCluster`. + Clear the `CredentialCache` entry and `lastVerifiedIdentity` **only** when `dropCredentials` is + set (Remove). Disconnect keeps both (A3, decision 0011), so Connect and a tab's Reconnect are + silent and pinned to the same identity. + 6. Refresh the tree (T-2). - **Never touched:** VS Code auth sessions, the managed identity cache, the ARM cache. - **Keys:** every store keeps its current `clusterId` matching. Provider-specific equality is out of scope (decision 0009, #1105). Do not add case folding or unfolding in this iteration. - **Kubernetes tunnels:** the teardown does not stop port-forward tunnels, and does not change how removing a kubeconfig source works (#1105). 3. **Disconnect command** (`vscode-documentdb.command.disconnect`). - - Add a `connected` tag to the cluster item's `contextValue` while a client exists, and refresh it on - state changes. Use `viewItem` regex menus in the Connections, Azure Resources and Discovery views. + - Add a `connected` tag to the cluster item's `contextValue` while a client exists, and refresh it when + the item refreshes. Use `viewItem` regex menus in the Connections, Azure Resources and Discovery + views. - **The choice (A2):** - Use a modal warning: `showWarningMessage` with `{ modal: true, detail }` and the two buttons Close all and Keep open (disabled). The built-in Cancel cancels the whole operation. @@ -1186,7 +1177,7 @@ shim (0005). - The setting never skips the unsaved-edits confirmation: when Close all is chosen and an editor is dirty, that confirmation still appears. - Skip the modal when no surfaces are registered. - - Add a disconnected cluster node child action, "Connect" (T-2). + - Add a disconnected cluster node child action, "Connect" (T-2). It clears the latch and connects. 4. **Remove Connection.** Teardown with reason `connectionRemoved` and `dropCredentials: true`, then delete the stored connection and clear the schema, as today. Keep the existing confirmation. 5. **Update Credentials and Update Connection String.** @@ -1196,13 +1187,14 @@ shim (0005). - **Same fingerprint:** save. Only after a confirmed success, call `invalidate` and replace the client with a new generation; surfaces continue. - **Different fingerprint:** - 1. `prepare` (preflight, choice, dirty check, reservation) **before** saving. + 1. `confirmTeardown` **before** saving. 2. Save. - 3. On a confirmed success: `commit` with reason `credentialsChanged` and `dropCredentials: false`, - so the **new** credentials stay. - 4. On a failed save: release the reservation. The old binding stays usable, and nothing was latched. - - The reservation and the `invalidate` call in `commit` make sure a concurrent connect cannot publish - the old credentials after the change. + 3. On a confirmed success: `commitTeardown` with reason `credentialsChanged` and + `dropCredentials: false`, so the **new** credentials stay. `lastVerifiedIdentity` is replaced on + the next successful connect. + 4. On a failed save: nothing was changed, and the old binding stays usable. + - The `invalidate` call in `commitTeardown` makes sure a concurrent connect cannot publish the old + credentials after the change. - Add a **Disconnect** button to the D12 modal for open shells. 6. **Telemetry.** - One `connection.disconnect` event with `source` (`command`, `remove`, `credentialsChanged`), @@ -1212,17 +1204,20 @@ shim (0005). **Tests:** - teardown for each surface type; -- blocked for a copy source, a copy destination and an export source; an unrelated cluster is not - blocked; Disconnect succeeds once the task is done or stopped; +- blocked for a copy source, a copy destination, an export source and an import target; an unrelated + cluster is not blocked; Disconnect succeeds once the task is done or stopped; - a token response that arrives after Disconnect is ignored; - Reconnect uses the current credentials and cloud settings; +- after Disconnect, a tab's Reconnect and the tree's Connect succeed without the tree reloading + credentials and without a prompt (native, Entra and discovery with a typed password); after Remove, + the `CredentialCache` entry and `lastVerifiedIdentity` are gone; - Remove reuses the same teardown; - cancelling the dirty prompt changes nothing; -- a copy or export that starts while the Disconnect prompt is open blocks the commit, and nothing changes; -- a task or lease cannot start while a teardown reservation is held; +- a copy, export or import that starts while the Disconnect prompt is open stops the commit, and nothing + changes; - a shell or playground left open after Disconnect does not respawn on its next command; -- Disconnect while a query or save is in flight: the operation fails and is reported (a write as outcome - unknown), and nothing runs afterwards under the old binding; +- Disconnect while a query or save is in flight: the operation fails and is reported, and nothing runs + afterwards under the old binding; - a failed save keeps the old binding; - a concurrent connect during Update Credentials does not publish the old credentials. @@ -1234,15 +1229,18 @@ shim (0005). ## WI-8: Cluster Dashboard health polling (PR 6) -**Outcome:** the poll stops on a terminal state, shows the banner, and resumes with exactly one loop. +**Outcome:** the poll stops when the cluster is unavailable, shows the banner, and resumes with exactly +one loop. **Steps:** -1. `measureRtt` resolves through the WI-6 binding with `foreground: false` (T-4). It returns a - structured result, `{ ok, rttMs } | { terminal: reason }`, instead of throwing for terminal states. -2. The webview poll effect stops on `terminal` and on any `disconnected` state from the channel. It - restarts only on `connected`, guarded by one loop token, so that two loops can never run at once. -3. A late successful ping that started before the disconnect epoch cannot clear the banner (epoch check). +1. `measureRtt` resolves through the WI-6 binding with `background: true`, so it never replaces a client + (T-4). It returns a structured result, `{ ok, rttMs } | { unavailable }`, instead of throwing. +2. The webview poll effect depends on the banner state: it stops on `unavailable` or on a `disable` + message, and starts again after Reconnect. React's effect cleanup keeps it to one loop; no extra loop + token. +3. A ping that resolves while the banner shows is ignored (the WI-6 webview rule), so it cannot clear the + banner. 4. Visibility pause and backoff are the rest of #1091. Do them here only if they are trivial; otherwise leave them to #1091. @@ -1257,47 +1255,44 @@ shim (0005). --- -## WI-9: Token renewal and recovery telemetry (PR 7) +## WI-9: Token renewal telemetry (PR 7) **Outcome:** the release can be judged from events that need no joins and no persistent identifiers. **Steps:** 1. **`connection.tokenRenewal`.** - - Emitted from the C-3 observer (host client) and from the host side of the shell and playground relays. + - Emitted from the C-3 observer (host client) and from the host side of the shell and playground + relays. - Once per completed post-startup Entra **database** token lookup. The initial acquisition is excluded. - - Properties: - - `surface` (`extension`, `shell`, `playground`); - - `renewalOutcome`: `changed`, `unchanged`, `noSession`, `identityMismatch`, `failed`, or `unknown` - when there is no earlier observation in the same binding. - - Measurements: `connectionAgeMs`, `previousTokenObservedAgeSeconds`, `tokenLifetimeSeconds` and - `tokenRemainingSeconds`. Omit any value that is unknown; never send 0 or the worker's fallback TTL. + - Properties: `surface` (`extension`, `shell`, `playground`) and `renewalOutcome` (`returned`, + `noSession`, `identityMismatch`, `failed`). + - One measurement: `tokenLifetimeSeconds`. Omit it when unknown; never send 0 or the worker's fallback + TTL. - Never send a token, hash, claim, account, tenant, cluster ID, fingerprint or host name. -2. **`connection.recovered`.** - - The state owner (WI-5) keeps a "pending recovery" flag per cluster, with the trigger: `silentRenewal`, - `reconnect` or `signInAgain`. - - The event is emitted on the **first successful database operation** after that flag was set, with - `trigger` and `connectionAgeMs`. - - A callback returning a token does not count as recovery. +2. **Recovery, without a new event.** Existing `connect`, `rpc` and `getchildren` events carry + `connectionAgeMs` and `clientGeneration` (WI-4 `addEstablishedConnectionContext`). A successful + operation on a generation above 1 shows that a replacement worked, and late auth, socket and + closed-client failures should drop against the baseline. 3. **ARM.** Report challenge outcomes separately from database renewal. Confirm that the final ARM request succeeded, not just that a token was acquired. 4. **Volume.** - - Both events are background events. If the dashboards keep an event-scope exclusion list for - "active users" totals, add `connection.tokenRenewal` to it. + - `connection.tokenRenewal` is a background event. If the dashboards keep an event-scope exclusion list + for "active users" totals, add it there. - Check the expected volume (about one renewal per active Entra client per hour) against the telemetry budget. 5. **Queries.** - Commit runnable Kusto queries in a durable `../telemetry.md` at the feature root: - - daily renewal outcomes and the changed-token rate; - - p50/p90 of lifetime, remaining validity and connection age at refresh; - - recoveries by trigger; + - daily renewal outcomes; + - p50/p90 of the token lifetime; + - successful operations on a replaced client (generation above 1); - late auth, socket and closed-client failures against the pre-release baseline, using the same exposure denominator. - Show sample counts and missing timing data next to every percentile. - If the operator's telemetry dashboards worktree is available, port the queries there too. -6. **Fake-clock test** for the token sequence unchanged → changed → silent miss: +6. **Fake-clock test** for the sequence returned → returned → noSession: - check counts and units; - - include an opaque token and a database rejection after the lookup. + - include an opaque token (no lifetime) and a database rejection after the lookup. **Done when:** @@ -1342,7 +1337,8 @@ shim (0005). - **OT-1:** check the shell separately. After the wait, its worker's own connection must renew without a prompt; record the token relay in the output channel, never the token. - **OT-7:** also Disconnect while a query or save is in flight. It must fail and be reported, and - nothing may run afterwards under the old connection. + nothing may run afterwards under the old connection. Also Disconnect during an **import**: it must be + blocked before the Close/Keep prompt, and the import continues. 4. CP-5 verdict, then open PR F. Watch telemetry for about one week after the merge (WI-9 queries). # Outcome 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 b785dcd0b..934cbdc2c 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 @@ -338,6 +338,8 @@ In [ClustersClient.ts](../../../../../src/documentdb/ClustersClient.ts): clients `signInRequired`. Never sign the user out, and never remove sessions (#1059 "must NOT be touched"). The event identifies the provider, not the removed account. Silently recheck affected bindings and ignore results from stale generations; another account's change must not disconnect this one. + - **Changed 2026-11-19 (decision [0012](../decisions.md)):** dropped. The next operation's silent lookup + finds a signed-out account and fails with `signInRequired`, with no listener. - **Unit tests:** - classifier table tests; - Retry after `clientClosed` produces a new generation; @@ -486,6 +488,10 @@ must be queryable without a join or a new persistent identifier. `signInAgain`) and `connectionAgeMs`. A callback returning a token is not that success. Keep WI-4's classified post-connect failures and WI-7's Disconnect event. Report ARM challenges separately from database renewal and verify the final ARM request, not just token acquisition. + - **Changed 2026-11-19 (decision [0012](../decisions.md)):** no `connection.recovered` event and no + changed-token or remaining-validity measures. `connection.tokenRenewal` keeps its outcome and the token + lifetime; recovery shows as successful operations on a replaced client (`clientGeneration` above 1) + and fewer late failures. - **Release dashboard and acceptance:** check in runnable queries that show daily renewal outcomes and changed-token rate (`changed / all completed lookups`), plus p50/p90 token lifetime, remaining validity and connection age at refresh, split by version and surface. Show sample @@ -564,8 +570,11 @@ denominator; a cohort with no challenges is inconclusive, and timing alone does - ~~**Q2:** The default for the Disconnect choice, and whether to remember it. The proposal is Keep open (disabled), remembered in `globalState`.~~ **Resolved 2026-11-19:** a VS Code modal with nothing remembered, plus a setting for the default (decision [0007](../decisions.md)). -- **Q3:** Should Disconnect drop the `CredentialCache` entry (#1059 proposes yes), so a password - typed only for a discovery connection must be entered again? +- ~~**Q3:** Should Disconnect drop the `CredentialCache` entry (#1059 proposes yes), so a password + typed only for a discovery connection must be entered again?~~ **Resolved 2026-11-19:** no. Disconnect + keeps the cached credentials and the verified identity; only Remove drops them (decision + [0011](../decisions.md)). The WI-7 teardown bullet above still lists `CredentialCache`; read it as + "Remove only". - **Q4:** Ask the Azure DocumentDB service team whether the server closes connections when the token expires, and whether it ever sends code 391 `ReauthenticationRequired` (research §1). - ~~**Q5:** Release slicing. Should WI-1 and WI-2 ship early as a patch (backport skill)? They are From 2ac698882fb2ef9710ae41fb99d6254a0565e2d2 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 19 Nov 2026 14:44:38 +0000 Subject: [PATCH 007/380] wip: complexity reduction --- .../iterations/01-dev-plan.md | 69 ++++++++++++++++--- 1 file changed, 58 insertions(+), 11 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index 95c215039..4106d729f 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 @@ -107,8 +107,42 @@ result may continue, but say so in the message. Record the result in the Progres `iterations/01-pr--review.md`, for example `01-pr1-entra-renewal-review.md`. When this folder reaches three or more iteration-1 documents, ask the operator before promoting it to an `iterations/01-…/` folder. Moving the files breaks links in the issues. -- **PR description:** name the WIs, the provisional answers (§1) the PR relies on, the checkpoint verdicts - it implements, and which verification case ran. +- **PR description:** name the WIs, the issues (next section), the provisional answers (§1) the PR relies + on, the checkpoint verdicts it implements, and which verification case ran. + +### Issues: link them, and comment on partial fixes + +Every PR names the issues it may resolve, using the table below, and says for each one whether it +**resolves** it or is a **partial fix**. + +- **Closing keywords only in PR F.** GitHub closes an issue through `Fixes #n` only when the PR merges into + the default branch. Sub-PRs merge into `feature/connection-lifecycle`, so they write + `Resolves #n (closes with PR F)` or `Part of #n`. PR F carries `Fixes #n` for every issue that the + iteration resolves in full. +- **Partial fix → a comment on the issue.** When a PR merges with only part of an issue done, post a + dedicated comment on that issue (`gh issue comment --body-file `). It contains: + - the PR link and the WIs it implemented; + - what now works, in user terms; + - what is still open, and where it is planned (a later PR, or a follow-up issue); + - decisions taken on the way that change the issue's scope, linked to `decisions.md`; + - the tests or operator tests that cover it. + + 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 + follow-up in the same way, so it can be planned from that comment alone. + +| Issue | Title (short) | PRs | Expected | +| ----- | ------------------------------------------------- | ------------- | -------------------------------------------------------------- | +| #1102 | Keep connections usable across expiry and idle | 1, 3, 4, 5, 7 | Partial in each sub-PR; resolved by PR F | +| #990 | Upgrade azureauth to v6 | 2 | Resolved by PR 2 (closes with PR F) | +| #626 | Upgrade azext-utils v3 → v4 | 2 | Check after CP-W3: likely superseded by the utils v5 upgrade | +| #1059 | Disconnect action that ends live sessions | 6 | Resolved by PR 6 (closes with PR F) | +| #566 | Unified disconnect/remove experience | 6 | Resolved or partial; decide against the issue text in PR 6 | +| #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 | ### Skills to load per work item @@ -381,19 +415,28 @@ verdict exists, do not start the work it gates. The fingerprint table (formerly ## 6. PR 0: plan, research, decisions -1. Have the operator create `feature/connection-lifecycle` from `main`, or create it yourself if you +1. **Carry over the planning commits first.** The plan, research and decisions were written as commits on + the local branch `tnaum-ms/issue1102` (from `e22a39b8d` "wip: initial plan" onward). PR 0 is made of + **those commits**. Do not re-create the files in a fresh commit, and do not squash or rebase them: the + repository merges with merge commits only, so the history stays intact. + - Check that the branch holds only docs: `git --no-pager diff --stat origin/main...tnaum-ms/issue1102`. + - Push it as the PR 0 head branch, either under its current name or as `dev/tnaum/connection-lifecycle-plan` + (`git push origin tnaum-ms/issue1102:refs/heads/dev/tnaum/connection-lifecycle-plan`). +2. Have the operator create `feature/connection-lifecycle` from `main`, or create it yourself if you have permission: `git push origin origin/main:refs/heads/feature/connection-lifecycle`. Deletion and - force-push are blocked afterwards, so check the base commit first. -2. The PR contains: + force-push are blocked afterwards, so check the base commit first. It must contain the planning + branch's base commit (`git merge-base --is-ancestor $(git merge-base origin/main tnaum-ms/issue1102) origin/main`). +3. Open PR 0 from that head branch into `feature/connection-lifecycle`. It contains: - `research-findings.md`, `decisions.md`, `README.md`; - `01-implementation-plan.md` with the pointer to this file; - **this file**; - the index row in `docs/ai-and-plans/README.md` (already present). - The current branch `tnaum-ms/issue1102` can be the head branch; renaming it to `dev/tnaum/*` is - optional for PR 0. -3. Its description states that §4 (C-1 to C-6) is the agreement that lets PR 1–3 run in parallel, and - lists A1–A6 for the operator to confirm. -4. Verification: docs only, so none, beyond `npm run prettier` on the changed Markdown. +4. Its description: + - states that §4 (C-1 to C-6) is the agreement that lets PR 1–3 run in parallel; + - lists A1 as the one provisional answer for the operator to confirm; + - links the issues as `Part of #1102`, plus #1059, #566 and #990 (references only; PR 0 resolves + nothing, so it posts no issue comments). +5. Verification: docs only, so none, beyond `npm run prettier` on the changed Markdown. **Progress:** @@ -1339,7 +1382,11 @@ one loop. - **OT-7:** also Disconnect while a query or save is in flight. It must fail and be reported, and nothing may run afterwards under the old connection. Also Disconnect during an **import**: it must be blocked before the Close/Keep prompt, and the import continues. -4. CP-5 verdict, then open PR F. Watch telemetry for about one week after the merge (WI-9 queries). +4. CP-5 verdict, then open PR F. Its description carries `Fixes #n` for every issue the iteration + resolves in full (see the §0 issue table), and `Part of #n` for the rest. +5. After the merge: for every linked issue that stays open, post the partial-fix comment (§0), summarizing + the whole iteration and what is left. Do the same on #1105 and #1106 for the work handed to them. +6. Watch telemetry for about one week after the merge (WI-9 queries). # Outcome From 453669a5993e674f8778ad7b2f3e6ce5bf201b8b Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 19 Nov 2026 15:45:04 +0000 Subject: [PATCH 008/380] wip: plans finalized --- .../features/connection-lifecycle/README.md | 3 +- .../connection-lifecycle/decisions.md | 33 +++ .../iterations/01-dev-plan.md | 209 +++++++++++++----- 3 files changed, 189 insertions(+), 56 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/README.md b/docs/ai-and-plans/features/connection-lifecycle/README.md index 37d5afd1e..81153e4f7 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/README.md +++ b/docs/ai-and-plans/features/connection-lifecycle/README.md @@ -74,7 +74,8 @@ See [decisions.md](./decisions.md): - 0009 Kubernetes tunnel recovery, case handling and wider network-resilience testing move to #1105; - 0010 rely on the server to reject expired tokens; same-identity client replacement is transparent; - 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. +- 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. ## Timeline diff --git a/docs/ai-and-plans/features/connection-lifecycle/decisions.md b/docs/ai-and-plans/features/connection-lifecycle/decisions.md index e1d956209..2f3c29967 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/decisions.md +++ b/docs/ai-and-plans/features/connection-lifecycle/decisions.md @@ -24,6 +24,7 @@ created: 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 | — | > 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 @@ -354,3 +355,35 @@ The dev plan ([iterations/01-dev-plan.md](./iterations/01-dev-plan.md)) now foll Unchanged: everything that carries an accepted decision (0001 to 0011), the single-flight startup, the cancelled-reuse fix, closed-client replacement, the failure classifier and the export and import lease. + +## 0013. Correct the minimal design where it lost edits, identity or recovery: latch before save, epoch checks + +**Accepted** by the operator on 2026-11-19. It modifies 0012. Source: a review of the dev plan against the +code for omissions that could lose data, break reconnection or force a redesign; the operator agreed with +every finding and asked to "update the plan". + +The findings, each confirmed in the code, and the corrections now in the dev plan +([iterations/01-dev-plan.md](./iterations/01-dev-plan.md)): + +- **A credential change could be stored while teardown was refused**, and a failed save can still have + written the secrets (F-21). Correction: an identity-changing update sets the latch **before** it saves, + and new tasks and leases are refused while latched. After the save, the re-read stored connection + decides: a changed fingerprint commits the teardown, an unchanged one clears the latch. This keeps 0012's + "no reservation"; the latch is the only thing that can be undone. +- **An old reply could overwrite a newer edit after a Reconnect as the same user.** Correction: host-side + results check the per-cluster epoch, not only the fingerprint and the latch, and the Document View + applies a reply only if the editor has not changed since the request. +- **The binding was lost in handoffs** (F-23). Correction: a playground stores its fingerprint on the + document's connection, not on the shared evaluator; Collection View passes its fingerprint to import and + export, which check it before their first `getClient`. +- **Recovery was tied to tree expansion.** 0012 removed the operation wrapper. Correction: one stateless + function, `runWithClient`, reports failures that happen during an operation; the dashboard sampler + classifies errors before it turns them into strings (F-24). +- **Folder deletion bypassed teardown** (F-23). Correction: it runs the teardown for every connected + descendant, with one combined confirmation. +- **Gates.** OP-1 is split: before the handler change it can only tell code 18 apart from a socket close; + renewal is proven after it, on a new socket of the same client (`maxIdleTimeMS`). OT-7 no longer + requires in-flight saves to fail, because `close(force)` cancels nothing (F-22); it requires no new + 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. 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 4106d729f..e2d68918d 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 @@ -83,14 +83,14 @@ followed by: Do not continue past the blocked step until the operator replies. Work that does not depend on the result may continue, but say so in the message. Record the result in the Progress block of the WI. -| OP | When | Test | -| ---- | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -| OP-1 | WI-1, CP-0 | Entra connection, idle past the token lifetime (60–90 min or more), then force a new connection. Does the server answer code 18 or close the socket? | -| OP-2 | WI-3, CP-W3 | The azext workflow checks on the packaged VSIX: Azure sign-in, discovery, filters, deep links, wizards, Azure Resources view. | -| OP-3 | WI-5 done | OT-2's tree part with a real sign-out: Sign in again, a dismissal, no reprompt. | -| OP-4 | WI-6 done | OT-1 (short form, with the WI-4 hook) and OT-3(a) and (b) on a dev build. | -| OP-5 | WI-7 done | OT-7 on a dev build, including a Disconnect during a running copy, export or import, and while a query or save is in flight. | -| OP-6 | Before PR F (CP-5) | OT-1 to OT-7 on the packaged VSIX, with at least one real wait of two hours or more (PR F step 3). | +| OP | When | Test | +| ---- | ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------- | +| OP-1 | WI-1, CP-0 | **Two parts.** (a) Before the handler change: does an expired token on a new socket get code 18 or a socket close? (b) After it: renewal succeeds. | +| OP-2 | WI-3, CP-W3 | The azext workflow checks on the packaged VSIX: Azure sign-in, discovery, filters, deep links, wizards, Azure Resources view. | +| OP-3 | WI-5 done | OT-2's tree part with a real sign-out: Sign in again, a dismissal, no reprompt. | +| OP-4 | WI-6 done | OT-1 (short form, with the WI-4 hook) and OT-3(a) and (b) on a dev build. | +| OP-5 | WI-7 done | OT-7 on a dev build: Disconnect during a copy, export or import, during an in-flight query or save, and a folder delete with a connected child. | +| OP-6 | Before PR F (CP-5) | OT-1 to OT-7 on the packaged VSIX, with at least one real wait of two hours or more (PR F step 3). | ### Per-PR workflow @@ -284,6 +284,23 @@ upgrade changes any of them, stop and re-plan the affected WI. `CredentialCache.deleteCredentials`, whatever the cause: `DocumentDBClusterItem`, the Azure Resources vCore and RU items, and the Atlas, Kubernetes, VM, vCore and RU discovery items. - So a tree expand during a network outage leaves open surfaces with nothing to reconnect from. +- **F-21. Storage saves are not atomic.** `StorageService.push` writes the secrets to `SecretStorage` + first, then the metadata to `globalState`. A failure after the secret write leaves the new secrets beside + the old metadata, so "the save failed" does not mean "nothing changed". +- **F-22. `MongoClient.close(force)` does not cancel anything.** In the installed driver the `force` + argument is "currently an unused flag that has no effect". An operation already sent may still + complete, and a write the server accepted cannot be undone. +- **F-23. Handoffs that drop the binding.** + - Playground evaluators are shared per `clusterId` and deleted on shutdown + (`executePlaygroundCode.ts`). The per-document connection lives in `PlaygroundService` + (`getConnection(uri)`), and it has no fingerprint today. + - Collection View starts import and export by passing a tree node to a command + (`collectionViewRouter.ts`), so the work runs under whatever credentials the cluster has when it starts. + - Folder deletion (`deleteFolder/ExecuteStep.ts`) deletes descendant connections straight from storage. + It never touches their clients, credentials, shells or tabs. +- **F-24. The dashboard sampler turns errors into strings.** `getClusterHealth.ts` catches every command + separately and records `name: message` in `errors`. An authentication failure during a ping therefore + reaches the router as a partial sample, not as an error. - **F-14. VS Code has no API to collapse one tree node.** - The repository uses `reveal(..., { expand: false })`, which does not collapse a node. - Collapsing through a changed `TreeItem.id` would conflict with the `treeId`/`clusterId` rules. @@ -389,7 +406,9 @@ semantics are binding unless a checkpoint changes them. `background: true`. They never replace a client; they just fail (T-4). - **Latch:** while a cluster is disconnected (Disconnect, Remove, an identity-changing credentials update), `getClient` throws `ConnectionUnavailableError` with the latch's reason, for every caller. - Only the explicit Connect and Reconnect actions clear the latch. + 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. - **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 @@ -405,7 +424,7 @@ verdict exists, do not start the work it gates. The fingerprint table (formerly | CP | When | Question | Evidence required | | ----- | --------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| CP-0 | WI-1, after step 1, before the handler is changed | What does the server do when an expired token reaches a new socket: does it answer code 18, or close the socket? The strategy itself is decided (0010); this only tells the WI-5 classifier what to act on. | Contract test output, and the **operator test OP-1** (§0): one real waited session, never logging tokens. | +| CP-0 | WI-1, after step 1, before the handler is changed | What does the server do when an expired token reaches a new socket: does it answer code 18, or close the socket? The strategy itself is decided (0010); this only tells the WI-5 classifier what to act on. | Contract test output, and **OP-1a** (§0): one real waited session, never logging tokens. OP-1b, after step 5, proves renewal. | | CP-W3 | WI-3, after the version probe | Which azext versions (A4)? | `npm ls` for each package, bundle scan for duplicate copies, build-error list per level, and the **packaged VSIX** loading and passing the WI-3 workflow checks. | | CP-2 | WI-5, after the classifier is drafted, before recovery is wired | The classifier table and T-5. | Classifier table tests run on **real** driver error shapes captured by the contract test and the tree paths. | | CP-4 | Before WI-7 starts | Teardown order, T-2, the export and import lease (A5). | Teardown sequence diagram in the PR description. | @@ -480,7 +499,14 @@ verdict exists, do not start the work it gates. The fingerprint table (formerly our callback, which renews silently (step 5). - Add **tracing** that makes this visible without logging tokens: each callback call with its outcome (C-3), and the server error code or socket error that preceded it. - - Then **stop and hand OP-1 to the operator** (§0, operator tests). + - Then **stop and hand OP-1a to the operator** (§0, operator tests). Today's callback returns the token + captured at connect, so OP-1a can only tell code 18 apart from a socket close; it **cannot** show + renewal. + - **A new socket on the same client** is what is under test. A new client would discard the token + cache. Add `maxIdleTimeMS=60000` to the test connection string, so the idle pool drops its sockets + and the next operation authenticates a fresh socket on the same `MongoClient`. + - The evidence is the trace line (server code or socket error, then whether the callback ran), not + "the query worked": a query on a socket that is already authenticated proves nothing. - Act on the result: - **code 18, then a second callback, then success:** nothing more to do; - **socket closed or reset, with no callback:** the driver keeps its stale cached token, so retrying @@ -488,6 +514,9 @@ verdict exists, do not start the work it gates. The fingerprint table (formerly connection during authentication is `clientClosed`, so the next **foreground** operation creates a new generation with a fresh token cache. No local expiry check (decision 0010). - Record the result and the rule, if one was added, in Progress. + - **After step 5, hand OP-1b to the operator:** the same setup on the changed handler. Pass when the trace + shows the expiry signal, a callback with outcome `returned`, and a successful operation, with no + prompt. 3. **Session helper.** - Add `src/documentdb/auth/entraSession.ts`. It calls `vscode.authentication.getSession` with an @@ -586,9 +615,12 @@ verdict exists, do not start the work it gates. The fingerprint table (formerly "initial acquisition pending" flag. - Every later relay uses `entraSession.ts` in silent mode with the pinned account, and the same C-2 errors as WI-1. - - **The shell or playground session stores its fingerprint string** (C-4) when it spawns. It does - **not** join the surface registry; teardown finds shells through `getRegisteredShellTerminals` and - the playground through its evaluator (WI-7). Before an automatic respawn + - **Where the fingerprint lives (F-23).** A shell stores its fingerprint string (C-4) on its terminal + session, which lives as long as the terminal. A playground stores it on the **document's** + `PlaygroundConnection` in `PlaygroundService` when the document is bound to a cluster, never on the + evaluator, which is shared per cluster and deleted on shutdown. Every Run compares the document's + fingerprint, whether or not a worker is warm. Neither joins the surface registry; teardown finds + shells through `getRegisteredShellTerminals` and playgrounds through `PlaygroundService` (WI-7). Before an automatic respawn (`ShellSessionManager.evaluate`, `executePlaygroundCode.ts`), compare the fingerprint of the current credentials with the stored one, and check the cluster latch (C-6): - same fingerprint and not latched: respawn as today; @@ -641,6 +673,9 @@ verdict exists, do not start the work it gates. The fingerprint table (formerly - after the cluster's credentials change to another user, the next shell command does **not** respawn silently; it prints `credentialsChanged`. A password-only change does respawn; - a latched (disconnected) shell or playground does not respawn on its next command; + - a playground document bound as identity A, left open while the cluster moves to B (and its evaluator is + shut down and recreated for another document), does not run as B; it prints `credentialsChanged` + until the user rebinds it; - after a `refreshFailed` token error (Entra and managed identity), the next command respawns the worker once under the same fingerprint, and the command after that runs on the new worker. - Add a test of the worker message round trip for `reason` and `authReason`. @@ -928,6 +963,12 @@ shim (0005). error and ignores it when `binding.generation` is stale. It evicts or marks the client according to the table, and returns the kind so the caller can choose its UI. - It keeps no connection state and fires no events (C-5). + - **Every operation reports its own failure.** A client can resolve and then fail authentication + **during** a read, save or ping. Add one thin function, `runWithClient(binding, op, { background? })`: + it resolves the client (WI-6), runs `op`, and on a throw calls `reportFailure`. For a terminal kind + (`signInRequired`, `credentialsRejected`, `credentialsMissing`, `identityChanged`) it returns the + structured unavailable result (C-5); otherwise it rethrows. Every WI-6 router operation and WI-8 + ping goes through it. It keeps no state (decision 0013). 4. **Tree.** - Route both catch paths in `getChildren` (cached-client reuse and `listDatabases`) through `reportFailure`. Keep the modal-plus-actions presentation. @@ -987,6 +1028,8 @@ shim (0005). - a stale-generation result is ignored; - an old Retry that resolves after the client was replaced does not evict the new client; - Sign in again that completes after a Disconnect does not reconnect or clear the latch; +- with the tree untouched, an OIDC callback failure during a Document View read offers the recovery + action (through `runWithClient`), and the next foreground read gets a new generation; - a tree expand that fails with a network error keeps the `CredentialCache` entry, and an open surface then reconnects silently once the network is back; a code 18 failure still evicts it. @@ -1042,8 +1085,9 @@ approved plan allows; the webview half then opens after the host half merges. `lastVerifiedIdentity`; - **a different fingerprint, or a latched cluster:** throw `ConnectionUnavailableError(reason)`. - A surface **never** prompts (C-6). - - Router procedures catch `ConnectionUnavailableError` and return a structured - `{ unavailable: { reason, text, action } }` result instead of an error (F-12). + - Router procedures run their operations through `runWithClient` (WI-5 step 3), so failures **during** + the operation are classified too, and return a structured `{ unavailable: { reason, text, action } }` + result instead of an error (F-12). - **No regression for tunneled connections** (Kubernetes `ClusterIP` through port-forward). Creating a new generation from this path may not do less than today's tree path, and it does not re-create tunnels. A tab whose tunnel died behaves as it does today: it fails transiently until a tree expand @@ -1063,13 +1107,16 @@ approved plan allows; the webview half then opens after the host half merges. 5. **Writes.** - Save document, inserts and deletes, and index create, drop, hide and unhide. - The extension **never resubmits** a write; that is OT-4's "not replayed". A failed write is reported - as it is today. The driver's own retryable writes (`retryWrites`) stay as they are: the server + as it is today, and never with text that claims the write was not applied: when the reply was lost, + the server may have applied it (F-22). The driver's own retryable writes (`retryWrites`) stay as they are: the server deduplicates them by design, and RU connection strings disable them. - Test that one application-level submission results in exactly one call to the driver. 6. **Stale results.** - - Every request records the generation it started with. - - **Before any host-side mutation**, check once that the binding still resolves to the same fingerprint - and that the cluster is not latched. Otherwise drop the result. That covers `ClusterSession`'s + - Every request records the C-6 **epoch** when it starts. + - **Before any host-side mutation**, check once that the epoch is unchanged, that the binding still + resolves to the same fingerprint, and that the cluster is not latched. Otherwise drop the result. + Disconnect, Reconnect and every eviction bump the epoch, so a reply that started before a Disconnect + is dropped even after a Reconnect as the same user. That covers `ClusterSession`'s `_currentRawDocuments`, its query caches, the Query Insights caches and `SchemaStore` updates. A stale result must not change host state at all. 7. Every router error path uses `addEstablishedConnectionContext` (WI-4). @@ -1088,6 +1135,10 @@ approved plan allows; the webview half then opens after the host half merges. refresh, save, delete, insert, index actions, Query Insights stages and AI calls. - Editors stay **editable**. The user can keep typing. - A response that arrives while the banner shows is ignored. + - **A reply never overwrites a newer edit.** The Document View applies a save or load reply to the editor + only if the editor content has not changed since the request was sent; otherwise it keeps the edit and + stays dirty. Today's save handler (`documentView.tsx`) replaces the content and clears `isDirty` + unconditionally. The Collection View applies a page only for the latest query request it sent. 3. **What each view keeps.** - **Collection View:** query text, filter, sort, projection, page number and size, the selected tab, and the Query Insights results as they were. @@ -1109,18 +1160,27 @@ approved plan allows; the webview half then opens after the host half merges. - `documentView/disconnected-dirty`: edit kept, Save disabled; - `clusterDashboard/disconnected`; - a scenario that injects a disconnect after typing and then delivers a page response: the applied - results are not overwritten. + results are not overwritten; + - `documentView/stale-save-after-reconnect`: send Save, Disconnect, Reconnect, edit again, then deliver + the old save reply: the new edit stays and the view stays dirty. - Run them with the browser scenario config. Screenshots are artifacts, not baselines. -**Transfers:** do not touch copy, paste or export (approved plan). +**Transfers:** do not change how copy, paste or export work (approved plan). One addition: when Collection +View starts an import or export, it passes its binding's fingerprint in the command arguments (F-23). The +command checks it once, where it takes the WI-7 lease and before its first `getClient`. A mismatch stops +with `credentialsChanged` and nothing is written. Commands started from the tree carry no fingerprint and +behave as today. **Tests:** - router tests for both resolution outcomes on each converted router; - `ClusterSession` no longer stores a client (a type-level or structural test); -- a stale result is dropped before any host-side mutation; +- a stale result is dropped before any host-side mutation, including a reply that started before a + Disconnect and arrives after a Reconnect as the same user; - the webview ignores a response that arrives while the banner shows; - one submission for a write whose reply is lost; +- an import started from Collection View as identity A, with its file picker left open while the cluster + moves to B, writes nothing until the user starts it again; - the scenarios above. **Done when:** @@ -1140,11 +1200,14 @@ approved plan allows; the webview half then opens after the host half merges. - One teardown serves Disconnect, Remove and identity-changing credential updates. - It is guarded by task conflicts and dirty editors. - It covers every per-cluster resource. -- **What it guarantees:** after the commit, no operation **starts** under the old binding. Operations - already in flight are not tracked individually: - - `deleteClient` closes the client with `force`, so they fail and their failure is reported normally; - - shell and playground workers are stopped; - - tasks, exports and imports are protected by the conflict check. +- **What it guarantees** (F-22: closing a client cancels nothing already sent): + - no **new** submission under the old binding after the latch is set; + - no automatic replay of anything; + - no stale reply changes host state or the UI (WI-6 step 6 and the webview rule); + - no message claims that an unacknowledged write was not applied. + + Operations already in flight may complete or fail; whatever happens is reported normally. Shell and + playground workers are stopped. Tasks, exports and imports are protected by the conflict check. This is the right level for an interactive tool; do not build per-operation admission control. @@ -1154,6 +1217,8 @@ approved plan allows; the webview half then opens after the host half merges. - `resourceUsageHelper.ts` and `taskService.ts` (`getConflictingTasks`); - `CopyPasteCollectionTask.ts` and `CopyIndexesTask.ts` (`getUsedResources`); - `exportDocuments.ts` and `importDocuments.ts`; +- `deleteFolder/` (`ExecuteStep.ts`, `VerifyNoConflictsStep.ts`); +- `storageService.ts` `push` (F-21); - `updateCredentials.ts`, including the D12 modal; - `updateConnectionString.ts`; - `CredentialCache.ts`, `entraTokenFailures.ts` and `SchemaStore.clearCluster`; @@ -1170,11 +1235,13 @@ approved plan allows; the webview half then opens after the host half merges. - `exportDocuments.ts` holds the lease for the whole export, and `importDocuments.ts` for the whole import (from the first `getClient` to the last flushed batch), on the target collection. - Copy/paste and copy-indexes are tasks already and need no lease (F-9). + - `acquireResourceLease`, and starting a task, are refused while the cluster is latched (C-6), with the + latch's reason. The latch is what keeps new work out during a credential save (step 5). - Test that export and import each conflict with Disconnect of their cluster and with Delete Collection of their collection, and that an unrelated cluster does not. -2. **Teardown** (`src/documentdb/connectionTeardown.ts`): two plain functions, with no reservation and no - rollback. Disconnect and Remove call them back to back; Update Credentials puts the save between them - (step 5). +2. **Teardown** (`src/documentdb/connectionTeardown.ts`): plain functions, with no reservation. The latch + is the only thing that can be undone, and only Update Credentials ever undoes it (step 5). Disconnect + and Remove call `confirmTeardown` and `commitTeardown` back to back. - **`confirmTeardown(clusterId, intent)`**, which may prompt and may be cancelled. It changes nothing: 1. **Conflicts:** task and lease conflicts through `checkCanProceedAndInformUser`. On a conflict, stop; the conflicting task is named. @@ -1183,20 +1250,23 @@ approved plan allows; the webview half then opens after the host half merges. 3. **Dirty check** (only for `close`): if any registered surface reports `isDirty`, ask for confirmation. Cancelling leaves every panel, draft and connection intact, also when Remove started the teardown. + - **`latchForTeardown(clusterId, reason)`**, synchronous: recheck conflicts with `getConflictingTasks`, + because a copy, export or import may have started while a prompt was open; on a conflict return + `false` and change nothing. Otherwise set the latch (C-6) and call `ClustersClient.invalidate`, which + increases the epoch, with no `await` in between, and return `true`. From here on no new task, lease or + client can start. - **`commitTeardown(clusterId, { reason, choice, dropCredentials })`**, which has no prompts: - 1. **Recheck** conflicts with `getConflictingTasks`, because a copy, export or import may have started - while a prompt was open. On a conflict, stop and inform the user; nothing has changed. - 2. **With no `await` between the recheck and this step:** set the latch (C-6) with `reason`, and call - `ClustersClient.invalidate`, which increases the epoch. - 3. **Surfaces:** for Keep open, call each registered surface's `disable(reason)`; for Close all, + 1. Call `latchForTeardown` unless the caller already did (step 5). On a conflict, stop and inform the + user; nothing has changed. + 2. **Surfaces:** for Keep open, call each registered surface's `disable(reason)`; for Close all, dispose them. - 4. **Shells** (found through `getRegisteredShellTerminals`): print "Disconnected", then stop the + 3. **Shells** (found through `getRegisteredShellTerminals`): print "Disconnected", then stop the worker. **Playground:** stop the worker. The latch keeps both from respawning (F-15). - 5. Close the client (`deleteClient`). Clear the Entra failure registry and `SchemaStore.clearCluster`. + 4. Close the client (`deleteClient`). Clear the Entra failure registry and `SchemaStore.clearCluster`. Clear the `CredentialCache` entry and `lastVerifiedIdentity` **only** when `dropCredentials` is set (Remove). Disconnect keeps both (A3, decision 0011), so Connect and a tab's Reconnect are silent and pinned to the same identity. - 6. Refresh the tree (T-2). + 5. Refresh the tree (T-2). - **Never touched:** VS Code auth sessions, the managed identity cache, the ARM cache. - **Keys:** every store keeps its current `clusterId` matching. Provider-specific equality is out of scope (decision 0009, #1105). Do not add case folding or unfolding in this iteration. @@ -1221,8 +1291,14 @@ approved plan allows; the webview half then opens after the host half merges. dirty, that confirmation still appears. - Skip the modal when no surfaces are registered. - Add a disconnected cluster node child action, "Connect" (T-2). It clears the latch and connects. -4. **Remove Connection.** Teardown with reason `connectionRemoved` and `dropCredentials: true`, then delete - the stored connection and clear the schema, as today. Keep the existing confirmation. +4. **Remove Connection and folder deletion.** + - Remove Connection: teardown with reason `connectionRemoved` and `dropCredentials: true`, then delete + the stored connection and clear the schema, as today. Keep the existing confirmation. + - **Deleting a folder** (F-23) runs the same teardown for **every connected descendant**, with **one** + combined `confirmTeardown` for all of them (conflicts, choice, dirty check), not one modal per + connection. It runs before `deleteFolder/ExecuteStep.ts` deletes anything. Cancelling leaves the + folder, its connections, panels, drafts and shells intact. Descendants without a client or open + surface still get their `CredentialCache` entry and schema cleared, as Remove does. 5. **Update Credentials and Update Connection String.** - Compute the **new** fingerprint from the wizard context before saving. - **Make save success explicit** (F-19): the execute step must report whether the save succeeded, for @@ -1231,13 +1307,20 @@ approved plan allows; the webview half then opens after the host half merges. with a new generation; surfaces continue. - **Different fingerprint:** 1. `confirmTeardown` **before** saving. - 2. Save. - 3. On a confirmed success: `commitTeardown` with reason `credentialsChanged` and - `dropCredentials: false`, so the **new** credentials stay. `lastVerifiedIdentity` is replaced on - the next successful connect. - 4. On a failed save: nothing was changed, and the old binding stays usable. - - The `invalidate` call in `commitTeardown` makes sure a concurrent connect cannot publish the old - credentials after the change. + 2. `latchForTeardown` **before** saving. On a conflict, stop: nothing is saved. Now no import, task or + connect can start while the save runs. + 3. Save. + 4. **Storage decides, not the success flag** (F-21). Re-read the stored connection and compute its + fingerprint: + - it differs from the live binding (a full save, **or** a partial one where the secrets were + written): `commitTeardown` with reason `credentialsChanged` and `dropCredentials: false`, so what + is stored is what the next connect uses. `lastVerifiedIdentity` is replaced on the next successful + connect. If the save reported a failure, also tell the user the change may be incomplete and offer + Update Credentials; + - it equals the live binding (nothing reached storage): clear the latch. The old binding stays + usable, and the user is told the save failed. + - The latch and the `invalidate` call make sure a concurrent connect cannot publish the old credentials + after the change. - Add a **Disconnect** button to the D12 modal for open shells. 6. **Telemetry.** - One `connection.disconnect` event with `source` (`command`, `remove`, `credentialsChanged`), @@ -1259,9 +1342,16 @@ approved plan allows; the webview half then opens after the host half merges. - a copy, export or import that starts while the Disconnect prompt is open stops the commit, and nothing changes; - a shell or playground left open after Disconnect does not respawn on its next command; -- Disconnect while a query or save is in flight: the operation fails and is reported, and nothing runs - afterwards under the old binding; -- a failed save keeps the old binding; +- Disconnect while a query or save is in flight: whatever the operation's outcome, it is reported, its + reply changes no state, and nothing new is submitted under the old binding; +- an import attempted while Update Credentials is saving is refused with the latch's reason, and nothing + is half-applied; +- a save that fails before any write keeps the old binding and clears the latch; +- a save whose metadata write fails after the secret write ends in teardown under `credentialsChanged`, + never in a split state (old client, new stored secrets); +- deleting a folder with a connected child that has a dirty Document View and a live shell: cancelling + leaves everything intact; confirming leaves no usable client, cached credentials, shell or tab for the + child; - a concurrent connect during Update Credentials does not publish the old credentials. **Done when:** Case 1 is green, and the OT-7 flows can be reproduced on a dev build. @@ -1277,8 +1367,12 @@ one loop. **Steps:** -1. `measureRtt` resolves through the WI-6 binding with `background: true`, so it never replaces a client +1. `measureRtt` runs through `runWithClient` with `background: true`, so it never replaces a client (T-4). It returns a structured result, `{ ok, rttMs } | { unavailable }`, instead of throwing. + - **Classify before the sampler stringifies (F-24).** `sampleClusterHealth` keeps the error object + of a failed command long enough to classify it. A terminal kind (auth, closed client) is rethrown so + that `runWithClient` returns `unavailable`. An unsupported command, such as `serverStatus` on some + servers, stays an ordinary partial sample with its entry in `errors`. 2. The webview poll effect depends on the banner state: it stops on `unavailable` or on a `disable` message, and starts again after Reconnect. React's effect cleanup keeps it to one loop; no extra loop token. @@ -1292,7 +1386,9 @@ one loop. - no client lookups on ticks or on reveal after Disconnect; - a late success does not clear the banner; - reconnecting starts exactly one loop; -- `signInRequired` and `credentialsRejected` stop the loop after one tick. +- `signInRequired` and `credentialsRejected` stop the loop after one tick, including when they happen + **inside** the sampler's ping with the tree untouched; +- an unsupported `serverStatus` still yields a partial sample and keeps polling. **Progress:** @@ -1379,8 +1475,11 @@ one loop. result, and the evidence the approved plan requires, in `# Outcome`. In addition: - **OT-1:** check the shell separately. After the wait, its worker's own connection must renew without a prompt; record the token relay in the output channel, never the token. - - **OT-7:** also Disconnect while a query or save is in flight. It must fail and be reported, and - nothing may run afterwards under the old connection. Also Disconnect during an **import**: it must be + - **OT-7:** also Disconnect while a query or save is in flight. Whatever its outcome, it is reported; + its reply does not change the open view; nothing new is submitted under the old connection; and no + message claims that an unacknowledged save was not applied (F-22). + - **OT-1 and OT-2 evidence:** a callback trace line after the wait or the sign-out, on a fresh socket + (`maxIdleTimeMS`), not only a successful query. Also Disconnect during an **import**: it must be blocked before the Close/Keep prompt, and the import continues. 4. CP-5 verdict, then open PR F. Its description carries `Fixes #n` for every issue the iteration resolves in full (see the §0 issue table), and `Part of #n` for the rest. From be2f45dc79d9ef45fdc5a4e16c293c4e198dd5d6 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 19 Nov 2026 15:53:21 +0000 Subject: [PATCH 009/380] docs: record PR 0 gate and lifecycle model assignments Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../connection-lifecycle/iterations/01-dev-plan.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index e2d68918d..5bd00c1d4 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 @@ -459,6 +459,20 @@ verdict exists, do not start the work it gates. The fingerprint table (formerly **Progress:** +- **Deferred, escalated (2026-11-19):** The existing planning commits through `453669a59` were + verified to be docs-only. The remote feature branch and PR 0 did not exist when checked. Publishing + is waiting for operator authorization or operator-created branches and PR. Recommendation: create + `feature/connection-lifecycle` from `origin/main`, publish the planning branch as + `dev/tnaum/connection-lifecycle-plan`, and open draft PR 0. No implementation PR starts before PR 0 + merges. +- **Coding model assignments (2026-11-19), advised (`claude-opus-5.5`):** `gpt-6.1-sol` for WI-1 + (including the pre-OP-1a work), WI-2, the WI-3 version probe, WI-4, WI-5, the WI-6 host, and WI-7, + where auth, lifecycle or cross-module contracts dominate. `mai-code-2` for the WI-6 webviews and + WI-8, which consume those contracts; `gpt-6.1-terra` is the fallback. `gpt-6.1-terra` for WI-3 + follow-through after the version verdict, WI-9 and WI-10 prose; `gpt-6-luna` for WI-10 cross-links + and preview. If a webview design decision is needed, consult the advisor in a fresh session before + dispatch. These assignments do not move any operator gate. No coding workers have been started. + --- ## WI-1: Entra ID, silent renewal on every OIDC callback (PR 1) From 29312ae045874e511f8df3874f9e6e0e6890ca72 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 19 Nov 2026 15:55:05 +0000 Subject: [PATCH 010/380] docs: bump lifecycle Sol assignments to GPT-6.2 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../features/connection-lifecycle/iterations/01-dev-plan.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index 5bd00c1d4..1982cb2d0 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 @@ -472,6 +472,9 @@ verdict exists, do not start the work it gates. The fingerprint table (formerly follow-through after the version verdict, WI-9 and WI-10 prose; `gpt-6-luna` for WI-10 cross-links and preview. If a webview design decision is needed, consult the advisor in a fresh session before dispatch. These assignments do not move any operator gate. No coding workers have been started. +- **Model override (operator, 2026-11-19):** Use `gpt-6.2-sol` for the Sol assignments above. + Keep `gpt-6.1-terra` until a GPT-6.2 Terra model is available. The MAI Code 2, Luna, and advisor + assignments are unchanged. --- From 2666f2ac741e66ae6e70fd87d8e83b3524783b86 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 19 Nov 2026 16:00:48 +0000 Subject: [PATCH 011/380] docs: stack connection lifecycle implementation PRs Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../features/connection-lifecycle/README.md | 5 +- .../connection-lifecycle/decisions.md | 19 +++--- .../iterations/01-dev-plan.md | 26 ++++---- .../iterations/01-implementation-plan.md | 63 +++++++++---------- 4 files changed, 57 insertions(+), 56 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/README.md b/docs/ai-and-plans/features/connection-lifecycle/README.md index 81153e4f7..82f9176dd 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/README.md +++ b/docs/ai-and-plans/features/connection-lifecycle/README.md @@ -21,7 +21,8 @@ code: - 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) -**Branch:** `feature/connection-lifecycle`, with sub-PRs from `dev/tnaum/*` (decision 0006) +**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). > How database connections stay usable across Entra token expiry, idle drops and credential > changes, and what open surfaces do when the user must act or the identity changes. @@ -68,7 +69,7 @@ See [decisions.md](./decisions.md): - 0003 no silent identity change; - 0004 the Disconnect tab choice; - 0005 azureauth v6; -- 0006 delivery through a feature branch, shipped once; +- 0006 delivery through a feature branch with stacked sub-PRs, shipped once; - 0007 the Disconnect choice is a modal, not remembered, with a setting for the default; - 0008 the azext stack is upgraded as high as viable, with Azure Resources as the reference; - 0009 Kubernetes tunnel recovery, case handling and wider network-resilience testing move to #1105; diff --git a/docs/ai-and-plans/features/connection-lifecycle/decisions.md b/docs/ai-and-plans/features/connection-lifecycle/decisions.md index 2f3c29967..4fb988407 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/decisions.md +++ b/docs/ai-and-plans/features/connection-lifecycle/decisions.md @@ -17,7 +17,7 @@ created: 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 sub-PRs, avoid PRs on top of open PRs, ship once | Accepted | Operator chose this over one big PR and GitHub stacks | 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 | — | @@ -140,7 +140,7 @@ Rejected: logic, and it would be thrown away when #990 lands. - **Staying on 5.1.1, the latest stable.** It still captures the token. -## 0006. Deliver through `feature/connection-lifecycle` with sub-PRs, avoid PRs on top of open PRs, ship once +## 0006. Deliver through `feature/connection-lifecycle` with stacked sub-PRs, ship once **Accepted** by the operator on 2026-11-19. Source: operator input during planning. @@ -150,8 +150,13 @@ Rejected: > without the 'stack' feature from github. [...] it won't be a partial release, it all will go out > at once. -After the evaluation, the operator chose the feature-branch model and asked to reduce PRs opened on -top of other open PRs: "not required, just welcomed". +After the evaluation, the operator initially asked to reduce PRs opened on top of other open PRs: +"not required, just welcomed". + +**Amended by the operator on 2026-11-19:** Approvals will take time, so build and open each next +sub-PR on the preceding PR's branch without waiting for it to merge. The operator will follow up +with approvals and merges. This changes neither the explicit operator test gates nor the single +release from the feature branch. - It follows CONTRIBUTING §1.4 (large features). - It fits the repository's enforcement: @@ -159,8 +164,7 @@ top of other open PRs: "not required, just welcomed". - the `feature/**` ruleset requires a reviewed PR and blocks force pushes; - only merge commits are allowed, and head branches are deleted on merge. - Merge commits keep the original commits. A PR opened on top of another one therefore shrinks to - its own diff, and is retargeted automatically, once its base merges. That makes the exception - workable without moving updates up the chain. + its own diff once its base merges and GitHub retargets it. Verify the retargeting after each merge. - The split and the rules are in [the plan's Delivery section](./iterations/01-implementation-plan.md#delivery). Rejected: @@ -170,8 +174,7 @@ Rejected: review and AI pre-review get worse. - Each push dismisses the approval. - There are no reviewed checkpoints, and conflicts with `main` are resolved only at the end. -- **GitHub stacked PRs:** the operator's experience was that updates must move up the chain and the - PRs end up merged one by one anyway. +- **GitHub's stack feature:** not needed; use ordinary PRs targeting the preceding branch. - **Shipping WI-1 and WI-2 early as a patch (plan Q5):** no partial release. ## 0007. The Disconnect choice is a VS Code modal with nothing remembered; a setting can set the default 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 1982cb2d0..527372952 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 @@ -94,8 +94,10 @@ result may continue, but say so in the message. Record the result in the Progres ### Per-PR workflow -- **Branch:** create `dev/tnaum/` from `feature/connection-lifecycle`. Follow the approved plan's - rules for keeping PRs off each other. +- **Branch:** create `dev/tnaum/` from the preceding PR's head and target that branch while + the preceding PR is open. If it is already merged, branch from and target + `feature/connection-lifecycle`. Do not wait for intermediate approvals or merges; the operator + handles those. The advisor checkpoints and explicit operator decisions and tests still apply. - **Commits:** one or more commits per WI, never one commit that mixes two WIs. Each commit ends with the `Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>` trailer. - **While working, and for draft PRs:** Case 1 only: `npm run build` plus `npx vitest run `. @@ -343,9 +345,9 @@ working as they do today. ## 4. Contracts that cross PRs -The approved plan lets PR 1–3 run in parallel "if PR 0 agrees how WI-1 passes the verified account, -provider and tenant to WI-4". These contracts are that agreement. The field names are illustrative; the -semantics are binding unless a checkpoint changes them. +These contracts define how PRs 1–3 share the verified account, provider and tenant while the +implementation PRs are stacked. The field names are illustrative; the semantics are binding unless +a checkpoint changes them. - **C-1. Verified identity.** - WI-1 produces it on the first successful Entra acquisition: @@ -451,7 +453,7 @@ verdict exists, do not start the work it gates. The fingerprint table (formerly - **this file**; - the index row in `docs/ai-and-plans/README.md` (already present). 4. Its description: - - states that §4 (C-1 to C-6) is the agreement that lets PR 1–3 run in parallel; + - states that §4 (C-1 to C-6) is the agreement that lets PRs 1–3 share the connection contracts; - lists A1 as the one provisional answer for the operator to confirm; - links the issues as `Part of #1102`, plus #1059, #566 and #990 (references only; PR 0 resolves nothing, so it posts no issue comments). @@ -459,12 +461,10 @@ verdict exists, do not start the work it gates. The fingerprint table (formerly **Progress:** -- **Deferred, escalated (2026-11-19):** The existing planning commits through `453669a59` were - verified to be docs-only. The remote feature branch and PR 0 did not exist when checked. Publishing - is waiting for operator authorization or operator-created branches and PR. Recommendation: create - `feature/connection-lifecycle` from `origin/main`, publish the planning branch as - `dev/tnaum/connection-lifecycle-plan`, and open draft PR 0. No implementation PR starts before PR 0 - merges. +- **Published (2026-11-19):** [Draft PR 0 (#1107)](https://github.com/microsoft/vscode-documentdb/pull/1107) + targets `feature/connection-lifecycle` from `dev/tnaum/connection-lifecycle-plan`. The operator + removed the intermediate merge gate: PR 1 can build on PR 0 now. The operator will handle reviews + and merges; CP-0 and OP-1a still apply before any OIDC handler change. - **Coding model assignments (2026-11-19), advised (`claude-opus-5.5`):** `gpt-6.1-sol` for WI-1 (including the pre-OP-1a work), WI-2, the WI-3 version probe, WI-4, WI-5, the WI-6 host, and WI-7, where auth, lifecycle or cross-module contracts dominate. `mai-code-2` for the WI-6 webviews and @@ -1084,7 +1084,7 @@ shim (0005). - `build/verification/browser/scenarios.ts` and `fixtures.ts`. PR 5 is one PR. Split it into host and webviews only if the diff becomes too large to review well, as the -approved plan allows; the webview half then opens after the host half merges. +approved plan allows; the webview half then stacks on the host half without waiting for it to merge. ### Host 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 934cbdc2c..1173c7cc9 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 @@ -87,10 +87,11 @@ WI-4 ─┴─> WI-5 ─> WI-6 ─> WI-7 ─> WI-8 (lifecycle core, then Disco [CONTRIBUTING §1.4](../../../../../CONTRIBUTING.md#14-large-features). - `feature/connection-lifecycle` is created from `main`. -- Each sub-PR comes from a `dev/tnaum/` branch and merges into the feature branch, where it - gets its own review, AI pre-review and checks. +- Each sub-PR comes from a `dev/tnaum/` branch and ultimately merges into the feature + branch, where it gets its own review, AI pre-review and checks. The operator handles approvals + and merges. - **One** final PR, `feature/connection-lifecycle` → `main`, ships everything in a single release. -- GitHub's stacked PRs are not used. +- Use ordinary PRs targeting the preceding branch, not GitHub's stack feature. **How the repository enforces this** (checked 2026-11-19): @@ -103,22 +104,20 @@ WI-4 ─┴─> WI-5 ─> WI-6 ─> WI-7 ─> WI-8 (lifecycle core, then Disco - Repository merge settings: **merge commits only** (squash and rebase are disabled), and head branches are deleted on merge. -### Rules for keeping PRs off each other +### Rules for stacking sub-PRs -The goal is to open few PRs on top of other unmerged PRs. It is preferred, not required. - -1. **Open a PR only when everything it depends on has merged** into the feature branch. While a - dependency is still in review, keep building on a local branch made from it. Once the dependency - merges, `git merge feature/connection-lifecycle` into the local branch, then open the PR against - the feature branch. -2. **Use parallel tracks.** Independent work items each get their own PR off the feature branch, - so they never stack (PR 1–3 below). +1. **Do not wait for approvals or an intermediate merge to start or open the next PR.** Branch from + the preceding PR's head and target that branch while its PR is open. If it has already merged, + branch from and target `feature/connection-lifecycle` instead. +2. **Keep implementation gates.** The stack order does not remove any advisor checkpoint or + operator decision or test. Stop at those as specified. Run the existing verification locally + even when CI does not run on a PR targeting an intermediate branch. 3. **Group work items into one PR** when they are strongly coupled and reviewable together. Keep commits per work item inside the PR, so the inline progress notes can name them. -4. **Exception:** if waiting would block progress, a PR _may_ target another open PR's branch. Merge - commits keep the commits intact, and deleting the base branch on merge makes GitHub retarget the - PR to the feature branch automatically. To pick up later changes from the base, use - `git merge `. Never rebase or force-push after a human review (CONTRIBUTING §1.6). +4. **Integrate bottom-up.** Do not merge a sub-PR into the preceding topic branch. After the + predecessor merges, verify the next PR targets `feature/connection-lifecycle` before merging it. + To pick up later changes from the base, use `git merge `. Never rebase or force-push after a + human review (CONTRIBUTING §1.6). 5. **Sync `main` into the feature branch** through a PR, because force pushes are blocked: - weekly, and once more right before the final PR; - as a pure merge, with no feature work in it; @@ -127,24 +126,22 @@ The goal is to open few PRs on top of other unmerged PRs. It is preferred, not r ### PR split -| PR | Content | Base when opened | Opens after | -| --- | -------------------------------------------------------------------------------- | ----------------------------- | ------------------------- | -| 0 | This plan, `research-findings.md`, `decisions.md`, README and index row | feature branch (just created) | — | -| 1 | WI-1 + WI-2: Entra silent renewal, plus the shell and playground relays | feature branch | PR 0 | -| 2 | WI-3: azureauth v6 (#990) + the diagnostics `signInRequired` mapping | feature branch | PR 0 | -| 3 | WI-4: client identity and generation, the two cache fixes, telemetry helper | feature branch | PR 0 | -| 4 | WI-5: failure classifier, recovery, Sign in again, Retry, `onDidChangeSessions` | feature branch | PR 1 and PR 3 merged | -| 5 | WI-6: surface binding and the disconnected state (host and webviews) | feature branch | PR 4 merged | -| 6 | WI-7 + WI-8: teardown, Disconnect, Remove, Update Credentials, dashboard polling | feature branch | PR 5 merged | -| 7 | WI-9 + WI-10: telemetry signals and dashboards, documentation | feature branch | PR 6 merged | -| F | `feature/connection-lifecycle` → `main` | `main` | all merged, OT-1–7 passed | - -- PR 1–3 can run in parallel if PR 0 agrees how WI-1 passes the verified account, provider and - tenant to WI-4. Otherwise, land PR 1 before PR 3; do not reconstruct the identity from a later cache read. -- PR 4 to PR 7 are sequential, because each builds on the previous one. Under rule 1, local work on - the next item may begin early, but its PR opens only after its base has merged. +| PR | Content | Base while predecessor is open | +| --- | -------------------------------------------------------------------------------- | ------------------------------------------ | +| 0 | This plan, `research-findings.md`, `decisions.md`, README and index row | feature branch | +| 1 | WI-1 + WI-2: Entra silent renewal, plus the shell and playground relays | PR 0 head | +| 2 | WI-3: azureauth v6 (#990) + the diagnostics `signInRequired` mapping | PR 1 head | +| 3 | WI-4: client identity and generation, the two cache fixes, telemetry helper | PR 2 head | +| 4 | WI-5: failure classifier, recovery, Sign in again, Retry, `onDidChangeSessions` | PR 3 head | +| 5 | WI-6: surface binding and the disconnected state (host and webviews) | PR 4 head | +| 6 | WI-7 + WI-8: teardown, Disconnect, Remove, Update Credentials, dashboard polling | PR 5 head | +| 7 | WI-9 + WI-10: telemetry signals and dashboards, documentation | PR 6 head | +| F | `feature/connection-lifecycle` → `main` | `main` (all sub-PRs merged, OT-1–7 passed) | + +- WI-4 consumes the verified account, provider and tenant contract from WI-1. Do not reconstruct + the identity from a later cache read. - **PR 5 is the largest.** If it becomes too large to review well, split it into host (5a) and - webviews (5b). 5b opens after 5a merges, following rule 1. + webviews (5b). Stack 5b on 5a, and PR 6 on 5b, following rule 1. - **#990 alternative:** #990 is its own issue in the 1.2.0 milestone. It can merge to `main` instead, which keeps the busiest lockfile changes off the feature branch; it would still ship in the same release. The default is the feature branch, so that the discovery fix and the WI-3 diagnostics From df0c22adedd7c28559d83c766b7233333afcf4fb Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 19 Nov 2026 16:04:48 +0000 Subject: [PATCH 012/380] test: pin MongoDB OIDC driver behavior (WI-1a) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../auth/driverOidcContract.test.ts | 134 ++++++++++++++++++ 1 file changed, 134 insertions(+) create mode 100644 src/documentdb/auth/driverOidcContract.test.ts diff --git a/src/documentdb/auth/driverOidcContract.test.ts b/src/documentdb/auth/driverOidcContract.test.ts new file mode 100644 index 000000000..0144c7a8a --- /dev/null +++ b/src/documentdb/auth/driverOidcContract.test.ts @@ -0,0 +1,134 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { + BSON, + MongoNetworkError, + MongoServerError, + type Binary, + type MongoCredentials, + type MongoDBNamespace, + type OIDCCallbackFunction, + type OIDCResponse, +} from 'mongodb'; +// eslint-disable-next-line import/no-internal-modules -- Exercise the installed driver's real OIDC workflow. +import { AutomatedCallbackWorkflow as DriverWorkflow } from 'mongodb/lib/cmap/auth/mongodb_oidc/automated_callback_workflow.js'; +// 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'; + +// The driver's public declarations omit these internals. Type only the surface the suite uses. +interface SaslStart { + saslStart: number; + mechanism: string; + payload: Binary; +} + +interface FakeConnection { + command(namespace: MongoDBNamespace, command: SaslStart, options: undefined): Promise<{ ok: number }>; +} + +interface OidcTokenCache { + put(response: OIDCResponse): void; +} + +type WorkflowCredentials = Pick; + +interface OidcWorkflow { + fetchAccessToken(credentials: WorkflowCredentials): Promise; + speculativeAuth( + connection: FakeConnection, + credentials: WorkflowCredentials, + ): Promise<{ speculativeAuthenticate?: SaslStart & { db: string } }>; + execute(connection: FakeConnection, credentials: WorkflowCredentials): Promise; +} + +const TokenCache = DriverTokenCache as new () => OidcTokenCache; +const AutomatedCallbackWorkflow = DriverWorkflow as new ( + cache: OidcTokenCache, + callback: OIDCCallbackFunction, +) => OidcWorkflow; + +const credentials: WorkflowCredentials = { + source: '$external', + username: 'dummy-user', + mechanismProperties: {}, +}; + +describe('driver contract: mongodb OIDC workflow (7.2.0)', () => { + it('rethrows the identical callback error on the next fetch without calling the callback again', async () => { + const error = new Error('dummy callback failure'); + const callback = vi.fn().mockRejectedValueOnce(error); + const workflow = new AutomatedCallbackWorkflow(new TokenCache(), callback); + + await expect(workflow.fetchAccessToken(credentials)).rejects.toBe(error); + await expect(workflow.fetchAccessToken(credentials)).rejects.toBe(error); + expect(callback).toHaveBeenCalledTimes(1); + }); + + it('offers the cached token in speculative authentication after its advertised lifetime', async () => { + vi.useFakeTimers({ toFake: ['Date'] }); + try { + vi.setSystemTime(1_000); + const cache = new TokenCache(); + cache.put({ accessToken: 'dummy-cached-token', expiresInSeconds: 1 }); + const callback = vi.fn(); + const workflow = new AutomatedCallbackWorkflow(cache, callback); + const command = vi.fn(); + vi.setSystemTime(3_000); + + const { speculativeAuthenticate } = await workflow.speculativeAuth({ command }, credentials); + + expect(speculativeAuthenticate).toMatchObject({ + db: '$external', + saslStart: 1, + mechanism: 'MONGODB-OIDC', + }); + expect(speculativeAuthenticate && BSON.deserialize(speculativeAuthenticate.payload.value())).toEqual({ + jwt: 'dummy-cached-token', + }); + expect(callback).not.toHaveBeenCalled(); + expect(command).not.toHaveBeenCalled(); + } finally { + vi.useRealTimers(); + } + }); + + it('calls the callback again on code 18 and retries authentication with the new token', async () => { + const callback = vi + .fn() + .mockResolvedValueOnce({ accessToken: 'dummy-cached-token' }) + .mockResolvedValueOnce({ accessToken: 'dummy-renewed-token' }); + const workflow = new AutomatedCallbackWorkflow(new TokenCache(), callback); + await workflow.execute({ command: vi.fn().mockResolvedValue({ ok: 1 }) }, credentials); + expect(callback).toHaveBeenCalledTimes(1); + + const command = vi + .fn() + .mockRejectedValueOnce(new MongoServerError({ code: 18, errmsg: 'dummy authentication failure' })) + .mockResolvedValue({ ok: 1 }); + await workflow.execute({ command }, credentials); + + expect(callback).toHaveBeenCalledTimes(2); + expect(command.mock.calls.map(([, request]) => BSON.deserialize(request.payload.value()))).toEqual([ + { jwt: 'dummy-cached-token' }, + { jwt: 'dummy-renewed-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); + await workflow.execute({ command: vi.fn().mockResolvedValue({ ok: 1 }) }, credentials); + expect(callback).toHaveBeenCalledTimes(1); + + const error = new MongoNetworkError('dummy network failure'); + const command = vi.fn().mockRejectedValueOnce(error).mockResolvedValue({ ok: 1 }); + + await expect(workflow.execute({ command }, credentials)).rejects.toBe(error); + expect(callback).toHaveBeenCalledTimes(1); + expect(command).toHaveBeenCalledTimes(1); + }); +}); From 1202e1c55567f3b560134ab85aea97d8882ed11c Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 19 Nov 2026 16:05:15 +0000 Subject: [PATCH 013/380] docs: record WI-1a driver contract results Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../features/connection-lifecycle/iterations/01-dev-plan.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index 527372952..192648b76 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 @@ -600,6 +600,12 @@ verdict exists, do not start the work it gates. The fingerprint table (formerly **Progress:** +- **Done (2026-11-19), commit `df0c22ade` (WI-1a, `gpt-6.2-sol`):** Added four MongoDB driver + contract tests for the pinned 7.2.0 workflow: callback rejection, cached-token speculation, + auth code 18 retry, and network error propagation without a retry. The accepted operator strategy + (decision 0010) is unchanged; the tests confirm the mocked driver behavior, not the live server's + response. All four focused tests and `npx tsc --noEmit -p .` passed. OP-1a is pending tracing. + --- ## WI-2: Shell and Playground token relays (PR 1) From 01c0d4846ff4189ab2081f6fe9f0ee493bbda717 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 19 Nov 2026 16:11:18 +0000 Subject: [PATCH 014/380] chore: trace interactive Entra socket authentication (WI-1b) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/documentdb/ClustersClient.test.ts | 71 ++++++++++++++++++- src/documentdb/ClustersClient.ts | 53 +++++++++++++- .../auth/MicrosoftEntraIDAuthHandler.test.ts | 27 +++++++ .../auth/MicrosoftEntraIDAuthHandler.ts | 15 +++- 4 files changed, 160 insertions(+), 6 deletions(-) diff --git a/src/documentdb/ClustersClient.test.ts b/src/documentdb/ClustersClient.test.ts index ff388565b..ab0661191 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -6,8 +6,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { UserCancelledError, type IActionContext, type ITelemetryContext } from '@microsoft/vscode-azext-utils'; +import { EventEmitter } from 'events'; import type * as Mongodb from 'mongodb'; -import { MongoClient, MongoServerError, type MongoClientOptions } from 'mongodb'; +import { MongoClient, MongoNetworkError, MongoServerError, type MongoClientOptions } from 'mongodb'; import { ext } from '../extensionVariables'; import { traceAuthFlow, type AuthTraceContext } from '../utils/authTrace'; import { AuthMethodId } from './auth/AuthMethod'; @@ -120,6 +121,8 @@ describe('regular connection startup diagnostics', () => { const clusterId = 'private-cluster'; const mockConnect = vi.fn(); const mockClose = vi.fn(); + const mockListDatabases = vi.fn<() => Promise>(); + let poolEvents: EventEmitter; beforeEach(() => { vi.clearAllMocks(); @@ -140,8 +143,14 @@ describe('regular connection startup diagnostics', () => { vi.advanceTimersByTime(30); }); mockClose.mockResolvedValue(undefined); + mockListDatabases.mockReset(); vi.mocked(MongoClient).mockImplementation(function () { - return { connect: mockConnect, close: mockClose } as unknown as MongoClient; + poolEvents = new EventEmitter(); + return Object.assign(poolEvents, { + connect: mockConnect, + close: mockClose, + db: () => ({ admin: () => ({ listDatabases: mockListDatabases }) }), + }) as unknown as MongoClient; }); for (const handler of [ MicrosoftEntraIDAuthHandler, @@ -164,6 +173,64 @@ describe('regular connection startup diagnostics', () => { vi.useRealTimers(); }); + it('records only allowed pool fields at Debug under the Entra startup ID, starting before connect', async () => { + const privateFields = { address: 'private-host:27017', error: new Error('private-error') }; + mockConnect.mockImplementationOnce(async (): Promise => { + poolEvents.emit('connectionCreated', { connectionId: 7, ...privateFields }); + poolEvents.emit('connectionReady', { connectionId: 7, ...privateFields }); + }); + const client = await ClustersClient.getClient(clusterId); + poolEvents.emit('connectionClosed', { connectionId: 7, reason: 'idle', ...privateFields }); + poolEvents.emit('connectionCheckOutFailed', { reason: 'connectionError', ...privateFields }); + poolEvents.emit('connectionClosed', { connectionId: '', reason: 'private-reason', ...privateFields }); + poolEvents.emit('connectionCheckOutFailed', { reason: 'private-reason', ...privateFields }); + + const prefix = `[ClustersClient] startup=${client.connectionCorrelationId}`; + expect(vi.mocked(ext.outputChannel.debug).mock.calls).toEqual([ + [`${prefix} connectionCreated connectionId=7`], + [`${prefix} connectionReady connectionId=7`], + [`${prefix} connectionClosed connectionId=7 reason=idle`], + [`${prefix} connectionCheckOutFailed reason=connectionError`], + [`${prefix} connectionClosed`], + [`${prefix} connectionCheckOutFailed`], + ]); + }); + + it('logs only bounded listDatabases error details for Entra and rethrows each original error', async () => { + const client = await ClustersClient.getClient(clusterId); + const serverError = new MongoServerError({ code: 18, errmsg: 'private-server-message' }); + const networkError = new MongoNetworkError('private-network-message'); + networkError.code = 'private-code'; + const otherError = new Error('private-other-message'); + otherError.name = 'private-name'; + mockListDatabases + .mockRejectedValueOnce(serverError) + .mockRejectedValueOnce(networkError) + .mockRejectedValueOnce(otherError); + + await expect(client.listDatabases()).rejects.toBe(serverError); + await expect(client.listDatabases()).rejects.toBe(networkError); + await expect(client.listDatabases()).rejects.toBe(otherError); + + const prefix = `[ClustersClient] startup=${client.connectionCorrelationId} listDatabases.failed`; + expect(vi.mocked(ext.outputChannel.debug).mock.calls).toEqual([ + [`${prefix} kind=MongoServerError code=18`], + [`${prefix} kind=MongoNetworkError`], + [`${prefix} kind=other`], + ]); + }); + + it('does not attach pool diagnostics or log listDatabases failures for native auth', async () => { + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.NativeAuth, 'mongodb://private-host:27017'); + const client = await ClustersClient.getClient(clusterId); + const error = new MongoServerError({ code: 18, errmsg: 'private-server-message' }); + mockListDatabases.mockRejectedValueOnce(error); + + expect(poolEvents.eventNames()).toEqual([]); + await expect(client.listDatabases()).rejects.toBe(error); + expect(ext.outputChannel.debug).not.toHaveBeenCalled(); + }); + function startupEvent(): RecordedTelemetry { const events = mockTelemetryEvents.filter((event) => event.eventName === 'connect.startup'); expect(events).toHaveLength(1); diff --git a/src/documentdb/ClustersClient.ts b/src/documentdb/ClustersClient.ts index e95dc632a..40c785b73 100644 --- a/src/documentdb/ClustersClient.ts +++ b/src/documentdb/ClustersClient.ts @@ -22,6 +22,9 @@ import { randomUUID } from 'crypto'; import { MongoBulkWriteError, MongoClient, + MongoError, + MongoNetworkError, + MongoServerError, ObjectId, type ClientSession, type Collection, @@ -196,6 +199,7 @@ export class ClustersClient { static _clients: Map = new Map(); private _mongoClient: MongoClient; + private _interactiveEntraStartupId?: string; private _llmEnhancedFeatureApis: llmEnhancedFeatureApis | null = null; private _queryInsightsApis: QueryInsightsApis | null = null; private _clusterMetadataPromise: Promise | null = null; @@ -420,6 +424,7 @@ export class ClustersClient { startup, prepared.connectionString, prepared.options, + authMethod === AuthMethodId.MicrosoftEntraID, credentials.emulatorConfiguration, abortSignal, connectionString, @@ -442,10 +447,35 @@ export class ClustersClient { }); } + private traceInteractiveEntraPool(startupId: string): void { + const log = (event: string, connectionId?: number | '', reason?: string): void => { + const idField = typeof connectionId === 'number' ? ` connectionId=${connectionId}` : ''; + const reasonField = reason === undefined ? '' : ` reason=${reason}`; + ext.outputChannel?.debug(`[ClustersClient] startup=${startupId} ${event}${idField}${reasonField}`); + }; + this._mongoClient.on('connectionCreated', ({ connectionId }) => log('connectionCreated', connectionId)); + this._mongoClient.on('connectionReady', ({ connectionId }) => log('connectionReady', connectionId)); + this._mongoClient.on('connectionClosed', ({ connectionId, reason }) => { + log( + 'connectionClosed', + connectionId, + ['idle', 'stale', 'poolClosed', 'error'].includes(reason) ? reason : undefined, + ); + }); + this._mongoClient.on('connectionCheckOutFailed', ({ reason }) => { + log( + 'connectionCheckOutFailed', + undefined, + ['poolClosed', 'timeout', 'connectionError'].includes(reason) ? reason : undefined, + ); + }); + } + private async connect( startup: ClientStartup, connectionString: string, options: MongoClientOptions, + interactiveEntra: boolean, emulatorConfiguration?: EmulatorConfiguration, abortSignal?: AbortSignal, originalConnectionString: string = connectionString, @@ -453,6 +483,10 @@ export class ClustersClient { // Create the client instance first so we hold a reference during connection. // This allows callers to abort via abortSignal by closing the underlying client. this._mongoClient = new MongoClient(connectionString, options); + if (interactiveEntra) { + this._interactiveEntraStartupId = startup.id; + this.traceInteractiveEntraPool(startup.id); + } if (abortSignal?.aborted) { ext.outputChannel.debug( @@ -790,7 +824,24 @@ export class ClustersClient { // filter below relies on the `empty` field, which `nameOnly` omits (along with // `sizeOnDisk`). Keeping the full listing ensures an empty `admin` database stays // hidden while a non-empty `admin` (user-managed roles/collections) remains visible. - const rawDatabases: ListDatabasesResult = await this._mongoClient.db().admin().listDatabases(); + let rawDatabases: ListDatabasesResult; + try { + rawDatabases = await this._mongoClient.db().admin().listDatabases(); + } catch (error) { + if (this._interactiveEntraStartupId) { + let kind = 'other'; + if (error instanceof MongoServerError) { + kind = 'MongoServerError'; + } else if (error instanceof MongoNetworkError) { + kind = 'MongoNetworkError'; + } + const code = error instanceof MongoError && typeof error.code === 'number' ? ` code=${error.code}` : ''; + ext.outputChannel?.debug( + `[ClustersClient] startup=${this._interactiveEntraStartupId} listDatabases.failed kind=${kind}${code}`, + ); + } + throw error; + } const databases: DatabaseItemModel[] = rawDatabases.databases.filter( // Filter out the 'admin' database if it's empty (databaseInfo) => !(databaseInfo.name && databaseInfo.name.toLowerCase() === 'admin' && databaseInfo.empty), diff --git a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts index d4b061e19..849aeacb7 100644 --- a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts +++ b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts @@ -193,6 +193,33 @@ describe('MicrosoftEntraIDAuthHandler', () => { }, ); + it('traces successive OIDC callback invocations under the startup ID without changing the captured result', async () => { + const handler = new MicrosoftEntraIDAuthHandler( + buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'), + ); + const { options } = await handler.configureAuth(undefined, { + startupCorrelationId: 'startup-id', + surface: 'extension', + }); + const callback = options.authMechanismProperties?.OIDC_CALLBACK; + if (!callback) { + throw new Error('Missing OIDC callback'); + } + const params = { version: 1, timeoutContext: new AbortController().signal } as const; + + await expect(callback(params)).resolves.toEqual({ accessToken: 'access-token', expiresInSeconds: 0 }); + await expect(callback(params)).resolves.toEqual({ accessToken: 'access-token', expiresInSeconds: 0 }); + expect(getSessionFromVSCode).toHaveBeenCalledTimes(1); + expect( + mockOutputChannel.info.mock.calls + .map(([message]) => String(message)) + .filter((message) => message.includes('interactiveEntra.oidcCallback')), + ).toEqual([ + '[Authentication] startup=startup-id surface=extension interactiveEntra.oidcCallback: {"invocation":1,"outcome":"returned"}', + '[Authentication] startup=startup-id surface=extension interactiveEntra.oidcCallback: {"invocation":2,"outcome":"returned"}', + ]); + }); + it('rechecks the eager captured-token callback and existing TLS hook after trust removal', async (): Promise => { let suffix: string | undefined = 'database.example.com'; vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ diff --git a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts index d253a24d1..ead18febb 100644 --- a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts +++ b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts @@ -151,14 +151,23 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { }), ); + let invocation = 0; const configuration = buildOidcClientConfiguration({ connectionString, policy, - oidcCallback: (_params: OIDCCallbackParams): Promise => - Promise.resolve({ + oidcCallback: (_params: OIDCCallbackParams): Promise => { + const result = Promise.resolve({ accessToken: session.accessToken, expiresInSeconds: 0, - }), + }); + traceAuthFlow( + 'interactiveEntra.oidcCallback', + { invocation: ++invocation, outcome: 'returned' }, + authCorrelationId, + traceContext, + ); + return result; + }, }); if (configuration.ignoredTlsBypass || this.clusterCredentials.emulatorConfiguration?.disableEmulatorSecurity) { ext.outputChannel.info( From 3aefec386d6162815461556b2df326102406eadf Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 19 Nov 2026 16:11:49 +0000 Subject: [PATCH 015/380] docs: record WI-1b tracing results and OP-1a gate Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../connection-lifecycle/iterations/01-dev-plan.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) 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 192648b76..8d39a4728 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 @@ -604,7 +604,13 @@ verdict exists, do not start the work it gates. The fingerprint table (formerly contract tests for the pinned 7.2.0 workflow: callback rejection, cached-token speculation, auth code 18 retry, and network error propagation without a retry. The accepted operator strategy (decision 0010) is unchanged; the tests confirm the mocked driver behavior, not the live server's - response. All four focused tests and `npx tsc --noEmit -p .` passed. OP-1a is pending tracing. + response. All four focused tests and `npx tsc --noEmit -p .` passed. +- **Done (2026-11-19), commit `01c0d4846` (WI-1b, `gpt-6.2-sol`):** Added local callback, socket, + and final-error traces without changing token handling. The implementation and review were advised + (`claude-opus-5.5`, high confidence): the driver does not emit the initial code 18 it handles, + so infer that path from the callback and final numeric code. Four trace tests added; Case 1 build + and 92 focused tests passed. **Waiting for OP-1a** before recording the CP-0 verdict or proceeding + with renewal. --- From fa3586bddd0d2bbcf5cfcc45882559cb695e3a30 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 19 Nov 2026 18:23:19 +0000 Subject: [PATCH 016/380] docs: record OP-1a evidence and CP-0 verdict Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../connection-lifecycle/iterations/01-dev-plan.md | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index 8d39a4728..f9ea07661 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 @@ -609,8 +609,16 @@ verdict exists, do not start the work it gates. The fingerprint table (formerly and final-error traces without changing token handling. The implementation and review were advised (`claude-opus-5.5`, high confidence): the driver does not emit the initial code 18 it handles, so infer that path from the callback and final numeric code. Four trace tests added; Case 1 build - and 92 focused tests passed. **Waiting for OP-1a** before recording the CP-0 verdict or proceeding - with renewal. + and 92 focused tests passed. +- **OP-1a / CP-0 (2026-11-19), advised (`claude-opus-5.5`, 80%):** After about two hours idle, + the cached client opened two fresh sockets. Both called back with the original captured token + and closed before they became ready. The final error was `MongoNetworkError`, with no numeric + code exposed. A contemporaneous diagnostics run authenticated with its own client and separate + non-interactive session lookup; it did not measure token freshness. The pinned driver's + cached-token path calls back after code 18, but the live trace does not show that code directly. + Proceed with the accepted silent renewal plan. Keep WI-5 unchanged for now; carry the possible + network-error shape to CP-2. OP-1b must verify a post-idle callback and successful operation + without prompting, including if the driver has to retry the read on a second socket. --- From d05b669096893a79c8691d7ea6e7bca1dfecb63e Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 19 Nov 2026 18:29:55 +0000 Subject: [PATCH 017/380] fix: silently renew Entra tokens for the original account (WI-1c) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/connectionDiagnostics/acceptance.test.ts | 5 +- .../checks/authenticate.test.ts | 16 +- src/documentdb/auth/AuthHandler.ts | 9 + .../auth/MicrosoftEntraIDAuthHandler.test.ts | 188 +++++++++++++++--- .../auth/MicrosoftEntraIDAuthHandler.ts | 122 +++++++++--- .../auth/authConnectionTarget.test.ts | 9 +- .../auth/entraErrors/entraCallbackErrors.ts | 30 +++ src/documentdb/auth/entraSession.test.ts | 34 ++++ src/documentdb/auth/entraSession.ts | 37 ++++ .../auth/sovereignAuth.integration.test.ts | 17 +- src/documentdb/auth/tokenExpiry.test.ts | 22 ++ src/documentdb/auth/tokenExpiry.ts | 24 +++ .../playground/playgroundWorker.test.ts | 2 +- src/documentdb/playground/playgroundWorker.ts | 18 +- 14 files changed, 455 insertions(+), 78 deletions(-) create mode 100644 src/documentdb/auth/entraErrors/entraCallbackErrors.ts create mode 100644 src/documentdb/auth/entraSession.test.ts create mode 100644 src/documentdb/auth/entraSession.ts create mode 100644 src/documentdb/auth/tokenExpiry.test.ts diff --git a/src/connectionDiagnostics/acceptance.test.ts b/src/connectionDiagnostics/acceptance.test.ts index 293896e5d..82b10be49 100644 --- a/src/connectionDiagnostics/acceptance.test.ts +++ b/src/connectionDiagnostics/acceptance.test.ts @@ -95,8 +95,9 @@ vi.mock('../extensionVariables', () => ({ outputChannel: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), trace: vi.fn(), debug: vi.fn() }, }, })); -vi.mock('@microsoft/vscode-azext-azureauth/out/src/getSessionFromVSCode', () => ({ - getSessionFromVSCode: (...args: unknown[]): unknown => bridge.getSessionFromVSCode(...args), +vi.mock('vscode', async (importOriginal) => ({ + ...(await importOriginal()), + authentication: { getSession: bridge.getSessionFromVSCode }, })); vi.mock('../documentdb/auth/managedIdentityTokenProvider', () => ({ getManagedIdentityAccessToken: (...args: unknown[]): unknown => bridge.getManagedIdentityAccessToken(...args), diff --git a/src/connectionDiagnostics/checks/authenticate.test.ts b/src/connectionDiagnostics/checks/authenticate.test.ts index 2bf54d48e..53047a24a 100644 --- a/src/connectionDiagnostics/checks/authenticate.test.ts +++ b/src/connectionDiagnostics/checks/authenticate.test.ts @@ -58,8 +58,9 @@ const mocks = vi.hoisted(() => ({ vi.mock('../../extensionVariables', () => ({ ext: { outputChannel: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), trace: vi.fn(), debug: vi.fn() } }, })); -vi.mock('@microsoft/vscode-azext-azureauth/out/src/getSessionFromVSCode', () => ({ - getSessionFromVSCode: (...args: unknown[]): unknown => mocks.getSessionFromVSCode(...args), +vi.mock('vscode', async (importOriginal) => ({ + ...(await importOriginal()), + authentication: { getSession: mocks.getSessionFromVSCode }, })); vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ ...(await importOriginal()), @@ -946,9 +947,11 @@ describe('createAuthenticateCheck', (): void => { hostCloud: 'AzureCloud', entraFailureKind: 'none', }); - expect(mocks.getSessionFromVSCode).toHaveBeenCalledWith([`${publicResource}/.default`], tenant, { - silent: true, - }); + expect(mocks.getSessionFromVSCode).toHaveBeenCalledWith( + 'microsoft', + [`${publicResource}/.default`, `VSCODE_TENANT:${tenant}`], + { silent: true }, + ); for (const call of mocks.getSessionFromVSCode.mock.calls) { expect(JSON.stringify(call[2])).not.toMatch(/createIfNone|forceNewSession/); } @@ -957,6 +960,7 @@ describe('createAuthenticateCheck', (): void => { it('keeps audience and tenant mismatches as warnings that never fail the check by themselves', async (): Promise => { mocks.getSessionFromVSCode.mockResolvedValue({ accessToken: entraToken({ aud: governmentResource, tid: '99999999-2222-3333-4444-555555555555' }), + account: { label: 'alice@contoso.example', id: 'account-id' }, }); const { result } = await runAuth( setupFor(AuthMethodId.MicrosoftEntraID, publicHost, { entraIdConfig: { tenantId: tenant } }), @@ -1188,7 +1192,7 @@ describe('createAuthenticateCheck', (): void => { timeouts: { authenticationTimeoutMs: 30 }, }); expect(codes(result)).toEqual(['check.timeout']); - session.resolve({ accessToken: entraToken() }); + session.resolve({ accessToken: entraToken(), account: { label: 'alice@contoso.example', id: 'account-id' } }); await flush(); expect(deps.createClient).not.toHaveBeenCalled(); }); diff --git a/src/documentdb/auth/AuthHandler.ts b/src/documentdb/auth/AuthHandler.ts index 7549d27df..1c8e7be5b 100644 --- a/src/documentdb/auth/AuthHandler.ts +++ b/src/documentdb/auth/AuthHandler.ts @@ -25,4 +25,13 @@ export interface AuthHandler { export interface AuthHandlerResponse { connectionString: string; options: MongoClientOptions; + verifiedIdentity?: VerifiedEntraIdentity; +} + +export interface VerifiedEntraIdentity { + readonly kind: 'entra'; + readonly providerId: string; + readonly accountId: string; + readonly accountLabel: string; + readonly tenantId?: string; } diff --git a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts index 849aeacb7..560e8a1fd 100644 --- a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts +++ b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts @@ -9,6 +9,9 @@ import * as vscode from 'vscode'; import type * as documentdbTokenResource from './documentdbTokenResource'; const getSessionFromVSCode = vi.fn(); +const getConfiguredAuthProviderId = vi.fn<() => string>(); +const account = { id: 'account-id', label: 'account-label' }; +const session = { accessToken: 'access-token', account }; const mockOutputChannel = { info: vi.fn(), error: vi.fn() }; vi.mock('../../extensionVariables', () => ({ ext: { @@ -18,8 +21,14 @@ vi.mock('../../extensionVariables', () => ({ }, })); -vi.mock('@microsoft/vscode-azext-azureauth/out/src/getSessionFromVSCode', () => ({ - getSessionFromVSCode: (...args: unknown[]) => getSessionFromVSCode(...args), +vi.mock('vscode', async (importOriginal) => ({ + ...(await importOriginal()), + authentication: { getSession: (...args: unknown[]): unknown => getSessionFromVSCode(...args) }, +})); + +vi.mock('@microsoft/vscode-azext-azureauth', async (importOriginal) => ({ + ...(await importOriginal()), + getConfiguredAuthProviderId: (): string => getConfiguredAuthProviderId(), })); vi.mock('./documentdbTokenResource', async (importOriginal) => ({ @@ -33,6 +42,11 @@ import { AuthInputUnavailableError, type AuthPhaseObserver } from './authCallerP import { buildAuthConnectionTarget } from './authConnectionTarget'; import { AuthMethodId } from './AuthMethod'; import { resolveInteractiveTokenResource, TokenResourceResolutionError } from './documentdbTokenResource'; +import { + EntraIdentityMismatchError, + EntraSignInRequiredError, + TokenCallbackError, +} from './entraErrors/entraCallbackErrors'; import { EntraErrorExplainer } from './entraErrors/EntraErrorExplainer'; import { getRecentEntraTokenFailure, @@ -57,7 +71,8 @@ describe('MicrosoftEntraIDAuthHandler', () => { vi.clearAllMocks(); resetEntraTokenFailuresForTests(); getSessionFromVSCode.mockReset(); - getSessionFromVSCode.mockResolvedValue({ accessToken: 'access-token' }); + getSessionFromVSCode.mockResolvedValue(session); + getConfiguredAuthProviderId.mockReset().mockReturnValue('microsoft'); vi.mocked(resolveInteractiveTokenResource).mockResolvedValue({ resource: 'https://ossrdbms-aad.database.windows.net', scope: 'https://ossrdbms-aad.database.windows.net/.default', @@ -103,7 +118,7 @@ describe('MicrosoftEntraIDAuthHandler', () => { getSessionFromVSCode.mockImplementationOnce(async () => { expect(resolveInteractiveTokenResource).toHaveBeenCalledExactlyOnceWith(connectionString); expect(mockOutputChannel.info.mock.calls[0][0]).toContain('entraDestination.evaluated'); - return { accessToken: 'access-token' }; + return session; }); const result = await new MicrosoftEntraIDAuthHandler(buildCredentials(connectionString)).configureAuth(); expect(getSessionFromVSCode).toHaveBeenCalledTimes(1); @@ -132,8 +147,8 @@ describe('MicrosoftEntraIDAuthHandler', () => { expect(result.connectionString).toContain('retryWrites=true'); expect(result.options.authMechanismProperties).toHaveProperty('OIDC_CALLBACK'); expect(getSessionFromVSCode).toHaveBeenCalledWith( - ['https://ossrdbms-aad.database.windows.net/.default'], - 'tenant', + 'microsoft', + ['https://ossrdbms-aad.database.windows.net/.default', 'VSCODE_TENANT:tenant'], { createIfNone: true }, ); const output = JSON.stringify(mockOutputChannel.info.mock.calls); @@ -193,11 +208,16 @@ describe('MicrosoftEntraIDAuthHandler', () => { }, ); - it('traces successive OIDC callback invocations under the startup ID without changing the captured result', async () => { + it('silently accepts the same still-valid token twice with the pinned identity and bounded diagnostics', async () => { + const now = Math.floor(Date.now() / 1000); + const accessToken = `header.${Buffer.from(JSON.stringify({ iat: now - 60, exp: now + 600 })).toString('base64url')}.signature`; + getSessionFromVSCode.mockResolvedValue({ accessToken, account }); + const onTokenLookup = vi.fn(); const handler = new MicrosoftEntraIDAuthHandler( buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'), + { interactive: true, onTokenLookup }, ); - const { options } = await handler.configureAuth(undefined, { + const { options, verifiedIdentity } = await handler.configureAuth(undefined, { startupCorrelationId: 'startup-id', surface: 'extension', }); @@ -207,9 +227,30 @@ describe('MicrosoftEntraIDAuthHandler', () => { } const params = { version: 1, timeoutContext: new AbortController().signal } as const; - await expect(callback(params)).resolves.toEqual({ accessToken: 'access-token', expiresInSeconds: 0 }); - await expect(callback(params)).resolves.toEqual({ accessToken: 'access-token', expiresInSeconds: 0 }); - expect(getSessionFromVSCode).toHaveBeenCalledTimes(1); + expect(verifiedIdentity).toEqual({ + kind: 'entra', + providerId: 'microsoft', + accountId: account.id, + accountLabel: account.label, + tenantId: 'tenant', + }); + const clock = vi.spyOn(Date, 'now').mockReturnValue(now * 1000); + try { + await expect(callback(params)).resolves.toEqual({ accessToken, expiresInSeconds: 600 }); + await expect(callback(params)).resolves.toEqual({ accessToken, expiresInSeconds: 600 }); + } finally { + clock.mockRestore(); + } + const scopes = ['https://ossrdbms-aad.database.windows.net/.default', 'VSCODE_TENANT:tenant']; + expect(getSessionFromVSCode.mock.calls).toEqual([ + ['microsoft', scopes, { createIfNone: true }], + ['microsoft', scopes, { silent: true, account }], + ['microsoft', scopes, { silent: true, account }], + ]); + expect(onTokenLookup.mock.calls).toEqual([ + [{ outcome: 'returned', lifetimeSeconds: 660 }], + [{ outcome: 'returned', lifetimeSeconds: 660 }], + ]); expect( mockOutputChannel.info.mock.calls .map(([message]) => String(message)) @@ -220,16 +261,17 @@ describe('MicrosoftEntraIDAuthHandler', () => { ]); }); - it('rechecks the eager captured-token callback and existing TLS hook after trust removal', async (): Promise => { + it('rechecks destination trust before the silent callback and applies the existing TLS hook', async (): Promise => { let suffix: string | undefined = 'database.example.com'; vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ + get: vi.fn(), inspect: vi.fn(() => ({ globalValue: { hostnameSuffix: suffix } })), } as unknown as vscode.WorkspaceConfiguration); const { options } = await new MicrosoftEntraIDAuthHandler( buildCredentials('mongodb://cluster.database.example.com/'), ).configureAuth(); const callback = options.authMechanismProperties!.OIDC_CALLBACK!; - await expect(callback({ version: 1, timeoutContext: new AbortController().signal })).resolves.toMatchObject({ + await expect(callback({ version: 1, timeoutContext: new AbortController().signal })).resolves.toEqual({ accessToken: 'access-token', }); suffix = undefined; @@ -239,7 +281,101 @@ describe('MicrosoftEntraIDAuthHandler', () => { expect(options.checkServerIdentity?.('cluster.database.example.com', {} as PeerCertificate)).toBeInstanceOf( EntraDestinationRejectedError, ); - expect(getSessionFromVSCode).toHaveBeenCalledTimes(1); + expect(getSessionFromVSCode).toHaveBeenCalledTimes(2); + }); + + it('rechecks destination trust after a silent lookup, before returning its token', async () => { + let suffix: string | undefined = 'database.example.com'; + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ + get: vi.fn(), + inspect: vi.fn(() => ({ globalValue: { hostnameSuffix: suffix } })), + } as unknown as vscode.WorkspaceConfiguration); + const { options } = await new MicrosoftEntraIDAuthHandler( + buildCredentials('mongodb://cluster.database.example.com/'), + ).configureAuth(); + getSessionFromVSCode.mockImplementationOnce(async () => { + suffix = undefined; + return session; + }); + await expect( + options.authMechanismProperties!.OIDC_CALLBACK!({ version: 1, timeoutContext: new AbortController().signal }), + ).rejects.toBeInstanceOf(EntraDestinationRejectedError); + expect(getSessionFromVSCode).toHaveBeenCalledTimes(2); + }); + + it('does not reject or repeat a lookup based on the token expiration claim', async () => { + const { options } = await new MicrosoftEntraIDAuthHandler( + buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'), + ).configureAuth(); + const accessToken = `header.${Buffer.from('{"exp":1}').toString('base64url')}.signature`; + getSessionFromVSCode.mockResolvedValueOnce({ accessToken, account }); + await expect( + options.authMechanismProperties!.OIDC_CALLBACK!({ version: 1, timeoutContext: new AbortController().signal }), + ).resolves.toEqual({ accessToken, expiresInSeconds: 0 }); + expect(getSessionFromVSCode).toHaveBeenCalledTimes(2); + }); + + it.each([ + ['noSession', 'noSession', EntraSignInRequiredError], + ['providerChanged', 'noSession', EntraSignInRequiredError], + ['identityMismatch', 'identityMismatch', EntraIdentityMismatchError], + ] as const)('rejects %s without prompting or recording a token failure', async (failure, outcome, errorType) => { + const onTokenLookup = vi.fn(); + const { options } = await new MicrosoftEntraIDAuthHandler( + buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'), + { interactive: true, onTokenLookup }, + ).configureAuth(); + if (failure === 'providerChanged') { + getConfiguredAuthProviderId.mockReturnValue('microsoft-sovereign-cloud'); + } else { + getSessionFromVSCode.mockResolvedValueOnce( + failure === 'noSession' ? undefined : { ...session, account: { ...account, id: 'different-account' } }, + ); + } + const result = options.authMechanismProperties!.OIDC_CALLBACK!({ + version: 1, + timeoutContext: new AbortController().signal, + }); + await expect(result).rejects.toBeInstanceOf(errorType); + if (failure !== 'identityMismatch') { + await expect(result).rejects.toMatchObject({ reason: failure }); + } + if (failure === 'providerChanged') { + expect(getSessionFromVSCode).toHaveBeenCalledTimes(1); + } else { + expect(getSessionFromVSCode).toHaveBeenCalledTimes(2); + expect(getSessionFromVSCode.mock.calls[1]?.[2]).toEqual({ silent: true, account }); + } + expect(onTokenLookup.mock.calls).toEqual([[{ outcome }]]); + expect(getRecentEntraTokenFailure('cluster-1')).toBeUndefined(); + }); + + it('wraps and records only an unexpected callback failure, without logging its cause', async () => { + const onTokenLookup = vi.fn(); + const { options } = await new MicrosoftEntraIDAuthHandler( + buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'), + { interactive: true, onTokenLookup }, + ).configureAuth(); + const cause = new Error('AADSTS65002: private-cause'); + getSessionFromVSCode.mockRejectedValueOnce(cause); + + const result = options.authMechanismProperties!.OIDC_CALLBACK!({ + version: 1, + timeoutContext: new AbortController().signal, + }); + await expect(result).rejects.toBeInstanceOf(TokenCallbackError); + await expect(result).rejects.toMatchObject({ authMethod: AuthMethodId.MicrosoftEntraID, cause }); + expect(getRecentEntraTokenFailure('cluster-1')).toMatchObject({ + authMethod: 'interactive', + ruleId: 'firstPartyPreauthorization', + }); + expect(onTokenLookup.mock.calls).toEqual([[{ outcome: 'failed' }]]); + expect(JSON.stringify([mockOutputChannel.info.mock.calls, mockOutputChannel.error.mock.calls])).not.toContain( + 'private-cause', + ); + expect(mockOutputChannel.info).toHaveBeenLastCalledWith( + expect.stringContaining('interactiveEntra.oidcCallback: {"invocation":1,"outcome":"threw"}'), + ); }); it('captures the original destination and tenant before resolving the audience', async (): Promise => { @@ -258,9 +394,11 @@ describe('MicrosoftEntraIDAuthHandler', () => { }); const { connectionString } = await new MicrosoftEntraIDAuthHandler(credentials).configureAuth(); expect(connectionString).toBe(original); - expect(getSessionFromVSCode).toHaveBeenCalledWith(['https://database.example/.default'], 'tenant', { - createIfNone: true, - }); + expect(getSessionFromVSCode).toHaveBeenCalledWith( + 'microsoft', + ['https://database.example/.default', 'VSCODE_TENANT:tenant'], + { createIfNone: true }, + ); }); it('requests the resolved US Government scope and records its category on the existing trace', async () => { @@ -275,7 +413,9 @@ describe('MicrosoftEntraIDAuthHandler', () => { const connectionString = 'mongodb://cluster.mongocluster.cosmos.azure.us/'; await new MicrosoftEntraIDAuthHandler(buildCredentials(connectionString)).configureAuth(); expect(resolveInteractiveTokenResource).toHaveBeenCalledWith(connectionString); - expect(getSessionFromVSCode).toHaveBeenCalledWith([scope], 'tenant', { createIfNone: true }); + expect(getSessionFromVSCode).toHaveBeenCalledWith('microsoft', [scope, 'VSCODE_TENANT:tenant'], { + createIfNone: true, + }); const output = mockOutputChannel.info.mock.calls.map((call) => String(call[0])).join('\n'); expect(output).toContain('"cloudCategory":"usgov"'); expect(output).toContain('"tokenResourceReason":"setting"'); @@ -432,7 +572,7 @@ describe('MicrosoftEntraIDAuthHandler', () => { getSessionFromVSCode.mockImplementationOnce(async () => { expect(getRecentEntraTokenFailure('cluster-1')).toBe(failure); - return { accessToken: 'access-token' }; + return session; }); const successfulProperties: Record = {}; await handler.configureAuth(undefined, { @@ -515,7 +655,7 @@ describe('MicrosoftEntraIDAuthHandler', () => { const timings = new ConnectionStartupTimings(() => now); getSessionFromVSCode.mockImplementationOnce(async () => { now = 25; - return { accessToken: 'access-token' }; + return session; }); const handler = new MicrosoftEntraIDAuthHandler( buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'), @@ -599,8 +739,8 @@ describe('MicrosoftEntraIDAuthHandler', () => { ); await handler.configureAuth(); expect(getSessionFromVSCode).toHaveBeenCalledWith( - ['https://ossrdbms-aad.database.windows.net/.default'], - 'tenant', + 'microsoft', + ['https://ossrdbms-aad.database.windows.net/.default', 'VSCODE_TENANT:tenant'], { createIfNone: true }, ); const output = mockOutputChannel.info.mock.calls.map((call) => String(call[0])).join('\n'); @@ -618,8 +758,8 @@ describe('MicrosoftEntraIDAuthHandler', () => { const { options } = await handler.configureAuth(); expect(getSessionFromVSCode).toHaveBeenCalledTimes(1); expect(getSessionFromVSCode).toHaveBeenCalledWith( - ['https://ossrdbms-aad.database.windows.net/.default'], - 'tenant', + 'microsoft', + ['https://ossrdbms-aad.database.windows.net/.default', 'VSCODE_TENANT:tenant'], { silent: true }, ); const sessionOptions: unknown = getSessionFromVSCode.mock.calls[0]?.[2]; diff --git a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts index ead18febb..7de478002 100644 --- a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts +++ b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts @@ -3,8 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -// eslint-disable-next-line import/no-internal-modules -import { getSessionFromVSCode } from '@microsoft/vscode-azext-azureauth/out/src/getSessionFromVSCode'; +import { getConfiguredAuthProviderId } from '@microsoft/vscode-azext-azureauth'; import * as l10n from '@vscode/l10n'; import { randomUUID } from 'crypto'; import { type OIDCCallbackParams, type OIDCResponse } from 'mongodb'; @@ -19,13 +18,29 @@ import { type AuthCallerPolicy, type AuthPhaseObserver, } from './authCallerPolicy'; -import { type AuthHandler, type AuthHandlerResponse } from './AuthHandler'; +import { type AuthHandler, type AuthHandlerResponse, type VerifiedEntraIdentity } from './AuthHandler'; import { resolveInteractiveTokenResource, TokenResourceResolutionError } from './documentdbTokenResource'; import { evaluateEntraDestinationFromSettings, getEntraCustomHostnameSuffix } from './entraDestinationSettings'; import { classifyEntraError } from './entraErrors/classifyEntraError'; +import { + EntraIdentityMismatchError, + EntraSignInRequiredError, + TokenCallbackError, +} from './entraErrors/entraCallbackErrors'; import { clearEntraTokenFailure, recordEntraTokenFailure } from './entraErrors/entraTokenFailures'; +import { getEntraSession } from './entraSession'; import { EntraDestinationRejectedError } from './oidcAllowedHosts'; import { buildOidcClientConfiguration, createOidcDestinationPolicy } from './oidcClientOptions'; +import { readJwtTimes } from './tokenExpiry'; + +interface EntraTokenLookupObservation { + readonly outcome: 'returned' | 'noSession' | 'identityMismatch' | 'failed'; + readonly lifetimeSeconds?: number; +} + +interface EntraCallerPolicy extends AuthCallerPolicy { + readonly onTokenLookup?: (observation: EntraTokenLookupObservation) => void; +} /** * Handler for Microsoft Entra ID authentication via OIDC. @@ -36,7 +51,7 @@ import { buildOidcClientConfiguration, createOidcDestinationPolicy } from './oid export class MicrosoftEntraIDAuthHandler implements AuthHandler { constructor( private readonly clusterCredentials: CachedClusterCredentials, - public readonly policy: AuthCallerPolicy = { interactive: true }, + public readonly policy: EntraCallerPolicy = { interactive: true }, ) {} private notify(notify: (observer: AuthPhaseObserver) => void): void { @@ -87,18 +102,23 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { // caller looks up an existing session silently and never forces a new one. const interactive = this.policy.interactive; let session: vscode.AuthenticationSession | undefined; + let providerId: string; + const resource = resolved.scope; this.notify((observer) => observer.onTokenStarted?.()); try { - session = await traceAuthOperation( + ({ session, providerId } = await traceAuthOperation( 'interactiveEntra.getSession', () => - withTokenAcquisitionTiming(timings, () => - getSessionFromVSCode( - [resolved.scope], + withTokenAcquisitionTiming(timings, async () => { + const providerId = getConfiguredAuthProviderId(); + const session = await getEntraSession({ + providerId, + resource, tenantId, - interactive ? { createIfNone: true } : { silent: true }, - ), - ), + mode: interactive ? 'interactive' : 'silent', + }); + return { session, providerId }; + }), { tenantSpecified: !!tenantId, ...(interactive ? { createIfNone: true } : { silent: true }), @@ -107,7 +127,7 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { }, authCorrelationId, traceContext, - ); + )); if (!session) { traceAuthFlow( @@ -128,10 +148,11 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { if (traceContext?.startupProperties) { traceContext.startupProperties.entraFailureKind = 'tokenAcquisitionFailed'; } + const message = error instanceof Error ? error.message : typeof error === 'string' ? error : ''; recordEntraTokenFailure(clusterId, { cloudCategory: resolved.cloudCategory, authMethod: 'interactive', - ruleId: classifyEntraError(error instanceof Error ? error.message : String(error))?.ruleId, + ruleId: classifyEntraError(message)?.ruleId, }); } this.notify((observer) => observer.onTokenFailed?.(error)); @@ -140,6 +161,15 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { policy.assertAllowed(); clearEntraTokenFailure(clusterId); + const { id: accountId, label: accountLabel } = session.account; + const verifiedIdentity: VerifiedEntraIdentity = { + kind: 'entra', + providerId, + accountId, + accountLabel, + tenantId, + }; + const account: vscode.AuthenticationSessionAccountInformation = { id: accountId, label: accountLabel }; const acquiredSession = session; this.notify((observer) => observer.onTokenAcquired?.({ @@ -155,18 +185,59 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { const configuration = buildOidcClientConfiguration({ connectionString, policy, - oidcCallback: (_params: OIDCCallbackParams): Promise => { - const result = Promise.resolve({ - accessToken: session.accessToken, - expiresInSeconds: 0, - }); - traceAuthFlow( - 'interactiveEntra.oidcCallback', - { invocation: ++invocation, outcome: 'returned' }, - authCorrelationId, - traceContext, - ); - return result; + oidcCallback: async (_params: OIDCCallbackParams): Promise => { + const currentInvocation = ++invocation; + let observation: EntraTokenLookupObservation = { outcome: 'failed' }; + try { + if (getConfiguredAuthProviderId() !== providerId) { + observation = { outcome: 'noSession' }; + throw new EntraSignInRequiredError('providerChanged'); + } + const renewed = await getEntraSession({ providerId, resource, tenantId, account, mode: 'silent' }); + if (!renewed) { + observation = { outcome: 'noSession' }; + throw new EntraSignInRequiredError('noSession'); + } + if (renewed.account.id !== accountId) { + observation = { outcome: 'identityMismatch' }; + throw new EntraIdentityMismatchError(); + } + const { accessToken } = renewed; + const { iatSec, expSec } = readJwtTimes(accessToken); + const lifetimeSeconds = iatSec !== undefined && expSec !== undefined ? expSec - iatSec : undefined; + observation = { + outcome: 'returned', + ...(lifetimeSeconds !== undefined && Number.isFinite(lifetimeSeconds) ? { lifetimeSeconds } : {}), + }; + return expSec === undefined + ? { accessToken } + : { accessToken, expiresInSeconds: Math.max(0, Math.floor(expSec - Date.now() / 1000)) }; + } catch (error) { + if (observation.outcome === 'noSession' || observation.outcome === 'identityMismatch') { + throw error; + } + recordEntraTokenFailure(clusterId, { + cloudCategory: resolved.cloudCategory, + authMethod: 'interactive', + ruleId: classifyEntraError(error instanceof Error ? error.message : String(error))?.ruleId, + }); + throw new TokenCallbackError(error); + } finally { + traceAuthFlow( + 'interactiveEntra.oidcCallback', + { + invocation: currentInvocation, + outcome: observation.outcome === 'returned' ? 'returned' : 'threw', + }, + authCorrelationId, + traceContext, + ); + try { + this.policy.onTokenLookup?.(observation); + } catch { + // Observers never change the auth flow. + } + } }, }); if (configuration.ignoredTlsBypass || this.clusterCredentials.emulatorConfiguration?.disableEmulatorSecurity) { @@ -184,6 +255,7 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { return { connectionString: configuration.connectionString, options: configuration.options, + verifiedIdentity, }; } } diff --git a/src/documentdb/auth/authConnectionTarget.test.ts b/src/documentdb/auth/authConnectionTarget.test.ts index 3ef6eadae..74ee620ac 100644 --- a/src/documentdb/auth/authConnectionTarget.test.ts +++ b/src/documentdb/auth/authConnectionTarget.test.ts @@ -7,11 +7,12 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import * as vscode from 'vscode'; import type * as documentdbTokenResource from './documentdbTokenResource'; -const getSessionFromVSCode = vi.hoisted(() => vi.fn()); +const getSession = vi.hoisted(() => vi.fn()); const getManagedIdentityAccessToken = vi.hoisted(() => vi.fn()); -vi.mock('@microsoft/vscode-azext-azureauth/out/src/getSessionFromVSCode', () => ({ - getSessionFromVSCode, +vi.mock('vscode', async (importOriginal) => ({ + ...(await importOriginal()), + authentication: { getSession }, })); vi.mock('./managedIdentityTokenProvider', () => ({ getManagedIdentityAccessToken })); @@ -242,7 +243,7 @@ describe('buildAuthConnectionTarget', () => { ); } - expect(getSessionFromVSCode).not.toHaveBeenCalled(); + expect(getSession).not.toHaveBeenCalled(); expect(getManagedIdentityAccessToken).not.toHaveBeenCalled(); expect(resolveInteractiveTokenResource).not.toHaveBeenCalled(); expect(resolveManagedIdentityTokenResource).not.toHaveBeenCalled(); diff --git a/src/documentdb/auth/entraErrors/entraCallbackErrors.ts b/src/documentdb/auth/entraErrors/entraCallbackErrors.ts new file mode 100644 index 000000000..ab2167fbe --- /dev/null +++ b/src/documentdb/auth/entraErrors/entraCallbackErrors.ts @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as l10n from '@vscode/l10n'; +import { AuthMethodId } from '../AuthMethod'; + +export class EntraSignInRequiredError extends Error { + constructor(public readonly reason: 'noSession' | 'providerChanged') { + super(l10n.t('Sign in again to continue using Microsoft Entra ID.')); + this.name = 'EntraSignInRequiredError'; + } +} + +export class EntraIdentityMismatchError extends Error { + constructor() { + super(l10n.t('Visual Studio Code returned a different Microsoft account for this connection.')); + this.name = 'EntraIdentityMismatchError'; + } +} + +export class TokenCallbackError extends Error { + public readonly authMethod = AuthMethodId.MicrosoftEntraID; + + constructor(cause: unknown) { + super(l10n.t('Failed to obtain a Microsoft Entra ID token.'), { cause }); + this.name = 'TokenCallbackError'; + } +} diff --git a/src/documentdb/auth/entraSession.test.ts b/src/documentdb/auth/entraSession.test.ts new file mode 100644 index 000000000..8456a447d --- /dev/null +++ b/src/documentdb/auth/entraSession.test.ts @@ -0,0 +1,34 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { expect, it, vi } from 'vitest'; +import { getEntraSession } from './entraSession'; + +const { getSession } = vi.hoisted(() => ({ getSession: vi.fn() })); +vi.mock('vscode', () => ({ authentication: { getSession } })); + +it.each([ + ['interactive', { createIfNone: true }], + ['silent', { silent: true }], + ['forceNew', { forceNewSession: true }], +] as const)('uses the explicit provider, scopes and account in %s mode', async (mode, expectedOptions) => { + const account = { id: 'account-id', label: 'account-label' }; + const session = { id: 'session-id', accessToken: 'dummy', account, scopes: [] }; + getSession.mockResolvedValueOnce(session); + await expect( + getEntraSession({ + providerId: 'pinned-provider', + resource: mode === 'forceNew' ? 'https://resource.example/.default' : 'https://resource.example', + tenantId: 'tenant-id', + mode, + account, + }), + ).resolves.toBe(session); + expect(getSession).toHaveBeenLastCalledWith( + 'pinned-provider', + ['https://resource.example/.default', 'VSCODE_TENANT:tenant-id'], + { ...expectedOptions, account }, + ); +}); diff --git a/src/documentdb/auth/entraSession.ts b/src/documentdb/auth/entraSession.ts new file mode 100644 index 000000000..d9a75c423 --- /dev/null +++ b/src/documentdb/auth/entraSession.ts @@ -0,0 +1,37 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as vscode from 'vscode'; +import { toEntraScope } from './entraScopes'; + +interface EntraSessionRequest { + providerId: string; + resource: string; + tenantId?: string; + account?: vscode.AuthenticationSessionAccountInformation; + mode: 'interactive' | 'silent' | 'forceNew'; +} + +export async function getEntraSession({ + providerId, + resource, + tenantId, + account, + mode, +}: EntraSessionRequest): Promise { + const scopes = [resource.endsWith('.default') ? resource : toEntraScope(resource)]; + if (tenantId) { + scopes.push(`VSCODE_TENANT:${tenantId}`); + } + const options = account ? { account } : {}; + switch (mode) { + case 'interactive': + return await vscode.authentication.getSession(providerId, scopes, { ...options, createIfNone: true }); + case 'silent': + return await vscode.authentication.getSession(providerId, scopes, { ...options, silent: true }); + case 'forceNew': + return await vscode.authentication.getSession(providerId, scopes, { ...options, forceNewSession: true }); + } +} diff --git a/src/documentdb/auth/sovereignAuth.integration.test.ts b/src/documentdb/auth/sovereignAuth.integration.test.ts index c0c9dab08..c9f907666 100644 --- a/src/documentdb/auth/sovereignAuth.integration.test.ts +++ b/src/documentdb/auth/sovereignAuth.integration.test.ts @@ -21,6 +21,7 @@ interface TokenWorker { const workers = vi.hoisted((): TokenWorker[] => []); const getSession = vi.hoisted(() => vi.fn()); +const getHandlerSession = vi.hoisted(() => vi.fn()); const getManagedToken = vi.hoisted(() => vi.fn()); const postedMessages = vi.hoisted((): MainToWorkerMessage[] => []); const events = vi.hoisted((): { eventName: string; telemetry: ITelemetryContext }[] => []); @@ -36,6 +37,11 @@ vi.mock('@microsoft/vscode-azext-azureauth/out/src/getSessionFromVSCode', () => getSessionFromVSCode: getSession, })); +vi.mock('vscode', async (importOriginal) => ({ + ...(await importOriginal()), + authentication: { getSession: getHandlerSession }, +})); + vi.mock('./managedIdentityTokenProvider', () => ({ getManagedIdentityAccessToken: getManagedToken })); vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ @@ -176,6 +182,10 @@ describe('sovereign authentication with real audience resolvers', () => { selectedCloud = 'USGovernment'; resetEntraTokenFailuresForTests(); getSession.mockResolvedValue({ accessToken: 'private-token', account: { label: 'private-account' } }); + getHandlerSession.mockResolvedValue({ + accessToken: 'private-token', + account: { id: 'account-id', label: 'private-account' }, + }); getManagedToken.mockResolvedValue({ accessToken: 'private-token', expiresOnTimestamp: Date.now() + 3_600_000 }); const configuration = { get: vi.fn(), inspect: vi.fn(), has: vi.fn(), update: vi.fn() }; configuration.get.mockImplementation((key: string, defaultValue?: unknown): unknown => { @@ -201,7 +211,11 @@ describe('sovereign authentication with real audience resolvers', () => { const { options } = await new MicrosoftEntraIDAuthHandler( credentials(AuthMethodId.MicrosoftEntraID, cloud.suffix), ).configureAuth(undefined, { startupCorrelationId: 'startup-id', surface: 'extension', startupProperties }); - expect(getSession).toHaveBeenCalledExactlyOnceWith([cloud.scope], 'private-tenant', { createIfNone: true }); + expect(getHandlerSession).toHaveBeenCalledExactlyOnceWith( + cloud.setting === 'AzureCloud' ? 'microsoft' : 'microsoft-sovereign-cloud', + [cloud.scope, 'VSCODE_TENANT:private-tenant'], + { createIfNone: true }, + ); expect(options.authMechanismProperties?.ALLOWED_HOSTS).toEqual([`*.mongocluster.cosmos.azure.${cloud.suffix}`]); expect(startupProperties).toEqual({ entraDestinationClass: 'documentdbService', @@ -239,6 +253,7 @@ describe('sovereign authentication with real audience resolvers', () => { expect.any(String), undefined, ); + expect(getHandlerSession).not.toHaveBeenCalled(); expect(getSession).not.toHaveBeenCalled(); }, ); diff --git a/src/documentdb/auth/tokenExpiry.test.ts b/src/documentdb/auth/tokenExpiry.test.ts new file mode 100644 index 000000000..0642cc458 --- /dev/null +++ b/src/documentdb/auth/tokenExpiry.test.ts @@ -0,0 +1,22 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { expect, it } from 'vitest'; +import { readJwtTimes } from './tokenExpiry'; + +it.each([ + ['{"iat":100,"exp":200,"sub":"unused"}', { iatSec: 100, expSec: 200 }], + ['{"exp":200}', { expSec: 200 }], + ['{"iat":100,"exp":"200"}', { iatSec: 100 }], + ['{"iat":1e309,"exp":null}', {}], + ['not json', {}], +])('reads only finite numeric JWT times from %s', (payload, expected) => { + const token = `header.${Buffer.from(payload).toString('base64url')}.signature`; + expect(readJwtTimes(token)).toEqual(expected); +}); + +it('does not infer expiry from an opaque token', () => { + expect(readJwtTimes('opaque-token')).toEqual({}); +}); diff --git a/src/documentdb/auth/tokenExpiry.ts b/src/documentdb/auth/tokenExpiry.ts index 8a0747a17..0d6f4dd7f 100644 --- a/src/documentdb/auth/tokenExpiry.ts +++ b/src/documentdb/auth/tokenExpiry.ts @@ -3,6 +3,30 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +/** Reads timing metadata only; this does not validate the token. */ +export function readJwtTimes(token: string): { iatSec?: number; expSec?: number } { + const parts = token.split('.'); + if (parts.length !== 3 || !parts[1]) { + return {}; + } + try { + const claims: unknown = JSON.parse(Buffer.from(parts[1], 'base64url').toString()); + if (typeof claims !== 'object' || claims === null) { + return {}; + } + return { + ...('iat' in claims && typeof claims.iat === 'number' && Number.isFinite(claims.iat) + ? { iatSec: claims.iat } + : {}), + ...('exp' in claims && typeof claims.exp === 'number' && Number.isFinite(claims.exp) + ? { expSec: claims.exp } + : {}), + }; + } catch { + return {}; + } +} + /** * Seconds until an absolute expiry timestamp (milliseconds since the epoch), floored at zero. * diff --git a/src/documentdb/playground/playgroundWorker.test.ts b/src/documentdb/playground/playgroundWorker.test.ts index b4f2d48a9..e927cb2b5 100644 --- a/src/documentdb/playground/playgroundWorker.test.ts +++ b/src/documentdb/playground/playgroundWorker.test.ts @@ -133,7 +133,7 @@ describe('playground worker OIDC configuration at the driver boundary', () => { .find((message) => message.type === 'tokenRequest'); expect(request).toBeDefined(); receive({ type: 'tokenResponse', requestId: request!.requestId, accessToken: 'dummy-token' }); - await expect(token).resolves.toMatchObject({ accessToken: 'dummy-token' }); + await expect(token).resolves.toMatchObject({ accessToken: 'dummy-token', expiresInSeconds: 3500 }); }, ); diff --git a/src/documentdb/playground/playgroundWorker.ts b/src/documentdb/playground/playgroundWorker.ts index a43dcd507..1bd7d3d27 100644 --- a/src/documentdb/playground/playgroundWorker.ts +++ b/src/documentdb/playground/playgroundWorker.ts @@ -30,7 +30,7 @@ import { createOidcDestinationPolicy, type OidcDestinationPolicy, } from '../auth/oidcClientOptions'; -import { expiresInSecondsFromTimestamp } from '../auth/tokenExpiry'; +import { expiresInSecondsFromTimestamp, readJwtTimes } from '../auth/tokenExpiry'; import { type MainToWorkerMessage, type WorkerStartupStage, type WorkerToMainMessage } from './workerTypes'; if (!parentPort) { @@ -212,20 +212,8 @@ async function handleInit(msg: Extract): // Parse the JWT exp claim for a meaningful cache duration. // This avoids re-acquiring the token on every database operation // in persistent shell sessions. - let expiresInSeconds = 3500; // Conservative default (~1 hour) - try { - const payload = accessToken.split('.')[1]; - if (payload) { - const decoded = JSON.parse(Buffer.from(payload, 'base64url').toString()) as { - exp?: number; - }; - if (typeof decoded.exp === 'number') { - expiresInSeconds = expiresInSecondsFromTimestamp(decoded.exp * 1000); - } - } - } catch { - // JWT parsing failed — use conservative default - } + const { expSec } = readJwtTimes(accessToken); + const expiresInSeconds = expSec === undefined ? 3500 : expiresInSecondsFromTimestamp(expSec * 1000); return { accessToken, expiresInSeconds }; }, From fa38709a9898fa6148534cb2c41a7915e8e07e96 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 19 Nov 2026 18:30:05 +0000 Subject: [PATCH 018/380] docs: record WI-1c and the OP-1b handoff Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../features/connection-lifecycle/iterations/01-dev-plan.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index f9ea07661..07108920e 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 @@ -619,6 +619,12 @@ verdict exists, do not start the work it gates. The fingerprint table (formerly Proceed with the accepted silent renewal plan. Keep WI-5 unchanged for now; carry the possible network-error shape to CP-2. OP-1b must verify a post-idle callback and successful operation without prompting, including if the driver has to retry the read on a second socket. +- **Done (2026-11-19), commit `d05b66909` (WI-1c, `gpt-6.2-sol`):** Added silent token lookup + for the originally verified provider and account, shared JWT time parsing, typed callback + failures, and bounded lookup observations. Kept the destination policy and Playground TTL + fallback. Added 15 focused tests and updated dependent test mocks for the new session API. + The advisor approved the OP-1b candidate (`claude-opus-5.5`, 85% confidence). `npm run build` + and all 254 targeted tests passed. **Waiting for OP-1b** before proceeding with the rest of PR 1. --- From 226cd4714e019dd9e2c9ecdb584e46e730ac4087 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 19 Nov 2026 20:03:19 +0000 Subject: [PATCH 019/380] docs: record OP-1b renewal trace evidence Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../connection-lifecycle/iterations/01-dev-plan.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) 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 07108920e..c0bf16d36 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 @@ -624,7 +624,13 @@ verdict exists, do not start the work it gates. The fingerprint table (formerly failures, and bounded lookup observations. Kept the destination policy and Playground TTL fallback. Added 15 focused tests and updated dependent test mocks for the new session API. The advisor approved the OP-1b candidate (`claude-opus-5.5`, 85% confidence). `npm run build` - and all 254 targeted tests passed. **Waiting for OP-1b** before proceeding with the rest of PR 1. + and all 254 targeted tests passed. +- **OP-1b evidence (2026-11-19):** After about 43 minutes idle, Refresh reused the same client. + A fresh socket triggered callback invocation 2 (`returned`) and then closed. The next socket + became ready without another callback; later sockets and a second Refresh also succeeded at + socket authentication on the same client. No `listDatabases.failed` was logged. This verifies + the post-idle renewal and retry path; no longer wait is needed for OP-1b. The trace cannot alone + confirm whether the database list was visible or whether a sign-in prompt appeared. --- From 7a18015fa0ca52a83cf65c70b212c85c64e730f0 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 19 Nov 2026 20:04:34 +0000 Subject: [PATCH 020/380] docs: record operator pass for OP-1b Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../features/connection-lifecycle/iterations/01-dev-plan.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index c0bf16d36..762ddfac7 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 @@ -631,6 +631,9 @@ verdict exists, do not start the work it gates. The fingerprint table (formerly socket authentication on the same client. No `listDatabases.failed` was logged. This verifies the post-idle renewal and retry path; no longer wait is needed for OP-1b. The trace cannot alone confirm whether the database list was visible or whether a sign-in prompt appeared. +- **OP-1b passed (2026-11-19), operator verification:** The database list loaded and no sign-in + prompt appeared. Resume the remaining PR 1 work. The separate long-wait requirement for OP-6 + still applies. --- From 5ee98385cafb63d1005f868825c34a0f0e2db9eb Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 19 Nov 2026 20:06:23 +0000 Subject: [PATCH 021/380] feat: explain typed Entra sign-in failures (WI-1d) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/documentdb/ClustersExtension.ts | 2 + .../EntraSignInRequiredErrorExplainer.test.ts | 57 +++++++++++++++++++ .../EntraSignInRequiredErrorExplainer.ts | 42 ++++++++++++++ 3 files changed, 101 insertions(+) create mode 100644 src/documentdb/auth/entraErrors/EntraSignInRequiredErrorExplainer.test.ts create mode 100644 src/documentdb/auth/entraErrors/EntraSignInRequiredErrorExplainer.ts diff --git a/src/documentdb/ClustersExtension.ts b/src/documentdb/ClustersExtension.ts index adde5809d..5141727e1 100644 --- a/src/documentdb/ClustersExtension.ts +++ b/src/documentdb/ClustersExtension.ts @@ -143,6 +143,7 @@ import { import { withCommandCorrelation, withTreeNodeCommandCorrelation } from '../utils/commandTelemetry'; import { registerClusterDashboardContextMenuCommands } from '../webviews/documentdb/clusterDashboard/clusterDashboardController'; import { EntraErrorExplainer } from './auth/entraErrors/EntraErrorExplainer'; +import { EntraSignInRequiredErrorExplainer } from './auth/entraErrors/EntraSignInRequiredErrorExplainer'; import { PLAYGROUND_FILE_EXTENSION, PLAYGROUND_LANGUAGE_ID, PlaygroundCommandIds } from './playground/constants'; import { PlaygroundBlockHighlighter } from './playground/PlaygroundBlockHighlighter'; import { PlaygroundCodeLensProvider } from './playground/PlaygroundCodeLensProvider'; @@ -187,6 +188,7 @@ export class ClustersExtension implements vscode.Disposable { ErrorExplanationService.registerProvider(new AtlasErrorExplainer()); // First explanation wins, so source-specific explanations take priority over generic SRV failures. ErrorExplanationService.registerProvider(new SrvDnsErrorExplainer()); + ErrorExplanationService.registerProvider(new EntraSignInRequiredErrorExplainer()); ErrorExplanationService.registerProvider(new EntraErrorExplainer()); } diff --git a/src/documentdb/auth/entraErrors/EntraSignInRequiredErrorExplainer.test.ts b/src/documentdb/auth/entraErrors/EntraSignInRequiredErrorExplainer.test.ts new file mode 100644 index 000000000..11d63d84b --- /dev/null +++ b/src/documentdb/auth/entraErrors/EntraSignInRequiredErrorExplainer.test.ts @@ -0,0 +1,57 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { MongoNetworkError, MongoServerSelectionError, type TopologyDescription } from 'mongodb'; +import { describe, expect, it } from 'vitest'; +import { EntraIdentityMismatchError, EntraSignInRequiredError, TokenCallbackError } from './entraCallbackErrors'; +import { EntraSignInRequiredErrorExplainer } from './EntraSignInRequiredErrorExplainer'; + +describe('EntraSignInRequiredErrorExplainer', () => { + const explainer = new EntraSignInRequiredErrorExplainer(); + const clusterId = 'private-cluster'; + + it('explains a typed sign-in error two causes deep without changing the errors', async () => { + const signIn = Object.freeze(new EntraSignInRequiredError('providerChanged')); + const wrapper = Object.freeze(new TokenCallbackError(signIn)); + const error = Object.freeze(new Error('private-detail', { cause: wrapper })); + + await expect(explainer.explain({ clusterId, error })).resolves.toBe( + 'Your Microsoft sign-in for this connection expired. Sign in again to continue.', + ); + expect(error.cause).toBe(wrapper); + expect(wrapper.cause).toBe(signIn); + }); + + it('recognizes the bounded name on an Error reconstructed at a boundary', async () => { + const error = new Error('private-account'); + error.name = 'EntraIdentityMismatchError'; + + await expect(explainer.explain({ clusterId, error })).resolves.toBe( + 'VS Code returned a different Microsoft account for this connection.', + ); + }); + + it('finds a typed cause in the driver’s per-server errors', async () => { + const mismatch = new EntraIdentityMismatchError(); + const servers = new Map([ + ['private-host:27017', { error: new MongoNetworkError('private-detail', { cause: mismatch }) }], + ['unrelated-host:27017', { error: new MongoNetworkError('unrelated') }], + ]); + const error = new MongoServerSelectionError('selection failed', { servers } as unknown as TopologyDescription); + + await expect(explainer.explain({ clusterId, error })).resolves.toBe( + 'VS Code returned a different Microsoft account for this connection.', + ); + }); + + it('declines strings, message-only matches, and unrelated cyclic callback errors', async () => { + const unrelated = new Error('EntraSignInRequiredError'); + const wrapper = new TokenCallbackError(unrelated); + unrelated.cause = wrapper; + + await expect(explainer.explain({ clusterId, error: 'EntraIdentityMismatchError' })).resolves.toBeUndefined(); + await expect(explainer.explain({ clusterId, error: wrapper })).resolves.toBeUndefined(); + }); +}); diff --git a/src/documentdb/auth/entraErrors/EntraSignInRequiredErrorExplainer.ts b/src/documentdb/auth/entraErrors/EntraSignInRequiredErrorExplainer.ts new file mode 100644 index 000000000..1778d75c4 --- /dev/null +++ b/src/documentdb/auth/entraErrors/EntraSignInRequiredErrorExplainer.ts @@ -0,0 +1,42 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as l10n from '@vscode/l10n'; +import { MongoServerSelectionError } from 'mongodb'; +import { type ErrorExplanationProvider, type ErrorExplanationRequest } from '../../../services/errorExplanationService'; + +export class EntraSignInRequiredErrorExplainer implements ErrorExplanationProvider { + public readonly id = 'entraSignInRequired'; + + public async explain({ error }: ErrorExplanationRequest): Promise { + const pending: unknown[] = [error]; + const visited = new Set(); + while (pending.length > 0) { + const current = pending.pop(); + if (!(current instanceof Error) || visited.has(current)) { + continue; + } + visited.add(current); + + switch (current.name) { + case 'EntraSignInRequiredError': + return l10n.t('Your Microsoft sign-in for this connection expired. Sign in again to continue.'); + case 'EntraIdentityMismatchError': + return l10n.t('VS Code returned a different Microsoft account for this connection.'); + } + + if (current instanceof MongoServerSelectionError) { + const servers = current.reason?.servers; + if (servers instanceof Map) { + for (const description of servers.values()) { + pending.push(description?.error); + } + } + } + pending.push(current.cause); + } + return undefined; + } +} From 154d5ee7af3a914c6e4d18f3c0c40dfa8f1fb882 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 19 Nov 2026 20:06:41 +0000 Subject: [PATCH 022/380] docs: record WI-1 sign-in explanation results Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../features/connection-lifecycle/iterations/01-dev-plan.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index 762ddfac7..0af078d29 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 @@ -634,6 +634,11 @@ verdict exists, do not start the work it gates. The fingerprint table (formerly - **OP-1b passed (2026-11-19), operator verification:** The database list loaded and no sign-in prompt appeared. Resume the remaining PR 1 work. The separate long-wait requirement for OP-6 still applies. +- **Done (2026-11-19), commit `5ee98385c` (WI-1d, `gpt-6.2-sol`):** Added a localized, text-only + explanation for typed sign-in and identity mismatch errors, including errors wrapped by the + driver. Used “this connection” rather than introducing a display-name lookup, as allowed by + step 8. Four new tests; 51 focused tests and `npx tsc --noEmit -p .` passed. Localization + generation and the remaining PR checks are deferred to handoff. --- From be25c2d0471ade18d1f3b4113d9b9d9fc7aa3433 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 19 Nov 2026 20:07:21 +0000 Subject: [PATCH 023/380] docs: record WI-2 delivery decision gate Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../connection-lifecycle/iterations/01-dev-plan.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index 0af078d29..71861e016 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 @@ -741,6 +741,15 @@ verdict exists, do not start the work it gates. The fingerprint table (formerly **Progress:** +- **Deferred, escalated (2026-11-19), advised (`claude-opus-5.5`):** PR 1 does not yet have WI-4's + verified identity or fingerprint, or the disconnect latch. The worker IPC and session-local + pinning can be built independently, but delivering only those pieces in PR 1 would leave the + existing respawn behavior in place until the later guards land. Recommendation: keep WI-2 + together and deliver it after both prerequisites exist. Alternative: approve a split, with + IPC and session-local pinning in PR 1 and the identity and respawn guards later. Also confirm + whether A1's provisional **Sign in again** action should remain in the worker delivery. No + relay implementation has started. + --- ## WI-3: Azure discovery on azureauth v6 (#990) (PR 2) From f731f482f9c7b9ab5ab762f30c53be4ee4002557 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 06:26:09 +0000 Subject: [PATCH 024/380] docs: reschedule WI-2 after lifecycle safeguards Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../connection-lifecycle/iterations/01-dev-plan.md | 7 +++++-- .../iterations/01-implementation-plan.md | 12 +++++++++--- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index 71861e016..46bfe7a41 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 @@ -642,7 +642,7 @@ verdict exists, do not start the work it gates. The fingerprint table (formerly --- -## WI-2: Shell and Playground token relays (PR 1) +## WI-2: Shell and Playground token relays (after WI-7) **Outcome:** @@ -737,7 +737,7 @@ verdict exists, do not start the work it gates. The fingerprint table (formerly worker once under the same fingerprint, and the command after that runs on the new worker. - Add a test of the worker message round trip for `reason` and `authReason`. -**Done when:** Case 1 is green, and the PR 1 pre-review is committed. +**Done when:** Case 1 is green, and the relay PR pre-review is committed. **Progress:** @@ -749,6 +749,9 @@ verdict exists, do not start the work it gates. The fingerprint table (formerly IPC and session-local pinning in PR 1 and the identity and respawn guards later. Also confirm whether A1's provisional **Sign in again** action should remain in the worker delivery. No relay implementation has started. +- **Rescheduled (2026-11-20), operator decision:** Finish PR 1 with WI-1 only. Deliver WI-2 + intact after WI-4's verified identity and fingerprint and WI-7's disconnect latch exist, + retaining the planned **Sign in again** action. Do not implement the partial relay option. --- 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 1173c7cc9..83c00becd 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 @@ -69,15 +69,17 @@ and **never loses work** (query text, filters, sort, projection, unsaved documen ## Execution order ``` -WI-1 ─┬─> WI-2 (Entra, small, independent) +WI-1 ──┐ (Entra silent renewal) │ WI-3 ─┤ (azureauth v6 / #990, parallel track) │ WI-4 ─┴─> WI-5 ─> WI-6 ─> WI-7 ─> WI-8 (lifecycle core, then Disconnect, then dashboard) + └──> WI-2 (worker relays, after the disconnect guard) └──> WI-9 (telemetry check) ─> WI-10 (docs) ``` -- WI-1, WI-2 and WI-3 are independent of the lifecycle core. +- WI-1 and WI-3 are independent of the lifecycle core. WI-2 needs WI-4's verified identity and + fingerprint, and the disconnect latch used by WI-7. - WI-1 and WI-2 remove most of the user impact (defect #1). They still ship with everything else; there is no partial release (decision [0006](../decisions.md)). @@ -129,7 +131,7 @@ WI-4 ─┴─> WI-5 ─> WI-6 ─> WI-7 ─> WI-8 (lifecycle core, then Disco | PR | Content | Base while predecessor is open | | --- | -------------------------------------------------------------------------------- | ------------------------------------------ | | 0 | This plan, `research-findings.md`, `decisions.md`, README and index row | feature branch | -| 1 | WI-1 + WI-2: Entra silent renewal, plus the shell and playground relays | PR 0 head | +| 1 | WI-1: Entra silent renewal | PR 0 head | | 2 | WI-3: azureauth v6 (#990) + the diagnostics `signInRequired` mapping | PR 1 head | | 3 | WI-4: client identity and generation, the two cache fixes, telemetry helper | PR 2 head | | 4 | WI-5: failure classifier, recovery, Sign in again, Retry, `onDidChangeSessions` | PR 3 head | @@ -140,6 +142,10 @@ WI-4 ─┴─> WI-5 ─> WI-6 ─> WI-7 ─> WI-8 (lifecycle core, then Disco - WI-4 consumes the verified account, provider and tenant contract from WI-1. Do not reconstruct the identity from a later cache read. +- **WI-2 scheduling (operator approved 2026-11-20):** Deliver the Shell and Playground token relays + together, after WI-4's verified identity and connection fingerprint and WI-7's disconnect latch + are available. Keep the planned **Sign in again** action. PR 1 is WI-1 only; it does not change + worker relay behavior. - **PR 5 is the largest.** If it becomes too large to review well, split it into host (5a) and webviews (5b). Stack 5b on 5a, and PR 6 on 5b, following rule 1. - **#990 alternative:** #990 is its own issue in the 1.2.0 milestone. It can merge to `main` instead, From 9e0a375a52605726becb70b29b4b8223c25e7fa1 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 06:46:37 +0000 Subject: [PATCH 025/380] docs: record PR 1 Entra renewal pre-review Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iterations/01-pr1-entra-renewal-review.md | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1-entra-renewal-review.md diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1-entra-renewal-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1-entra-renewal-review.md new file mode 100644 index 000000000..4e30dde35 --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1-entra-renewal-review.md @@ -0,0 +1,49 @@ +--- +feature: connection-lifecycle +kind: review +status: active +created: 2026-11-20 +--- + +# PR 1 pre-review: Entra silent renewal + +Reviewed `2666f2ac7..f731f482f` (WI-1 only). GPT-6.2-Sol performed the initial review; +Claude Opus 5.5 validated the findings and performed an independent sweep. The PR was not yet +published, so there were no GitHub review comments to incorporate. + +## F1. Regenerate localization before review + +**Confirmed; blocks full CI.** The five new strings in +[entraCallbackErrors.ts](../../../../../src/documentdb/auth/entraErrors/entraCallbackErrors.ts) +and [EntraSignInRequiredErrorExplainer.ts](../../../../../src/documentdb/auth/entraErrors/EntraSignInRequiredErrorExplainer.ts) +are not in the checked-in bundle. Generate the bundle as already scheduled for Case 2, then run +`npm run l10n:check`. No wording change is needed. + +## F2. Typed Entra explanations do not yet reach webviews + +**Confirmed; delivery decision pending.** The existing webview explanation request passes only +an error message. The new explainer needs the typed error or its cause chain. The current +Collection View path can show a generic heading; the detail depends on what survives transport. + +**Advisor recommendation:** Track this in WI-5/WI-6, whose classifier and structured unavailable +response are designed to handle it. PR 1 does not ship separately. The alternative is to add an +allowlisted error name to the current webview request, but that still does not convey driver +server-selection causes and would add call-site changes that WI-6 replaces. Do not match raw +message text or wrap errors solely to transport explanations. + +**Author decision:** Pending. + +## Independent sweep + +- **Recovery depends on WI-5.** The driver retains a rejected callback. PR 1 diagnoses the silent + miss but cannot recover that client by signing in again; WI-5 must replace it. +- **Provider-change wording:** `providerChanged` uses the planned expired-sign-in wording. + Changing it would be a separate user-visible decision. +- **Callback failure detail:** The new wrapper uses a bounded message and preserves the original + cause. Do not expose raw cause text as part of this PR. +- **Provider seam:** The installed dependency has a public getter, but the repository's token + resource module does not export a shared getter. WI-1 uses the public getter directly; WI-3 + should check both consumers during the dependency upgrade. + +OP-1b passed with a real cluster: the database list loaded after idle and no sign-in prompt +appeared. That test did not cover webview failure presentation or replacement after a silent miss. From bf486ba156ed108e551b07d8910c1527464a3923 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 09:04:16 +0000 Subject: [PATCH 026/380] docs: defer PR 1 webview sign-in handling to WI-5/WI-6 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../features/connection-lifecycle/iterations/01-dev-plan.md | 6 ++++++ .../iterations/01-pr1-entra-renewal-review.md | 5 +++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index 46bfe7a41..9f200576b 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 @@ -639,6 +639,9 @@ verdict exists, do not start the work it gates. The fingerprint table (formerly driver. Used “this connection” rather than introducing a display-name lookup, as allowed by step 8. Four new tests; 51 focused tests and `npx tsc --noEmit -p .` passed. Localization generation and the remaining PR checks are deferred to handoff. +- **PR 1 pre-review F2 (2026-11-20), operator decision:** Defer typed webview sign-in errors to + the WI-5 classifier and WI-6 structured unavailable response. PR 1 keeps the existing webview + error transport. See the [review finding](./01-pr1-entra-renewal-review.md#f2-typed-entra-explanations-do-not-yet-reach-webviews). --- @@ -1114,6 +1117,9 @@ shim (0005). ## WI-6: Bind surfaces and add the unavailable state (PR 5) +**Carry-forward from PR 1:** Verify that a typed sign-in error classified by WI-5 reaches the +webview as a structured unavailable result, not a generic query error. + **Outcome:** - Collection View (all tabs), Document View and the Cluster Dashboard resolve their client per operation diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1-entra-renewal-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1-entra-renewal-review.md index 4e30dde35..77e5d7b32 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1-entra-renewal-review.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1-entra-renewal-review.md @@ -21,7 +21,7 @@ are not in the checked-in bundle. Generate the bundle as already scheduled for C ## F2. Typed Entra explanations do not yet reach webviews -**Confirmed; delivery decision pending.** The existing webview explanation request passes only +**Confirmed; deferred to WI-5/WI-6.** The existing webview explanation request passes only an error message. The new explainer needs the typed error or its cause chain. The current Collection View path can show a generic heading; the detail depends on what survives transport. @@ -31,7 +31,8 @@ allowlisted error name to the current webview request, but that still does not c server-selection causes and would add call-site changes that WI-6 replaces. Do not match raw message text or wrap errors solely to transport explanations. -**Author decision:** Pending. +**Author decision (2026-11-20):** Defer F2 to WI-5/WI-6. PR 1 will not add a temporary webview +transport for typed sign-in errors. ## Independent sweep From fd66391bd4e3709e96640dc0168a14fa4f9efa9c Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 09:06:51 +0000 Subject: [PATCH 027/380] docs: pre-approve lifecycle draft PR publication Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/ai-and-plans/features/connection-lifecycle/decisions.md | 4 ++++ .../features/connection-lifecycle/iterations/01-dev-plan.md | 2 ++ 2 files changed, 6 insertions(+) diff --git a/docs/ai-and-plans/features/connection-lifecycle/decisions.md b/docs/ai-and-plans/features/connection-lifecycle/decisions.md index 4fb988407..42dc1c27a 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/decisions.md +++ b/docs/ai-and-plans/features/connection-lifecycle/decisions.md @@ -158,6 +158,10 @@ sub-PR on the preceding PR's branch without waiting for it to merge. The operato with approvals and merges. This changes neither the explicit operator test gates nor the single release from the feature branch. +**Amended by the operator on 2026-11-20:** PR publication is pre-approved. Push the topic branch +and open its draft PR without asking for separate confirmation. This does not authorize merges +or remove review, verification, or operator test gates. + - It follows CONTRIBUTING §1.4 (large features). - It fits the repository's enforcement: - CI runs on PRs to `feature/**`; 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 9f200576b..7c46ea61f 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 @@ -98,6 +98,8 @@ result may continue, but say so in the message. Record the result in the Progres the preceding PR is open. If it is already merged, branch from and target `feature/connection-lifecycle`. Do not wait for intermediate approvals or merges; the operator handles those. The advisor checkpoints and explicit operator decisions and tests still apply. +- **Publish:** pushing the topic branch and opening its draft PR are pre-approved (decision 0006). + Do not pause for separate publication confirmation. Normal review and merge requirements remain. - **Commits:** one or more commits per WI, never one commit that mixes two WIs. Each commit ends with the `Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>` trailer. - **While working, and for draft PRs:** Case 1 only: `npm run build` plus `npx vitest run `. From 6e108f0a333135369be313e2ab848dcaf9e484d4 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 09:10:01 +0000 Subject: [PATCH 028/380] docs: use plan numbers in lifecycle PR titles Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../features/connection-lifecycle/iterations/01-dev-plan.md | 1 + 1 file changed, 1 insertion(+) 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 7c46ea61f..a9a6b0658 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 @@ -100,6 +100,7 @@ result may continue, but say so in the message. Record the result in the Progres handles those. The advisor checkpoints and explicit operator decisions and tests still apply. - **Publish:** pushing the topic branch and opening its draft PR are pre-approved (decision 0006). Do not pause for separate publication confirmation. Normal review and merge requirements remain. + Prefix the GitHub title with the plan number, for example `PR0:` or `PR1:`. - **Commits:** one or more commits per WI, never one commit that mixes two WIs. Each commit ends with the `Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>` trailer. - **While working, and for draft PRs:** Case 1 only: `npm run build` plus `npx vitest run `. From a52f063206a3eee2e820d00c9049c88fbf05ea84 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 09:19:54 +0000 Subject: [PATCH 029/380] chore: regenerate localization and format PR1 changes Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iterations/01-implementation-plan.md | 2 +- l10n/bundle.l10n.json | 5 +++++ src/connectionDiagnostics/checks/authenticate.test.ts | 5 ++++- .../auth/MicrosoftEntraIDAuthHandler.test.ts | 10 ++++++++-- src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts | 4 +++- src/documentdb/auth/driverOidcContract.test.ts | 10 ++++++++-- 6 files changed, 29 insertions(+), 7 deletions(-) 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 83c00becd..36a2570e0 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 @@ -131,7 +131,7 @@ WI-4 ─┴─> WI-5 ─> WI-6 ─> WI-7 ─> WI-8 (lifecycle core, then Disco | PR | Content | Base while predecessor is open | | --- | -------------------------------------------------------------------------------- | ------------------------------------------ | | 0 | This plan, `research-findings.md`, `decisions.md`, README and index row | feature branch | -| 1 | WI-1: Entra silent renewal | PR 0 head | +| 1 | WI-1: Entra silent renewal | PR 0 head | | 2 | WI-3: azureauth v6 (#990) + the diagnostics `signInRequired` mapping | PR 1 head | | 3 | WI-4: client identity and generation, the two cache fixes, telemetry helper | PR 2 head | | 4 | WI-5: failure classifier, recovery, Sign in again, Retry, `onDidChangeSessions` | PR 3 head | diff --git a/l10n/bundle.l10n.json b/l10n/bundle.l10n.json index f732fa292..8f7d70a46 100644 --- a/l10n/bundle.l10n.json +++ b/l10n/bundle.l10n.json @@ -1424,6 +1424,7 @@ "Failed to load the Kubernetes client library: {0}. Try reloading the window; if the problem persists, reinstall the extension.": "Failed to load the Kubernetes client library: {0}. Try reloading the window; if the problem persists, reinstall the extension.", "Failed to load this kubeconfig source: {0}": "Failed to load this kubeconfig source: {0}", "Failed to modify index: {error}": "Failed to modify index: {error}", + "Failed to obtain a Microsoft Entra ID token.": "Failed to obtain a Microsoft Entra ID token.", "Failed to obtain Entra ID token.": "Failed to obtain Entra ID token.", "Failed to open Collection View: {0}": "Failed to open Collection View: {0}", "Failed to open Data Migration.": "Failed to open Data Migration.", @@ -2716,6 +2717,7 @@ "Showing the first {shown} collections; {omitted} more are not listed.": "Showing the first {shown} collections; {omitted} more are not listed.", "Showing the first {shown} databases; {omitted} more are not listed.": "Showing the first {shown} databases; {omitted} more are not listed.", "Sign in": "Sign in", + "Sign in again to continue using Microsoft Entra ID.": "Sign in again to continue using Microsoft Entra ID.", "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.", @@ -3482,8 +3484,10 @@ "Viewing Azure account information for: {0}": "Viewing Azure account information for: {0}", "Visible in the tree, but not connectable until the cluster returns to IDLE.": "Visible in the tree, but not connectable until the cluster returns to IDLE.", "Visit the [documentation]({0}) for more information about TLS/SSL certificates.": "Visit the [documentation]({0}) for more information about TLS/SSL certificates.", + "Visual Studio Code returned a different Microsoft account for this connection.": "Visual Studio Code returned a different Microsoft account for this connection.", "VS Code connects through the Kubernetes PortForward API. Connection strings using 127.0.0.1 only work on this machine while the tunnel is active.": "VS Code connects through the Kubernetes PortForward API. Connection strings using 127.0.0.1 only work on this machine while the tunnel is active.", "VS Code is signed in to a custom cloud, and we could not find which Microsoft Entra resource to request a token for. Set \"{setting}\" to the open-source database resource of your cloud, usually \"https://ossrdbms-aad.database.\". Your cloud operator or Azure administrator can tell you the exact value.": "VS Code is signed in to a custom cloud, and we could not find which Microsoft Entra resource to request a token for. Set \"{setting}\" to the open-source database resource of your cloud, usually \"https://ossrdbms-aad.database.\". Your cloud operator or Azure administrator can tell you the exact value.", + "VS Code returned a different Microsoft account for this connection.": "VS Code returned a different Microsoft account for this connection.", "VS Code version: {0}": "VS Code version: {0}", "VS Code: v{0}": "VS Code: v{0}", "Wait longer": "Wait longer", @@ -3611,6 +3615,7 @@ "Your default kubeconfig ({0}) could not be loaded: {1}. Fix the kubeconfig and try again.": "Your default kubeconfig ({0}) could not be loaded: {1}. Fix the kubeconfig and try again.", "Your Docker group change requires a new WSL session. Run this command in a Windows terminal. This VS Code window will disconnect. Reconnect to WSL, then open DocumentDB Local setup again.": "Your Docker group change requires a new WSL session. Run this command in a Windows terminal. This VS Code window will disconnect. Reconnect to WSL, then open DocumentDB Local setup again.", "Your local connections have been moved to '{0}' in the Connections view.": "Your local connections have been moved to '{0}' in the Connections view.", + "Your Microsoft sign-in for this connection expired. Sign in again to continue.": "Your Microsoft sign-in for this connection expired. Sign in again to continue.", "Your organization policy appears to have blocked sign-in.": "Your organization policy appears to have blocked sign-in.", "Your organization's policy appears to have blocked this sign-in. Contact your IT help desk with code AADSTS53003 and the time of the failure so they can check the sign-in policy. See {link}": "Your organization's policy appears to have blocked this sign-in. Contact your IT help desk with code AADSTS53003 and the time of the failure so they can check the sign-in policy. See {link}", "Your own DocumentDB": "Your own DocumentDB", diff --git a/src/connectionDiagnostics/checks/authenticate.test.ts b/src/connectionDiagnostics/checks/authenticate.test.ts index 53047a24a..ced8a5652 100644 --- a/src/connectionDiagnostics/checks/authenticate.test.ts +++ b/src/connectionDiagnostics/checks/authenticate.test.ts @@ -1192,7 +1192,10 @@ describe('createAuthenticateCheck', (): void => { timeouts: { authenticationTimeoutMs: 30 }, }); expect(codes(result)).toEqual(['check.timeout']); - session.resolve({ accessToken: entraToken(), account: { label: 'alice@contoso.example', id: 'account-id' } }); + session.resolve({ + accessToken: entraToken(), + account: { label: 'alice@contoso.example', id: 'account-id' }, + }); await flush(); expect(deps.createClient).not.toHaveBeenCalled(); }); diff --git a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts index 560e8a1fd..c304384ba 100644 --- a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts +++ b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts @@ -298,7 +298,10 @@ describe('MicrosoftEntraIDAuthHandler', () => { return session; }); await expect( - options.authMechanismProperties!.OIDC_CALLBACK!({ version: 1, timeoutContext: new AbortController().signal }), + options.authMechanismProperties!.OIDC_CALLBACK!({ + version: 1, + timeoutContext: new AbortController().signal, + }), ).rejects.toBeInstanceOf(EntraDestinationRejectedError); expect(getSessionFromVSCode).toHaveBeenCalledTimes(2); }); @@ -310,7 +313,10 @@ describe('MicrosoftEntraIDAuthHandler', () => { const accessToken = `header.${Buffer.from('{"exp":1}').toString('base64url')}.signature`; getSessionFromVSCode.mockResolvedValueOnce({ accessToken, account }); await expect( - options.authMechanismProperties!.OIDC_CALLBACK!({ version: 1, timeoutContext: new AbortController().signal }), + options.authMechanismProperties!.OIDC_CALLBACK!({ + version: 1, + timeoutContext: new AbortController().signal, + }), ).resolves.toEqual({ accessToken, expiresInSeconds: 0 }); expect(getSessionFromVSCode).toHaveBeenCalledTimes(2); }); diff --git a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts index 7de478002..a656d9082 100644 --- a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts +++ b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts @@ -207,7 +207,9 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { const lifetimeSeconds = iatSec !== undefined && expSec !== undefined ? expSec - iatSec : undefined; observation = { outcome: 'returned', - ...(lifetimeSeconds !== undefined && Number.isFinite(lifetimeSeconds) ? { lifetimeSeconds } : {}), + ...(lifetimeSeconds !== undefined && Number.isFinite(lifetimeSeconds) + ? { lifetimeSeconds } + : {}), }; return expSec === undefined ? { accessToken } diff --git a/src/documentdb/auth/driverOidcContract.test.ts b/src/documentdb/auth/driverOidcContract.test.ts index 0144c7a8a..8048bce08 100644 --- a/src/documentdb/auth/driverOidcContract.test.ts +++ b/src/documentdb/auth/driverOidcContract.test.ts @@ -102,7 +102,10 @@ describe('driver contract: mongodb OIDC workflow (7.2.0)', () => { .mockResolvedValueOnce({ accessToken: 'dummy-cached-token' }) .mockResolvedValueOnce({ accessToken: 'dummy-renewed-token' }); const workflow = new AutomatedCallbackWorkflow(new TokenCache(), callback); - await workflow.execute({ command: vi.fn().mockResolvedValue({ ok: 1 }) }, credentials); + await workflow.execute( + { command: vi.fn().mockResolvedValue({ ok: 1 }) }, + credentials, + ); expect(callback).toHaveBeenCalledTimes(1); const command = vi @@ -121,7 +124,10 @@ describe('driver contract: mongodb OIDC workflow (7.2.0)', () => { 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); - await workflow.execute({ command: vi.fn().mockResolvedValue({ ok: 1 }) }, credentials); + await workflow.execute( + { command: vi.fn().mockResolvedValue({ ok: 1 }) }, + credentials, + ); expect(callback).toHaveBeenCalledTimes(1); const error = new MongoNetworkError('dummy network failure'); From a0c1d1312f77b0b73708f28cf305f90f26a675f1 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 09:22:18 +0000 Subject: [PATCH 030/380] test: use a type-only import for the Entra provider mock Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts index c304384ba..11471a596 100644 --- a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts +++ b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts @@ -3,6 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import type * as azureAuth from '@microsoft/vscode-azext-azureauth'; import { type PeerCertificate } from 'tls'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import * as vscode from 'vscode'; @@ -27,7 +28,7 @@ vi.mock('vscode', async (importOriginal) => ({ })); vi.mock('@microsoft/vscode-azext-azureauth', async (importOriginal) => ({ - ...(await importOriginal()), + ...(await importOriginal()), getConfiguredAuthProviderId: (): string => getConfiguredAuthProviderId(), })); From c60e5035c921340eadd809bb740568714e15204e Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 09:22:31 +0000 Subject: [PATCH 031/380] docs: record PR1 verification results Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iterations/01-pr1-entra-renewal-review.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1-entra-renewal-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1-entra-renewal-review.md index 77e5d7b32..120e03a4c 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1-entra-renewal-review.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1-entra-renewal-review.md @@ -19,6 +19,9 @@ and [EntraSignInRequiredErrorExplainer.ts](../../../../../src/documentdb/auth/en are not in the checked-in bundle. Generate the bundle as already scheduled for Case 2, then run `npm run l10n:check`. No wording change is needed. +**Resolved:** `a52f06320` regenerates the bundle with exactly five new keys. `npm run l10n:check` +passed. + ## F2. Typed Entra explanations do not yet reach webviews **Confirmed; deferred to WI-5/WI-6.** The existing webview explanation request passes only @@ -48,3 +51,11 @@ transport for typed sign-in errors. OP-1b passed with a real cluster: the database list loaded after idle and no sign-in prompt appeared. That test did not cover webview failure presentation or replacement after a silent miss. + +## Review handoff (2026-11-20) + +Case 2 ran on `6e108f0a3` with the generated localization and formatting applied. Localization, +formatting, localization check, build, test type-check, full Vitest (9,651 passed, one skipped), +and VSIX packaging passed. Lint initially rejected an inline import type in the Entra handler +test. `a0c1d1312` replaced it with a type-only import; full lint, the affected suite (47 passed), +and its formatting check then passed. No runtime code changed in that follow-up. From cae1db8901a1da0652e951f91e33cd38189814d6 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 09:57:37 +0000 Subject: [PATCH 032/380] fix: classify Entra callback failures during client startup (PR1-R3) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../utils/startupFailureTelemetry.test.ts | 16 ++++++++++++++++ src/documentdb/utils/startupFailureTelemetry.ts | 3 +++ 2 files changed, 19 insertions(+) diff --git a/src/documentdb/utils/startupFailureTelemetry.test.ts b/src/documentdb/utils/startupFailureTelemetry.test.ts index c5420f9ca..5eafd636b 100644 --- a/src/documentdb/utils/startupFailureTelemetry.test.ts +++ b/src/documentdb/utils/startupFailureTelemetry.test.ts @@ -13,6 +13,11 @@ import { } from 'mongodb'; import { describe, expect, it, vi } from 'vitest'; import { allowListedErrorType, innermostCauseTypeOf } from '../../utils/telemetryErrorType'; +import { + EntraIdentityMismatchError, + EntraSignInRequiredError, + TokenCallbackError, +} from '../auth/entraErrors/entraCallbackErrors'; import { applyStartupFailureTelemetry, classifyStartupFailure } from './startupFailureTelemetry'; vi.mock('vscode', async (importOriginal) => { @@ -101,6 +106,17 @@ describe('classifyStartupFailure', (): void => { }); describe('applyStartupFailureTelemetry', (): void => { + it.each([ + ['a direct token callback error', new TokenCallbackError(nodeError('ECONNRESET'))], + ['a wrapped sign-in requirement', new Error('Wrapper', { cause: new EntraSignInRequiredError('noSession') })], + ['a server selection error wrapping an account mismatch', selectionError(new EntraIdentityMismatchError())], + ])('attributes %s to Entra during startup', (_label, error): void => { + const properties: ITelemetryContext['properties'] = { entraFailureKind: 'none' }; + applyStartupFailureTelemetry(properties, error); + expect(properties.startupFailureCategory).toBe('entraToken'); + expect(properties.entraFailureKind).toBe('none'); + }); + it('records only allow-listed values under names whole-error masking keeps', (): void => { const properties: ITelemetryContext['properties'] = {}; applyStartupFailureTelemetry(properties, new Error('private-host private-user')); diff --git a/src/documentdb/utils/startupFailureTelemetry.ts b/src/documentdb/utils/startupFailureTelemetry.ts index 325504b59..3f08b3d30 100644 --- a/src/documentdb/utils/startupFailureTelemetry.ts +++ b/src/documentdb/utils/startupFailureTelemetry.ts @@ -52,6 +52,9 @@ const CREDENTIALS_UNAVAILABLE_NAMES: ReadonlySet = new Set([ ]); const ENTRA_TOKEN_NAMES: ReadonlySet = new Set([ 'EntraDestinationRejectedError', + 'EntraIdentityMismatchError', + 'EntraSignInRequiredError', + 'TokenCallbackError', 'TokenResourceResolutionError', 'CredentialUnavailableError', 'AuthenticationRequiredError', From 036a1dfea9dcf8f9aa0ce5328f646924a639d65c Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 09:58:38 +0000 Subject: [PATCH 033/380] docs: record PR1 startup telemetry review fix Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iterations/01-pr1-entra-renewal-review.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1-entra-renewal-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1-entra-renewal-review.md index 120e03a4c..ec3734f27 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1-entra-renewal-review.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1-entra-renewal-review.md @@ -59,3 +59,20 @@ formatting, localization check, build, test type-check, full Vitest (9,651 passe and VSIX packaging passed. Lint initially rejected an inline import type in the Entra handler test. `a0c1d1312` replaced it with a type-only import; full lint, the affected suite (47 passed), and its formatting check then passed. No runtime code changed in that follow-up. + +## Copilot review follow-up (2026-11-20) + +- **R3, done in `cae1db890`:** Startup telemetry recognizes the three typed Entra callback + failures as `entraToken`, including wrapped and server-selection errors. The callback does not + write startup telemetry. The advisor (`claude-opus-5.5`, 80% confidence) recommended classifying + the error at the existing startup boundary; the leader applied that recommendation directly. + Build and 79 focused tests passed, including three new cases. [Thread reply](https://github.com/microsoft/vscode-documentdb/pull/1108#discussion_r4641033663). +- **R1, pending operator approval:** Pin the effective cloud and authority before and after the + silent lookup, including when the provider ID does not change. +- **R2, pending operator decision:** The advisor recommends reusing the initially verified token + once, which amends decision 0001. The alternative keeps the silent lookup on every callback and + makes diagnostics observe the result actually sent to the server. +- **R4, pending wording approval:** Use an account-mismatch explanation that tells the user to + sign in with the account originally used for the connection. +- **R5, pending disposition:** The advisor recommends deferring mixed-server AADSTS traversal to + the shared WI-5 classifier rather than adding a second traversal in PR1. From 963348f7ee4b2b671bdf24d24e3d06b0cccf1837 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 10:14:15 +0000 Subject: [PATCH 034/380] docs: carry PR1 mixed-server error follow-up into WI-5 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../features/connection-lifecycle/iterations/01-dev-plan.md | 4 ++++ .../iterations/01-pr1-entra-renewal-review.md | 6 ++++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index a9a6b0658..0d96069f9 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 @@ -1006,6 +1006,10 @@ shim (0005). 1. **Classifier** (`src/documentdb/connectionFailures.ts`, pure). Draft the table, then hold CP-2. - It walks `cause`, plus `MongoServerSelectionError.reason.servers[*].error` where present. + - Carry-forward from [PR1 review R5](https://github.com/microsoft/vscode-documentdb/pull/1108#discussion_r4640902166): + recheck whether the installed driver can retain callback failures in per-server errors. If it + can, use the same bounded traversal for `EntraErrorExplainer`, test mixed-server failures, and + render only the rule-based explanation, not raw cause text. Recheck on driver upgrades. - Initial table: | Signal | Auth | Kind | Generation | Offered action | diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1-entra-renewal-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1-entra-renewal-review.md index ec3734f27..13a88c1e8 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1-entra-renewal-review.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1-entra-renewal-review.md @@ -74,5 +74,7 @@ and its formatting check then passed. No runtime code changed in that follow-up. makes diagnostics observe the result actually sent to the server. - **R4, pending wording approval:** Use an account-mismatch explanation that tells the user to sign in with the account originally used for the connection. -- **R5, pending disposition:** The advisor recommends deferring mixed-server AADSTS traversal to - the shared WI-5 classifier rather than adding a second traversal in PR1. +- **R5, deferred to WI-5:** The advisor (`claude-opus-5.5`, 85% confidence) verified from the pinned + driver's source that plain callback errors are not stored in per-server descriptions. They reach + the caller directly, where the existing cause traversal can explain them. WI-5 carries forward + the driver check and the shared explanation path if needed; PR1 does not add a second traversal. From 897329a8f10ee767615b1bc6048ade75a0a0d19f Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 10:29:35 +0000 Subject: [PATCH 035/380] fix: give an actionable Entra account-mismatch explanation (PR1-R4) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- l10n/bundle.l10n.json | 2 +- .../entraErrors/EntraSignInRequiredErrorExplainer.test.ts | 4 ++-- .../auth/entraErrors/EntraSignInRequiredErrorExplainer.ts | 4 +++- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/l10n/bundle.l10n.json b/l10n/bundle.l10n.json index 8f7d70a46..f3c551b94 100644 --- a/l10n/bundle.l10n.json +++ b/l10n/bundle.l10n.json @@ -339,6 +339,7 @@ "A credential contains a reserved character that is not percent-encoded.": "A credential contains a reserved character that is not percent-encoded.", "a custom cloud": "a custom cloud", "A default kubeconfig source already exists.": "A default kubeconfig source already exists.", + "A different Microsoft account was returned for this connection. Sign in with the account you originally used for this connection, then try again.": "A different Microsoft account was returned for this connection. Sign in with the account you originally used for this connection, then try again.", "A direct connection is requested with more than one seed host.": "A direct connection is requested with more than one seed host.", "A firewall or IP allowlist may be blocking this connection. Check access from the computer or remote host where these checks ran, including VPN and network rules.": "A firewall or IP allowlist may be blocking this connection. Check access from the computer or remote host where these checks ran, including VPN and network rules.", "A folder with this name already exists at this level": "A folder with this name already exists at this level", @@ -3487,7 +3488,6 @@ "Visual Studio Code returned a different Microsoft account for this connection.": "Visual Studio Code returned a different Microsoft account for this connection.", "VS Code connects through the Kubernetes PortForward API. Connection strings using 127.0.0.1 only work on this machine while the tunnel is active.": "VS Code connects through the Kubernetes PortForward API. Connection strings using 127.0.0.1 only work on this machine while the tunnel is active.", "VS Code is signed in to a custom cloud, and we could not find which Microsoft Entra resource to request a token for. Set \"{setting}\" to the open-source database resource of your cloud, usually \"https://ossrdbms-aad.database.\". Your cloud operator or Azure administrator can tell you the exact value.": "VS Code is signed in to a custom cloud, and we could not find which Microsoft Entra resource to request a token for. Set \"{setting}\" to the open-source database resource of your cloud, usually \"https://ossrdbms-aad.database.\". Your cloud operator or Azure administrator can tell you the exact value.", - "VS Code returned a different Microsoft account for this connection.": "VS Code returned a different Microsoft account for this connection.", "VS Code version: {0}": "VS Code version: {0}", "VS Code: v{0}": "VS Code: v{0}", "Wait longer": "Wait longer", diff --git a/src/documentdb/auth/entraErrors/EntraSignInRequiredErrorExplainer.test.ts b/src/documentdb/auth/entraErrors/EntraSignInRequiredErrorExplainer.test.ts index 11d63d84b..ac0e787b4 100644 --- a/src/documentdb/auth/entraErrors/EntraSignInRequiredErrorExplainer.test.ts +++ b/src/documentdb/auth/entraErrors/EntraSignInRequiredErrorExplainer.test.ts @@ -29,7 +29,7 @@ describe('EntraSignInRequiredErrorExplainer', () => { error.name = 'EntraIdentityMismatchError'; await expect(explainer.explain({ clusterId, error })).resolves.toBe( - 'VS Code returned a different Microsoft account for this connection.', + 'A different Microsoft account was returned for this connection. Sign in with the account you originally used for this connection, then try again.', ); }); @@ -42,7 +42,7 @@ describe('EntraSignInRequiredErrorExplainer', () => { const error = new MongoServerSelectionError('selection failed', { servers } as unknown as TopologyDescription); await expect(explainer.explain({ clusterId, error })).resolves.toBe( - 'VS Code returned a different Microsoft account for this connection.', + 'A different Microsoft account was returned for this connection. Sign in with the account you originally used for this connection, then try again.', ); }); diff --git a/src/documentdb/auth/entraErrors/EntraSignInRequiredErrorExplainer.ts b/src/documentdb/auth/entraErrors/EntraSignInRequiredErrorExplainer.ts index 1778d75c4..790b7b3e0 100644 --- a/src/documentdb/auth/entraErrors/EntraSignInRequiredErrorExplainer.ts +++ b/src/documentdb/auth/entraErrors/EntraSignInRequiredErrorExplainer.ts @@ -24,7 +24,9 @@ export class EntraSignInRequiredErrorExplainer implements ErrorExplanationProvid case 'EntraSignInRequiredError': return l10n.t('Your Microsoft sign-in for this connection expired. Sign in again to continue.'); case 'EntraIdentityMismatchError': - return l10n.t('VS Code returned a different Microsoft account for this connection.'); + return l10n.t( + 'A different Microsoft account was returned for this connection. Sign in with the account you originally used for this connection, then try again.', + ); } if (current instanceof MongoServerSelectionError) { From 98be5f18e54d56cc25c102a99ee93f3bf0fa6b2a Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 10:35:02 +0000 Subject: [PATCH 036/380] fix: pin the Entra cloud and authority during token acquisition (PR1-R1) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../auth/MicrosoftEntraIDAuthHandler.test.ts | 173 ++++++++++++++++++ .../auth/MicrosoftEntraIDAuthHandler.ts | 75 +++++--- src/documentdb/auth/entraSession.ts | 13 ++ 3 files changed, 240 insertions(+), 21 deletions(-) diff --git a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts index 11471a596..29d5f218b 100644 --- a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts +++ b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts @@ -11,6 +11,8 @@ import type * as documentdbTokenResource from './documentdbTokenResource'; const getSessionFromVSCode = vi.fn(); const getConfiguredAuthProviderId = vi.fn<() => string>(); +type AzureSignInSettings = Pick, 'name' | 'activeDirectoryEndpointUrl'>; +const getConfiguredAzureEnv = vi.fn<() => AzureSignInSettings>(); const account = { id: 'account-id', label: 'account-label' }; const session = { accessToken: 'access-token', account }; const mockOutputChannel = { info: vi.fn(), error: vi.fn() }; @@ -30,6 +32,7 @@ vi.mock('vscode', async (importOriginal) => ({ vi.mock('@microsoft/vscode-azext-azureauth', async (importOriginal) => ({ ...(await importOriginal()), getConfiguredAuthProviderId: (): string => getConfiguredAuthProviderId(), + getConfiguredAzureEnv: (): AzureSignInSettings => getConfiguredAzureEnv(), })); vi.mock('./documentdbTokenResource', async (importOriginal) => ({ @@ -74,6 +77,10 @@ describe('MicrosoftEntraIDAuthHandler', () => { getSessionFromVSCode.mockReset(); getSessionFromVSCode.mockResolvedValue(session); getConfiguredAuthProviderId.mockReset().mockReturnValue('microsoft'); + getConfiguredAzureEnv.mockReset().mockReturnValue({ + name: 'AzureCloud', + activeDirectoryEndpointUrl: 'https://login.microsoftonline.com/', + }); vi.mocked(resolveInteractiveTokenResource).mockResolvedValue({ resource: 'https://ossrdbms-aad.database.windows.net', scope: 'https://ossrdbms-aad.database.windows.net/.default', @@ -357,6 +364,172 @@ describe('MicrosoftEntraIDAuthHandler', () => { expect(getRecentEntraTokenFailure('cluster-1')).toBeUndefined(); }); + it.each([ + { + name: 'AzureChinaCloud', + activeDirectoryEndpointUrl: 'https://login.chinacloudapi.cn/', + }, + { + name: 'CustomCloud', + activeDirectoryEndpointUrl: 'https://login.microsoftonline.us/', + }, + ])( + 'rejects a sovereign cloud switch to $name before lookup even when the provider ID is unchanged', + async (environment): Promise => { + getConfiguredAuthProviderId.mockReturnValue('microsoft-sovereign-cloud'); + getConfiguredAzureEnv.mockReturnValue({ + name: 'AzureUSGovernment', + activeDirectoryEndpointUrl: 'https://login.microsoftonline.us/', + }); + const { options } = await new MicrosoftEntraIDAuthHandler( + buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.us/'), + ).configureAuth(); + getConfiguredAzureEnv.mockReturnValue(environment); + + await expect( + options.authMechanismProperties!.OIDC_CALLBACK!({ + version: 1, + timeoutContext: new AbortController().signal, + }), + ).rejects.toMatchObject({ name: 'EntraSignInRequiredError', reason: 'providerChanged' }); + expect(getSessionFromVSCode).toHaveBeenCalledOnce(); + expect(getRecentEntraTokenFailure('cluster-1')).toBeUndefined(); + }, + ); + + it.each(['returns', 'rejects'] as const)( + 'rejects same-cloud authority path drift when the silent lookup %s', + async (lookupOutcome): Promise => { + getConfiguredAuthProviderId.mockReturnValue('microsoft-sovereign-cloud'); + getConfiguredAzureEnv.mockReturnValue({ + name: 'CustomCloud', + activeDirectoryEndpointUrl: 'https://authority.example.com/original/', + }); + const onTokenLookup = vi.fn(); + const { options } = await new MicrosoftEntraIDAuthHandler( + buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'), + { interactive: true, onTokenLookup }, + ).configureAuth(); + recordEntraTokenFailure('cluster-1', { cloudCategory: 'custom', authMethod: 'interactive' }); + const priorFailure = getRecentEntraTokenFailure('cluster-1'); + getSessionFromVSCode.mockImplementationOnce(async () => { + getConfiguredAzureEnv.mockReturnValue({ + name: 'CustomCloud', + activeDirectoryEndpointUrl: 'https://authority.example.com/changed/', + }); + if (lookupOutcome === 'rejects') { + throw new Error('AADSTS65002: private-lookup-cause'); + } + return { ...session, accessToken: 'mismatched-token' }; + }); + + const result = options.authMechanismProperties!.OIDC_CALLBACK!({ + version: 1, + timeoutContext: new AbortController().signal, + }); + await expect(result).rejects.toMatchObject({ name: 'EntraSignInRequiredError', reason: 'providerChanged' }); + await expect(result).rejects.not.toHaveProperty('cause'); + expect(getSessionFromVSCode).toHaveBeenCalledTimes(2); + expect(getRecentEntraTokenFailure('cluster-1')).toBe(priorFailure); + expect(onTokenLookup.mock.calls).toEqual([[{ outcome: 'noSession' }]]); + const logs = JSON.stringify([mockOutputChannel.info.mock.calls, mockOutputChannel.error.mock.calls]); + expect(logs).not.toMatch(/authority\.example\.com|mismatched-token|private-lookup-cause|AADSTS65002/); + }, + ); + + it.each(['before', 'after'] as const)( + 'treats an unreadable environment %s the silent lookup as controlled drift', + async (when): Promise => { + const { options } = await new MicrosoftEntraIDAuthHandler( + buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'), + ).configureAuth(); + const makeEnvironmentUnreadable = (): void => { + getConfiguredAzureEnv.mockImplementationOnce(() => { + throw new Error('private-configuration-cause'); + }); + }; + if (when === 'before') { + makeEnvironmentUnreadable(); + } else { + getSessionFromVSCode.mockImplementationOnce(async () => { + makeEnvironmentUnreadable(); + return session; + }); + } + + const result = options.authMechanismProperties!.OIDC_CALLBACK!({ + version: 1, + timeoutContext: new AbortController().signal, + }); + await expect(result).rejects.toMatchObject({ name: 'EntraSignInRequiredError', reason: 'providerChanged' }); + await expect(result).rejects.not.toHaveProperty('cause'); + expect(getSessionFromVSCode).toHaveBeenCalledTimes(when === 'before' ? 1 : 2); + expect(getRecentEntraTokenFailure('cluster-1')).toBeUndefined(); + const logs = JSON.stringify([mockOutputChannel.info.mock.calls, mockOutputChannel.error.mock.calls]); + expect(logs).not.toContain('private-configuration-cause'); + }, + ); + + it('does not request a session when the authority changes during resource resolution', async () => { + getConfiguredAuthProviderId.mockReturnValue('microsoft-sovereign-cloud'); + getConfiguredAzureEnv.mockReturnValue({ + name: 'CustomCloud', + activeDirectoryEndpointUrl: 'https://authority.example.com/original/', + }); + const resolveResource = vi.mocked(resolveInteractiveTokenResource); + const resolveWithoutDrift = resolveResource.getMockImplementation()!; + resolveResource.mockImplementationOnce(async (connectionString) => { + const resolved = await resolveWithoutDrift(connectionString); + getConfiguredAzureEnv.mockReturnValue({ + name: 'CustomCloud', + activeDirectoryEndpointUrl: 'https://authority.example.com/changed/', + }); + return resolved; + }); + + const handler = new MicrosoftEntraIDAuthHandler( + buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'), + ); + await expect(handler.configureAuth()).rejects.toMatchObject({ + name: 'EntraSignInRequiredError', + reason: 'providerChanged', + }); + expect(getSessionFromVSCode).not.toHaveBeenCalled(); + expect(getRecentEntraTokenFailure('cluster-1')).toBeUndefined(); + }); + + it.each([true, false])( + 'does not pin a session or change the prior failure if the initial lookup environment changes (interactive=%s)', + async (interactive): Promise => { + getConfiguredAuthProviderId.mockReturnValue('microsoft-sovereign-cloud'); + getConfiguredAzureEnv.mockReturnValue({ + name: 'AzureUSGovernment', + activeDirectoryEndpointUrl: 'https://login.microsoftonline.us/', + }); + recordEntraTokenFailure('cluster-1', { cloudCategory: 'usgov', authMethod: 'interactive' }); + const priorFailure = getRecentEntraTokenFailure('cluster-1'); + getSessionFromVSCode.mockImplementationOnce(async () => { + getConfiguredAzureEnv.mockReturnValue({ + name: 'AzureChinaCloud', + activeDirectoryEndpointUrl: 'https://login.chinacloudapi.cn/', + }); + return session; + }); + const onTokenAcquired = vi.fn(); + const handler = new MicrosoftEntraIDAuthHandler( + buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.us/'), + { interactive, observer: { onTokenAcquired } }, + ); + + await expect(handler.configureAuth()).rejects.toMatchObject({ + name: 'EntraSignInRequiredError', + reason: 'providerChanged', + }); + expect(onTokenAcquired).not.toHaveBeenCalled(); + expect(getRecentEntraTokenFailure('cluster-1')).toBe(priorFailure); + }, + ); + it('wraps and records only an unexpected callback failure, without logging its cause', async () => { const onTokenLookup = vi.fn(); const { options } = await new MicrosoftEntraIDAuthHandler( diff --git a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts index a656d9082..14088c352 100644 --- a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts +++ b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts @@ -3,7 +3,6 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { getConfiguredAuthProviderId } from '@microsoft/vscode-azext-azureauth'; import * as l10n from '@vscode/l10n'; import { randomUUID } from 'crypto'; import { type OIDCCallbackParams, type OIDCResponse } from 'mongodb'; @@ -28,7 +27,7 @@ import { TokenCallbackError, } from './entraErrors/entraCallbackErrors'; import { clearEntraTokenFailure, recordEntraTokenFailure } from './entraErrors/entraTokenFailures'; -import { getEntraSession } from './entraSession'; +import { getEntraSession, readEntraSignInEnvironment, type EntraSignInEnvironment } from './entraSession'; import { EntraDestinationRejectedError } from './oidcAllowedHosts'; import { buildOidcClientConfiguration, createOidcDestinationPolicy } from './oidcClientOptions'; import { readJwtTimes } from './tokenExpiry'; @@ -42,6 +41,24 @@ interface EntraCallerPolicy extends AuthCallerPolicy { readonly onTokenLookup?: (observation: EntraTokenLookupObservation) => void; } +function assertEntraSignInEnvironment(expected: EntraSignInEnvironment | undefined): EntraSignInEnvironment { + let current: EntraSignInEnvironment; + try { + current = readEntraSignInEnvironment(); + } catch { + throw new EntraSignInRequiredError('providerChanged'); + } + if ( + !expected || + current.providerId !== expected.providerId || + current.cloudName !== expected.cloudName || + current.authority !== expected.authority + ) { + throw new EntraSignInRequiredError('providerChanged'); + } + return expected; +} + /** * Handler for Microsoft Entra ID authentication via OIDC. * @@ -71,6 +88,12 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { throw new EntraDestinationRejectedError(decision); } const policy = createOidcDestinationPolicy(connectionString, getEntraCustomHostnameSuffix); + let environmentBeforeResolution: EntraSignInEnvironment | undefined; + try { + environmentBeforeResolution = readEntraSignInEnvironment(); + } catch { + // Let resource resolution report invalid cloud configuration with its existing diagnostics. + } let resolved: Awaited>; try { resolved = await resolveInteractiveTokenResource(connectionString); @@ -102,22 +125,26 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { // caller looks up an existing session silently and never forces a new one. const interactive = this.policy.interactive; let session: vscode.AuthenticationSession | undefined; - let providerId: string; + let signInEnvironment: EntraSignInEnvironment; const resource = resolved.scope; this.notify((observer) => observer.onTokenStarted?.()); try { - ({ session, providerId } = await traceAuthOperation( + ({ session, signInEnvironment } = await traceAuthOperation( 'interactiveEntra.getSession', () => withTokenAcquisitionTiming(timings, async () => { - const providerId = getConfiguredAuthProviderId(); - const session = await getEntraSession({ - providerId, - resource, - tenantId, - mode: interactive ? 'interactive' : 'silent', - }); - return { session, providerId }; + const signInEnvironment = assertEntraSignInEnvironment(environmentBeforeResolution); + try { + const session = await getEntraSession({ + providerId: signInEnvironment.providerId, + resource, + tenantId, + mode: interactive ? 'interactive' : 'silent', + }); + return { session, signInEnvironment }; + } finally { + assertEntraSignInEnvironment(signInEnvironment); + } }), { tenantSpecified: !!tenantId, @@ -142,9 +169,8 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { throw new Error(l10n.t('Failed to obtain Entra ID token.')); } } catch (error) { - // A silent lookup without a session is not a token failure: recording it would change how - // the next real connect's error is explained. - if (!(error instanceof AuthInputUnavailableError)) { + // Missing input or configuration drift must not alter the next connect's failure context. + if (!(error instanceof AuthInputUnavailableError || error instanceof EntraSignInRequiredError)) { if (traceContext?.startupProperties) { traceContext.startupProperties.entraFailureKind = 'tokenAcquisitionFailed'; } @@ -161,6 +187,7 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { policy.assertAllowed(); clearEntraTokenFailure(clusterId); + const { providerId } = signInEnvironment; const { id: accountId, label: accountLabel } = session.account; const verifiedIdentity: VerifiedEntraIdentity = { kind: 'entra', @@ -189,13 +216,15 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { const currentInvocation = ++invocation; let observation: EntraTokenLookupObservation = { outcome: 'failed' }; try { - if (getConfiguredAuthProviderId() !== providerId) { - observation = { outcome: 'noSession' }; - throw new EntraSignInRequiredError('providerChanged'); + assertEntraSignInEnvironment(signInEnvironment); + let renewed: vscode.AuthenticationSession | undefined; + try { + renewed = await getEntraSession({ providerId, resource, tenantId, account, mode: 'silent' }); + } finally { + // Drift takes precedence even if the lookup rejects with an error from the new provider. + assertEntraSignInEnvironment(signInEnvironment); } - const renewed = await getEntraSession({ providerId, resource, tenantId, account, mode: 'silent' }); if (!renewed) { - observation = { outcome: 'noSession' }; throw new EntraSignInRequiredError('noSession'); } if (renewed.account.id !== accountId) { @@ -215,7 +244,11 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { ? { accessToken } : { accessToken, expiresInSeconds: Math.max(0, Math.floor(expSec - Date.now() / 1000)) }; } catch (error) { - if (observation.outcome === 'noSession' || observation.outcome === 'identityMismatch') { + if (error instanceof EntraSignInRequiredError) { + observation = { outcome: 'noSession' }; + throw error; + } + if (observation.outcome === 'identityMismatch') { throw error; } recordEntraTokenFailure(clusterId, { diff --git a/src/documentdb/auth/entraSession.ts b/src/documentdb/auth/entraSession.ts index d9a75c423..617a1cc8e 100644 --- a/src/documentdb/auth/entraSession.ts +++ b/src/documentdb/auth/entraSession.ts @@ -3,9 +3,22 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import { getConfiguredAuthProviderId, getConfiguredAzureEnv } from '@microsoft/vscode-azext-azureauth'; import * as vscode from 'vscode'; import { toEntraScope } from './entraScopes'; +export interface EntraSignInEnvironment { + readonly providerId: string; + readonly cloudName: string; + readonly authority?: string; +} + +export function readEntraSignInEnvironment(): EntraSignInEnvironment { + const providerId = getConfiguredAuthProviderId(); + const { name: cloudName, activeDirectoryEndpointUrl: authority } = getConfiguredAzureEnv(); + return { providerId, cloudName, authority }; +} + interface EntraSessionRequest { providerId: string; resource: string; From 7ed07bd1f2e722f2ebad8020713e6c3384aa38ea Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 10:42:06 +0000 Subject: [PATCH 037/380] fix: report the Entra callback acquisition in diagnostics (PR1-R2) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../checks/authenticate.test.ts | 203 +++++++++++++++++- .../checks/authenticate.ts | 106 ++++++--- .../auth/MicrosoftEntraIDAuthHandler.test.ts | 40 +++- .../auth/MicrosoftEntraIDAuthHandler.ts | 27 +++ src/documentdb/auth/authCallerPolicy.ts | 6 + 5 files changed, 352 insertions(+), 30 deletions(-) diff --git a/src/connectionDiagnostics/checks/authenticate.test.ts b/src/connectionDiagnostics/checks/authenticate.test.ts index ced8a5652..a3dbd7c6c 100644 --- a/src/connectionDiagnostics/checks/authenticate.test.ts +++ b/src/connectionDiagnostics/checks/authenticate.test.ts @@ -24,6 +24,7 @@ import { MongoServerSelectionError, type MongoClientOptions, type OIDCCallbackParams, + type OIDCResponse, type TopologyDescription, } from 'mongodb'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; @@ -32,6 +33,10 @@ import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; import { AuthInputUnavailableError } from '../../documentdb/auth/createAuthHandler'; import type * as documentdbTokenResource from '../../documentdb/auth/documentdbTokenResource'; import { type TokenResourceResolverDeps } from '../../documentdb/auth/documentdbTokenResource'; +import { + EntraIdentityMismatchError, + TokenCallbackError, +} from '../../documentdb/auth/entraErrors/entraCallbackErrors'; import type * as entraTokenFailures from '../../documentdb/auth/entraErrors/entraTokenFailures'; import { clearEntraTokenFailure, @@ -190,6 +195,14 @@ interface FakeClient { readonly close: ReturnType; } +function invokeOidcCallback(client: FakeClient): Promise { + const callback = client.options.authMechanismProperties?.OIDC_CALLBACK; + if (!callback) { + throw new Error('Missing OIDC callback'); + } + return callback({ version: 1, timeoutContext: new AbortController().signal }); +} + let connectBehavior: (client: FakeClient) => Promise; let clients: FakeClient[]; let tick: number; @@ -975,6 +988,148 @@ describe('createAuthenticateCheck', (): void => { expect(result.facts.authenticated).toBe(true); }); + it('replaces eager evidence with the latest callback claims without changing timing or accepting late events', async (): Promise => { + const account = { label: 'alice@contoso.example', id: 'account-id' }; + const mismatchedToken = entraToken({ aud: governmentResource, tid: 'different-tenant' }); + const callbackToken = entraToken({ ver: '1.0' }); + mocks.getSessionFromVSCode + .mockResolvedValue({ accessToken: mismatchedToken, account }) + .mockResolvedValueOnce({ accessToken: mismatchedToken, account }) + .mockResolvedValueOnce({ accessToken: mismatchedToken, account }) + .mockResolvedValueOnce({ accessToken: callbackToken, account }); + connectBehavior = async (client): Promise => { + await expect(invokeOidcCallback(client)).resolves.toMatchObject({ accessToken: mismatchedToken }); + await expect(invokeOidcCallback(client)).resolves.toMatchObject({ accessToken: callbackToken }); + }; + const deps = fakeDeps(); + const now = vi.fn(deps.now); + const { result, events, telemetry } = await runAuth( + setupFor(AuthMethodId.MicrosoftEntraID, publicHost, { entraIdConfig: { tenantId: tenant } }), + { deps: { ...deps, now } }, + ); + expect(result.status).toBe('pass'); + const token = step(result, 'auth.token'); + expect(token).toMatchObject({ + status: 'pass', + durationMs: 10, + facts: { claims: { tokenVersion: '1.0', audience: 'match', tenantMatch: 'match' } }, + }); + expect(token.findings).toEqual([]); + const snapshots = JSON.stringify([result, events, telemetry]); + const clockCalls = now.mock.calls.length; + await expect(invokeOidcCallback(clients[0])).resolves.toMatchObject({ accessToken: mismatchedToken }); + expect(now).toHaveBeenCalledTimes(clockCalls); + expect(JSON.stringify([result, events, telemetry])).toBe(snapshots); + for (const secret of [callbackToken, callbackToken.split('.')[1], claimSentinel]) { + expect(snapshots + outputLines().join('\n')).not.toContain(secret); + } + }); + + it.each(['callback noSession', 'initial providerChanged'] as const)( + 'skips unavailable Entra input on %s without recording authError', + async (kind): Promise => { + if (kind === 'callback noSession') { + mocks.getSessionFromVSCode + .mockResolvedValueOnce({ + accessToken: entraToken({ aud: governmentResource }), + account: { label: 'alice@contoso.example', id: 'account-id' }, + }) + .mockResolvedValueOnce(undefined); + connectBehavior = async (client): Promise => { + await invokeOidcCallback(client); + }; + } else { + mocks.getSessionFromVSCode.mockImplementationOnce(async () => { + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ + get: vi.fn((name: string): string | undefined => + name === 'environment' ? 'USGovernment' : undefined, + ), + inspect: vi.fn().mockReturnValue(undefined), + } as unknown as vscode.WorkspaceConfiguration); + return { accessToken: entraToken(), account: { label: 'alice@contoso.example', id: 'account-id' } }; + }); + } + const { result, holder } = await runAuth(setupFor(AuthMethodId.MicrosoftEntraID, publicHost)); + expect(clients).toHaveLength(kind === 'callback noSession' ? 1 : 0); + expect(holder.authError).toBeUndefined(); + expect(holder.client).toBeUndefined(); + expect(result).toMatchObject({ + status: 'skipped', + skippedBecause: { reason: 'inputUnavailable' }, + facts: { signInLimitation: 'silentLookupCannotDistinguishConsent', authenticated: false }, + }); + expect(result.facts.account).toBeUndefined(); + expect(codes(result)).toEqual(['auth.credentialsUnavailable']); + expect(step(result, 'auth.token')).toMatchObject({ + status: 'skipped', + skippedBecause: { reason: 'inputUnavailable' }, + }); + expect(step(result, 'auth.token').facts).toEqual({}); + expect(step(result, 'auth.token').findings).toEqual([]); + expect(step(result, 'auth.serverAuthentication')).toMatchObject({ + status: 'skipped', + skippedBecause: { reason: 'dependencySkipped', stepId: 'auth.token' }, + }); + expect(recordEntraTokenFailure).not.toHaveBeenCalled(); + }, + ); + + it.each([ + [TokenCallbackError, 'resourceNotInTenant', '500011'], + [EntraIdentityMismatchError, 'unclassified', undefined], + ] as const)( + 'replaces eager evidence for callback-only %s with bounded token failure evidence', + async (errorType, ruleId, aadstsCode): Promise => { + const accessToken = entraToken({ aud: governmentResource }); + mocks.getSessionFromVSCode.mockResolvedValueOnce({ + accessToken, + account: { label: 'alice@contoso.example', id: 'account-id' }, + }); + if (errorType === TokenCallbackError) { + mocks.getSessionFromVSCode.mockRejectedValueOnce(new Error(`AADSTS500011: ${errorSentinel}`)); + } else { + mocks.getSessionFromVSCode.mockResolvedValueOnce({ + accessToken, + account: { label: errorSentinel, id: 'different-account' }, + }); + } + connectBehavior = async (client): Promise => { + await invokeOidcCallback(client); + }; + const { result, holder, events, telemetry } = await runAuth( + setupFor(AuthMethodId.MicrosoftEntraID, publicHost), + ); + expect(holder.authError).toBeInstanceOf(errorType); + expect(holder.client).toBeUndefined(); + expect(result).toMatchObject({ status: 'fail', facts: { authenticated: false } }); + expect(result.facts.account).toBeUndefined(); + const token = step(result, 'auth.token'); + expect(token).toMatchObject({ + status: 'fail', + facts: { errorName: errorType.name, ruleId }, + }); + expect(token.facts.claims).toBeUndefined(); + expect(token.facts.aadstsCode).toBe(aadstsCode); + expect(token.findings).toEqual([ + expect.objectContaining({ + code: 'auth.entraTokenFailed', + data: { + ruleId, + ...(aadstsCode === undefined ? {} : { aadstsCode }), + authMethod: AuthMethodId.MicrosoftEntraID, + }, + }), + ]); + const server = step(result, 'auth.serverAuthentication'); + expect(server.status).toBe('fail'); + expect(server.findings).toEqual([]); + expect(result.findings).toEqual([]); + expect(JSON.stringify([result, events, telemetry]) + outputLines().join('\n')).not.toContain( + errorSentinel, + ); + }, + ); + it('never claims acceptance when the token succeeds and the server rejects it', async (): Promise => { connectBehavior = (): Promise => Promise.reject( @@ -982,7 +1137,11 @@ describe('createAuthenticateCheck', (): void => { ); const { result, holder } = await runAuth(setupFor(AuthMethodId.MicrosoftEntraID, publicHost)); expect(result).toMatchObject({ status: 'fail', facts: { authenticated: false } }); - expect(step(result, 'auth.token').status).toBe('pass'); + expect(step(result, 'auth.token')).toMatchObject({ + status: 'pass', + facts: { claims: { available: true, audience: 'match', tokenVersion: '2.0' } }, + }); + expect(mocks.getSessionFromVSCode).toHaveBeenCalledOnce(); const server = step(result, 'auth.serverAuthentication'); expect(server).toMatchObject({ status: 'fail', @@ -1154,6 +1313,48 @@ describe('createAuthenticateCheck', (): void => { }); describe('owned client lifetime', (): void => { + it('does not summarize a callback lookup that completes after cancellation while connect is pending', async (): Promise => { + const controller = new AbortController(); + const lookup = pending(); + const startedLookup = pending(); + const finishedCallback = pending(); + const connection = pending(); + mocks.getSessionFromVSCode.mockImplementationOnce(async () => ({ + accessToken: entraToken(), + account: { label: 'alice@contoso.example', id: 'account-id' }, + })); + mocks.getSessionFromVSCode.mockImplementationOnce(() => { + startedLookup.resolve(); + return lookup.promise; + }); + connectBehavior = async (client): Promise => { + try { + await invokeOidcCallback(client); + } finally { + finishedCallback.resolve(); + } + await connection.promise; + }; + const deps = fakeDeps(); + const now = vi.fn(deps.now); + const running = runAuth(setupFor(AuthMethodId.MicrosoftEntraID, publicHost), { + signal: controller.signal, + deps: { ...deps, now }, + }); + await startedLookup.promise; + controller.abort(); + await expect(running).rejects.toBeInstanceOf(DiagnosticsCancelledError); + const clockCalls = now.mock.calls.length; + lookup.resolve({ + accessToken: entraToken({ ver: '1.0' }), + account: { label: 'alice@contoso.example', id: 'account-id' }, + }); + await finishedCallback.promise; + expect(now).toHaveBeenCalledTimes(clockCalls); + connection.resolve(); + await flush(); + }); + it('closes a client that finishes connecting after the run timed out, and never publishes it', async (): Promise => { const connection = pending(); connectBehavior = (): Promise => connection.promise; diff --git a/src/connectionDiagnostics/checks/authenticate.ts b/src/connectionDiagnostics/checks/authenticate.ts index dba4f41cb..cd2c36426 100644 --- a/src/connectionDiagnostics/checks/authenticate.ts +++ b/src/connectionDiagnostics/checks/authenticate.ts @@ -30,6 +30,7 @@ import { } from '../../documentdb/auth/createAuthHandler'; import { TokenResourceResolutionError } from '../../documentdb/auth/documentdbTokenResource'; import { classifyEntraError } from '../../documentdb/auth/entraErrors/classifyEntraError'; +import { EntraSignInRequiredError } from '../../documentdb/auth/entraErrors/entraCallbackErrors'; import { getRecentEntraTokenFailure } from '../../documentdb/auth/entraErrors/entraTokenFailures'; import { getCloudForTokenResource } from '../../documentdb/auth/entraScopes'; import { @@ -130,6 +131,8 @@ const knownErrorNames: ReadonlySet = new Set([ 'UserCancelledError', 'TokenResourceResolutionError', 'AuthInputUnavailableError', + 'EntraIdentityMismatchError', + 'TokenCallbackError', 'CredentialUnavailableError', 'AuthenticationRequiredError', 'AggregateAuthenticationError', @@ -211,13 +214,21 @@ class AuthSteps { record.findings.push(...findings); } - /** Overrides an already recorded result, for a phase whose failure becomes known later. */ - public replace(id: AuthStepId, status: CheckStatus, findings: readonly Finding[]): void { + /** Replaces a phase's evidence without changing its original timing. */ + public replace( + id: AuthStepId, + status: CheckStatus, + facts: Facts, + findings: readonly Finding[], + skippedBecause?: StepRecord['skippedBecause'], + ): void { const record = this.get(id); record.startedAt ??= this.now(); record.finishedAt ??= this.now(); record.status = status; - record.findings.push(...findings); + record.skippedBecause = skippedBecause; + record.facts = facts; + record.findings = [...findings]; } public skip(id: AuthStepId, reason: SkipReason, stepId?: AuthStepId): void { @@ -320,6 +331,31 @@ export function createAuthenticateCheck( const timings = new ConnectionStartupTimings(); let requestedResource = ''; let tokenFailed = false; + let observingCallbackToken = false; + let callbackInputUnavailable = false; + + function summarizeAcquisition( + info: { readonly accessToken: string; readonly tenantId?: string }, + ): [status: 'pass' | 'warning', facts: Facts, findings: Finding[]] { + const claims = summarizeTokenClaims( + info.accessToken, + { requestedResource, configuredTenantId: info.tenantId }, + deps.now(), + ); + const findings = claimFindings(claims); + return [findings.length > 0 ? 'warning' : 'pass', { claims }, findings]; + } + + function summarizeTokenFailure(error: unknown): [status: 'fail', facts: Facts, findings: Finding[]] { + const classification = classifyEntraError(errorMessages(error)); + const ruleId = classification?.ruleId ?? 'unclassified'; + const aadstsCode = classification?.code; + return [ + 'fail', + { ...errorFacts(error), ruleId, ...(aadstsCode === undefined ? {} : { aadstsCode }) }, + [entraTokenFailedFinding(ruleId, aadstsCode, method)], + ]; + } const observer: AuthPhaseObserver = { onSignInConfigurationResolved(info): void { @@ -338,32 +374,33 @@ export function createAuthenticateCheck( }, onTokenAcquired(info): void { // The token is summarized here and never stored; only the allowlisted summary remains. - const claims = summarizeTokenClaims( - info.accessToken, - { requestedResource, configuredTenantId: info.tenantId }, - deps.now(), - ); if (info.account?.label) { facts.account = info.account.label; } - const findings = claimFindings(claims); - steps?.finish('auth.token', findings.length > 0 ? 'warning' : 'pass', { claims }, findings); + steps?.finish('auth.token', ...summarizeAcquisition(info)); }, onTokenFailed(error): void { - if (error instanceof AuthInputUnavailableError) { + if (error instanceof AuthInputUnavailableError || error instanceof EntraSignInRequiredError) { steps?.finish('auth.token', 'skipped', {}, [], { reason: 'inputUnavailable' }); return; } tokenFailed = true; - const classification = classifyEntraError(errorMessages(error)); - const ruleId = classification?.ruleId ?? 'unclassified'; - const aadstsCode = classification?.code; - steps?.finish( - 'auth.token', - 'fail', - { ...errorFacts(error), ruleId, ...(aadstsCode === undefined ? {} : { aadstsCode }) }, - [entraTokenFailedFinding(ruleId, aadstsCode, method)], - ); + steps?.finish('auth.token', ...summarizeTokenFailure(error)); + }, + onCallbackTokenObserved(observation): void { + if (!observingCallbackToken || signal.aborted) { + return; + } + callbackInputUnavailable = + observation.outcome === 'failed' && observation.error instanceof EntraSignInRequiredError; + tokenFailed = observation.outcome === 'failed' && !callbackInputUnavailable; + if (observation.outcome === 'acquired') { + steps?.replace('auth.token', ...summarizeAcquisition(observation)); + } else if (callbackInputUnavailable) { + steps?.replace('auth.token', 'skipped', {}, [], { reason: 'inputUnavailable' }); + } else { + steps?.replace('auth.token', ...summarizeTokenFailure(observation.error)); + } }, }; @@ -380,6 +417,9 @@ export function createAuthenticateCheck( status: CheckStatus; findings?: Finding[]; }): CheckOutcome => { + if (tokenFailed && method === AuthMethodId.MicrosoftEntraID) { + delete facts.account; + } const costs = timings.finish(); if (costs.tokenAcquireDurationMs !== undefined) { facts.tokenMs = Math.round(costs.tokenAcquireDurationMs); @@ -419,8 +459,9 @@ export function createAuthenticateCheck( const handler = createAuthHandler(method, credentials, { interactive: false, observer }); configured = await handler.configureAuth(timings, traceContext); } catch (error) { - if (error instanceof AuthInputUnavailableError) { - return finish(inputUnavailable(error.missing, method, steps, facts)); + if (error instanceof AuthInputUnavailableError || error instanceof EntraSignInRequiredError) { + const missing = error instanceof AuthInputUnavailableError ? error.missing : 'entraSession'; + return finish(inputUnavailable(missing, method, steps, facts)); } getRunOwnedClient().authError = error; if (isEntraDestinationRejectedError(error)) { @@ -491,12 +532,20 @@ export function createAuthenticateCheck( signal.addEventListener('abort', onAbort, { once: true }); const stopDatabaseConnect = timings.startDatabaseConnect(); try { + observingCallbackToken = true; await ownedClient.connect(); } finally { + observingCallbackToken = false; stopDatabaseConnect(); signal.removeEventListener('abort', onAbort); } } catch (error) { + if (method === AuthMethodId.MicrosoftEntraID && signal.aborted) { + return finish({ status: 'fail' }); + } + if (callbackInputUnavailable) { + return finish(inputUnavailable('entraSession', method, steps, facts)); + } if (!(error instanceof AuthInputUnavailableError)) getRunOwnedClient().authError = error; failure ??= { error, phase: 'connect' }; return finish(connectFailure(error, client, options, seedAddresses(context, driverConnectionString))); @@ -507,6 +556,9 @@ export function createAuthenticateCheck( await client.close().catch((): void => undefined); return finish({ status: 'fail' }); } + if (callbackInputUnavailable) { + return finish(inputUnavailable('entraSession', method, steps, facts)); + } getRunOwnedClient().client = client; steps?.finish('auth.serverAuthentication', 'pass'); facts.authenticated = method !== AuthMethodId.NoAuth; @@ -535,8 +587,11 @@ export function createAuthenticateCheck( "Microsoft Entra ID isn't allowed for this server.", ); if (steps) { - steps.replace('auth.signInConfiguration', 'fail', [finding]); - steps.get('auth.signInConfiguration').facts.allHostsAllowed = false; + const signIn = steps.get('auth.signInConfiguration'); + steps.replace('auth.signInConfiguration', 'fail', { ...signIn.facts, allHostsAllowed: false }, [ + ...signIn.findings, + finding, + ]); steps.skip('auth.serverAuthentication', 'dependencyFailed', 'auth.signInConfiguration'); return { status: 'fail' }; } @@ -636,6 +691,7 @@ export function createAuthenticateCheck( facts: Facts, ): { status: CheckStatus; findings: Finding[] } { if (missing === 'entraSession') { + delete facts.account; // The silent lookup cannot tell "not signed in" from a consent or preauthorization // failure; an earlier recorded failure is evidence only and never changes the outcome. facts.signInLimitation = 'silentLookupCannotDistinguishConsent'; @@ -647,7 +703,7 @@ export function createAuthenticateCheck( ...(earlier.ruleId === undefined ? {} : { ruleId: earlier.ruleId }), }; } - steps?.finish('auth.token', 'skipped', {}, [], { reason: 'inputUnavailable' }); + steps?.replace('auth.token', 'skipped', {}, [], { reason: 'inputUnavailable' }); steps?.skip('auth.serverAuthentication', 'dependencySkipped', 'auth.token'); } facts.authenticated = false; diff --git a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts index 29d5f218b..e5b925c6e 100644 --- a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts +++ b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts @@ -294,12 +294,14 @@ describe('MicrosoftEntraIDAuthHandler', () => { it('rechecks destination trust after a silent lookup, before returning its token', async () => { let suffix: string | undefined = 'database.example.com'; + const onCallbackTokenObserved = vi.fn(); vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ get: vi.fn(), inspect: vi.fn(() => ({ globalValue: { hostnameSuffix: suffix } })), } as unknown as vscode.WorkspaceConfiguration); const { options } = await new MicrosoftEntraIDAuthHandler( buildCredentials('mongodb://cluster.database.example.com/'), + { interactive: false, observer: { onCallbackTokenObserved } }, ).configureAuth(); getSessionFromVSCode.mockImplementationOnce(async () => { suffix = undefined; @@ -312,6 +314,7 @@ describe('MicrosoftEntraIDAuthHandler', () => { }), ).rejects.toBeInstanceOf(EntraDestinationRejectedError); expect(getSessionFromVSCode).toHaveBeenCalledTimes(2); + expect(onCallbackTokenObserved).not.toHaveBeenCalled(); }); it('does not reject or repeat a lookup based on the token expiration claim', async () => { @@ -335,9 +338,10 @@ describe('MicrosoftEntraIDAuthHandler', () => { ['identityMismatch', 'identityMismatch', EntraIdentityMismatchError], ] as const)('rejects %s without prompting or recording a token failure', async (failure, outcome, errorType) => { const onTokenLookup = vi.fn(); + const onCallbackTokenObserved = vi.fn>(); const { options } = await new MicrosoftEntraIDAuthHandler( buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'), - { interactive: true, onTokenLookup }, + { interactive: true, onTokenLookup, observer: { onCallbackTokenObserved } }, ).configureAuth(); if (failure === 'providerChanged') { getConfiguredAuthProviderId.mockReturnValue('microsoft-sovereign-cloud'); @@ -351,6 +355,10 @@ describe('MicrosoftEntraIDAuthHandler', () => { timeoutContext: new AbortController().signal, }); await expect(result).rejects.toBeInstanceOf(errorType); + expect(onCallbackTokenObserved).toHaveBeenCalledOnce(); + const observed = onCallbackTokenObserved.mock.lastCall?.[0]; + expect(observed?.outcome).toBe('failed'); + await expect(result).rejects.toBe(observed?.outcome === 'failed' ? observed.error : undefined); if (failure !== 'identityMismatch') { await expect(result).rejects.toMatchObject({ reason: failure }); } @@ -532,9 +540,10 @@ describe('MicrosoftEntraIDAuthHandler', () => { it('wraps and records only an unexpected callback failure, without logging its cause', async () => { const onTokenLookup = vi.fn(); + const onCallbackTokenObserved = vi.fn>(); const { options } = await new MicrosoftEntraIDAuthHandler( buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'), - { interactive: true, onTokenLookup }, + { interactive: true, onTokenLookup, observer: { onCallbackTokenObserved } }, ).configureAuth(); const cause = new Error('AADSTS65002: private-cause'); getSessionFromVSCode.mockRejectedValueOnce(cause); @@ -545,6 +554,10 @@ describe('MicrosoftEntraIDAuthHandler', () => { }); await expect(result).rejects.toBeInstanceOf(TokenCallbackError); await expect(result).rejects.toMatchObject({ authMethod: AuthMethodId.MicrosoftEntraID, cause }); + expect(onCallbackTokenObserved).toHaveBeenCalledOnce(); + const observed = onCallbackTokenObserved.mock.lastCall?.[0]; + expect(observed?.outcome).toBe('failed'); + await expect(result).rejects.toBe(observed?.outcome === 'failed' ? observed.error : undefined); expect(getRecentEntraTokenFailure('cluster-1')).toMatchObject({ authMethod: 'interactive', ruleId: 'firstPartyPreauthorization', @@ -1031,6 +1044,7 @@ describe('MicrosoftEntraIDAuthHandler', () => { }); const events: string[] = []; const acquired: unknown[] = []; + const onCallbackTokenObserved = vi.fn(); const observer = recordingObserver(events); const handler = new MicrosoftEntraIDAuthHandler( buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'), @@ -1038,6 +1052,7 @@ describe('MicrosoftEntraIDAuthHandler', () => { interactive: false, observer: { ...observer, + onCallbackTokenObserved, onTokenStarted: () => { expect(getSessionFromVSCode).not.toHaveBeenCalled(); observer.onTokenStarted?.(); @@ -1050,7 +1065,18 @@ describe('MicrosoftEntraIDAuthHandler', () => { }, ); - await handler.configureAuth(); + const { options } = await handler.configureAuth(); + expect(onCallbackTokenObserved).not.toHaveBeenCalled(); + getSessionFromVSCode.mockResolvedValueOnce({ ...session, accessToken: 'callback-token' }); + await expect( + options.authMechanismProperties!.OIDC_CALLBACK!({ + version: 1, + timeoutContext: new AbortController().signal, + }), + ).resolves.toEqual({ accessToken: 'callback-token' }); + expect(onCallbackTokenObserved.mock.calls).toEqual([ + [{ outcome: 'acquired', accessToken: 'callback-token', tenantId: 'tenant' }], + ]); expect(events).toEqual([ 'resolved:*.mongocluster.cosmos.azure.com', @@ -1064,7 +1090,7 @@ describe('MicrosoftEntraIDAuthHandler', () => { tenantId: 'tenant', }, ]); - expect(JSON.stringify(mockOutputChannel.info.mock.calls)).not.toContain('access-token'); + expect(JSON.stringify(mockOutputChannel.info.mock.calls)).not.toMatch(/access-token|callback-token/); }); it('passes the resolver details and reason to the observer', async () => { @@ -1133,6 +1159,7 @@ describe('MicrosoftEntraIDAuthHandler', () => { onTokenStarted: throwing, onTokenAcquired: throwing, onTokenFailed: throwing, + onCallbackTokenObserved: throwing, }; const credentials = buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'); const expected = await new MicrosoftEntraIDAuthHandler(credentials, { interactive }).configureAuth(); @@ -1146,6 +1173,11 @@ describe('MicrosoftEntraIDAuthHandler', () => { expect(result.options.authMechanismProperties?.ALLOWED_HOSTS).toEqual( expected.options.authMechanismProperties?.ALLOWED_HOSTS, ); + const callback = result.options.authMechanismProperties!.OIDC_CALLBACK!; + const params = { version: 1, timeoutContext: new AbortController().signal } as const; + await expect(callback(params)).resolves.toEqual({ accessToken: session.accessToken }); + getSessionFromVSCode.mockResolvedValueOnce(undefined); + await expect(callback(params)).rejects.toBeInstanceOf(EntraSignInRequiredError); const error = new Error('token request failed'); getSessionFromVSCode.mockRejectedValueOnce(error); diff --git a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts index 14088c352..f004d560e 100644 --- a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts +++ b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts @@ -275,6 +275,33 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { } }, }); + const properties = configuration.options.authMechanismProperties; + const callback = properties?.OIDC_CALLBACK; + if (this.policy.observer?.onCallbackTokenObserved && properties && callback) { + properties.OIDC_CALLBACK = async (params): Promise => { + try { + // Report acquisition only after the configured callback re-checks destination trust. + const response = await callback(params); + this.notify((observer) => + observer.onCallbackTokenObserved?.({ + outcome: 'acquired', + accessToken: response.accessToken, + tenantId, + }), + ); + return response; + } catch (error) { + if ( + error instanceof EntraSignInRequiredError || + error instanceof EntraIdentityMismatchError || + error instanceof TokenCallbackError + ) { + this.notify((observer) => observer.onCallbackTokenObserved?.({ outcome: 'failed', error })); + } + throw error; + } + }; + } if (configuration.ignoredTlsBypass || this.clusterCredentials.emulatorConfiguration?.disableEmulatorSecurity) { ext.outputChannel.info( l10n.t('[Auth] TLS validation bypass parameters are ignored for Microsoft Entra ID connections.'), diff --git a/src/documentdb/auth/authCallerPolicy.ts b/src/documentdb/auth/authCallerPolicy.ts index 3aa76ad3e..52b1e5764 100644 --- a/src/documentdb/auth/authCallerPolicy.ts +++ b/src/documentdb/auth/authCallerPolicy.ts @@ -27,6 +27,12 @@ export interface AuthPhaseObserver { readonly tenantId?: string; }): void; onTokenFailed?(error: unknown): void; + /** Host-only: summarize callback tokens immediately; never store or log them. */ + onCallbackTokenObserved?( + observation: + | { readonly outcome: 'acquired'; readonly accessToken: string; readonly tenantId?: string } + | { readonly outcome: 'failed'; readonly error: unknown }, + ): void; } /** From ab01ea15b2f1e59dc9bc65db1fdb6efca649c05f Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 10:42:19 +0000 Subject: [PATCH 038/380] docs: record PR1 review follow-up decisions and checks Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iterations/01-pr1-entra-renewal-review.md | 22 +++++++++++++------ 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1-entra-renewal-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1-entra-renewal-review.md index 13a88c1e8..97b73fe7f 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1-entra-renewal-review.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1-entra-renewal-review.md @@ -67,14 +67,22 @@ and its formatting check then passed. No runtime code changed in that follow-up. write startup telemetry. The advisor (`claude-opus-5.5`, 80% confidence) recommended classifying the error at the existing startup boundary; the leader applied that recommendation directly. Build and 79 focused tests passed, including three new cases. [Thread reply](https://github.com/microsoft/vscode-documentdb/pull/1108#discussion_r4641033663). -- **R1, pending operator approval:** Pin the effective cloud and authority before and after the - silent lookup, including when the provider ID does not change. -- **R2, pending operator decision:** The advisor recommends reusing the initially verified token - once, which amends decision 0001. The alternative keeps the silent lookup on every callback and - makes diagnostics observe the result actually sent to the server. -- **R4, pending wording approval:** Use an account-mismatch explanation that tells the user to - sign in with the account originally used for the connection. +- **R1, done in `98be5f18e`:** The operator approved pinning the effective cloud and authority. + The handler checks that snapshot before acquisition, after acquisition, and around silent + lookups. The snapshot also covers the wait for token-resource resolution. The advisor + (`claude-opus-5.5`, 85% confidence) approved the revised guard. Build and 137 focused tests passed. + [Thread reply](https://github.com/microsoft/vscode-documentdb/pull/1108#discussion_r4641386918). +- **R2, done in `7ed07bd1f`:** The operator kept decision 0001: every callback does a silent + lookup. Diagnostics now reports the callback acquisition that supplies the token to the driver, + or reports an acquisition failure instead of keeping the earlier token facts. Late callbacks + cannot change a finished report. `claude-opus-5.5` approved the implementation at 85% confidence. + Build and 213 focused tests passed for the review fixes. +- **R4, done in `897329a8f`:** The operator approved the actionable account-mismatch heading. It + tells users to sign in with the account originally used for the connection. The error detail + is unchanged. Localization was regenerated and 16 focused tests passed. + [Thread reply](https://github.com/microsoft/vscode-documentdb/pull/1108#discussion_r4641336633). - **R5, deferred to WI-5:** The advisor (`claude-opus-5.5`, 85% confidence) verified from the pinned driver's source that plain callback errors are not stored in per-server descriptions. They reach the caller directly, where the existing cause traversal can explain them. WI-5 carries forward the driver check and the shared explanation path if needed; PR1 does not add a second traversal. + The operator confirmed this deferral. From d6c4efc55b258b302189da664c25b7e8df83cd40 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 11:21:11 +0000 Subject: [PATCH 039/380] chore: format PR1 Entra review fixes Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/connectionDiagnostics/checks/authenticate.test.ts | 10 +++++----- src/connectionDiagnostics/checks/authenticate.ts | 11 +++++++---- .../auth/MicrosoftEntraIDAuthHandler.test.ts | 5 ++++- 3 files changed, 16 insertions(+), 10 deletions(-) diff --git a/src/connectionDiagnostics/checks/authenticate.test.ts b/src/connectionDiagnostics/checks/authenticate.test.ts index a3dbd7c6c..e9b07d38a 100644 --- a/src/connectionDiagnostics/checks/authenticate.test.ts +++ b/src/connectionDiagnostics/checks/authenticate.test.ts @@ -33,10 +33,7 @@ import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; import { AuthInputUnavailableError } from '../../documentdb/auth/createAuthHandler'; import type * as documentdbTokenResource from '../../documentdb/auth/documentdbTokenResource'; import { type TokenResourceResolverDeps } from '../../documentdb/auth/documentdbTokenResource'; -import { - EntraIdentityMismatchError, - TokenCallbackError, -} from '../../documentdb/auth/entraErrors/entraCallbackErrors'; +import { EntraIdentityMismatchError, TokenCallbackError } from '../../documentdb/auth/entraErrors/entraCallbackErrors'; import type * as entraTokenFailures from '../../documentdb/auth/entraErrors/entraTokenFailures'; import { clearEntraTokenFailure, @@ -1046,7 +1043,10 @@ describe('createAuthenticateCheck', (): void => { ), inspect: vi.fn().mockReturnValue(undefined), } as unknown as vscode.WorkspaceConfiguration); - return { accessToken: entraToken(), account: { label: 'alice@contoso.example', id: 'account-id' } }; + return { + accessToken: entraToken(), + account: { label: 'alice@contoso.example', id: 'account-id' }, + }; }); } const { result, holder } = await runAuth(setupFor(AuthMethodId.MicrosoftEntraID, publicHost)); diff --git a/src/connectionDiagnostics/checks/authenticate.ts b/src/connectionDiagnostics/checks/authenticate.ts index cd2c36426..74e9d32b5 100644 --- a/src/connectionDiagnostics/checks/authenticate.ts +++ b/src/connectionDiagnostics/checks/authenticate.ts @@ -334,9 +334,10 @@ export function createAuthenticateCheck( let observingCallbackToken = false; let callbackInputUnavailable = false; - function summarizeAcquisition( - info: { readonly accessToken: string; readonly tenantId?: string }, - ): [status: 'pass' | 'warning', facts: Facts, findings: Finding[]] { + function summarizeAcquisition(info: { + readonly accessToken: string; + readonly tenantId?: string; + }): [status: 'pass' | 'warning', facts: Facts, findings: Finding[]] { const claims = summarizeTokenClaims( info.accessToken, { requestedResource, configuredTenantId: info.tenantId }, @@ -346,7 +347,9 @@ export function createAuthenticateCheck( return [findings.length > 0 ? 'warning' : 'pass', { claims }, findings]; } - function summarizeTokenFailure(error: unknown): [status: 'fail', facts: Facts, findings: Finding[]] { + function summarizeTokenFailure( + error: unknown, + ): [status: 'fail', facts: Facts, findings: Finding[]] { const classification = classifyEntraError(errorMessages(error)); const ruleId = classification?.ruleId ?? 'unclassified'; const aadstsCode = classification?.code; diff --git a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts index e5b925c6e..d95ac2972 100644 --- a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts +++ b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts @@ -11,7 +11,10 @@ import type * as documentdbTokenResource from './documentdbTokenResource'; const getSessionFromVSCode = vi.fn(); const getConfiguredAuthProviderId = vi.fn<() => string>(); -type AzureSignInSettings = Pick, 'name' | 'activeDirectoryEndpointUrl'>; +type AzureSignInSettings = Pick< + ReturnType, + 'name' | 'activeDirectoryEndpointUrl' +>; const getConfiguredAzureEnv = vi.fn<() => AzureSignInSettings>(); const account = { id: 'account-id', label: 'account-label' }; const session = { accessToken: 'access-token', account }; From 0b4fbed6543693756d648cb1150f0dd6eab811bc Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 11:30:46 +0000 Subject: [PATCH 040/380] docs: record Azure Discovery migration decision gates Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iterations/01-dev-plan.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index 0d96069f9..c82c1a146 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 @@ -867,6 +867,22 @@ shim (0005). **Progress:** +- **Deferred, awaiting operator decisions (2026-11-20):** The L2 probe installed one copy of each + azext package and found no fresh versions among the 13 newly resolved packages. The partial + migration passed 402 focused tests; the build still has 19 diagnostics in the unconverted + subscription-listing paths. No draft or packaged candidate is ready. +- **ARM challenge prompts:** The advisor (`claude-opus-5.5`) verified that each planned v6 level + can prompt on a challenge during passive Discovery. The SDK has no supported option to limit + prompts to explicit actions. Recommended for operator consideration: preserve silent + Discovery, accepting that its own wizard and deep-link flows would also forgo step-up. The + alternatives are to accept the v6 prompt behavior or widen the design to distinguish passive + and explicit calls. +- **Partial subscription results:** The advisor verified that v6 can skip tenants after ARM + failures and return a partial list. Recommended for operator consideration: retain healthy + results with a sanitized output diagnostic for failed tenants. Preserving visible failure and + Retry instead would require a larger change to listing. Neither behavior change was adopted. + OP-2 and the final CP-W3 verdict remain pending. + --- ## WI-4: Client identity, generation and the two cache fixes (PR 3) From 00265f02eb15488553db199e032fdd02d5a3abf7 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 11:45:05 +0000 Subject: [PATCH 041/380] docs: record Azure Discovery challenge and partial-result decisions Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/ai-and-plans/features/connection-lifecycle/README.md | 6 ++++-- .../features/connection-lifecycle/iterations/01-dev-plan.md | 6 ++++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/README.md b/docs/ai-and-plans/features/connection-lifecycle/README.md index 82f9176dd..c53663161 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/README.md +++ b/docs/ai-and-plans/features/connection-lifecycle/README.md @@ -41,8 +41,10 @@ Evidence, telemetry and source pointers: [research-findings.md](./research-findi ## Intent -- **Recover silently** from token expiry and idle drops. Prompt only on a user click, and never from - a token callback. +- **Recover database connections silently** from token expiry and idle drops. For database + authentication, prompt only on a user click, never from a token callback. Separately, an Azure + Resource Manager challenge can prompt during Azure Discovery. Subscription listing keeps + successful results and records a sanitized diagnostic if an account or tenant cannot be listed. - **Keep one client per cluster.** Surfaces resolve it per operation and check its identity fingerprint and generation. - **Never change identity under an open surface.** It becomes disconnected, keeps its state, says why 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 c82c1a146..f4394a7ff 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 @@ -882,6 +882,12 @@ shim (0005). results with a sanitized output diagnostic for failed tenants. Preserving visible failure and Retry instead would require a larger change to listing. Neither behavior change was adopted. OP-2 and the final CP-W3 verdict remain pending. +- **Unblocked (2026-11-20), operator decisions:** Keep successful subscription results when an + account or tenant cannot be listed, and record a sanitized diagnostic in the Output channel. + Keep the SDK's default ARM challenge behavior. The operator allowed that fallback if keeping + browsing silent required more than a small update. A prompt override would have to cover + both the SDK listing pipeline and subscription authentication, so PR2 will not add one. + OP-2 should include checking where prompts appear and what happens when they are dismissed. --- From 1869c22aba3373dfab84c13e7e58c8c0855a8cbe Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 11:53:24 +0000 Subject: [PATCH 042/380] feat: migrate Azure Discovery to azureauth v6 (WI-3) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- package-lock.json | 377 ++++++------------ package.json | 8 +- .../newConnection/PromptTenantStep.test.ts | 87 ++-- .../newConnection/PromptTenantStep.ts | 27 +- .../refreshTreeElement.test.ts | 28 ++ .../refreshTreeElement/refreshTreeElement.ts | 5 + src/commands/refreshView/refreshView.test.ts | 45 +++ src/commands/refreshView/refreshView.ts | 5 + .../retryAuthentication.test.ts | 17 + .../retryAuthentication.ts | 4 + .../updateCredentials/PromptTenantStep.ts | 27 +- .../checks/resolveTarget.test.ts | 31 +- .../checks/resolveTarget.ts | 20 +- src/deepLinks/azureSubscription.test.ts | 118 ++++-- src/deepLinks/azureSubscription.ts | 16 +- .../auth/documentdbTokenResource.test.ts | 2 +- .../auth/sovereignAuth.integration.test.ts | 3 +- .../playground/PlaygroundEvaluator.test.ts | 3 +- .../playground/PlaygroundEvaluator.ts | 5 +- .../shell/ShellSessionManager.test.ts | 3 +- src/documentdb/shell/ShellSessionManager.ts | 5 +- ...ureSubscriptionProviderWithFilters.test.ts | 166 ++++++++ .../AzureSubscriptionProviderWithFilters.ts | 85 +++- .../AccountTenantsStep.ts | 2 +- .../SelectAccountStep.ts | 10 +- .../InitializeFilteringStep.ts | 14 +- .../azure/wizard/SelectSubscriptionStep.ts | 14 +- .../AzureMongoRUDiscoveryProvider.ts | 8 + .../AzureMongoRUServiceRootItem.ts | 24 +- .../AzureDiscoveryProvider.ts | 8 + .../discovery-tree/AzureServiceRootItem.ts | 26 +- .../AzureVMDiscoveryProvider.ts | 8 + .../discovery-tree/AzureServiceRootItem.ts | 26 +- src/services/discoveryServices.ts | 2 + src/tree/TreeElementWithExplicitReload.ts | 17 + src/utils/azureClients.ts | 7 +- 36 files changed, 827 insertions(+), 426 deletions(-) create mode 100644 src/commands/refreshTreeElement/refreshTreeElement.test.ts create mode 100644 src/commands/refreshView/refreshView.test.ts create mode 100644 src/plugins/api-shared/azure/AzureSubscriptionProviderWithFilters.test.ts create mode 100644 src/tree/TreeElementWithExplicitReload.ts diff --git a/package-lock.json b/package-lock.json index e3484a30d..919b04803 100644 --- a/package-lock.json +++ b/package-lock.json @@ -26,10 +26,10 @@ "@fluentui/react-components": "~9.74.4", "@fluentui/react-icons": "~2.0.320", "@kubernetes/client-node": "1.4.0", - "@microsoft/vscode-azext-azureauth": "~4.1.1", - "@microsoft/vscode-azext-azureutils": "~4.2.0", - "@microsoft/vscode-azext-utils": "~4.1.0", - "@microsoft/vscode-azureresources-api": "~2.5.0", + "@microsoft/vscode-azext-azureauth": "6.1.0-alpha.2", + "@microsoft/vscode-azext-azureutils": "~5.1.0", + "@microsoft/vscode-azext-utils": "~5.1.0", + "@microsoft/vscode-azureresources-api": "~3.1.1", "@microsoft/vscode-container-client": "^0.5.4", "@microsoft/vscode-ext-webview": "*", "@microsoft/vscode-ext-webview-fluentui": "*", @@ -1088,19 +1088,20 @@ } }, "node_modules/@azure/arm-resources-subscriptions": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/@azure/arm-resources-subscriptions/-/arm-resources-subscriptions-2.1.0.tgz", - "integrity": "sha512-vKiu/3Yh84IV3IuJJ+0Fgs/ZQpvuGzoZ3dAoBksIV++Uu/Qz9RcQVz7pj+APWYIuODuR9I0eGKswZvzynzekug==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@azure/arm-resources-subscriptions/-/arm-resources-subscriptions-3.0.0.tgz", + "integrity": "sha512-Uu3i3HZ3nv69tVeNaXTr7KZ2qtcrJQiLvhREnZ0p5xNrV8Pmtrnx1o8A+z2T+OVQZlnySU5nPT4O4gJIJbfA5A==", "license": "MIT", "dependencies": { - "@azure/core-auth": "^1.3.0", - "@azure/core-client": "^1.7.0", - "@azure/core-paging": "^1.2.0", - "@azure/core-rest-pipeline": "^1.8.0", - "tslib": "^2.2.0" + "@azure-rest/core-client": "^2.3.1", + "@azure/core-auth": "^1.9.0", + "@azure/core-rest-pipeline": "^1.20.0", + "@azure/core-util": "^1.12.0", + "@azure/logger": "^1.2.0", + "tslib": "^2.8.1" }, "engines": { - "node": ">=14.0.0" + "node": ">=22.0.0" } }, "node_modules/@azure/arm-storage": { @@ -4540,53 +4541,38 @@ "license": "MIT" }, "node_modules/@microsoft/1ds-core-js": { - "version": "4.4.1", - "resolved": "https://registry.npmjs.org/@microsoft/1ds-core-js/-/1ds-core-js-4.4.1.tgz", - "integrity": "sha512-utqwacfUkiGJROn4WC7aNdRBsRxwhNWXuqaJM2B0N0WHmv1+IhSuI7RQ3FHwxRP1dxZi/xn9aELMZ7HMStsW1w==", + "version": "4.4.6", + "resolved": "https://registry.npmjs.org/@microsoft/1ds-core-js/-/1ds-core-js-4.4.6.tgz", + "integrity": "sha512-u19bMRL3XvxMYL8PcJZz/ADOSDBSBYrzrtZoEvIxKaA9+nxSygu7suos/RIPdmNTBkqLJmANHzITZFX/2P9bkA==", "license": "MIT", "dependencies": { - "@microsoft/applicationinsights-core-js": "3.4.1", + "@microsoft/applicationinsights-core-js": "3.4.6", "@microsoft/applicationinsights-shims": "3.0.1", "@microsoft/dynamicproto-js": "^2.0.3", - "@nevware21/ts-async": ">= 0.5.5 < 2.x", - "@nevware21/ts-utils": ">= 0.12.6 < 2.x" + "@nevware21/ts-async": ">= 0.5.5 < 0.6.0", + "@nevware21/ts-utils": ">= 0.14.0 < 2.x" } }, "node_modules/@microsoft/1ds-post-js": { - "version": "4.4.1", - "resolved": "https://registry.npmjs.org/@microsoft/1ds-post-js/-/1ds-post-js-4.4.1.tgz", - "integrity": "sha512-CkFEhDY7X8E2JLr6HsEvRiC0DaLOCsA7vlbq/9DJP65gAumgw2NnFNIAOg6Je5Geq1LDu76/nb2hP34p8eGggw==", + "version": "4.4.6", + "resolved": "https://registry.npmjs.org/@microsoft/1ds-post-js/-/1ds-post-js-4.4.6.tgz", + "integrity": "sha512-B8XMrquo1l1JQBSd7ft4r1dKPfOj4I0JoU2kMqlKtZJh/y4TYcR4CuNDZ1jnyx2q8rLj4ikivBTxgAUuQd/UJw==", "license": "MIT", "dependencies": { - "@microsoft/applicationinsights-core-js": "3.4.1", - "@microsoft/applicationinsights-shims": "3.0.1", - "@microsoft/dynamicproto-js": "^2.0.3", - "@nevware21/ts-async": ">= 0.5.5 < 2.x", - "@nevware21/ts-utils": ">= 0.12.6 < 2.x" - } - }, - "node_modules/@microsoft/applicationinsights-channel-js": { - "version": "3.4.2", - "resolved": "https://registry.npmjs.org/@microsoft/applicationinsights-channel-js/-/applicationinsights-channel-js-3.4.2.tgz", - "integrity": "sha512-Q7Q9gV45WSgSmOP2abu0y9tdbFh8sPELMgKUCDy62FsNd3xmE8X3zLtkzc7mcXPlpTeoDXwMCYjCRIAYd6d2lQ==", - "license": "MIT", - "dependencies": { - "@microsoft/applicationinsights-core-js": "3.4.2", + "@microsoft/applicationinsights-core-js": "3.4.6", "@microsoft/applicationinsights-shims": "3.0.1", "@microsoft/dynamicproto-js": "^2.0.3", "@nevware21/ts-async": ">= 0.5.5 < 0.6.0", "@nevware21/ts-utils": ">= 0.14.0 < 2.x" - }, - "peerDependencies": { - "tslib": ">= 1.0.0" } }, - "node_modules/@microsoft/applicationinsights-channel-js/node_modules/@microsoft/applicationinsights-core-js": { - "version": "3.4.2", - "resolved": "https://registry.npmjs.org/@microsoft/applicationinsights-core-js/-/applicationinsights-core-js-3.4.2.tgz", - "integrity": "sha512-Iw3gq1JREKLbXiVpr3F0+Ezuzphe+o25n9me9H5Kkjmck6tIkuGQea01SNfeemE4wf2mop2QQSvTcKxT8tNN1g==", + "node_modules/@microsoft/applicationinsights-channel-js": { + "version": "3.4.6", + "resolved": "https://registry.npmjs.org/@microsoft/applicationinsights-channel-js/-/applicationinsights-channel-js-3.4.6.tgz", + "integrity": "sha512-cDCDsQqvd6/4bp5X4f/IRDmiBRaHEcLxFefVkqb9nUPslXeA62NXloGBXK4CtRfN43ULg3R7NM/atY4TkzC3iw==", "license": "MIT", "dependencies": { + "@microsoft/applicationinsights-core-js": "3.4.6", "@microsoft/applicationinsights-shims": "3.0.1", "@microsoft/dynamicproto-js": "^2.0.3", "@nevware21/ts-async": ">= 0.5.5 < 0.6.0", @@ -4597,30 +4583,30 @@ } }, "node_modules/@microsoft/applicationinsights-common": { - "version": "3.4.1", - "resolved": "https://registry.npmjs.org/@microsoft/applicationinsights-common/-/applicationinsights-common-3.4.1.tgz", - "integrity": "sha512-CTbD0g/68tiv2yCItsodDQBYxyHdfQkG7VhvVU8OHenukpl/7W4wEuxZuOntqhv5m9Nx/DFncbz+T83nvYTG3g==", + "version": "3.4.6", + "resolved": "https://registry.npmjs.org/@microsoft/applicationinsights-common/-/applicationinsights-common-3.4.6.tgz", + "integrity": "sha512-X/5fPRv3FevJZXqRDr9hERM3BhplbnAqyGKv2R2xHO/EJy5V/5R/2r2anItTXaOnWIGHv5Bj2cSsjnvOdWrJsw==", "license": "MIT", "dependencies": { - "@microsoft/applicationinsights-core-js": "3.4.1", + "@microsoft/applicationinsights-core-js": "3.4.6", "@microsoft/applicationinsights-shims": "3.0.1", "@microsoft/dynamicproto-js": "^2.0.3", - "@nevware21/ts-utils": ">= 0.12.6 < 2.x" + "@nevware21/ts-utils": ">= 0.14.0 < 2.x" }, "peerDependencies": { "tslib": ">= 1.0.0" } }, "node_modules/@microsoft/applicationinsights-core-js": { - "version": "3.4.1", - "resolved": "https://registry.npmjs.org/@microsoft/applicationinsights-core-js/-/applicationinsights-core-js-3.4.1.tgz", - "integrity": "sha512-eXIHZ1+nvBiJgVpufBiTP801Vtr5FEwjWZioUsb44NC/z/UcsZh2MDJ1mBpjaDO73LVYUw/ZZmDCCo6Pg/61kA==", + "version": "3.4.6", + "resolved": "https://registry.npmjs.org/@microsoft/applicationinsights-core-js/-/applicationinsights-core-js-3.4.6.tgz", + "integrity": "sha512-YPvGUCgcpQa0MkUnJAcWi/SPDBabAohXSoa85c/GDkFiXWPsjihN8RcVj43r5I6nY4Y3+gHRvGVT6hBPTumKJg==", "license": "MIT", "dependencies": { "@microsoft/applicationinsights-shims": "3.0.1", "@microsoft/dynamicproto-js": "^2.0.3", - "@nevware21/ts-async": ">= 0.5.5 < 2.x", - "@nevware21/ts-utils": ">= 0.12.6 < 2.x" + "@nevware21/ts-async": ">= 0.5.5 < 0.6.0", + "@nevware21/ts-utils": ">= 0.14.0 < 2.x" }, "peerDependencies": { "tslib": ">= 1.0.0" @@ -4636,28 +4622,13 @@ } }, "node_modules/@microsoft/applicationinsights-web-basic": { - "version": "3.4.2", - "resolved": "https://registry.npmjs.org/@microsoft/applicationinsights-web-basic/-/applicationinsights-web-basic-3.4.2.tgz", - "integrity": "sha512-ONJbCSdJ/KMOVT7b8oVVPa2Etp99SHhehprpQn51QrHTiJtTehBLOmovBBIKQZuwWm0ZLKOaoUBWHCkRXUqNAw==", - "license": "MIT", - "dependencies": { - "@microsoft/applicationinsights-channel-js": "3.4.2", - "@microsoft/applicationinsights-core-js": "3.4.2", - "@microsoft/applicationinsights-shims": "3.0.1", - "@microsoft/dynamicproto-js": "^2.0.3", - "@nevware21/ts-async": ">= 0.5.5 < 0.6.0", - "@nevware21/ts-utils": ">= 0.14.0 < 2.x" - }, - "peerDependencies": { - "tslib": ">= 1.0.0" - } - }, - "node_modules/@microsoft/applicationinsights-web-basic/node_modules/@microsoft/applicationinsights-core-js": { - "version": "3.4.2", - "resolved": "https://registry.npmjs.org/@microsoft/applicationinsights-core-js/-/applicationinsights-core-js-3.4.2.tgz", - "integrity": "sha512-Iw3gq1JREKLbXiVpr3F0+Ezuzphe+o25n9me9H5Kkjmck6tIkuGQea01SNfeemE4wf2mop2QQSvTcKxT8tNN1g==", + "version": "3.4.6", + "resolved": "https://registry.npmjs.org/@microsoft/applicationinsights-web-basic/-/applicationinsights-web-basic-3.4.6.tgz", + "integrity": "sha512-T3CX9EwHPbI95I5CQ1aVRRRRynxtKVejW4if5EvGB6QaShcOOK56xnJ7Yn9Bb39YHkYqstQ7tMfxDDuO782XXg==", "license": "MIT", "dependencies": { + "@microsoft/applicationinsights-channel-js": "3.4.6", + "@microsoft/applicationinsights-core-js": "3.4.6", "@microsoft/applicationinsights-shims": "3.0.1", "@microsoft/dynamicproto-js": "^2.0.3", "@nevware21/ts-async": ">= 0.5.5 < 0.6.0", @@ -4677,21 +4648,25 @@ } }, "node_modules/@microsoft/vscode-azext-azureauth": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/@microsoft/vscode-azext-azureauth/-/vscode-azext-azureauth-4.1.1.tgz", - "integrity": "sha512-ZHRoNBBwZBg8sqZ7/C+VMQOp7zusJxIpXzLlRpWGjrDI8PSFQk2bZloVdW877YeSLMe2464mjTlWMhEEa07Kaw==", + "version": "6.1.0-alpha.2", + "resolved": "https://registry.npmjs.org/@microsoft/vscode-azext-azureauth/-/vscode-azext-azureauth-6.1.0-alpha.2.tgz", + "integrity": "sha512-hiEpLpNe/TiV1Cvx5gcgTxybfI1sYIRjKJ361bZyDOz3CchLjbupKiEi1jqyonMq5MvWftVlENBnvk3vq8AT0w==", "license": "MIT", "dependencies": { - "@azure/arm-resources-subscriptions": "^2.1.0", - "@azure/core-client": "^1.9.2", - "@azure/core-rest-pipeline": "^1.16.0", + "@azure/arm-resources-subscriptions": "^3.0.0-beta.1", + "@azure/core-auth": "^1.10.1", + "@azure/core-rest-pipeline": "^1.23.0", + "@azure/identity": "^4.13.1", "@azure/ms-rest-azure-env": "^2.0.0" + }, + "engines": { + "vscode": "^1.106.0" } }, "node_modules/@microsoft/vscode-azext-azureutils": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/@microsoft/vscode-azext-azureutils/-/vscode-azext-azureutils-4.2.0.tgz", - "integrity": "sha512-j/YzGI0uRzQjCM+jr9YyLxnJRHl2H9WQCw9Dlw7DhztV4ED3NCoIuG6k6jjKmSS3c5cTF/lqmPaVZ4SxZUssvA==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@microsoft/vscode-azext-azureutils/-/vscode-azext-azureutils-5.1.0.tgz", + "integrity": "sha512-Jm2hEEMBcTocq8AZ4sVO7vqNI3Sg0Wu4lvsTR4Oqp972d126ufcIZ7FVzU726BwkM2/BiA2NdUwJQhfNY61lGg==", "license": "MIT", "dependencies": { "@azure/arm-authorization": "^9.0.0", @@ -4699,14 +4674,14 @@ "@azure/arm-msi": "^2.2.0", "@azure/arm-resources": "^5.0.0", "@azure/arm-resources-profile-2020-09-01-hybrid": "^2.1.0", - "@azure/arm-resources-subscriptions": "^2.1.0", + "@azure/arm-resources-subscriptions": "^3.0.0-beta.1", "@azure/arm-storage": "^18.6.0", "@azure/arm-storage-profile-2020-09-01-hybrid": "^2.1.0", "@azure/core-client": "^1.10.1", "@azure/core-rest-pipeline": "^1.23.0", "@azure/logger": "^1.3.0", - "@microsoft/vscode-azext-azureauth": "^6.0.0-alpha.6", - "@microsoft/vscode-azext-utils": "^4.0.4", + "@microsoft/vscode-azext-azureauth": "^6.1.0-alpha.2", + "@microsoft/vscode-azext-utils": "^5.0.0", "@microsoft/vscode-azureresources-api": "^3.1.0", "semver": "^7.7.4" }, @@ -4747,53 +4722,24 @@ "node": ">=14.0.0" } }, - "node_modules/@microsoft/vscode-azext-azureutils/node_modules/@microsoft/vscode-azext-azureauth": { - "version": "6.0.0-alpha.8", - "resolved": "https://registry.npmjs.org/@microsoft/vscode-azext-azureauth/-/vscode-azext-azureauth-6.0.0-alpha.8.tgz", - "integrity": "sha512-oOZpeTe4tOupKzQpeKxyHOSG10Bxsyp8YhCeyadQMsz1wICR/JZEdSMKPR0GnXpXYlYSsEDFbSzJWqZUZ/3+Yw==", - "license": "MIT", - "dependencies": { - "@azure/arm-resources-subscriptions": "^2.1.0", - "@azure/core-rest-pipeline": "^1.22.2", - "@azure/identity": "^4.13.0", - "@azure/ms-rest-azure-env": "^2.0.0" - }, - "engines": { - "vscode": "^1.106.0" - } - }, - "node_modules/@microsoft/vscode-azext-azureutils/node_modules/@microsoft/vscode-azureresources-api": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/@microsoft/vscode-azureresources-api/-/vscode-azureresources-api-3.1.0.tgz", - "integrity": "sha512-jcx5VdDiOftjkjQ+ZXuGQ7xpy7WSKnB7oRLdmGuW3ykaB/PrBSHwStkItSg8l8ycJ0t1kaPOz3eDJP0Ol309jg==", - "license": "MIT", - "engines": { - "vscode": "^1.105.0" - }, - "peerDependencies": { - "@azure/ms-rest-azure-env": "^2.0.0" - } - }, "node_modules/@microsoft/vscode-azext-utils": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@microsoft/vscode-azext-utils/-/vscode-azext-utils-4.1.0.tgz", - "integrity": "sha512-00/wz3n2W6xNFZK4ur2lGjTqX8RhSrbAIoNwhMreOKk2n6gOpY389XO20oHu77uBxjgoqMTAL5R+SWcMeqD0Gg==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@microsoft/vscode-azext-utils/-/vscode-azext-utils-5.1.0.tgz", + "integrity": "sha512-Bmzz2p6vw0kk7lUJhY0wXb8iFc9jXe/etiV9h0vbI+2crMbMg0Vo7TvZTXTNbX2bqOtEvh2Cv4UhMUkuxn9NSg==", "license": "MIT", "dependencies": { - "@microsoft/vscode-azureresources-api": "^3.1.0", - "@microsoft/vscode-processutils": "^0.2.1", + "@microsoft/vscode-azureresources-api": "^3.1.1", + "@microsoft/vscode-processutils": "^1.0.0", "@vscode/extension-telemetry": "^1.5.2", "dayjs": "^1.11.19", - "html-to-text": "^9.0.5", - "semver": "^7.7.4", - "vscode-tas-client": "^0.1.84" + "semver": "^7.7.4" }, "engines": { "vscode": "^1.105.0" }, "peerDependencies": { "@azure/ms-rest-azure-env": "^2.0.0", - "@github/copilot-sdk": "0.1.32" + "@github/copilot-sdk": "^1.0.14" }, "peerDependenciesMeta": { "@github/copilot-sdk": { @@ -4801,23 +4747,42 @@ } } }, - "node_modules/@microsoft/vscode-azext-utils/node_modules/@microsoft/vscode-azureresources-api": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/@microsoft/vscode-azureresources-api/-/vscode-azureresources-api-3.1.0.tgz", - "integrity": "sha512-jcx5VdDiOftjkjQ+ZXuGQ7xpy7WSKnB7oRLdmGuW3ykaB/PrBSHwStkItSg8l8ycJ0t1kaPOz3eDJP0Ol309jg==", + "node_modules/@microsoft/vscode-azext-utils/node_modules/@microsoft/vscode-processutils": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@microsoft/vscode-processutils/-/vscode-processutils-1.0.0.tgz", + "integrity": "sha512-vAX1YRqQFb7PJgljQORY8gYJTDymVxh2hXnQaJYoVIb8uostOlin5Dpa9n9ZUkQbSw/K9FlxVR5GQtT3Uedzew==", "license": "MIT", + "dependencies": { + "tree-kill": "^1.2.2", + "which": "^5.0.0" + }, "engines": { - "vscode": "^1.105.0" + "node": ">=22" + } + }, + "node_modules/@microsoft/vscode-azext-utils/node_modules/which": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/which/-/which-5.0.0.tgz", + "integrity": "sha512-JEdGzHwwkrbWoGOlIHqQ5gtprKGOenpDHpxE9zVR1bWbOtYRyPPHMe9FaP6x61CmNaTThSkb0DAJte5jD+DmzQ==", + "license": "ISC", + "dependencies": { + "isexe": "^3.1.1" }, - "peerDependencies": { - "@azure/ms-rest-azure-env": "^2.0.0" + "bin": { + "node-which": "bin/which.js" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" } }, "node_modules/@microsoft/vscode-azureresources-api": { - "version": "2.5.1", - "resolved": "https://registry.npmjs.org/@microsoft/vscode-azureresources-api/-/vscode-azureresources-api-2.5.1.tgz", - "integrity": "sha512-CUlDVsau6RJA8F1IENnfA3N0XqyGQz/VJgh9QLnWjRkiBjW8/VSUpxNab6qflnN9SS38EHGv81v/92kEkoOQKQ==", + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@microsoft/vscode-azureresources-api/-/vscode-azureresources-api-3.1.1.tgz", + "integrity": "sha512-koV1+XvWSzA+pOc1g17Kbw9Gm26SIvg+j5puT5vB/T9vNiE2oeAlxlAatfZOT3tRHN1qGqPLl90HHs5mQAPkew==", "license": "MIT", + "engines": { + "vscode": "^1.105.0" + }, "peerDependencies": { "@azure/ms-rest-azure-env": "^2.0.0" } @@ -4851,15 +4816,6 @@ "which": "^5.0.0" } }, - "node_modules/@microsoft/vscode-processutils/node_modules/isexe": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-3.1.5.tgz", - "integrity": "sha512-6B3tLtFqtQS4ekarvLVMZ+X+VlvQekbe4taUkf/rhVO3d/h0M2rfARm/pXLcPEsjjMsFgrFgSrhQIxcSVrBz8w==", - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=18" - } - }, "node_modules/@microsoft/vscode-processutils/node_modules/which": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/which/-/which-5.0.0.tgz", @@ -5287,9 +5243,9 @@ } }, "node_modules/@nevware21/ts-utils": { - "version": "0.14.0", - "resolved": "https://registry.npmjs.org/@nevware21/ts-utils/-/ts-utils-0.14.0.tgz", - "integrity": "sha512-WoeqTIXQ8WPhl+lD2NbMHoAQ4sJl0n7EoRoDmVJui//Usg512enl9q1fdbVobuZt3omnxnmVsDrNIvPBvFgddQ==", + "version": "0.16.0", + "resolved": "https://registry.npmjs.org/@nevware21/ts-utils/-/ts-utils-0.16.0.tgz", + "integrity": "sha512-DDln15VUBSw5JjJlNno1UCSzgAGzHHklm7u695jXDCzwSn7W2F7B2VYHwLLcT1cOWQQBQAJK6e2/Y8oTG+W0Ig==", "funding": [ { "type": "github", @@ -6127,19 +6083,6 @@ "node": ">=20.0.0" } }, - "node_modules/@selderee/plugin-htmlparser2": { - "version": "0.11.0", - "resolved": "https://registry.npmjs.org/@selderee/plugin-htmlparser2/-/plugin-htmlparser2-0.11.0.tgz", - "integrity": "sha512-P33hHGdldxGabLFjPPpaTxVolMrzrcegejx+0GxjrIb9Zv48D8yAIA/QTDR2dFl7Uz7urX8aX6+5bCZslr+gWQ==", - "license": "MIT", - "dependencies": { - "domhandler": "^5.0.3", - "selderee": "^0.11.0" - }, - "funding": { - "url": "https://ko-fi.com/killymxi" - } - }, "node_modules/@slickgrid-universal/binding": { "version": "9.13.0", "resolved": "https://registry.npmjs.org/@slickgrid-universal/binding/-/binding-9.13.0.tgz", @@ -9386,15 +9329,6 @@ "dev": true, "license": "MIT" }, - "node_modules/deepmerge": { - "version": "4.3.1", - "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", - "integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/deepmerge-json": { "version": "1.5.0", "resolved": "https://registry.npmjs.org/deepmerge-json/-/deepmerge-json-1.5.0.tgz", @@ -9581,6 +9515,7 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz", "integrity": "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==", + "dev": true, "license": "MIT", "dependencies": { "domelementtype": "^2.3.0", @@ -9595,6 +9530,7 @@ "version": "2.3.0", "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz", "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==", + "dev": true, "funding": [ { "type": "github", @@ -9607,6 +9543,7 @@ "version": "5.0.3", "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz", "integrity": "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==", + "dev": true, "license": "BSD-2-Clause", "dependencies": { "domelementtype": "^2.3.0" @@ -9622,6 +9559,7 @@ "version": "3.2.2", "resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz", "integrity": "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==", + "dev": true, "license": "BSD-2-Clause", "dependencies": { "dom-serializer": "^2.0.0", @@ -9751,6 +9689,7 @@ "version": "4.5.0", "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", + "dev": true, "license": "BSD-2-Clause", "engines": { "node": ">=0.12" @@ -11634,41 +11573,6 @@ "node": ">=18" } }, - "node_modules/html-to-text": { - "version": "9.0.5", - "resolved": "https://registry.npmjs.org/html-to-text/-/html-to-text-9.0.5.tgz", - "integrity": "sha512-qY60FjREgVZL03vJU6IfMV4GDjGBIoOyvuFdpBDIX9yTlDw0TjxVBQp+P8NvpdIXNJvfWBTNul7fsAQJq2FNpg==", - "license": "MIT", - "dependencies": { - "@selderee/plugin-htmlparser2": "^0.11.0", - "deepmerge": "^4.3.1", - "dom-serializer": "^2.0.0", - "htmlparser2": "^8.0.2", - "selderee": "^0.11.0" - }, - "engines": { - "node": ">=14" - } - }, - "node_modules/html-to-text/node_modules/htmlparser2": { - "version": "8.0.2", - "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-8.0.2.tgz", - "integrity": "sha512-GYdjWKDkbRLkZ5geuHs5NY1puJ+PXwP7+fHPRz06Eirsb9ugf6d8kkXav6ADhcODhFFPMIXyxkxSuMf3D6NCFA==", - "funding": [ - "https://github.com/fb55/htmlparser2?sponsor=1", - { - "type": "github", - "url": "https://github.com/sponsors/fb55" - } - ], - "license": "MIT", - "dependencies": { - "domelementtype": "^2.3.0", - "domhandler": "^5.0.3", - "domutils": "^3.0.1", - "entities": "^4.4.0" - } - }, "node_modules/html-url-attributes": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/html-url-attributes/-/html-url-attributes-3.0.1.tgz", @@ -12457,6 +12361,15 @@ "dev": true, "license": "MIT" }, + "node_modules/isexe": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-3.1.5.tgz", + "integrity": "sha512-6B3tLtFqtQS4ekarvLVMZ+X+VlvQekbe4taUkf/rhVO3d/h0M2rfARm/pXLcPEsjjMsFgrFgSrhQIxcSVrBz8w==", + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" + } + }, "node_modules/isnumber": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/isnumber/-/isnumber-1.0.0.tgz", @@ -12862,15 +12775,6 @@ "node": ">=0.10" } }, - "node_modules/leac": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/leac/-/leac-0.6.0.tgz", - "integrity": "sha512-y+SqErxb8h7nE/fiEX07jsbuhrpO9lL8eca7/Y1nuWV2moNlXhyd59iDGcRf6moVyDMbmTNzL40SUyrFU/yDpg==", - "license": "MIT", - "funding": { - "url": "https://ko-fi.com/killymxi" - } - }, "node_modules/leven": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz", @@ -15136,19 +15040,6 @@ "url": "https://github.com/fb55/entities?sponsor=1" } }, - "node_modules/parseley": { - "version": "0.12.1", - "resolved": "https://registry.npmjs.org/parseley/-/parseley-0.12.1.tgz", - "integrity": "sha512-e6qHKe3a9HWr0oMRVDTRhKce+bRO8VGQR3NyVwcjwrbhMmFCX9KszEV35+rn4AdilFAq9VPxP/Fe1wC9Qjd2lw==", - "license": "MIT", - "dependencies": { - "leac": "^0.6.0", - "peberminta": "^0.9.0" - }, - "funding": { - "url": "https://ko-fi.com/killymxi" - } - }, "node_modules/parseurl": { "version": "1.3.3", "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", @@ -15232,15 +15123,6 @@ "dev": true, "license": "MIT" }, - "node_modules/peberminta": { - "version": "0.9.0", - "resolved": "https://registry.npmjs.org/peberminta/-/peberminta-0.9.0.tgz", - "integrity": "sha512-XIxfHpEuSJbITd1H3EeQwpcZbTLHc+VVr8ANI9t5sit565tsI4/xK3KWTUFE2e6QiangUkh3B0jihzmGnNrRsQ==", - "license": "MIT", - "funding": { - "url": "https://ko-fi.com/killymxi" - } - }, "node_modules/pend": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz", @@ -16330,18 +16212,6 @@ "node": ">=20.0.0" } }, - "node_modules/selderee": { - "version": "0.11.0", - "resolved": "https://registry.npmjs.org/selderee/-/selderee-0.11.0.tgz", - "integrity": "sha512-5TF+l7p4+OsnP8BCCvSyZiSPc4x4//p5uPwK8TCnVPJYRmU2aYKMpOXvw8zM5a5JvuuCGN1jmsMwuU2W02ukfA==", - "license": "MIT", - "dependencies": { - "parseley": "^0.12.0" - }, - "funding": { - "url": "https://ko-fi.com/killymxi" - } - }, "node_modules/semaphore": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/semaphore/-/semaphore-1.1.0.tgz", @@ -17317,15 +17187,6 @@ "streamx": "^2.15.0" } }, - "node_modules/tas-client": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/tas-client/-/tas-client-0.3.2.tgz", - "integrity": "sha512-Hr0k7swJSyI7fsgqWf28GoME3lDXysTV1pJW/OBCrokhkqd3dTL+79SLKRGaYNHNaHii5N7VLRlZZc/up6xdAA==", - "license": "MIT", - "engines": { - "node": ">=22" - } - }, "node_modules/teex": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/teex/-/teex-1.0.1.tgz", @@ -18545,18 +18406,6 @@ "integrity": "sha512-Ld1VelNuX9pdF39h2Hgaeb5hEZM2Z3jUrrMgWQAu82jMtZp7p3vJT3BzToKtZI7NgQssZje5o0zryOrhQvzQAg==", "license": "MIT" }, - "node_modules/vscode-tas-client": { - "version": "0.1.86", - "resolved": "https://registry.npmjs.org/vscode-tas-client/-/vscode-tas-client-0.1.86.tgz", - "integrity": "sha512-4P3zjGXTKXknbWOd6EDnD3lWZuc/aFrW8Ixzk0B8gQDBq2BXuKg0NwsZiFeAzBohAxCcsRA4gQipH57Bxf6XXg==", - "license": "MIT", - "dependencies": { - "tas-client": "^0.3.2" - }, - "engines": { - "vscode": "^1.85.0" - } - }, "node_modules/vscode-uri": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-3.1.0.tgz", diff --git a/package.json b/package.json index 35398ef8f..452852242 100644 --- a/package.json +++ b/package.json @@ -168,10 +168,10 @@ "@fluentui/react-components": "~9.74.4", "@fluentui/react-icons": "~2.0.320", "@kubernetes/client-node": "1.4.0", - "@microsoft/vscode-azext-azureauth": "~4.1.1", - "@microsoft/vscode-azext-azureutils": "~4.2.0", - "@microsoft/vscode-azext-utils": "~4.1.0", - "@microsoft/vscode-azureresources-api": "~2.5.0", + "@microsoft/vscode-azext-azureauth": "6.1.0-alpha.2", + "@microsoft/vscode-azext-azureutils": "~5.1.0", + "@microsoft/vscode-azext-utils": "~5.1.0", + "@microsoft/vscode-azureresources-api": "~3.1.1", "@microsoft/vscode-container-client": "^0.5.4", "@microsoft/vscode-ext-webview": "*", "@microsoft/vscode-ext-webview-fluentui": "*", diff --git a/src/commands/newConnection/PromptTenantStep.test.ts b/src/commands/newConnection/PromptTenantStep.test.ts index e1ae7c902..4b54a243c 100644 --- a/src/commands/newConnection/PromptTenantStep.test.ts +++ b/src/commands/newConnection/PromptTenantStep.test.ts @@ -5,8 +5,9 @@ import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest'; -const mockGetTenants = vi.fn(); -const mockIsSignedIn = vi.fn(); +const mockGetAccounts = vi.fn(); +const mockGetTenantsForAccount = vi.fn(); +const mockSignIn = vi.fn(); // Read eagerly by the credentialsManagement factory below, which `vi.mock` hoists above this line. const { mockConfigureAzureCredentials } = vi.hoisted(() => ({ mockConfigureAzureCredentials: vi.fn() })); const mockOutputChannel = { info: vi.fn(), warn: vi.fn(), error: vi.fn() }; @@ -19,12 +20,14 @@ vi.mock('../../extensionVariables', () => ({ }, })); -vi.mock('@microsoft/vscode-azext-azureauth', () => ({ +vi.mock('@microsoft/vscode-azext-azureauth', async (importOriginal) => ({ + ...(await importOriginal()), // A `function`, not an arrow: Vitest 4 calls the implementation with `new`. VSCodeAzureSubscriptionProvider: vi.fn().mockImplementation(function () { return { - getTenants: mockGetTenants, - isSignedIn: mockIsSignedIn, + getAccounts: mockGetAccounts, + getTenantsForAccount: mockGetTenantsForAccount, + signIn: mockSignIn, }; }), })); @@ -51,6 +54,8 @@ vi.mock('../../plugins/api-shared/azure/credentialsManagement', () => ({ configureAzureCredentials: mockConfigureAzureCredentials, })); +import { Environment } from '@azure/ms-rest-azure-env'; +import { ExtendedEnvironment } from '@microsoft/vscode-azext-azureauth'; import { type IActionContext } from '@microsoft/vscode-azext-utils'; import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; import { traceTenantLookup } from '../../plugins/api-shared/azure/traceTenantLookup'; @@ -62,7 +67,11 @@ const tenant = { tenantId: TENANT_ID, displayName: 'Example Organization', defaultDomain: 'example.test', - account: { id: 'account', label: 'alex@example.test' }, + account: { + id: 'account', + label: 'alex@example.test', + environment: new ExtendedEnvironment(Environment.AzureCloud, false), + }, }; type PromptTenantStep = NewConnectionPromptTenantStep | UpdateCredentialsPromptTenantStep; @@ -107,8 +116,9 @@ describe.each([ ])('PromptTenantStep for %s', (_name, makeStep: () => PromptTenantStep) => { beforeEach(() => { vi.clearAllMocks(); - mockIsSignedIn.mockReset().mockResolvedValue(true); - mockGetTenants.mockReset().mockResolvedValue([tenant]); + mockSignIn.mockReset().mockResolvedValue(true); + mockGetAccounts.mockReset().mockResolvedValue([tenant.account]); + mockGetTenantsForAccount.mockReset().mockResolvedValue([tenant]); mockConfigureAzureCredentials.mockResolvedValue(undefined); }); @@ -137,12 +147,13 @@ describe.each([ expect(mockOutputChannel.info).toHaveBeenCalledTimes(2); expect(mockOutputChannel.info.mock.calls[1][0]).toContain('"skipped":true'); expect(mockOutputChannel.info.mock.calls[1][0]).toContain('notInteractiveEntra'); - expect(mockIsSignedIn).not.toHaveBeenCalled(); - expect(mockGetTenants).not.toHaveBeenCalled(); + expect(mockSignIn).not.toHaveBeenCalled(); + expect(mockGetAccounts).not.toHaveBeenCalled(); + expect(mockGetTenantsForAccount).not.toHaveBeenCalled(); }); it('runs account management before listing tenants when signed out', async () => { - mockIsSignedIn.mockResolvedValue(false); + mockSignIn.mockResolvedValue(false); const showQuickPick = vi.fn().mockImplementation(async (itemsPromise: Promise) => { const items = await itemsPromise; return items.find((item) => (item as { tenant?: unknown }).tenant); @@ -152,7 +163,9 @@ describe.each([ await makeStep().prompt(context as never); expect(mockConfigureAzureCredentials).toHaveBeenCalledTimes(1); - expect(mockGetTenants).toHaveBeenCalledTimes(1); + expect(mockSignIn).toHaveBeenCalledExactlyOnceWith(undefined, { promptIfNeeded: false }); + expect(mockGetAccounts).toHaveBeenCalledExactlyOnceWith({ filter: false, noCache: true }); + expect(mockGetTenantsForAccount).toHaveBeenCalledExactlyOnceWith(tenant.account, { filter: false, noCache: true }); expect((context as IActionContext & { entraIdAuthConfig?: { tenantId?: string } }).entraIdAuthConfig).toEqual({ tenantId: TENANT_ID, }); @@ -162,7 +175,7 @@ describe.each([ }); it('re-enumerates tenants after account management without exiting the wizard', async () => { - mockIsSignedIn.mockResolvedValue(true); + mockSignIn.mockResolvedValue(true); const showQuickPick = vi .fn() .mockImplementationOnce(async (items: Promise) => { @@ -178,7 +191,11 @@ describe.each([ await makeStep().prompt(context as never); expect(showQuickPick).toHaveBeenCalledTimes(2); - expect(mockGetTenants).toHaveBeenCalledTimes(2); + expect(mockGetAccounts.mock.calls).toEqual([[{ filter: false }], [{ filter: false, noCache: true }]]); + expect(mockGetTenantsForAccount.mock.calls).toEqual([ + [tenant.account, { filter: false }], + [tenant.account, { filter: false, noCache: true }], + ]); expect(mockConfigureAzureCredentials).toHaveBeenCalledTimes(1); expect((context as IActionContext & { entraIdAuthConfig?: { tenantId?: string } }).entraIdAuthConfig).toEqual({ tenantId: TENANT_ID, @@ -186,7 +203,7 @@ describe.each([ }); it('distinguishes a successful empty result from failure and timeout', async () => { - mockGetTenants.mockResolvedValue([]); + mockGetTenantsForAccount.mockResolvedValue([]); const context = makeFallbackContext(); await makeStep().prompt(context as never); @@ -204,7 +221,7 @@ describe.each([ code: 'AuthorizationFailed', statusCode: 403, }); - mockGetTenants.mockRejectedValue(error); + mockGetTenantsForAccount.mockRejectedValue(error); await makeStep().prompt(makeFallbackContext() as never); @@ -215,7 +232,7 @@ describe.each([ }); it('does not print unrecognized error metadata', async () => { - mockGetTenants.mockRejectedValue( + mockGetTenantsForAccount.mockRejectedValue( Object.assign(new Error('secret-token'), { name: tenant.account.label, code: 'secret-token', @@ -230,7 +247,7 @@ describe.each([ }); it('does not print arbitrary thrown values', async () => { - mockGetTenants.mockRejectedValue(`secret-token ${tenant.account.label}`); + mockGetTenantsForAccount.mockRejectedValue(`secret-token ${tenant.account.label}`); await makeStep().prompt(makeFallbackContext() as never); @@ -239,19 +256,20 @@ describe.each([ }); it('logs sign-in failure while preserving the existing true fallback', async () => { - mockIsSignedIn.mockRejectedValue(new Error('secret-token')); + mockSignIn.mockRejectedValue(new Error('secret-token')); await makeStep().prompt(makeFallbackContext() as never); expect(outputText()).toMatch(/isSignedIn: failed in/); expect(mockConfigureAzureCredentials).not.toHaveBeenCalled(); - expect(mockGetTenants).toHaveBeenCalledTimes(1); + expect(mockGetAccounts).toHaveBeenCalledExactlyOnceWith({ filter: false }); + expect(mockGetTenantsForAccount).toHaveBeenCalledExactlyOnceWith(tenant.account, { filter: false }); expect(outputText()).not.toContain('secret-token'); }); it('logs sign-in timeout while preserving the existing true fallback', async () => { vi.useFakeTimers(); - mockIsSignedIn.mockReturnValue(new Promise(() => {})); + mockSignIn.mockReturnValue(new Promise(() => {})); const prompt = makeStep().prompt(makeFallbackContext() as never); await vi.advanceTimersByTimeAsync(5000); @@ -259,13 +277,14 @@ describe.each([ expect(outputText()).toContain('isSignedIn: timed out after 5000 ms; using fallback (signedIn=true)'); expect(mockConfigureAzureCredentials).not.toHaveBeenCalled(); - expect(mockGetTenants).toHaveBeenCalledTimes(1); + expect(mockGetAccounts).toHaveBeenCalledExactlyOnceWith({ filter: false }); + expect(mockGetTenantsForAccount).toHaveBeenCalledExactlyOnceWith(tenant.account, { filter: false }); }); it('logs late tenant completion without replacing the timeout fallback', async () => { vi.useFakeTimers(); let completeLookup!: (tenants: (typeof tenant)[]) => void; - mockGetTenants.mockReturnValue( + mockGetTenantsForAccount.mockReturnValue( new Promise<(typeof tenant)[]>((resolve) => { completeLookup = resolve; }), @@ -290,7 +309,7 @@ describe.each([ it('logs late provider rejection after a timeout', async () => { vi.useFakeTimers(); let failLookup!: (reason: Error) => void; - mockGetTenants.mockReturnValue( + mockGetTenantsForAccount.mockReturnValue( new Promise<(typeof tenant)[]>((_resolve, reject) => { failLookup = reject; }), @@ -308,7 +327,7 @@ describe.each([ it('offers an explicit retry after timeout and allows 30 seconds for it', async () => { vi.useFakeTimers(); - mockGetTenants + mockGetTenantsForAccount .mockReturnValueOnce(new Promise<(typeof tenant)[]>(() => {})) .mockImplementationOnce(() => new Promise((resolve) => setTimeout(() => resolve([tenant]), 29_000))); const showQuickPick = vi @@ -328,7 +347,11 @@ describe.each([ const prompt = makeStep().prompt(context as never); await vi.advanceTimersByTimeAsync(5000); - expect(mockGetTenants).toHaveBeenCalledTimes(2); + expect(mockGetAccounts.mock.calls).toEqual([[{ filter: false }], [{ filter: false, noCache: true }]]); + expect(mockGetTenantsForAccount.mock.calls).toEqual([ + [tenant.account, { filter: false }], + [tenant.account, { filter: false, noCache: true }], + ]); await vi.advanceTimersByTimeAsync(29_000); await prompt; @@ -339,7 +362,7 @@ describe.each([ it('keeps manual entry, account management, and retry available after a retry timeout', async () => { vi.useFakeTimers(); - mockGetTenants.mockReturnValue(new Promise<(typeof tenant)[]>(() => {})); + mockGetTenantsForAccount.mockReturnValue(new Promise<(typeof tenant)[]>(() => {})); const showQuickPick = vi .fn() .mockImplementationOnce(async (itemsPromise: Promise<{ isRetryOption?: boolean }[]>) => @@ -367,7 +390,8 @@ describe.each([ await vi.advanceTimersByTimeAsync(35_000); await prompt; - expect(mockGetTenants).toHaveBeenCalledTimes(2); + expect(mockGetAccounts).toHaveBeenCalledTimes(2); + expect(mockGetTenantsForAccount).toHaveBeenCalledTimes(2); }); it.each([ @@ -375,9 +399,9 @@ describe.each([ ['failure', new Error('synthetic failure'), 'Unable to load tenants'], ])('offers retry for a %s result without misreporting a timeout', async (_name, error, detail) => { if (error) { - mockGetTenants.mockRejectedValueOnce(error); + mockGetTenantsForAccount.mockRejectedValueOnce(error); } else { - mockGetTenants.mockResolvedValueOnce([]); + mockGetTenantsForAccount.mockResolvedValueOnce([]); } const showQuickPick = vi.fn().mockImplementation( async ( @@ -396,7 +420,8 @@ describe.each([ ); await makeStep().prompt(makeContext(showQuickPick) as never); - expect(mockGetTenants).toHaveBeenCalledTimes(1); + expect(mockGetAccounts).toHaveBeenCalledTimes(1); + expect(mockGetTenantsForAccount).toHaveBeenCalledTimes(1); }); }); diff --git a/src/commands/newConnection/PromptTenantStep.ts b/src/commands/newConnection/PromptTenantStep.ts index 7595c0fe1..246cbe379 100644 --- a/src/commands/newConnection/PromptTenantStep.ts +++ b/src/commands/newConnection/PromptTenantStep.ts @@ -8,7 +8,10 @@ import { AzureWizardPromptStep } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; import * as vscode from 'vscode'; import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; -import { type AzureSubscriptionProviderWithFilters } from '../../plugins/api-shared/azure/AzureSubscriptionProviderWithFilters'; +import { + getUnfilteredAzureTenants, + type AzureSubscriptionProviderWithFilters, +} from '../../plugins/api-shared/azure/AzureSubscriptionProviderWithFilters'; import { traceTenantLookup, type TenantLookupResult } from '../../plugins/api-shared/azure/traceTenantLookup'; import { traceAuthFlow } from '../../utils/authTrace'; import { nonNullValue } from '../../utils/nonNull'; @@ -29,16 +32,22 @@ export class PromptTenantStep extends AzureWizardPromptStep => { // Load available tenants from Azure subscription provider - const { tenants, status } = await this.getAvailableTenants(subscriptionProvider, lookupTimeoutMs); + const { tenants, status } = await this.getAvailableTenants( + subscriptionProvider, + lookupTimeoutMs, + reloadTenants, + ); context.telemetry.measurements.availableTenantsCount = tenants.length; // Create quick pick items @@ -122,9 +131,11 @@ export class PromptTenantStep extends AzureWizardPromptStep { try { - return await traceTenantLookup('newConnection.isSignedIn', () => subscriptionProvider.isSignedIn(), { - timeoutMs: TENANT_LOOKUP_TIMEOUT_MS, - fallbackValue: true, - }); + return await traceTenantLookup( + 'newConnection.isSignedIn', + () => subscriptionProvider.signIn(undefined, { promptIfNeeded: false }), + { timeoutMs: TENANT_LOOKUP_TIMEOUT_MS, fallbackValue: true }, + ); } catch { return true; } @@ -191,12 +203,13 @@ export class PromptTenantStep extends AzureWizardPromptStep { let timedOut = false; try { const tenants = await traceTenantLookup( 'newConnection.getTenants', - () => subscriptionProvider.getTenants(), + () => getUnfilteredAzureTenants(subscriptionProvider, noCache), { timeoutMs, fallbackValue: [], diff --git a/src/commands/refreshTreeElement/refreshTreeElement.test.ts b/src/commands/refreshTreeElement/refreshTreeElement.test.ts new file mode 100644 index 000000000..e6cf6dd76 --- /dev/null +++ b/src/commands/refreshTreeElement/refreshTreeElement.test.ts @@ -0,0 +1,28 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { expect, it, vi } from 'vitest'; +import { ext } from '../../extensionVariables'; +import { refreshTreeElement } from './refreshTreeElement'; + +vi.mock('../../extensionVariables', () => ({ + ext: { discoveryBranchDataProvider: { refresh: vi.fn() } }, +})); + +it('marks a node for an explicit reload before refreshing that node', async () => { + const node = { + id: 'discoveryView/azure', + contextValue: 'discoveryView', + getTreeItem: vi.fn(), + prepareExplicitReload: vi.fn(), + }; + + await refreshTreeElement({} as IActionContext, node); + + expect(node.prepareExplicitReload).toHaveBeenCalledTimes(1); + expect(node.prepareExplicitReload).toHaveBeenCalledBefore(vi.mocked(ext.discoveryBranchDataProvider.refresh)); + expect(ext.discoveryBranchDataProvider.refresh).toHaveBeenCalledExactlyOnceWith(node); +}); diff --git a/src/commands/refreshTreeElement/refreshTreeElement.ts b/src/commands/refreshTreeElement/refreshTreeElement.ts index 5a7fcb077..aa92ad262 100644 --- a/src/commands/refreshTreeElement/refreshTreeElement.ts +++ b/src/commands/refreshTreeElement/refreshTreeElement.ts @@ -7,12 +7,17 @@ import { type IActionContext } from '@microsoft/vscode-azext-utils'; import { l10n } from 'vscode'; import { ext } from '../../extensionVariables'; import { type TreeElement } from '../../tree/TreeElement'; +import { isTreeElementWithExplicitReload } from '../../tree/TreeElementWithExplicitReload'; export async function refreshTreeElement(context: IActionContext, node: TreeElement): Promise { if (!node) { throw new Error(l10n.t('No node selected.')); } + if (isTreeElementWithExplicitReload(node)) { + node.prepareExplicitReload(); + } + if (node && 'refresh' in node && typeof node.refresh === 'function') { await node.refresh.call(node, context); return; diff --git a/src/commands/refreshView/refreshView.test.ts b/src/commands/refreshView/refreshView.test.ts new file mode 100644 index 000000000..f33bf7c94 --- /dev/null +++ b/src/commands/refreshView/refreshView.test.ts @@ -0,0 +1,45 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { expect, it, vi } from 'vitest'; +import { Views } from '../../documentdb/Views'; +import { ext } from '../../extensionVariables'; +import { getVisibleDiscoveryProviders } from '../../services/discoveryProviderVisibility'; +import { DiscoveryService } from '../../services/discoveryServices'; +import { refreshView } from './refreshView'; + +vi.mock('../../extensionVariables', () => ({ + ext: { discoveryBranchDataProvider: { refresh: vi.fn() } }, +})); +vi.mock('../../services/discoveryProviderVisibility', () => ({ + getVisibleDiscoveryProviders: vi.fn(), +})); + +it('marks visible Discovery providers before refreshing the view', async () => { + const prepareExplicitReload = vi.fn(); + const azureProvider = { + id: 'azure', + label: 'Azure', + description: '', + iconPath: undefined, + getDiscoveryWizard: vi.fn(), + getDiscoveryTreeRootItem: vi.fn(), + prepareExplicitReload, + }; + const otherProvider = { ...azureProvider, id: 'other', prepareExplicitReload: undefined }; + const hiddenProvider = { ...azureProvider, id: 'hidden', prepareExplicitReload: vi.fn() }; + for (const provider of [azureProvider, otherProvider, hiddenProvider]) { + DiscoveryService.registerProvider(provider); + } + vi.mocked(getVisibleDiscoveryProviders).mockResolvedValue([azureProvider, otherProvider]); + + await refreshView({} as IActionContext, Views.DiscoveryView); + + expect(prepareExplicitReload).toHaveBeenCalledTimes(1); + expect(prepareExplicitReload).toHaveBeenCalledBefore(vi.mocked(ext.discoveryBranchDataProvider.refresh)); + expect(ext.discoveryBranchDataProvider.refresh).toHaveBeenCalledExactlyOnceWith(); + expect(hiddenProvider.prepareExplicitReload).not.toHaveBeenCalled(); +}); diff --git a/src/commands/refreshView/refreshView.ts b/src/commands/refreshView/refreshView.ts index 75fbab833..2967c4c50 100644 --- a/src/commands/refreshView/refreshView.ts +++ b/src/commands/refreshView/refreshView.ts @@ -6,6 +6,8 @@ import { type IActionContext } from '@microsoft/vscode-azext-utils'; import { Views } from '../../documentdb/Views'; import { ext } from '../../extensionVariables'; +import { getVisibleDiscoveryProviders } from '../../services/discoveryProviderVisibility'; +import { DiscoveryService } from '../../services/discoveryServices'; export async function refreshView(_context: IActionContext, view: Views): Promise { switch (view) { @@ -13,6 +15,9 @@ export async function refreshView(_context: IActionContext, view: Views): Promis ext.connectionsBranchDataProvider.refresh(); break; case Views.DiscoveryView: + for (const { id } of await getVisibleDiscoveryProviders()) { + DiscoveryService.getProvider(id)?.prepareExplicitReload?.(); + } ext.discoveryBranchDataProvider.refresh(); break; default: diff --git a/src/commands/retryAuthentication/retryAuthentication.test.ts b/src/commands/retryAuthentication/retryAuthentication.test.ts index e037391e8..e0c080d82 100644 --- a/src/commands/retryAuthentication/retryAuthentication.test.ts +++ b/src/commands/retryAuthentication/retryAuthentication.test.ts @@ -98,6 +98,23 @@ describe('retryAuthentication', () => { expect(ext.azureResourcesRUBranchDataProvider.resetNodeErrorState).not.toHaveBeenCalled(); }); + it('marks a Discovery node for an explicit reload before resetting or refreshing it', async () => { + const node = { + id: 'discoveryView/azure', + getTreeItem, + prepareExplicitReload: vi.fn(), + }; + + await retryAuthentication(actionContext as never, node); + + const { resetNodeErrorState, refresh } = ext.discoveryBranchDataProvider; + expect(node.prepareExplicitReload).toHaveBeenCalledTimes(1); + expect(node.prepareExplicitReload).toHaveBeenCalledBefore(vi.mocked(resetNodeErrorState)); + expect(resetNodeErrorState).toHaveBeenCalledBefore(vi.mocked(refresh)); + expect(resetNodeErrorState).toHaveBeenCalledExactlyOnceWith(node.id); + expect(refresh).toHaveBeenCalledExactlyOnceWith(node); + }); + it('throws for unsupported retry nodes', async () => { await expect( retryAuthentication(actionContext as never, { diff --git a/src/commands/retryAuthentication/retryAuthentication.ts b/src/commands/retryAuthentication/retryAuthentication.ts index 67be85e13..9389931b0 100644 --- a/src/commands/retryAuthentication/retryAuthentication.ts +++ b/src/commands/retryAuthentication/retryAuthentication.ts @@ -10,6 +10,7 @@ import { inferViewIdFromTreeId, Views } from '../../documentdb/Views'; import { ext } from '../../extensionVariables'; import { type TreeElement } from '../../tree/TreeElement'; import { type TreeElementWithContextValue } from '../../tree/TreeElementWithContextValue'; +import { isTreeElementWithExplicitReload } from '../../tree/TreeElementWithExplicitReload'; const containsDelimited = (fullContext: string | undefined, value: string): boolean => { if (!fullContext) { @@ -74,6 +75,9 @@ export async function retryAuthentication(context: IActionContext, node: Retryab return ext.connectionsBranchDataProvider.refresh(node); case Views.DiscoveryView: + if (isTreeElementWithExplicitReload(node)) { + node.prepareExplicitReload(); + } ext.discoveryBranchDataProvider.resetNodeErrorState(node.id); return ext.discoveryBranchDataProvider.refresh(node); diff --git a/src/commands/updateCredentials/PromptTenantStep.ts b/src/commands/updateCredentials/PromptTenantStep.ts index c4ccb5f14..433361a7a 100644 --- a/src/commands/updateCredentials/PromptTenantStep.ts +++ b/src/commands/updateCredentials/PromptTenantStep.ts @@ -8,7 +8,10 @@ import { AzureWizardPromptStep } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; import * as vscode from 'vscode'; import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; -import { type AzureSubscriptionProviderWithFilters } from '../../plugins/api-shared/azure/AzureSubscriptionProviderWithFilters'; +import { + getUnfilteredAzureTenants, + type AzureSubscriptionProviderWithFilters, +} from '../../plugins/api-shared/azure/AzureSubscriptionProviderWithFilters'; import { traceTenantLookup, type TenantLookupResult } from '../../plugins/api-shared/azure/traceTenantLookup'; import { traceAuthFlow } from '../../utils/authTrace'; import { nonNullValue } from '../../utils/nonNull'; @@ -29,16 +32,22 @@ export class PromptTenantStep extends AzureWizardPromptStep => { // Load available tenants from Azure subscription provider - const { tenants, status } = await this.getAvailableTenants(subscriptionProvider, lookupTimeoutMs); + const { tenants, status } = await this.getAvailableTenants( + subscriptionProvider, + lookupTimeoutMs, + reloadTenants, + ); context.telemetry.measurements.availableTenantsCount = tenants.length; // Create quick pick items @@ -119,9 +128,11 @@ export class PromptTenantStep extends AzureWizardPromptStep { try { - return await traceTenantLookup('updateCredentials.isSignedIn', () => subscriptionProvider.isSignedIn(), { - timeoutMs: TENANT_LOOKUP_TIMEOUT_MS, - fallbackValue: true, - }); + return await traceTenantLookup( + 'updateCredentials.isSignedIn', + () => subscriptionProvider.signIn(undefined, { promptIfNeeded: false }), + { timeoutMs: TENANT_LOOKUP_TIMEOUT_MS, fallbackValue: true }, + ); } catch { return true; } @@ -188,12 +200,13 @@ export class PromptTenantStep extends AzureWizardPromptStep { let timedOut = false; try { const tenants = await traceTenantLookup( 'updateCredentials.getTenants', - () => subscriptionProvider.getTenants(), + () => getUnfilteredAzureTenants(subscriptionProvider, noCache), { timeoutMs, fallbackValue: [], diff --git a/src/connectionDiagnostics/checks/resolveTarget.test.ts b/src/connectionDiagnostics/checks/resolveTarget.test.ts index f9a190440..1951d6c9b 100644 --- a/src/connectionDiagnostics/checks/resolveTarget.test.ts +++ b/src/connectionDiagnostics/checks/resolveTarget.test.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import { type CheckResult, type RunContext } from '@documentdb-js/connection-diagnostics'; +import { NotSignedInError } from '@microsoft/vscode-azext-azureauth'; import { describe, expect, it, vi } from 'vitest'; import { type AuthMethodId } from '../../documentdb/auth/AuthMethod'; import { @@ -150,13 +151,39 @@ describe('resolveTarget check (review R2, option A)', (): void => { 'target.sourceInaccessible', { source: 'azure', reason: 'accessDenied', errorName: 'RestError', statusCode: 403 }, ], + [ + new ConnectionSourceUnavailableError('azure', new NotSignedInError()), + 'target.sourceInaccessible', + { source: 'azure', reason: 'signInRequired', errorName: 'Error' }, + ], + [ + new ConnectionSourceUnavailableError('azure', withStatus(new Error('secret challenge'), { statusCode: 401 })), + 'target.sourceInaccessible', + { source: 'azure', reason: 'signInRequired', errorName: 'Error', statusCode: 401 }, + ], + [ + new ConnectionSourceUnavailableError( + 'azure', + withStatus(new Error('secret broker detail'), { code: 'interaction_required' }), + ), + 'target.sourceInaccessible', + { source: 'azure', reason: 'signInRequired', errorName: 'Error' }, + ], + [ + new ConnectionSourceUnavailableError( + 'azure', + withStatus(new Error('secret authority detail'), { code: 'AADSTS50076', statusCode: 403 }), + ), + 'target.sourceInaccessible', + { source: 'azure', reason: 'signInRequired', errorName: 'Error', statusCode: 403 }, + ], [ new ConnectionSourceUnavailableError( 'azure', - withStatus(new Error('expired'), { name: 'NotSignedInError' }), + withStatus(new Error('secret contains AADSTS50076'), { statusCode: 403 }), ), 'target.sourceInaccessible', - { source: 'azure', reason: 'signInRequired', errorName: 'NotSignedInError' }, + { source: 'azure', reason: 'accessDenied', errorName: 'Error', statusCode: 403 }, ], [ new ConnectionSourceUnavailableError( diff --git a/src/connectionDiagnostics/checks/resolveTarget.ts b/src/connectionDiagnostics/checks/resolveTarget.ts index ea01c7536..7d805654e 100644 --- a/src/connectionDiagnostics/checks/resolveTarget.ts +++ b/src/connectionDiagnostics/checks/resolveTarget.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import { type Check, type CheckOutcome, type Finding, type RunContext } from '@documentdb-js/connection-diagnostics'; +import { isNotSignedInError } from '@microsoft/vscode-azext-azureauth'; import { ConnectionEndpointUnavailableError, ConnectionInputCancelledError, @@ -25,6 +26,19 @@ const SIGN_IN_ERROR_NAMES: ReadonlySet = new Set([ 'NotSignedInError', ]); +function isAzureSignInSignal(error: unknown): boolean { + if (isNotSignedInError(error)) { + return true; + } + if (!(error instanceof Error)) { + return false; + } + const code = 'code' in error ? error.code : undefined; + return [error.name, code].some( + (value) => typeof value === 'string' && (value === 'interaction_required' || /^AADSTS\d{5,9}$/.test(value)), + ); +} + function finding(code: FindingCode, data: Readonly>, text: string): Finding { return { code, severity: 'error', data, detail: { language: 'en', text } }; } @@ -68,7 +82,11 @@ export function classifyResolutionFailure(error: unknown): Finding ); } let reason: SourceInaccessibleReason = 'other'; - if (status === 401 || (cause instanceof Error && SIGN_IN_ERROR_NAMES.has(cause.name))) { + if ( + status === 401 || + (cause instanceof Error && SIGN_IN_ERROR_NAMES.has(cause.name)) || + (source === 'azure' && isAzureSignInSignal(cause)) + ) { reason = 'signInRequired'; } else if (status === 403) { reason = 'accessDenied'; diff --git a/src/deepLinks/azureSubscription.test.ts b/src/deepLinks/azureSubscription.test.ts index 7cd8237f8..8218fb423 100644 --- a/src/deepLinks/azureSubscription.test.ts +++ b/src/deepLinks/azureSubscription.test.ts @@ -3,7 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { type AzureSubscription } from '@microsoft/vscode-azext-azureauth'; +import { getSessionFromVSCode, type AzureSubscription } from '@microsoft/vscode-azext-azureauth'; import { callWithTelemetryAndErrorHandling, type IActionContext } from '@microsoft/vscode-azext-utils'; import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest'; import * as vscode from 'vscode'; @@ -29,6 +29,10 @@ vi.mock('../extensionVariables', () => ({ vi.mock('@microsoft/vscode-azext-utils', () => ({ callWithTelemetryAndErrorHandling: vi.fn(), })); +vi.mock('@microsoft/vscode-azext-azureauth', async (importOriginal) => ({ + ...(await importOriginal()), + getSessionFromVSCode: vi.fn(), +})); vi.mock('../services/discoveryServices', () => ({ DiscoveryService: { getProvider: vi.fn() }, })); @@ -37,9 +41,16 @@ vi.mock('../plugins/api-shared/azure/subscriptionFiltering/subscriptionFiltering })); const azureSubscriptionProvider = { - isSignedIn: vi.fn(), signIn: vi.fn(), - getSubscriptions: vi.fn(), + getAvailableSubscriptions: vi.fn(), +}; +const listingOptions = { filter: false, maximumTenants: Number.POSITIVE_INFINITY }; + +const session: vscode.AuthenticationSession = { + id: 'session-id', + accessToken: 'token', + account: { id: 'account-id', label: 'account-id' }, + scopes: [], }; const provider = { @@ -76,9 +87,9 @@ beforeEach((): void => { }, ); provider.configureCredentials.mockResolvedValue(undefined); - azureSubscriptionProvider.isSignedIn.mockResolvedValue(true); azureSubscriptionProvider.signIn.mockResolvedValue(true); - azureSubscriptionProvider.getSubscriptions.mockResolvedValue([]); + azureSubscriptionProvider.getAvailableSubscriptions.mockResolvedValue([]); + vi.mocked(getSessionFromVSCode).mockResolvedValue(session); vi.mocked(isTenantFilteredOut).mockReturnValue(false); }); @@ -86,11 +97,11 @@ describe('resolveAzureSubscription', (): void => { it('reports sign-in and subscription lookup before running each step', async (): Promise => { const report = vi.fn<(message: string) => void>(); const found = subscription('tenant-id', 'account-id'); - azureSubscriptionProvider.isSignedIn.mockImplementation(async (): Promise => { + azureSubscriptionProvider.signIn.mockImplementation(async (): Promise => { expect(report).toHaveBeenLastCalledWith('Checking Azure sign-in…'); return true; }); - azureSubscriptionProvider.getSubscriptions.mockImplementation(async (): Promise => { + azureSubscriptionProvider.getAvailableSubscriptions.mockImplementation(async (): Promise => { expect(report).toHaveBeenLastCalledWith('Looking for the subscription…'); return [found]; }); @@ -102,21 +113,22 @@ describe('resolveAzureSubscription', (): void => { it('prompts a signed-out user, signs in, and resolves an unfiltered subscription', async (): Promise => { const found = subscription('tenant-id', 'account-id'); - azureSubscriptionProvider.isSignedIn.mockResolvedValue(false); - azureSubscriptionProvider.getSubscriptions.mockResolvedValue([found]); + azureSubscriptionProvider.signIn.mockResolvedValueOnce(false); + azureSubscriptionProvider.getAvailableSubscriptions.mockResolvedValue([found]); (vscode.window.showInformationMessage as Mock).mockResolvedValue('Sign in'); await expect(resolveAzureSubscription(context, request)).resolves.toBe(found); expect(DiscoveryService.getProvider).toHaveBeenCalledWith(request.providerId); - expect(azureSubscriptionProvider.isSignedIn).toHaveBeenCalledWith(); + expect(azureSubscriptionProvider.signIn).toHaveBeenNthCalledWith(1, undefined, { promptIfNeeded: false }); expect(vscode.window.showInformationMessage).toHaveBeenCalledWith( 'Sign in to Azure', { modal: true, detail: 'Sign in to Azure to open linked-resource.' }, 'Sign in', ); - expect(azureSubscriptionProvider.signIn).toHaveBeenCalledWith(); - expect(azureSubscriptionProvider.getSubscriptions).toHaveBeenCalledExactlyOnceWith(false); + expect(azureSubscriptionProvider.signIn).toHaveBeenNthCalledWith(2, undefined, { clearSessionPreference: true }); + expect(azureSubscriptionProvider.signIn).toHaveBeenCalledTimes(2); + expect(azureSubscriptionProvider.getAvailableSubscriptions).toHaveBeenCalledExactlyOnceWith(listingOptions); expect(ext.outputChannel.trace).toHaveBeenCalledWith('[DeepLink] Azure sign-in: sign-in required'); expect(ext.outputChannel.trace).toHaveBeenCalledWith('[DeepLink] Azure sign-in confirmation: accepted'); expect(ext.outputChannel.trace).toHaveBeenCalledWith('[DeepLink] 1 matching subscription(s) found'); @@ -132,7 +144,7 @@ describe('resolveAzureSubscription', (): void => { }); it('returns undefined without listing subscriptions when the Azure sign-in prompt is dismissed', async (): Promise => { - azureSubscriptionProvider.isSignedIn.mockResolvedValue(false); + azureSubscriptionProvider.signIn.mockResolvedValueOnce(false); (vscode.window.showInformationMessage as Mock).mockResolvedValue(undefined); await expect(resolveAzureSubscription(context, request)).resolves.toBeUndefined(); @@ -145,12 +157,11 @@ describe('resolveAzureSubscription', (): void => { result: 'Canceled', }); expect(ext.outputChannel.trace).toHaveBeenCalledWith('[DeepLink] Azure sign-in confirmation: dismissed'); - expect(azureSubscriptionProvider.signIn).not.toHaveBeenCalled(); - expect(azureSubscriptionProvider.getSubscriptions).not.toHaveBeenCalled(); + expect(azureSubscriptionProvider.signIn).toHaveBeenCalledExactlyOnceWith(undefined, { promptIfNeeded: false }); + expect(azureSubscriptionProvider.getAvailableSubscriptions).not.toHaveBeenCalled(); }); it('treats a false Azure sign-in result as cancellation', async (): Promise => { - azureSubscriptionProvider.isSignedIn.mockResolvedValue(false); azureSubscriptionProvider.signIn.mockResolvedValue(false); (vscode.window.showInformationMessage as Mock).mockResolvedValue('Sign in'); @@ -158,13 +169,24 @@ describe('resolveAzureSubscription', (): void => { expect(context.telemetry.properties.userCancelledAtStep).toBe('AzureSignIn'); expect(context.telemetry.properties.failureStage).toBe('azureSignIn'); - expect(azureSubscriptionProvider.getSubscriptions).not.toHaveBeenCalled(); + expect(azureSubscriptionProvider.getAvailableSubscriptions).not.toHaveBeenCalled(); + }); + + it('propagates unrelated silent sign-in failures without prompting or listing subscriptions', async () => { + const failure = new Error('Azure authentication provider failed'); + azureSubscriptionProvider.signIn.mockRejectedValueOnce(failure); + + await expect(resolveAzureSubscription(context, request)).rejects.toBe(failure); + + expect(azureSubscriptionProvider.signIn).toHaveBeenCalledExactlyOnceWith(undefined, { promptIfNeeded: false }); + expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); + expect(azureSubscriptionProvider.getAvailableSubscriptions).not.toHaveBeenCalled(); }); it('uses the case-insensitive tenant hint to select between accounts sharing a subscription ID', async (): Promise => { const otherTenant = subscription('other-tenant', 'account-one'); const hintedTenant = subscription('tenant-id', 'account-two'); - azureSubscriptionProvider.getSubscriptions.mockResolvedValue([otherTenant, hintedTenant]); + azureSubscriptionProvider.getAvailableSubscriptions.mockResolvedValue([otherTenant, hintedTenant]); await expect(resolveAzureSubscription(context, { ...request, tenantId: 'TENANT-ID' })).resolves.toBe( hintedTenant, @@ -176,13 +198,13 @@ describe('resolveAzureSubscription', (): void => { tenantSignInRequired: 'false', }); expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); - expect(azureSubscriptionProvider.signIn).not.toHaveBeenCalled(); + expect(azureSubscriptionProvider.signIn).toHaveBeenCalledExactlyOnceWith(undefined, { promptIfNeeded: false }); }); it('prefers the first non-filtered account when there is no tenant hint', async (): Promise => { const filtered = subscription('tenant-one', 'account-one'); const visible = subscription('tenant-two', 'account-two'); - azureSubscriptionProvider.getSubscriptions.mockResolvedValue([filtered, visible]); + azureSubscriptionProvider.getAvailableSubscriptions.mockResolvedValue([filtered, visible]); vi.mocked(isTenantFilteredOut).mockImplementation( (tenantId, accountId): boolean => tenantId === filtered.tenantId && accountId === filtered.account.id, ); @@ -196,7 +218,7 @@ describe('resolveAzureSubscription', (): void => { it('falls back to the first candidate when all matching tenants are filtered out', async (): Promise => { const first = subscription('tenant-one', 'account-one'); - azureSubscriptionProvider.getSubscriptions.mockResolvedValue([ + azureSubscriptionProvider.getAvailableSubscriptions.mockResolvedValue([ first, subscription('tenant-two', 'account-two'), ]); @@ -211,14 +233,14 @@ describe('resolveAzureSubscription', (): void => { it('signs into the hinted tenant and retries unfiltered subscription resolution exactly once', async (): Promise => { const report = vi.fn<(message: string) => void>(); const found = subscription('tenant-id', 'account-id'); - azureSubscriptionProvider.getSubscriptions.mockResolvedValueOnce([]).mockResolvedValueOnce([found]); + azureSubscriptionProvider.getAvailableSubscriptions.mockResolvedValueOnce([]).mockResolvedValueOnce([found]); (vscode.window.showInformationMessage as Mock).mockImplementation(async (): Promise => { expect(report).not.toHaveBeenCalledWith('Signing in to tenant…'); return 'Sign in to tenant'; }); - azureSubscriptionProvider.signIn.mockImplementation(async (): Promise => { + vi.mocked(getSessionFromVSCode).mockImplementation(async (): Promise => { expect(report).toHaveBeenLastCalledWith('Signing in to tenant…'); - return true; + return session; }); await expect(resolveAzureSubscription(context, { ...request, tenantId: 'TENANT-ID' }, report)).resolves.toBe( @@ -240,10 +262,16 @@ describe('resolveAzureSubscription', (): void => { }, 'Sign in to tenant', ); - expect(azureSubscriptionProvider.signIn).toHaveBeenCalledExactlyOnceWith('TENANT-ID'); - expect(azureSubscriptionProvider.getSubscriptions).toHaveBeenCalledTimes(2); - expect(azureSubscriptionProvider.getSubscriptions).toHaveBeenNthCalledWith(1, false); - expect(azureSubscriptionProvider.getSubscriptions).toHaveBeenNthCalledWith(2, false); + expect(getSessionFromVSCode).toHaveBeenCalledExactlyOnceWith(undefined, 'TENANT-ID', { + createIfNone: true, + clearSessionPreference: true, + }); + expect(azureSubscriptionProvider.getAvailableSubscriptions).toHaveBeenCalledTimes(2); + expect(azureSubscriptionProvider.getAvailableSubscriptions).toHaveBeenNthCalledWith(1, listingOptions); + expect(azureSubscriptionProvider.getAvailableSubscriptions).toHaveBeenNthCalledWith(2, { + ...listingOptions, + noCache: true, + }); expect(context.telemetry.properties).toEqual({ failureStage: 'resolveSubscription', azureSignInRequired: 'false', @@ -252,13 +280,16 @@ describe('resolveAzureSubscription', (): void => { }); it('treats a false tenant sign-in result as cancellation without retrying subscription lookup', async (): Promise => { - azureSubscriptionProvider.signIn.mockResolvedValue(false); + vi.mocked(getSessionFromVSCode).mockResolvedValue(undefined); (vscode.window.showInformationMessage as Mock).mockResolvedValue('Sign in to tenant'); await expect(resolveAzureSubscription(context, { ...request, tenantId: 'tenant-id' })).resolves.toBeUndefined(); - expect(azureSubscriptionProvider.signIn).toHaveBeenCalledExactlyOnceWith('tenant-id'); - expect(azureSubscriptionProvider.getSubscriptions).toHaveBeenCalledExactlyOnceWith(false); + expect(getSessionFromVSCode).toHaveBeenCalledExactlyOnceWith(undefined, 'tenant-id', { + createIfNone: true, + clearSessionPreference: true, + }); + expect(azureSubscriptionProvider.getAvailableSubscriptions).toHaveBeenCalledExactlyOnceWith(listingOptions); expect(context.telemetry.properties).toMatchObject({ tenantSignInRequired: 'true', deepLinkOutcome: 'canceled', @@ -271,7 +302,7 @@ describe('resolveAzureSubscription', (): void => { }); it('throws with a working Manage Azure accounts button when the tenant retry still cannot find the subscription', async (): Promise => { - azureSubscriptionProvider.getSubscriptions.mockResolvedValue([ + azureSubscriptionProvider.getAvailableSubscriptions.mockResolvedValue([ subscription('other-tenant', 'account-id'), subscription('tenant-id', 'account-id', 'different-subscription'), ]); @@ -281,8 +312,11 @@ describe('resolveAzureSubscription', (): void => { 'We could not find subscription Subscription-ID among your signed-in Azure accounts. Check that you are signed in with the right account and to the right Azure cloud.', ); - expect(azureSubscriptionProvider.getSubscriptions).toHaveBeenCalledTimes(2); - expect(azureSubscriptionProvider.signIn).toHaveBeenCalledExactlyOnceWith('tenant-id'); + expect(azureSubscriptionProvider.getAvailableSubscriptions).toHaveBeenCalledTimes(2); + expect(getSessionFromVSCode).toHaveBeenCalledExactlyOnceWith(undefined, 'tenant-id', { + createIfNone: true, + clearSessionPreference: true, + }); expect(vscode.window.showInformationMessage).toHaveBeenCalledTimes(1); expect(context.telemetry.properties).toEqual({ failureStage: 'resolveSubscription', @@ -314,13 +348,14 @@ describe('resolveAzureSubscription', (): void => { expect(context.telemetry.properties.userCancelledAtStep).toBe('AzureTenantSignIn'); expect(context.telemetry.properties.tenantSignInRequired).toBe('true'); - expect(azureSubscriptionProvider.getSubscriptions).toHaveBeenCalledTimes(1); - expect(azureSubscriptionProvider.signIn).not.toHaveBeenCalled(); + expect(azureSubscriptionProvider.getAvailableSubscriptions).toHaveBeenCalledExactlyOnceWith(listingOptions); + expect(azureSubscriptionProvider.signIn).toHaveBeenCalledExactlyOnceWith(undefined, { promptIfNeeded: false }); + expect(getSessionFromVSCode).not.toHaveBeenCalled(); expect(context.errorHandling.buttons).toBeUndefined(); }); it('throws without a tenant prompt when no subscription matches and there is no tenant hint', async (): Promise => { - azureSubscriptionProvider.getSubscriptions.mockResolvedValue([ + azureSubscriptionProvider.getAvailableSubscriptions.mockResolvedValue([ subscription('tenant-id', 'account-id', 'different-subscription'), ]); @@ -329,8 +364,9 @@ describe('resolveAzureSubscription', (): void => { ); expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); - expect(azureSubscriptionProvider.signIn).not.toHaveBeenCalled(); - expect(azureSubscriptionProvider.getSubscriptions).toHaveBeenCalledExactlyOnceWith(false); + expect(azureSubscriptionProvider.signIn).toHaveBeenCalledExactlyOnceWith(undefined, { promptIfNeeded: false }); + expect(getSessionFromVSCode).not.toHaveBeenCalled(); + expect(azureSubscriptionProvider.getAvailableSubscriptions).toHaveBeenCalledExactlyOnceWith(listingOptions); expect(context.telemetry.properties.tenantSignInRequired).toBe('false'); expect(context.telemetry.measurements.subscriptionAccountCount).toBe(0); expect(context.errorHandling.buttons?.[0].title).toBe('Manage Azure accounts'); @@ -346,8 +382,8 @@ describe('resolveAzureSubscription', (): void => { ); expect(context.telemetry.properties.failureStage).toBe('azureSignIn'); - expect(azureSubscriptionProvider.isSignedIn).not.toHaveBeenCalled(); - expect(azureSubscriptionProvider.getSubscriptions).not.toHaveBeenCalled(); + expect(azureSubscriptionProvider.signIn).not.toHaveBeenCalled(); + expect(azureSubscriptionProvider.getAvailableSubscriptions).not.toHaveBeenCalled(); expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); }, ); diff --git a/src/deepLinks/azureSubscription.ts b/src/deepLinks/azureSubscription.ts index da699af39..ee1f23906 100644 --- a/src/deepLinks/azureSubscription.ts +++ b/src/deepLinks/azureSubscription.ts @@ -3,7 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { type AzureSubscription } from '@microsoft/vscode-azext-azureauth'; +import { getSessionFromVSCode, type AzureSubscription } from '@microsoft/vscode-azext-azureauth'; import { callWithTelemetryAndErrorHandling, type IActionContext } from '@microsoft/vscode-azext-utils'; import * as vscode from 'vscode'; import { ext } from '../extensionVariables'; @@ -53,7 +53,7 @@ export async function resolveAzureSubscription( ext.outputChannel.trace('[DeepLink] Checking Azure sign-in'); report?.(vscode.l10n.t('Checking Azure sign-in…')); const isSignedIn = await measureDeepLinkPhase(context, 'azureSignInCheck', () => - azureSubscriptionProvider.isSignedIn(), + azureSubscriptionProvider.signIn(undefined, { promptIfNeeded: false }), ); ext.outputChannel.trace(`[DeepLink] Azure sign-in: ${isSignedIn ? 'signed in' : 'sign-in required'}`); context.telemetry.properties.azureSignInRequired = isSignedIn ? 'false' : 'true'; @@ -72,7 +72,9 @@ export async function resolveAzureSubscription( ); if ( choice !== signInButton || - !(await measureDeepLinkPhase(context, 'azureSignIn', () => azureSubscriptionProvider.signIn())) + !(await measureDeepLinkPhase(context, 'azureSignIn', () => + azureSubscriptionProvider.signIn(undefined, { clearSessionPreference: true }), + )) ) { ext.outputChannel.trace('[DeepLink] Azure sign-in stopped'); cancelDeepLink(context, 'AzureSignIn'); @@ -87,7 +89,11 @@ export async function resolveAzureSubscription( ext.outputChannel.trace('[DeepLink] Listing subscriptions'); report?.(vscode.l10n.t('Looking for the subscription…')); const subscriptions = await measureDeepLinkPhase(context, 'subscriptionLookup', () => - azureSubscriptionProvider.getSubscriptions(false), + azureSubscriptionProvider.getAvailableSubscriptions({ + filter: false, + maximumTenants: Number.POSITIVE_INFINITY, + ...(attempt === 1 ? { noCache: true } : {}), + }), ); const candidates = subscriptions.filter( (subscription) => @@ -134,7 +140,7 @@ export async function resolveAzureSubscription( } report?.(vscode.l10n.t('Signing in to tenant…')); const signedIn = await measureDeepLinkPhase(context, 'azureSignIn', () => - azureSubscriptionProvider.signIn(tenantId), + getSessionFromVSCode(undefined, tenantId, { createIfNone: true, clearSessionPreference: true }), ); if (!signedIn) { ext.outputChannel.trace('[DeepLink] Tenant sign-in stopped'); diff --git a/src/documentdb/auth/documentdbTokenResource.test.ts b/src/documentdb/auth/documentdbTokenResource.test.ts index 31eafd01f..195eecc5d 100644 --- a/src/documentdb/auth/documentdbTokenResource.test.ts +++ b/src/documentdb/auth/documentdbTokenResource.test.ts @@ -4,7 +4,7 @@ *--------------------------------------------------------------------------------------------*/ // eslint-disable-next-line import/no-internal-modules -import { getConfiguredAzureEnv } from '@microsoft/vscode-azext-azureauth/out/src/utils/configuredAzureEnv'; +import { getConfiguredAzureEnv } from '@microsoft/vscode-azext-azureauth'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import * as vscode from 'vscode'; import { diff --git a/src/documentdb/auth/sovereignAuth.integration.test.ts b/src/documentdb/auth/sovereignAuth.integration.test.ts index c9f907666..e0d6bdf04 100644 --- a/src/documentdb/auth/sovereignAuth.integration.test.ts +++ b/src/documentdb/auth/sovereignAuth.integration.test.ts @@ -33,7 +33,8 @@ vi.mock('../../extensionVariables', () => ({ }, })); -vi.mock('@microsoft/vscode-azext-azureauth/out/src/getSessionFromVSCode', () => ({ +vi.mock('@microsoft/vscode-azext-azureauth', async (importOriginal) => ({ + ...(await importOriginal()), getSessionFromVSCode: getSession, })); diff --git a/src/documentdb/playground/PlaygroundEvaluator.test.ts b/src/documentdb/playground/PlaygroundEvaluator.test.ts index f86ba3983..af0bb196e 100644 --- a/src/documentdb/playground/PlaygroundEvaluator.test.ts +++ b/src/documentdb/playground/PlaygroundEvaluator.test.ts @@ -80,7 +80,8 @@ vi.mock('../CredentialCache', () => ({ }, })); -vi.mock('@microsoft/vscode-azext-azureauth/out/src/getSessionFromVSCode', () => ({ +vi.mock('@microsoft/vscode-azext-azureauth', async (importOriginal) => ({ + ...(await importOriginal()), getSessionFromVSCode: mocks.interactiveToken, })); diff --git a/src/documentdb/playground/PlaygroundEvaluator.ts b/src/documentdb/playground/PlaygroundEvaluator.ts index 605db229f..246ab068e 100644 --- a/src/documentdb/playground/PlaygroundEvaluator.ts +++ b/src/documentdb/playground/PlaygroundEvaluator.ts @@ -454,10 +454,7 @@ export class PlaygroundEvaluator implements vscode.Disposable { throw error; } } else { - const { getSessionFromVSCode } = await import( - // eslint-disable-next-line import/no-internal-modules - '@microsoft/vscode-azext-azureauth/out/src/getSessionFromVSCode' - ); + const { getSessionFromVSCode } = await import('@microsoft/vscode-azext-azureauth'); let session: vscode.AuthenticationSession | undefined; try { session = await traceAuthOperation( diff --git a/src/documentdb/shell/ShellSessionManager.test.ts b/src/documentdb/shell/ShellSessionManager.test.ts index 071210175..ba1f6e65f 100644 --- a/src/documentdb/shell/ShellSessionManager.test.ts +++ b/src/documentdb/shell/ShellSessionManager.test.ts @@ -46,7 +46,8 @@ vi.mock('../../extensionVariables', () => ({ }, })); -vi.mock('@microsoft/vscode-azext-azureauth/out/src/getSessionFromVSCode', () => ({ +vi.mock('@microsoft/vscode-azext-azureauth', async (importOriginal) => ({ + ...(await importOriginal()), getSessionFromVSCode: (...args: unknown[]) => mockGetSessionFromVSCode(...args), })); diff --git a/src/documentdb/shell/ShellSessionManager.ts b/src/documentdb/shell/ShellSessionManager.ts index 8f7f9934c..12d8b9a31 100644 --- a/src/documentdb/shell/ShellSessionManager.ts +++ b/src/documentdb/shell/ShellSessionManager.ts @@ -437,10 +437,7 @@ export class ShellSessionManager implements vscode.Disposable { throw error; } } else { - const { getSessionFromVSCode } = await import( - // eslint-disable-next-line import/no-internal-modules - '@microsoft/vscode-azext-azureauth/out/src/getSessionFromVSCode' - ); + const { getSessionFromVSCode } = await import('@microsoft/vscode-azext-azureauth'); let session: vscode.AuthenticationSession | undefined; try { session = await traceAuthOperation( diff --git a/src/plugins/api-shared/azure/AzureSubscriptionProviderWithFilters.test.ts b/src/plugins/api-shared/azure/AzureSubscriptionProviderWithFilters.test.ts new file mode 100644 index 000000000..5c26f8598 --- /dev/null +++ b/src/plugins/api-shared/azure/AzureSubscriptionProviderWithFilters.test.ts @@ -0,0 +1,166 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { Environment } from '@azure/ms-rest-azure-env'; +import { + ExtendedEnvironment, + NotSignedInError, + VSCodeAzureSubscriptionProvider, + type AzureSubscription, + type AzureTenant, +} from '@microsoft/vscode-azext-azureauth'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import * as vscode from 'vscode'; +import { ext } from '../../../extensionVariables'; +import { AzureSubscriptionProviderWithFilters } from './AzureSubscriptionProviderWithFilters'; + +vi.mock('../../../extensionVariables', () => ({ ext: { outputChannel: { warn: vi.fn() } } })); + +vi.mock('vscode', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + authentication: { + ...actual.authentication, + getAccounts: vi.fn(), + onDidChangeSessions: vi.fn(() => ({ dispose: vi.fn() })), + }, + workspace: { + ...actual.workspace, + onDidChangeConfiguration: vi.fn(() => ({ dispose: vi.fn() })), + }, + }; +}); + +describe('AzureSubscriptionProviderWithFilters', () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('bypasses the cache for one requested listing, not for routine listings', async () => { + const baseListing = vi.spyOn(VSCodeAzureSubscriptionProvider.prototype, 'getAvailableSubscriptions'); + baseListing.mockResolvedValue([]); + const provider = new AzureSubscriptionProviderWithFilters(); + const options = { filter: true, maximumTenants: Number.POSITIVE_INFINITY }; + + await provider.getAvailableSubscriptions(options); + provider.requestFreshListing(); + const explicit = provider.getAvailableSubscriptions(options); + const routine = provider.getAvailableSubscriptions(options); + await Promise.all([explicit, routine]); + + expect(baseListing.mock.calls).toEqual([[options], [{ ...options, noCache: true }], [options]]); + expect(options).not.toHaveProperty('noCache'); + provider.dispose(); + }); + + it('returns an empty list only for the SDK no-session error', async () => { + const failure = new Error('ARM listing failed'); + vi.spyOn(VSCodeAzureSubscriptionProvider.prototype, 'getAvailableSubscriptions') + .mockRejectedValueOnce(new NotSignedInError()) + .mockRejectedValueOnce(failure); + const provider = new AzureSubscriptionProviderWithFilters(); + + await expect(provider.getAvailableSubscriptions()).resolves.toEqual([]); + await expect(provider.getAvailableSubscriptions()).rejects.toBe(failure); + provider.dispose(); + }); + + it.each(['cloud', 'session'] as const)('reloads cached accounts after a %s change', async (kind) => { + const cloudListener = vi.mocked(vscode.workspace.onDidChangeConfiguration); + const sessionListener = vi.mocked(vscode.authentication.onDidChangeSessions); + const getAccounts = vi.mocked(vscode.authentication.getAccounts); + cloudListener.mockClear(); + sessionListener.mockClear(); + getAccounts.mockClear(); + getAccounts.mockResolvedValue([{ id: 'fixture-account', label: 'Fixture account' }]); + vi.useFakeTimers(); + const provider = new AzureSubscriptionProviderWithFilters(); + vi.spyOn(provider, 'getTenantsForAccount').mockResolvedValue([]); + + try { + await provider.getAvailableSubscriptions({ filter: false }); + await provider.getAvailableSubscriptions({ filter: false }); + expect(getAccounts).toHaveBeenCalledOnce(); + + if (kind === 'cloud') { + cloudListener.mock.calls[0][0]({ + affectsConfiguration: (section): boolean => section === 'microsoft-sovereign-cloud', + }); + } else { + // The SDK suppresses session events during and just after account enumeration. + await vi.runOnlyPendingTimersAsync(); + sessionListener.mock.calls[0][0]({ provider: { id: 'microsoft', label: 'Microsoft' } }); + } + + await provider.getAvailableSubscriptions({ filter: false }); + expect(getAccounts).toHaveBeenCalledTimes(2); + } finally { + provider.dispose(); + vi.useRealTimers(); + } + + expect(cloudListener.mock.results[0].value.dispose).toHaveBeenCalledOnce(); + expect(sessionListener.mock.results[0].value.dispose).toHaveBeenCalledOnce(); + }); + + it('keeps subscriptions beyond ten tenants and emits only bounded warnings for skipped failures', async () => { + const provider = new AzureSubscriptionProviderWithFilters(); + const environment = new ExtendedEnvironment(Environment.AzureCloud, false); + const account = { id: 'private-account-id', label: 'private-account-label', environment }; + const failedAccount = { ...account, id: 'failed-account-id' }; + const tenants: AzureTenant[] = Array.from({ length: 11 }, (_, index) => ({ + account, + tenantId: `private-tenant-${index}`, + })); + const subscription: AzureSubscription = { + account, + authentication: { getSession: vi.fn(), getSessionWithScopes: vi.fn() }, + credential: { getToken: vi.fn() }, + environment, + isCustomCloud: false, + name: 'Private subscription', + subscriptionId: 'private-subscription-id', + tenantId: tenants[10].tenantId, + }; + const failure = new Error('ARM error with private details'); + vi.spyOn(provider, 'getAccounts').mockResolvedValue([account, failedAccount]); + vi.spyOn(provider, 'getTenantsForAccount').mockImplementation(async (requestedAccount) => { + if (requestedAccount === failedAccount) { + throw failure; + } + return tenants; + }); + const getSubscriptionsForTenant = vi + .spyOn(provider, 'getSubscriptionsForTenant') + .mockImplementation(async ({ tenantId }) => { + switch (tenantId) { + case tenants[0].tenantId: + throw failure; + case tenants[1].tenantId: + throw new NotSignedInError(); + case subscription.tenantId: + return [subscription]; + default: + return []; + } + }); + + await expect( + provider.getAvailableSubscriptions({ filter: false, maximumTenants: Number.POSITIVE_INFINITY }), + ).resolves.toEqual([subscription]); + + expect(getSubscriptionsForTenant).toHaveBeenCalledTimes(11); + const warnings = vi.mocked(ext.outputChannel.warn).mock.calls; + expect(warnings).toHaveLength(2); + expect(warnings).toEqual( + expect.arrayContaining([ + ['Skipped an Azure account because its tenants could not be listed.'], + ['Skipped an Azure tenant because its subscriptions could not be listed.'], + ]), + ); + provider.dispose(); + }); +}); diff --git a/src/plugins/api-shared/azure/AzureSubscriptionProviderWithFilters.ts b/src/plugins/api-shared/azure/AzureSubscriptionProviderWithFilters.ts index f10fb19a2..70b2e7ac6 100644 --- a/src/plugins/api-shared/azure/AzureSubscriptionProviderWithFilters.ts +++ b/src/plugins/api-shared/azure/AzureSubscriptionProviderWithFilters.ts @@ -4,20 +4,62 @@ *--------------------------------------------------------------------------------------------*/ import { + isNotSignedInError, VSCodeAzureSubscriptionProvider, + type AzureAccount, type AzureSubscription, - type GetSubscriptionsFilter, + type AzureTenant, + type GetAvailableSubscriptionsOptions, type SubscriptionId, + type TenantIdAndAccount, } from '@microsoft/vscode-azext-azureauth'; import * as vscode from 'vscode'; import { ext } from '../../../extensionVariables'; +export async function getUnfilteredAzureTenants( + provider: VSCodeAzureSubscriptionProvider, + noCache?: boolean, +): Promise { + const options = noCache ? { filter: false, noCache: true } : { filter: false }; + let accounts: AzureAccount[]; + try { + accounts = await provider.getAccounts(options); + } catch (error) { + if (isNotSignedInError(error)) { + return []; + } + throw error; + } + + const tenants: AzureTenant[] = []; + for (const account of accounts) { + try { + tenants.push(...(await provider.getTenantsForAccount(account, options))); + } catch (error) { + if (!isNotSignedInError(error)) { + throw error; + } + } + } + return tenants; +} + /** * Extends VSCodeAzureSubscriptionProvider to customize tenant and subscription filters */ export class AzureSubscriptionProviderWithFilters extends VSCodeAzureSubscriptionProvider { - constructor(logger?: vscode.LogOutputChannel) { - super(logger); + private freshListingRequested = false; + private readonly cacheRefreshSubscription: vscode.Disposable; + + constructor() { + super(); + // The SDK starts its cache invalidation listeners only when subscribed. + this.cacheRefreshSubscription = this.onRefreshSuggested(() => undefined); + } + + public override dispose(): void { + this.cacheRefreshSubscription.dispose(); + super.dispose(); } private getTenantAndSubscriptionFilters(): string[] { @@ -35,15 +77,34 @@ export class AzureSubscriptionProviderWithFilters extends VSCodeAzureSubscriptio return fullSubscriptionIds; } - /** - * Gets subscriptions from the Azure subscription provider. - * Note: Callers must explicitly call getTenantFilteredSubscriptions() if tenant filtering is needed. - * - * @param filter Whether to apply subscription filtering or a custom filter - * @returns List of subscriptions from the base provider (without tenant filtering) - */ - public override async getSubscriptions(filter?: boolean | GetSubscriptionsFilter): Promise { - return await super.getSubscriptions(filter); + public requestFreshListing(): void { + this.freshListingRequested = true; + } + + public override async getAvailableSubscriptions( + options?: GetAvailableSubscriptionsOptions, + ): Promise { + if (this.freshListingRequested) { + this.freshListingRequested = false; + options = { ...options, noCache: true }; + } + + try { + return await super.getAvailableSubscriptions(options); + } catch (error) { + if (isNotSignedInError(error)) { + return []; + } + throw error; + } + } + + protected override errorForAccount(_account: AzureAccount, _message: string, _error: unknown): void { + ext.outputChannel.warn(vscode.l10n.t('Skipped an Azure account because its tenants could not be listed.')); + } + + protected override errorForTenant(_tenant: TenantIdAndAccount, _message: string, _error: unknown): void { + ext.outputChannel.warn(vscode.l10n.t('Skipped an Azure tenant because its subscriptions could not be listed.')); } /** diff --git a/src/plugins/api-shared/azure/credentialsManagement/AccountTenantsStep.ts b/src/plugins/api-shared/azure/credentialsManagement/AccountTenantsStep.ts index 4441c6894..8d0512fe6 100644 --- a/src/plugins/api-shared/azure/credentialsManagement/AccountTenantsStep.ts +++ b/src/plugins/api-shared/azure/credentialsManagement/AccountTenantsStep.ts @@ -140,7 +140,7 @@ export class AccountTenantsStep extends AzureWizardPromptStep - context.azureSubscriptionProvider.getTenants(), + getUnfilteredAzureTenants(context.azureSubscriptionProvider), ); // Check sign-in status for all tenants with bounded parallelism @@ -158,7 +159,10 @@ export class SelectAccountStep extends AzureWizardPromptStep { const tenantId = nonNullProp(tenant, 'tenantId', 'tenant.tenantId', 'SelectAccountStep.ts'); const isSignedIn = await tenantSignInLimiter(() => - context.azureSubscriptionProvider.isSignedIn(tenantId, tenant.account), + context.azureSubscriptionProvider.signIn( + { tenantId, account: tenant.account }, + { promptIfNeeded: false }, + ), ); return { tenant, isSignedIn }; }), @@ -196,7 +200,7 @@ export class SelectAccountStep extends AzureWizardPromptStep { try { ext.outputChannel.info(l10n.t('Starting Azure sign-in process…')); - const success = await context.azureSubscriptionProvider.signIn(); + const success = await context.azureSubscriptionProvider.signIn(undefined, { clearSessionPreference: true }); if (success) { ext.outputChannel.info(l10n.t('Azure sign-in completed successfully')); } else { diff --git a/src/plugins/api-shared/azure/subscriptionFiltering/InitializeFilteringStep.ts b/src/plugins/api-shared/azure/subscriptionFiltering/InitializeFilteringStep.ts index ea3246165..e3a13ff49 100644 --- a/src/plugins/api-shared/azure/subscriptionFiltering/InitializeFilteringStep.ts +++ b/src/plugins/api-shared/azure/subscriptionFiltering/InitializeFilteringStep.ts @@ -14,7 +14,10 @@ import { type AzureSubscription } from '@microsoft/vscode-azureresources-api'; import * as l10n from '@vscode/l10n'; import { type QuickPickItem } from 'vscode'; import { askToConfigureCredentials } from '../askToConfigureCredentials'; -import { type AzureSubscriptionProviderWithFilters } from '../AzureSubscriptionProviderWithFilters'; +import { + getUnfilteredAzureTenants, + type AzureSubscriptionProviderWithFilters, +} from '../AzureSubscriptionProviderWithFilters'; import { tenantSignInLimiter } from '../tenantSignInLimiter'; import { type FilteringWizardContext } from './FilteringWizardContext'; import { FilterSubscriptionSubStep } from './FilterSubscriptionSubStep'; @@ -61,7 +64,7 @@ export class InitializeFilteringStep extends AzureWizardPromptStep - azureSubscriptionProvider.isSignedIn(tenant.tenantId, tenant.account), + azureSubscriptionProvider.signIn(tenant, { promptIfNeeded: false }), ); return { tenant, isSignedIn }; }), @@ -93,7 +96,10 @@ export class InitializeFilteringStep extends AzureWizardPromptStep => { // Note: No tenant filtering here, because this flow should allow the user to access everything with no filtering. - subscriptions = await subscriptionProvider.getSubscriptions(false); + subscriptions = await subscriptionProvider.getAvailableSubscriptions({ + filter: false, + maximumTenants: Number.POSITIVE_INFINITY, + }); // This information is extracted to improve the UX, that's why there are fallbacks to 'undefined' - // Note to future maintainers: we used to run getSubscriptions and getTenants "in parallel", however - // this lead to incorrect responses from getSubscriptions. We didn't investigate - const tenantPromise = subscriptionProvider.getTenants().catch(() => undefined); + const tenantPromise = getUnfilteredAzureTenants(subscriptionProvider).catch(() => undefined); const timeoutPromise = new Promise((resolve) => setTimeout(() => resolve(undefined), 5000)); const knownTenants = await Promise.race([tenantPromise, timeoutPromise]); diff --git a/src/plugins/service-azure-mongo-ru/AzureMongoRUDiscoveryProvider.ts b/src/plugins/service-azure-mongo-ru/AzureMongoRUDiscoveryProvider.ts index aed9fabe1..f3ded2da6 100644 --- a/src/plugins/service-azure-mongo-ru/AzureMongoRUDiscoveryProvider.ts +++ b/src/plugins/service-azure-mongo-ru/AzureMongoRUDiscoveryProvider.ts @@ -34,6 +34,10 @@ export class AzureMongoRUDiscoveryProvider extends Disposable implements Discove this.azureSubscriptionProvider = new AzureSubscriptionProviderWithFilters(); } + public prepareExplicitReload(): void { + this.azureSubscriptionProvider.requestFreshListing(); + } + getDiscoveryTreeRootItem(parentId: string): TreeElement { return new AzureMongoRUServiceRootItem(this.azureSubscriptionProvider, parentId); } @@ -71,6 +75,10 @@ export class AzureMongoRUDiscoveryProvider extends Disposable implements Discove const { configureAzureCredentials } = await import('../api-shared/azure/credentialsManagement'); await configureAzureCredentials(context, this.azureSubscriptionProvider, node); + if (context.telemetry.properties.credentialsManagementResult === 'Succeeded') { + this.prepareExplicitReload(); + } + if (node) { // Tree context: refresh specific node ext.discoveryBranchDataProvider.refresh(node); diff --git a/src/plugins/service-azure-mongo-ru/discovery-tree/AzureMongoRUServiceRootItem.ts b/src/plugins/service-azure-mongo-ru/discovery-tree/AzureMongoRUServiceRootItem.ts index 8908dec1d..a01bbf53b 100644 --- a/src/plugins/service-azure-mongo-ru/discovery-tree/AzureMongoRUServiceRootItem.ts +++ b/src/plugins/service-azure-mongo-ru/discovery-tree/AzureMongoRUServiceRootItem.ts @@ -3,37 +3,49 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { type AzureTenant, type VSCodeAzureSubscriptionProvider } from '@microsoft/vscode-azext-azureauth'; +import { type AzureTenant } from '@microsoft/vscode-azext-azureauth'; import * as l10n from '@vscode/l10n'; import { randomUUID } from 'crypto'; import * as vscode from 'vscode'; import { containsRetryNode, createRetryNode } from '../../../tree/api/retryNode'; import { type ExtTreeElementBase, type TreeElement } from '../../../tree/TreeElement'; import { type TreeElementWithContextValue } from '../../../tree/TreeElementWithContextValue'; +import { type TreeElementWithExplicitReload } from '../../../tree/TreeElementWithExplicitReload'; import { type TreeElementWithRetryChildren } from '../../../tree/TreeElementWithRetryChildren'; import { askToConfigureCredentials } from '../../api-shared/azure/askToConfigureCredentials'; +import { + getUnfilteredAzureTenants, + type AzureSubscriptionProviderWithFilters, +} from '../../api-shared/azure/AzureSubscriptionProviderWithFilters'; import { getTenantFilteredSubscriptions } from '../../api-shared/azure/subscriptionFiltering/subscriptionFilteringHelpers'; import { AzureMongoRUSubscriptionItem } from './AzureMongoRUSubscriptionItem'; export class AzureMongoRUServiceRootItem - implements TreeElement, TreeElementWithContextValue, TreeElementWithRetryChildren + implements TreeElement, TreeElementWithContextValue, TreeElementWithExplicitReload, TreeElementWithRetryChildren { public readonly id: string; public contextValue: string = 'enableRefreshCommand;enableManageCredentialsCommand;enableFilterCommand;enableLearnMoreCommand;azureMongoRUService'; constructor( - private readonly azureSubscriptionProvider: VSCodeAzureSubscriptionProvider, + private readonly azureSubscriptionProvider: AzureSubscriptionProviderWithFilters, public readonly parentId: string, ) { this.id = `${parentId}/azure-mongo-ru-discovery`; } + public prepareExplicitReload(): void { + this.azureSubscriptionProvider.requestFreshListing(); + } + async getChildren(): Promise { // Generate a journey correlation ID for funnel telemetry tracking const journeyCorrelationId = randomUUID(); - const allSubscriptions = await this.azureSubscriptionProvider.getSubscriptions(true); + const allSubscriptions = await this.azureSubscriptionProvider.getAvailableSubscriptions({ + filter: true, + maximumTenants: Number.POSITIVE_INFINITY, + }); const subscriptions = getTenantFilteredSubscriptions(allSubscriptions); if (!subscriptions || subscriptions.length === 0) { @@ -54,9 +66,7 @@ export class AzureMongoRUServiceRootItem } // This information is extracted to improve the UX, that's why there are fallbacks to 'undefined' - // Note to future maintainers: we used to run getSubscriptions and getTenants "in parallel", however - // this lead to incorrect responses from getSubscriptions. We didn't investigate - const tenantPromise = this.azureSubscriptionProvider.getTenants().catch(() => undefined); + const tenantPromise = getUnfilteredAzureTenants(this.azureSubscriptionProvider).catch(() => undefined); const timeoutPromise = new Promise((resolve) => setTimeout(() => resolve(undefined), 5000)); const knownTenants = await Promise.race([tenantPromise, timeoutPromise]); diff --git a/src/plugins/service-azure-mongo-vcore/AzureDiscoveryProvider.ts b/src/plugins/service-azure-mongo-vcore/AzureDiscoveryProvider.ts index 24b715f75..501881a57 100644 --- a/src/plugins/service-azure-mongo-vcore/AzureDiscoveryProvider.ts +++ b/src/plugins/service-azure-mongo-vcore/AzureDiscoveryProvider.ts @@ -35,6 +35,10 @@ export class AzureDiscoveryProvider extends Disposable implements DiscoveryProvi this.azureSubscriptionProvider = new AzureSubscriptionProviderWithFilters(); } + public prepareExplicitReload(): void { + this.azureSubscriptionProvider.requestFreshListing(); + } + getDiscoveryTreeRootItem(parentId: string): TreeElement { return new AzureServiceRootItem(this.azureSubscriptionProvider, parentId); } @@ -77,6 +81,10 @@ export class AzureDiscoveryProvider extends Disposable implements DiscoveryProvi const { configureAzureCredentials } = await import('../api-shared/azure/credentialsManagement'); await configureAzureCredentials(context, this.azureSubscriptionProvider, node); + if (context.telemetry.properties.credentialsManagementResult === 'Succeeded') { + this.prepareExplicitReload(); + } + if (node) { // Tree context: refresh specific node ext.discoveryBranchDataProvider.refresh(node); diff --git a/src/plugins/service-azure-mongo-vcore/discovery-tree/AzureServiceRootItem.ts b/src/plugins/service-azure-mongo-vcore/discovery-tree/AzureServiceRootItem.ts index 319cc47a0..436794734 100644 --- a/src/plugins/service-azure-mongo-vcore/discovery-tree/AzureServiceRootItem.ts +++ b/src/plugins/service-azure-mongo-vcore/discovery-tree/AzureServiceRootItem.ts @@ -3,36 +3,50 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { type AzureTenant, type VSCodeAzureSubscriptionProvider } from '@microsoft/vscode-azext-azureauth'; +import { type AzureTenant } from '@microsoft/vscode-azext-azureauth'; import * as l10n from '@vscode/l10n'; import { randomUUID } from 'crypto'; import * as vscode from 'vscode'; import { containsRetryNode, createRetryNode } from '../../../tree/api/retryNode'; import { type ExtTreeElementBase, type TreeElement } from '../../../tree/TreeElement'; import { type TreeElementWithContextValue } from '../../../tree/TreeElementWithContextValue'; +import { type TreeElementWithExplicitReload } from '../../../tree/TreeElementWithExplicitReload'; import { type TreeElementWithRetryChildren } from '../../../tree/TreeElementWithRetryChildren'; import { askToConfigureCredentials } from '../../api-shared/azure/askToConfigureCredentials'; +import { + getUnfilteredAzureTenants, + type AzureSubscriptionProviderWithFilters, +} from '../../api-shared/azure/AzureSubscriptionProviderWithFilters'; import { getTenantFilteredSubscriptions } from '../../api-shared/azure/subscriptionFiltering/subscriptionFilteringHelpers'; import { AzureSubscriptionItem } from './AzureSubscriptionItem'; -export class AzureServiceRootItem implements TreeElement, TreeElementWithContextValue, TreeElementWithRetryChildren { +export class AzureServiceRootItem + implements TreeElement, TreeElementWithContextValue, TreeElementWithExplicitReload, TreeElementWithRetryChildren +{ public readonly id: string; public contextValue: string = 'enableRefreshCommand;enableManageCredentialsCommand;enableFilterCommand;enableLearnMoreCommand;discoveryAzureServiceRootItem'; constructor( - private readonly azureSubscriptionProvider: VSCodeAzureSubscriptionProvider, + private readonly azureSubscriptionProvider: AzureSubscriptionProviderWithFilters, public readonly parentId: string, ) { this.id = `${parentId}/azure-mongo-vcore-discovery`; } + public prepareExplicitReload(): void { + this.azureSubscriptionProvider.requestFreshListing(); + } + async getChildren(): Promise { // Generate a new journey correlation ID for telemetry funnel analysis // This ID is passed to all child items and included in their telemetry events const journeyCorrelationId = randomUUID(); - const allSubscriptions = await this.azureSubscriptionProvider.getSubscriptions(true); + const allSubscriptions = await this.azureSubscriptionProvider.getAvailableSubscriptions({ + filter: true, + maximumTenants: Number.POSITIVE_INFINITY, + }); const subscriptions = getTenantFilteredSubscriptions(allSubscriptions); if (!subscriptions || subscriptions.length === 0) { @@ -53,9 +67,7 @@ export class AzureServiceRootItem implements TreeElement, TreeElementWithContext } // This information is extracted to improve the UX, that's why there are fallbacks to 'undefined' - // Note to future maintainers: we used to run getSubscriptions and getTenants "in parallel", however - // this lead to incorrect responses from getSubscriptions. We didn't investigate - const tenantPromise = this.azureSubscriptionProvider.getTenants().catch(() => undefined); + const tenantPromise = getUnfilteredAzureTenants(this.azureSubscriptionProvider).catch(() => undefined); const timeoutPromise = new Promise((resolve) => setTimeout(() => resolve(undefined), 5000)); const knownTenants = await Promise.race([tenantPromise, timeoutPromise]); diff --git a/src/plugins/service-azure-vm/AzureVMDiscoveryProvider.ts b/src/plugins/service-azure-vm/AzureVMDiscoveryProvider.ts index 025c3a686..f405d3f22 100644 --- a/src/plugins/service-azure-vm/AzureVMDiscoveryProvider.ts +++ b/src/plugins/service-azure-vm/AzureVMDiscoveryProvider.ts @@ -45,6 +45,10 @@ export class AzureVMDiscoveryProvider extends Disposable implements DiscoveryPro this.azureSubscriptionProvider = new AzureSubscriptionProviderWithFilters(); } + public prepareExplicitReload(): void { + this.azureSubscriptionProvider.requestFreshListing(); + } + getDiscoveryTreeRootItem(parentId: string): TreeElement { // For now, reusing AzureServiceRootItem. This might need to be a new AzureVMServiceRootItem if tree structure diverges significantly. return new AzureServiceRootItem(this.azureSubscriptionProvider, parentId); @@ -83,6 +87,10 @@ export class AzureVMDiscoveryProvider extends Disposable implements DiscoveryPro const { configureAzureCredentials } = await import('../api-shared/azure/credentialsManagement'); await configureAzureCredentials(context, this.azureSubscriptionProvider, node); + if (context.telemetry.properties.credentialsManagementResult === 'Succeeded') { + this.prepareExplicitReload(); + } + if (node) { // Tree context: refresh specific node ext.discoveryBranchDataProvider.refresh(node); diff --git a/src/plugins/service-azure-vm/discovery-tree/AzureServiceRootItem.ts b/src/plugins/service-azure-vm/discovery-tree/AzureServiceRootItem.ts index b2cc5aa0f..d001ae72c 100644 --- a/src/plugins/service-azure-vm/discovery-tree/AzureServiceRootItem.ts +++ b/src/plugins/service-azure-vm/discovery-tree/AzureServiceRootItem.ts @@ -3,35 +3,49 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { type AzureTenant, type VSCodeAzureSubscriptionProvider } from '@microsoft/vscode-azext-azureauth'; +import { type AzureTenant } from '@microsoft/vscode-azext-azureauth'; import * as l10n from '@vscode/l10n'; import { randomUUID } from 'crypto'; import * as vscode from 'vscode'; import { containsRetryNode, createRetryNode } from '../../../tree/api/retryNode'; import { type ExtTreeElementBase, type TreeElement } from '../../../tree/TreeElement'; import { type TreeElementWithContextValue } from '../../../tree/TreeElementWithContextValue'; +import { type TreeElementWithExplicitReload } from '../../../tree/TreeElementWithExplicitReload'; import { type TreeElementWithRetryChildren } from '../../../tree/TreeElementWithRetryChildren'; import { askToConfigureCredentials } from '../../api-shared/azure/askToConfigureCredentials'; +import { + getUnfilteredAzureTenants, + type AzureSubscriptionProviderWithFilters, +} from '../../api-shared/azure/AzureSubscriptionProviderWithFilters'; import { getTenantFilteredSubscriptions } from '../../api-shared/azure/subscriptionFiltering/subscriptionFilteringHelpers'; import { AzureSubscriptionItem } from './AzureSubscriptionItem'; -export class AzureServiceRootItem implements TreeElement, TreeElementWithContextValue, TreeElementWithRetryChildren { +export class AzureServiceRootItem + implements TreeElement, TreeElementWithContextValue, TreeElementWithExplicitReload, TreeElementWithRetryChildren +{ public readonly id: string; public contextValue: string = 'enableRefreshCommand;enableManageCredentialsCommand;enableFilterCommand;enableLearnMoreCommand;discoveryAzureVMRootItem'; constructor( - private readonly azureSubscriptionProvider: VSCodeAzureSubscriptionProvider, + private readonly azureSubscriptionProvider: AzureSubscriptionProviderWithFilters, public readonly parentId: string, ) { this.id = `${parentId}/azure-vm-discovery`; } + public prepareExplicitReload(): void { + this.azureSubscriptionProvider.requestFreshListing(); + } + async getChildren(): Promise { // Generate a journey correlation ID for funnel telemetry tracking const journeyCorrelationId = randomUUID(); - const allSubscriptions = await this.azureSubscriptionProvider.getSubscriptions(true); + const allSubscriptions = await this.azureSubscriptionProvider.getAvailableSubscriptions({ + filter: true, + maximumTenants: Number.POSITIVE_INFINITY, + }); const subscriptions = getTenantFilteredSubscriptions(allSubscriptions); if (!subscriptions || subscriptions.length === 0) { @@ -52,9 +66,7 @@ export class AzureServiceRootItem implements TreeElement, TreeElementWithContext } // This information is extracted to improve the UX, that's why there are fallbacks to 'undefined' - // Note to future maintainers: we used to run getSubscriptions and getTenants "in parallel", however - // this lead to incorrect responses from getSubscriptions. We didn't investigate - const tenantPromise = this.azureSubscriptionProvider.getTenants().catch(() => undefined); + const tenantPromise = getUnfilteredAzureTenants(this.azureSubscriptionProvider).catch(() => undefined); const timeoutPromise = new Promise((resolve) => setTimeout(() => resolve(undefined), 5000)); const knownTenants = await Promise.race([tenantPromise, timeoutPromise]); diff --git a/src/services/discoveryServices.ts b/src/services/discoveryServices.ts index 4fd2c9d41..f4ff3945a 100644 --- a/src/services/discoveryServices.ts +++ b/src/services/discoveryServices.ts @@ -62,6 +62,8 @@ export interface DiscoveryProvider extends ProviderDescription { */ getDiscoveryTreeRootItem(parentId: string): TreeElement; + prepareExplicitReload?(): void; + getLearnMoreUrl?(): string | undefined; configureTreeItemFilter?(context: IActionContext, node: TreeElement): Promise; diff --git a/src/tree/TreeElementWithExplicitReload.ts b/src/tree/TreeElementWithExplicitReload.ts new file mode 100644 index 000000000..ddd0832b4 --- /dev/null +++ b/src/tree/TreeElementWithExplicitReload.ts @@ -0,0 +1,17 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +export interface TreeElementWithExplicitReload { + prepareExplicitReload(): void; +} + +export function isTreeElementWithExplicitReload(value: unknown): value is TreeElementWithExplicitReload { + return ( + typeof value === 'object' && + value !== null && + 'prepareExplicitReload' in value && + typeof value.prepareExplicitReload === 'function' + ); +} diff --git a/src/utils/azureClients.ts b/src/utils/azureClients.ts index 65013668e..b56b655b3 100644 --- a/src/utils/azureClients.ts +++ b/src/utils/azureClients.ts @@ -40,12 +40,7 @@ export async function createMongoClustersManagementClient( subscription: AzureSubscription, ): Promise { const subContext = createSubscriptionContext(subscription); - return createAzureClient( - [context, subContext], - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-expect-error - (await import('@azure/arm-mongocluster')).MongoClusterManagementClient, - ) as unknown as MongoClusterManagementClient; + return createAzureClient([context, subContext], (await import('@azure/arm-mongocluster')).MongoClusterManagementClient); } export async function createComputeManagementClient( From 8e5eda461ad175b75ef46fe2380b81fd0c36df2e Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 12:07:48 +0000 Subject: [PATCH 043/380] chore: regenerate localization and format WI-3 changes Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- l10n/bundle.l10n.json | 2 ++ .../newConnection/PromptTenantStep.test.ts | 8 ++++++-- .../checks/resolveTarget.test.ts | 5 ++++- src/deepLinks/azureSubscription.test.ts | 17 +++++++++++------ .../auth/sovereignAuth.integration.test.ts | 3 ++- .../playground/PlaygroundEvaluator.test.ts | 3 ++- .../shell/ShellSessionManager.test.ts | 3 ++- .../InitializeFilteringStep.ts | 2 +- src/utils/azureClients.ts | 5 ++++- 9 files changed, 34 insertions(+), 14 deletions(-) diff --git a/l10n/bundle.l10n.json b/l10n/bundle.l10n.json index f3c551b94..a07aa3619 100644 --- a/l10n/bundle.l10n.json +++ b/l10n/bundle.l10n.json @@ -2769,6 +2769,8 @@ "Skip problematic documents and continue; issues are recorded. Good for scenarios where partial success is acceptable.": "Skip problematic documents and continue; issues are recorded. Good for scenarios where partial success is acceptable.", "skipped": "skipped", "Skipped": "Skipped", + "Skipped an Azure account because its tenants could not be listed.": "Skipped an Azure account because its tenants could not be listed.", + "Skipped an Azure tenant because its subscriptions could not be listed.": "Skipped an Azure tenant because its subscriptions could not be listed.", "Slow execution": "Slow execution", "Small breadcrumb example with buttons": "Small breadcrumb example with buttons", "Socket access": "Socket access", diff --git a/src/commands/newConnection/PromptTenantStep.test.ts b/src/commands/newConnection/PromptTenantStep.test.ts index 4b54a243c..2971c61ae 100644 --- a/src/commands/newConnection/PromptTenantStep.test.ts +++ b/src/commands/newConnection/PromptTenantStep.test.ts @@ -3,6 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import type * as azureAuth from '@microsoft/vscode-azext-azureauth'; import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest'; const mockGetAccounts = vi.fn(); @@ -21,7 +22,7 @@ vi.mock('../../extensionVariables', () => ({ })); vi.mock('@microsoft/vscode-azext-azureauth', async (importOriginal) => ({ - ...(await importOriginal()), + ...(await importOriginal()), // A `function`, not an arrow: Vitest 4 calls the implementation with `new`. VSCodeAzureSubscriptionProvider: vi.fn().mockImplementation(function () { return { @@ -165,7 +166,10 @@ describe.each([ expect(mockConfigureAzureCredentials).toHaveBeenCalledTimes(1); expect(mockSignIn).toHaveBeenCalledExactlyOnceWith(undefined, { promptIfNeeded: false }); expect(mockGetAccounts).toHaveBeenCalledExactlyOnceWith({ filter: false, noCache: true }); - expect(mockGetTenantsForAccount).toHaveBeenCalledExactlyOnceWith(tenant.account, { filter: false, noCache: true }); + expect(mockGetTenantsForAccount).toHaveBeenCalledExactlyOnceWith(tenant.account, { + filter: false, + noCache: true, + }); expect((context as IActionContext & { entraIdAuthConfig?: { tenantId?: string } }).entraIdAuthConfig).toEqual({ tenantId: TENANT_ID, }); diff --git a/src/connectionDiagnostics/checks/resolveTarget.test.ts b/src/connectionDiagnostics/checks/resolveTarget.test.ts index 1951d6c9b..b8f2819a4 100644 --- a/src/connectionDiagnostics/checks/resolveTarget.test.ts +++ b/src/connectionDiagnostics/checks/resolveTarget.test.ts @@ -157,7 +157,10 @@ describe('resolveTarget check (review R2, option A)', (): void => { { source: 'azure', reason: 'signInRequired', errorName: 'Error' }, ], [ - new ConnectionSourceUnavailableError('azure', withStatus(new Error('secret challenge'), { statusCode: 401 })), + new ConnectionSourceUnavailableError( + 'azure', + withStatus(new Error('secret challenge'), { statusCode: 401 }), + ), 'target.sourceInaccessible', { source: 'azure', reason: 'signInRequired', errorName: 'Error', statusCode: 401 }, ], diff --git a/src/deepLinks/azureSubscription.test.ts b/src/deepLinks/azureSubscription.test.ts index 8218fb423..0bbcc5688 100644 --- a/src/deepLinks/azureSubscription.test.ts +++ b/src/deepLinks/azureSubscription.test.ts @@ -3,6 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import type * as azureAuth from '@microsoft/vscode-azext-azureauth'; import { getSessionFromVSCode, type AzureSubscription } from '@microsoft/vscode-azext-azureauth'; import { callWithTelemetryAndErrorHandling, type IActionContext } from '@microsoft/vscode-azext-utils'; import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest'; @@ -30,7 +31,7 @@ vi.mock('@microsoft/vscode-azext-utils', () => ({ callWithTelemetryAndErrorHandling: vi.fn(), })); vi.mock('@microsoft/vscode-azext-azureauth', async (importOriginal) => ({ - ...(await importOriginal()), + ...(await importOriginal()), getSessionFromVSCode: vi.fn(), })); vi.mock('../services/discoveryServices', () => ({ @@ -101,10 +102,12 @@ describe('resolveAzureSubscription', (): void => { expect(report).toHaveBeenLastCalledWith('Checking Azure sign-in…'); return true; }); - azureSubscriptionProvider.getAvailableSubscriptions.mockImplementation(async (): Promise => { - expect(report).toHaveBeenLastCalledWith('Looking for the subscription…'); - return [found]; - }); + azureSubscriptionProvider.getAvailableSubscriptions.mockImplementation( + async (): Promise => { + expect(report).toHaveBeenLastCalledWith('Looking for the subscription…'); + return [found]; + }, + ); await expect(resolveAzureSubscription(context, request, report)).resolves.toBe(found); @@ -126,7 +129,9 @@ describe('resolveAzureSubscription', (): void => { { modal: true, detail: 'Sign in to Azure to open linked-resource.' }, 'Sign in', ); - expect(azureSubscriptionProvider.signIn).toHaveBeenNthCalledWith(2, undefined, { clearSessionPreference: true }); + expect(azureSubscriptionProvider.signIn).toHaveBeenNthCalledWith(2, undefined, { + clearSessionPreference: true, + }); expect(azureSubscriptionProvider.signIn).toHaveBeenCalledTimes(2); expect(azureSubscriptionProvider.getAvailableSubscriptions).toHaveBeenCalledExactlyOnceWith(listingOptions); expect(ext.outputChannel.trace).toHaveBeenCalledWith('[DeepLink] Azure sign-in: sign-in required'); diff --git a/src/documentdb/auth/sovereignAuth.integration.test.ts b/src/documentdb/auth/sovereignAuth.integration.test.ts index e0d6bdf04..185d48f3f 100644 --- a/src/documentdb/auth/sovereignAuth.integration.test.ts +++ b/src/documentdb/auth/sovereignAuth.integration.test.ts @@ -3,6 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import type * as azureAuth from '@microsoft/vscode-azext-azureauth'; import { type callWithTelemetryAndErrorHandling, type ITelemetryContext } from '@microsoft/vscode-azext-utils'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import * as vscode from 'vscode'; @@ -34,7 +35,7 @@ vi.mock('../../extensionVariables', () => ({ })); vi.mock('@microsoft/vscode-azext-azureauth', async (importOriginal) => ({ - ...(await importOriginal()), + ...(await importOriginal()), getSessionFromVSCode: getSession, })); diff --git a/src/documentdb/playground/PlaygroundEvaluator.test.ts b/src/documentdb/playground/PlaygroundEvaluator.test.ts index af0bb196e..fa24e08b9 100644 --- a/src/documentdb/playground/PlaygroundEvaluator.test.ts +++ b/src/documentdb/playground/PlaygroundEvaluator.test.ts @@ -3,6 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import type * as azureAuth from '@microsoft/vscode-azext-azureauth'; import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest'; import { type callWithTelemetryAndErrorHandling, type IActionContext } from '@microsoft/vscode-azext-utils'; @@ -81,7 +82,7 @@ vi.mock('../CredentialCache', () => ({ })); vi.mock('@microsoft/vscode-azext-azureauth', async (importOriginal) => ({ - ...(await importOriginal()), + ...(await importOriginal()), getSessionFromVSCode: mocks.interactiveToken, })); diff --git a/src/documentdb/shell/ShellSessionManager.test.ts b/src/documentdb/shell/ShellSessionManager.test.ts index ba1f6e65f..7e18eb3c4 100644 --- a/src/documentdb/shell/ShellSessionManager.test.ts +++ b/src/documentdb/shell/ShellSessionManager.test.ts @@ -3,6 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import type * as azureAuth from '@microsoft/vscode-azext-azureauth'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import * as vscode from 'vscode'; @@ -47,7 +48,7 @@ vi.mock('../../extensionVariables', () => ({ })); vi.mock('@microsoft/vscode-azext-azureauth', async (importOriginal) => ({ - ...(await importOriginal()), + ...(await importOriginal()), getSessionFromVSCode: (...args: unknown[]) => mockGetSessionFromVSCode(...args), })); diff --git a/src/plugins/api-shared/azure/subscriptionFiltering/InitializeFilteringStep.ts b/src/plugins/api-shared/azure/subscriptionFiltering/InitializeFilteringStep.ts index e3a13ff49..ce9222e78 100644 --- a/src/plugins/api-shared/azure/subscriptionFiltering/InitializeFilteringStep.ts +++ b/src/plugins/api-shared/azure/subscriptionFiltering/InitializeFilteringStep.ts @@ -6,9 +6,9 @@ import { type AzureTenant, type VSCodeAzureSubscriptionProvider } from '@microsoft/vscode-azext-azureauth'; import { AzureWizardPromptStep, + UserCancelledError, type IActionContext, type IWizardOptions, - UserCancelledError, } from '@microsoft/vscode-azext-utils'; import { type AzureSubscription } from '@microsoft/vscode-azureresources-api'; import * as l10n from '@vscode/l10n'; diff --git a/src/utils/azureClients.ts b/src/utils/azureClients.ts index b56b655b3..7bc1873ad 100644 --- a/src/utils/azureClients.ts +++ b/src/utils/azureClients.ts @@ -40,7 +40,10 @@ export async function createMongoClustersManagementClient( subscription: AzureSubscription, ): Promise { const subContext = createSubscriptionContext(subscription); - return createAzureClient([context, subContext], (await import('@azure/arm-mongocluster')).MongoClusterManagementClient); + return createAzureClient( + [context, subContext], + (await import('@azure/arm-mongocluster')).MongoClusterManagementClient, + ); } export async function createComputeManagementClient( From 423c2e1b7dd6d0e20d6bc693b7cf42dcde25d187 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 12:15:37 +0000 Subject: [PATCH 044/380] fix: refresh Azure account inventory independently of SDK events (WI-3) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- ...ureSubscriptionProviderWithFilters.test.ts | 90 ++++++++++++++++++- .../AzureSubscriptionProviderWithFilters.ts | 5 ++ 2 files changed, 91 insertions(+), 4 deletions(-) diff --git a/src/plugins/api-shared/azure/AzureSubscriptionProviderWithFilters.test.ts b/src/plugins/api-shared/azure/AzureSubscriptionProviderWithFilters.test.ts index 5c26f8598..89d8a0087 100644 --- a/src/plugins/api-shared/azure/AzureSubscriptionProviderWithFilters.test.ts +++ b/src/plugins/api-shared/azure/AzureSubscriptionProviderWithFilters.test.ts @@ -5,6 +5,7 @@ import { Environment } from '@azure/ms-rest-azure-env'; import { + AzureSubscriptionProviderBase, ExtendedEnvironment, NotSignedInError, VSCodeAzureSubscriptionProvider, @@ -68,7 +69,79 @@ describe('AzureSubscriptionProviderWithFilters', () => { provider.dispose(); }); - it.each(['cloud', 'session'] as const)('reloads cached accounts after a %s change', async (kind) => { + it('forces fresh account enumeration while preserving other account options', async () => { + const baseAccounts = vi.spyOn(VSCodeAzureSubscriptionProvider.prototype, 'getAccounts').mockResolvedValue([]); + const provider = new AzureSubscriptionProviderWithFilters(); + const token = { isCancellationRequested: false, onCancellationRequested: vi.fn() }; + const options = { filter: false, noCache: false, token }; + + await provider.getAccounts(); + await provider.getAccounts(options); + + expect(baseAccounts.mock.calls).toEqual([[{ noCache: true }], [{ ...options, noCache: true }]]); + expect(options.noCache).toBe(false); + provider.dispose(); + }); + + it('finds newly signed-in accounts without an event while reusing existing tenant and subscription caches', async () => { + const getAccounts = vi.mocked(vscode.authentication.getAccounts); + const firstAccount = { id: 'first-account', label: 'First account' }; + const secondAccount = { id: 'second-account', label: 'Second account' }; + getAccounts.mockResolvedValueOnce([firstAccount]).mockResolvedValue([firstAccount, secondAccount]); + const getTenants = vi + .spyOn(AzureSubscriptionProviderBase.prototype, 'getTenantsForAccount') + .mockImplementation(async (account) => [{ account, tenantId: `tenant-${account.id}` }]); + const getSubscriptions = vi + .spyOn(AzureSubscriptionProviderBase.prototype, 'getSubscriptionsForTenant') + .mockImplementation(async ({ account, tenantId }) => [ + { + account, + tenantId, + subscriptionId: `subscription-${account.id}`, + name: account.label, + authentication: { getSession: vi.fn(), getSessionWithScopes: vi.fn() }, + credential: { getToken: vi.fn() }, + environment: account.environment, + isCustomCloud: false, + }, + ]); + const provider = new AzureSubscriptionProviderWithFilters(); + const options = { filter: false, noCache: false, maximumTenants: 20, dedupe: false }; + + try { + const first = await provider.getAvailableSubscriptions(options); + const second = await provider.getAvailableSubscriptions(options); + + expect(first.map((subscription) => subscription.subscriptionId)).toEqual(['subscription-first-account']); + expect(second.map((subscription) => subscription.subscriptionId)).toEqual([ + 'subscription-first-account', + 'subscription-second-account', + ]); + expect(getTenants.mock.calls.map(([account]) => account.id)).toEqual(['first-account', 'second-account']); + expect(getSubscriptions.mock.calls.map(([tenant]) => tenant.account.id)).toEqual([ + 'first-account', + 'second-account', + ]); + expect(getTenants.mock.calls.every(([, passedOptions]) => passedOptions === options)).toBe(true); + expect(getSubscriptions.mock.calls.every(([, passedOptions]) => passedOptions === options)).toBe(true); + expect(options.noCache).toBe(false); + + const freshOptions = { ...options, noCache: true }; + await provider.getAvailableSubscriptions(freshOptions); + expect(getTenants).toHaveBeenCalledTimes(4); + expect(getSubscriptions).toHaveBeenCalledTimes(4); + expect(getTenants.mock.calls.slice(2).every(([, passedOptions]) => passedOptions === freshOptions)).toBe( + true, + ); + expect( + getSubscriptions.mock.calls.slice(2).every(([, passedOptions]) => passedOptions === freshOptions), + ).toBe(true); + } finally { + provider.dispose(); + } + }); + + it.each(['cloud', 'session'] as const)('handles tenant and subscription caches after a %s change', async (kind) => { const cloudListener = vi.mocked(vscode.workspace.onDidChangeConfiguration); const sessionListener = vi.mocked(vscode.authentication.onDidChangeSessions); const getAccounts = vi.mocked(vscode.authentication.getAccounts); @@ -76,14 +149,21 @@ describe('AzureSubscriptionProviderWithFilters', () => { sessionListener.mockClear(); getAccounts.mockClear(); getAccounts.mockResolvedValue([{ id: 'fixture-account', label: 'Fixture account' }]); + const getTenants = vi + .spyOn(AzureSubscriptionProviderBase.prototype, 'getTenantsForAccount') + .mockImplementation(async (account) => [{ account, tenantId: 'fixture-tenant' }]); + const getSubscriptions = vi + .spyOn(AzureSubscriptionProviderBase.prototype, 'getSubscriptionsForTenant') + .mockResolvedValue([]); vi.useFakeTimers(); const provider = new AzureSubscriptionProviderWithFilters(); - vi.spyOn(provider, 'getTenantsForAccount').mockResolvedValue([]); try { await provider.getAvailableSubscriptions({ filter: false }); await provider.getAvailableSubscriptions({ filter: false }); - expect(getAccounts).toHaveBeenCalledOnce(); + expect(getAccounts).toHaveBeenCalledTimes(2); + expect(getTenants).toHaveBeenCalledOnce(); + expect(getSubscriptions).toHaveBeenCalledOnce(); if (kind === 'cloud') { cloudListener.mock.calls[0][0]({ @@ -96,7 +176,9 @@ describe('AzureSubscriptionProviderWithFilters', () => { } await provider.getAvailableSubscriptions({ filter: false }); - expect(getAccounts).toHaveBeenCalledTimes(2); + expect(getAccounts).toHaveBeenCalledTimes(3); + expect(getTenants).toHaveBeenCalledTimes(kind === 'cloud' ? 2 : 1); + expect(getSubscriptions).toHaveBeenCalledTimes(kind === 'cloud' ? 2 : 1); } finally { provider.dispose(); vi.useRealTimers(); diff --git a/src/plugins/api-shared/azure/AzureSubscriptionProviderWithFilters.ts b/src/plugins/api-shared/azure/AzureSubscriptionProviderWithFilters.ts index 70b2e7ac6..b0b04478b 100644 --- a/src/plugins/api-shared/azure/AzureSubscriptionProviderWithFilters.ts +++ b/src/plugins/api-shared/azure/AzureSubscriptionProviderWithFilters.ts @@ -9,6 +9,7 @@ import { type AzureAccount, type AzureSubscription, type AzureTenant, + type GetAccountsOptions, type GetAvailableSubscriptionsOptions, type SubscriptionId, type TenantIdAndAccount, @@ -81,6 +82,10 @@ export class AzureSubscriptionProviderWithFilters extends VSCodeAzureSubscriptio this.freshListingRequested = true; } + public override getAccounts(options?: GetAccountsOptions): Promise { + return super.getAccounts({ ...options, noCache: true }); + } + public override async getAvailableSubscriptions( options?: GetAvailableSubscriptionsOptions, ): Promise { From 1d834972dca00e79fd273cc7394cdf48e0ce5b66 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 12:16:07 +0000 Subject: [PATCH 045/380] docs: record PR2 pre-review and cache follow-up Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iterations/01-pr2-azureauth-review.md | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr2-azureauth-review.md diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr2-azureauth-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr2-azureauth-review.md new file mode 100644 index 000000000..c4f38b734 --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr2-azureauth-review.md @@ -0,0 +1,38 @@ +--- +feature: connection-lifecycle +kind: review +status: active +created: 2026-11-20 +--- + +# PR2 pre-review: Azure Discovery and azureauth v6 + +Reviewed [PR #1111](https://github.com/microsoft/vscode-documentdb/pull/1111), comparing +`8e5eda461` with `d6c4efc55`. GPT-6.2-Sol performed the initial review; Claude Opus 5.5 validated +the findings. The operator approved native SDK challenge handling and partial subscription +results with sanitized warnings. Neither decision is reopened here. + +| Finding | Validation | Technical recommendation | +| ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- | +| Refresh can leave a root on Retry. | Existing behavior (95% confidence). An explicit Retry clears the failed child cache; Refresh did not clear it before the upgrade either. | Do not change the tree recovery contract in WI-3. | +| Another caller can consume the one-shot freshness request. | Confirmed, non-blocking (80%). The fresh listing refills the cache before filtering; an overlapping tree listing can still return old results. | Observe explicit Refresh in OP-2. Keep the existing design unless the race reproduces. | +| SDK event suppression can hide a newly signed-in account. | WI-3 regression (90%). The SDK can suppress its cache invalidation event. A subsequent listing can miss an account that VS Code now knows about. | Read the local VS Code account inventory on each listing, while keeping tenant and subscription caches. Retain the cloud-change listener. | +| An account error can stop the filter wizard before it shows partial results. | Existing behavior (85%). The previous tenant enumeration also stopped on errors other than missing sign-in. | Keep the existing wizard contract; record any live failure in OP-2. | + +## Verification before the cache follow-up + +Build, lint, test type-check, localization and formatting passed after test-only lint repairs. +The first full run timed out in an unchanged Fluent UI test; a focused rerun and the subsequent +full run passed (9,682 tests passed, one skipped). The VSIX built, passed inspection, and the +inspection rejected all 24 negative controls. Local L3 activation could not start because this +Linux host lacks Electron's GUI libraries. OP-2 and the final CP-W3 verdict are still pending. + +## Cache follow-up + +`423c2e1b7` refreshes the local Azure account inventory even when the SDK suppresses session +events. Tenant and subscription caches remain intact. Added two focused regressions and retained +cloud-invalidation and listener-disposal coverage. The three affected suites (55 tests), root +type-check, and targeted formatting check passed. + +The other three findings remain unchanged as recommended above. Author review of those +dispositions and the live OP-2 results are pending. From ebfc40cb0127c83d63cbf6bbb58cd79967a4ee43 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 12:16:56 +0000 Subject: [PATCH 046/380] docs: hand off the packaged WI-3 candidate for OP-2 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../connection-lifecycle/iterations/01-dev-plan.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index f4394a7ff..8ace75299 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 @@ -888,6 +888,14 @@ shim (0005). browsing silent required more than a small update. A prompt override would have to cover both the SDK listing pipeline and subscription authentication, so PR2 will not add one. OP-2 should include checking where prompts appear and what happens when they are dismissed. +- **OP-2 candidate ready (2026-11-20):** [Draft PR2 #1111](https://github.com/microsoft/vscode-documentdb/pull/1111) + contains the L2 migration (`1869c22ab`) and local account-cache fix (`423c2e1b7`). The + [PR2 pre-review](./01-pr2-azureauth-review.md) records the findings and verification. The full + suite passed before the cache follow-up (9,682 passed, one skipped); 55 focused tests and + root type-check passed after it. The rebuilt VSIX passed inspection and its host graph has one + azureauth ESM copy, with no legacy lowered initializer call in the Azure auth chunk. + Automated activation did not run in this host because Electron's GUI libraries are missing. + **Waiting for OP-2** on the packaged L2 candidate before the CP-W3 verdict. --- From 3105529e1f7e0fbbeb4612b61ad60ee96cf91d1b Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 12:39:50 +0000 Subject: [PATCH 047/380] docs: record operator acceptance of OP-2 (WI-3) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../connection-lifecycle/iterations/01-dev-plan.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) 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 8ace75299..0e66b9189 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 @@ -895,7 +895,13 @@ shim (0005). root type-check passed after it. The rebuilt VSIX passed inspection and its host graph has one azureauth ESM copy, with no legacy lowered initializer call in the Azure auth chunk. Automated activation did not run in this host because Electron's GUI libraries are missing. - **Waiting for OP-2** on the packaged L2 candidate before the CP-W3 verdict. +- **OP-2 accepted by the operator (2026-11-20):** The packaged extension activated. Discovery, + filters, and Refresh/Retry passed. The operator signed out and back in with the same account + and accepted the untested account-switch, MFA, and cloud cases. New Connection via Azure + service discovery and the Azure Resources RU and vCore/DocumentDB nodes worked. Deep-link URLs + were not tested; the operator accepted the risk. Update Credentials and workspace-provider + results were not reported. Partial failures could not be reproduced live; focused tests cover + partial results and sanitized warnings. Final CP-W3 verdict pending. --- From 96085c1ddaa44432d80f222d613409fd50e7972b Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 12:40:32 +0000 Subject: [PATCH 048/380] docs: retain the L2 Azure SDK candidate after OP-2 (WI-3) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../connection-lifecycle/iterations/01-dev-plan.md | 7 ++++++- .../iterations/01-pr2-azureauth-review.md | 13 ++++++++++++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index 0e66b9189..ca34c2e0d 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 @@ -901,7 +901,12 @@ shim (0005). service discovery and the Azure Resources RU and vCore/DocumentDB nodes worked. Deep-link URLs were not tested; the operator accepted the risk. Update Credentials and workspace-provider results were not reported. Partial failures could not be reproduced live; focused tests cover - partial results and sanitized warnings. Final CP-W3 verdict pending. + partial results and sanitized warnings. +- **CP-W3 (2026-11-20), advised (`claude-opus-5.5`, 85% confidence):** Retain L2: + azureauth `6.1.0-alpha.2`, azureutils and utils `5.1.0`, and Azure Resources API `3.1.1`. + The build, installed dependency tree, bundle inspection, and operator-accepted OP-2 support + this choice. L1 uses the same azureauth and Azure Resources API versions and does not reduce + the remaining risks. The untested OP-2 cases above remain unverified. --- diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr2-azureauth-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr2-azureauth-review.md index c4f38b734..879c05b8a 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr2-azureauth-review.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr2-azureauth-review.md @@ -35,4 +35,15 @@ cloud-invalidation and listener-disposal coverage. The three affected suites (55 type-check, and targeted formatting check passed. The other three findings remain unchanged as recommended above. Author review of those -dispositions and the live OP-2 results are pending. +dispositions is pending. + +## OP-2 and CP-W3 + +The operator accepted OP-2 after testing the installed VSIX. Activation, Discovery, filters, +Refresh/Retry, same-account sign-out/sign-in, Azure New Connection discovery, and the Azure +Resources RU and vCore/DocumentDB nodes worked. Different-account switching, MFA, sovereign +cloud, Update Credentials and workspace-provider checks were not confirmed. The operator +accepted the untested deep-link URLs; partial failures were not reproducible live. + +CP-W3 retains L2 (Claude Opus 5.5, 85% confidence). L1 uses the same azureauth and Azure +Resources API versions, so stepping down does not reduce the remaining risk. From 0e2a89576b8d99d3538477c5c004ea8c0dd1497a Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 06:32:30 +0000 Subject: [PATCH 049/380] Add connection fingerprint Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/documentdb/connectionFingerprint.test.ts | 82 ++++++++++++++++++++ src/documentdb/connectionFingerprint.ts | 36 +++++++++ 2 files changed, 118 insertions(+) create mode 100644 src/documentdb/connectionFingerprint.test.ts create mode 100644 src/documentdb/connectionFingerprint.ts diff --git a/src/documentdb/connectionFingerprint.test.ts b/src/documentdb/connectionFingerprint.test.ts new file mode 100644 index 000000000..ba58d6873 --- /dev/null +++ b/src/documentdb/connectionFingerprint.test.ts @@ -0,0 +1,82 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { describe, expect, it } from 'vitest'; + +import { computeConnectionFingerprint, type ConnectionPrincipal } from './connectionFingerprint'; + +describe('computeConnectionFingerprint', () => { + const connectionString = 'mongodb://user:test-password@Host.example:27017/db?authSource=admin&tls=true'; + const native = { kind: 'native', username: 'user' } as const; + const entra = { kind: 'entra', providerId: 'public', accountId: 'account', tenantId: 'tenant' } as const; + + it('returns a deterministic 32-character lowercase hex fingerprint', () => { + const fingerprint = computeConnectionFingerprint({ connectionString, principal: native }); + expect(fingerprint).toMatch(/^[a-f0-9]{32}$/); + expect(computeConnectionFingerprint({ connectionString, principal: { ...native } })).toBe(fingerprint); + }); + + it.each([ + ['mongodb+srv', 'user%40example.com', 'old%40%3A%2F%3F%23%25', 'new%3a%40%2f%3f%23%25'], + ['mongodb', 'account', 'dGVzdC9vbGQ%2B%2F%3D%3D', 'dGVzdC9uZXc%2B%2F%3D%3D'], + ])('ignores password or key rotation in %s URIs', (scheme, username, oldPassword, newPassword) => { + const principal = { kind: 'native', username } as const; + const suffix = '@host.example/db?appName=test@client'; + const before = `${scheme}://${username}:${oldPassword}${suffix}`; + const after = `${scheme}://${username}:${newPassword}${suffix}`; + const fingerprint = computeConnectionFingerprint({ connectionString: before, principal }); + expect(computeConnectionFingerprint({ connectionString: after, principal })).toBe(fingerprint); + }); + + it.each([ + ['username', 'user:', 'User:'], + ['host case', 'Host.example', 'host.example'], + ['port', ':27017', ':27018'], + ['database path', '/db?', '/other?'], + ['path escape spelling', '/db?', '/%64b?'], + ['authSource', 'authSource=admin', 'authSource=db'], + ['query order', 'authSource=admin&tls=true', 'tls=true&authSource=admin'], + ])('changes when the URI %s changes', (_edit, from, to) => { + const fingerprint = computeConnectionFingerprint({ connectionString, principal: native }); + expect( + computeConnectionFingerprint({ connectionString: connectionString.replace(from, to), principal: native }), + ).not.toBe(fingerprint); + }); + + it('preserves a literal @ in the query without misreading the host port as a password', () => { + const principal = { kind: 'none' } as const; + const before = 'mongodb://host.example:27017?appName=test@client'; + const after = 'mongodb://host.example:27018?appName=test@client'; + expect(computeConnectionFingerprint({ connectionString: before, principal })).not.toBe( + computeConnectionFingerprint({ connectionString: after, principal }), + ); + }); + + it('distinguishes all principal variants and each principal field', () => { + const principals: ConnectionPrincipal[] = [ + native, + { ...native, username: 'User' }, + entra, + { ...entra, providerId: 'government' }, + { ...entra, accountId: 'other' }, + { ...entra, tenantId: 'other' }, + { kind: 'entra', providerId: entra.providerId, accountId: entra.accountId }, + { kind: 'managedIdentity', clientId: 'client-a' }, + { kind: 'managedIdentity', clientId: 'client-b' }, + { kind: 'managedIdentity' }, + { kind: 'none' }, + ]; + const fingerprints = principals.map((principal) => computeConnectionFingerprint({ connectionString, principal })); + expect(new Set(fingerprints).size).toBe(principals.length); + }); + + it('keeps principal field boundaries unambiguous', () => { + const first = { ...entra, providerId: 'cloud:region', accountId: 'account' }; + const second = { ...entra, providerId: 'cloud', accountId: 'region:account' }; + expect(computeConnectionFingerprint({ connectionString, principal: first })).not.toBe( + computeConnectionFingerprint({ connectionString, principal: second }), + ); + }); +}); diff --git a/src/documentdb/connectionFingerprint.ts b/src/documentdb/connectionFingerprint.ts new file mode 100644 index 000000000..1b800cbbf --- /dev/null +++ b/src/documentdb/connectionFingerprint.ts @@ -0,0 +1,36 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { createHash } from 'node:crypto'; + +export type ConnectionPrincipal = + | { kind: 'native'; username: string } + | { kind: 'entra'; providerId: string; accountId: string; tenantId?: string } + | { kind: 'managedIdentity'; clientId?: string } + | { kind: 'none' }; + +export function computeConnectionFingerprint(input: { + connectionString: string; + principal: ConnectionPrincipal; +}): string { + // Match only the password in the URI authority, without decoding or reserializing the URI. + const uri = input.connectionString.replace(/^([^:/?#]+:\/\/[^:/?#@]*:)[^/?#@]*(?=@)/, '$1'); + const identity = JSON.stringify([uri, principalParts(input.principal)]); + return createHash('sha256').update(identity).digest('hex').slice(0, 32); +} + +function principalParts(principal: ConnectionPrincipal): readonly (string | null)[] { + switch (principal.kind) { + case 'native': + return [principal.kind, principal.username]; + case 'entra': + return [principal.kind, principal.providerId, principal.accountId, principal.tenantId ?? null]; + case 'managedIdentity': + // A missing client ID denotes system-assigned, not a particular instance of that identity. + return [principal.kind, principal.clientId ?? null]; + case 'none': + return [principal.kind]; + } +} From 48141f2f369681306552d7cad3b9ff50f35d278f Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 12:42:24 +0000 Subject: [PATCH 050/380] docs: record WI-4a fingerprint integration Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../features/connection-lifecycle/iterations/01-dev-plan.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index ca34c2e0d..2a966ddf6 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 @@ -1024,6 +1024,11 @@ shim (0005). **Progress:** +- **Done (2026-11-20), commit `0e2a89576` (WI-4a, `gpt-6.2-sol`):** Integrated the original + fingerprint comparison winner onto the actual PR3 base. The blind advisor scored it 94/100 + against 88/100 for `mai-code-2` (80% confidence). It hashes the stored URI without its password + and the principal, preserving all other URI bytes. The build and 13 fingerprint tests passed. + --- ## WI-5: Classify failures and recover: host and tree (PR 4) From a9a8d5103e74bf0a6ad34391580614b6d012b6f0 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 06:38:27 +0000 Subject: [PATCH 051/380] Record established connection bindings Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/documentdb/ClustersClient.test.ts | 139 +++++++++++++++++++++++++- src/documentdb/ClustersClient.ts | 129 ++++++++++++++++++------ 2 files changed, 236 insertions(+), 32 deletions(-) diff --git a/src/documentdb/ClustersClient.test.ts b/src/documentdb/ClustersClient.test.ts index ab0661191..dfb7b61cc 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -11,13 +11,20 @@ import type * as Mongodb from 'mongodb'; import { MongoClient, MongoNetworkError, MongoServerError, type MongoClientOptions } from 'mongodb'; import { ext } from '../extensionVariables'; 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 { ManagedIdentityAuthHandler } from './auth/ManagedIdentityAuthHandler'; import { MicrosoftEntraIDAuthHandler } from './auth/MicrosoftEntraIDAuthHandler'; import { NativeAuthHandler } from './auth/NativeAuthHandler'; import { NoAuthHandler } from './auth/NoAuthHandler'; -import { ClustersClient, getIndexExclusionReason, type IndexItemModel } from './ClustersClient'; +import { + addEstablishedConnectionContext, + ClustersClient, + getIndexExclusionReason, + type IndexItemModel, +} from './ClustersClient'; +import { computeConnectionFingerprint } from './connectionFingerprint'; import { CredentialCache } from './CredentialCache'; import { prepareDriverConnectionString } from './srv/prepareDriverConnectionString'; import { type SrvResolutionSummary } from './srv/srvResolutionSummary'; @@ -119,6 +126,13 @@ describe('ClustersClient', () => { describe('regular connection startup diagnostics', () => { const clusterId = 'private-cluster'; + const verifiedIdentity: VerifiedEntraIdentity = { + kind: 'entra', + providerId: 'microsoft', + accountId: 'private-test-account-id', + accountLabel: 'private-test-account-label', + tenantId: 'private-test-tenant', + }; const mockConnect = vi.fn(); const mockClose = vi.fn(); const mockListDatabases = vi.fn<() => Promise>(); @@ -160,11 +174,125 @@ describe('regular connection startup diagnostics', () => { ]) { vi.spyOn(handler.prototype, 'configureAuth').mockImplementation(async () => { vi.advanceTimersByTime(20); - return { connectionString: 'mongodb://private-host:27017', options: {} }; + return { + connectionString: 'mongodb://private-host:27017', + options: {}, + ...(handler === MicrosoftEntraIDAuthHandler ? { verifiedIdentity } : {}), + }; }); } }); + it('publishes a new binding only on successful establishment and advances generations across deletion', async () => { + expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); + const first = await ClustersClient.getClient(clusterId); + expect(first.binding).toEqual({ clusterId, fingerprint: first.fingerprint, generation: first.generation }); + expect(first.createdAt).toBe(Date.now()); + expect(await ClustersClient.getClient(clusterId)).toBe(first); + expect(ClustersClient.getBinding(clusterId)).toBe(first.binding); + + await ClustersClient.deleteClient(clusterId); + expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); + mockConnect.mockRejectedValueOnce(new Error('driver failure')); + await expect(ClustersClient.getClient(clusterId)).rejects.toThrow('driver failure'); + expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); + + const second = await ClustersClient.getClient(clusterId); + expect(ClustersClient.getBinding(clusterId)).toBe(second.binding); + expect(second.generation).toBe(first.generation + 1); + expect(second.fingerprint).toBe(first.fingerprint); + expect(second.createdAt).toBeGreaterThan(first.createdAt); + }); + + 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'; + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.MicrosoftEntraID, originalUri); + vi.mocked(MicrosoftEntraIDAuthHandler.prototype.configureAuth).mockImplementationOnce(async () => { + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.NoAuth, 'mongodb://replacement.example.com'); + return { + connectionString: `${originalUri}&authMechanism=MONGODB-OIDC`, + options: {}, + verifiedIdentity, + }; + }); + vi.mocked(prepareDriverConnectionString).mockResolvedValueOnce({ + connectionString: driverUri, + options: {}, + srvResolution: 'fallback', + }); + + const client = await ClustersClient.getClient(clusterId); + expect(MongoClient).toHaveBeenCalledWith(driverUri, {}); + expect(client.fingerprint).toBe( + computeConnectionFingerprint({ connectionString: originalUri, principal: verifiedIdentity }), + ); + expect(CredentialCache.getCredentials(clusterId)?.authMechanism).toBe(AuthMethodId.NoAuth); + expect(client.authMethod).toBe(AuthMethodId.MicrosoftEntraID); + }); + + it('does not publish an Entra binding when auth does not return a verified identity', async () => { + vi.mocked(MicrosoftEntraIDAuthHandler.prototype.configureAuth).mockResolvedValueOnce({ + connectionString: 'mongodb://private-host:27017', + options: {}, + }); + + await expect(ClustersClient.getClient(clusterId)).rejects.toThrow('verifiedIdentity'); + expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); + expect(MongoClient).not.toHaveBeenCalled(); + }); + + it('aborts only one cached waiter while both are waiting for the same driver connection', async () => { + const client = await ClustersClient.getClient(clusterId); + let finishConnect!: () => void; + const pendingConnect = new Promise((resolve) => { + finishConnect = resolve; + }); + mockConnect.mockReturnValue(pendingConnect); + const controller = new AbortController(); + const cancelled = ClustersClient.getClient(clusterId, controller.signal); + const other = ClustersClient.getClient(clusterId, new AbortController().signal); + expect(mockConnect).toHaveBeenCalledTimes(3); + + controller.abort(); + await expect(cancelled).rejects.toBeInstanceOf(UserCancelledError); + expect(mockClose).not.toHaveBeenCalled(); + + finishConnect(); + await expect(other).resolves.toBe(client); + expect(ClustersClient.getBinding(clusterId)).toBe(client.binding); + expect(mockClose).not.toHaveBeenCalled(); + }); + + it('adds only bounded established-connection context by ID or client and does nothing without one', async () => { + const context: ITelemetryContext = { properties: { existing: 'kept' }, measurements: { existing: 1 } }; + addEstablishedConnectionContext(context, clusterId); + expect(context).toEqual({ properties: { existing: 'kept' }, measurements: { existing: 1 } }); + + const client = await ClustersClient.getClient(clusterId); + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.NoAuth, 'mongodb://replacement.example.com'); + vi.advanceTimersByTime(125); + addEstablishedConnectionContext(context, clusterId); + expect(context).toEqual({ + properties: { + existing: 'kept', + authMethod: AuthMethodId.MicrosoftEntraID, + connectionCorrelationId: client.connectionCorrelationId, + }, + measurements: { existing: 1, connectionAgeMs: 125, clientGeneration: client.generation }, + }); + expect(JSON.stringify(context)).not.toContain(client.fingerprint); + expect(JSON.stringify(context)).not.toContain('private-'); + + vi.advanceTimersByTime(25); + addEstablishedConnectionContext(context, client); + expect(context.measurements.connectionAgeMs).toBe(150); + await ClustersClient.deleteClient(clusterId); + vi.advanceTimersByTime(25); + addEstablishedConnectionContext(context, client); + expect(context.measurements.connectionAgeMs).toBe(150); + }); + afterEach(() => { CredentialCache.deleteCredentials(clusterId); ClustersClient._clients.clear(); @@ -252,6 +380,7 @@ describe('regular connection startup diagnostics', () => { vi.mocked(MicrosoftEntraIDAuthHandler.prototype.configureAuth).mockResolvedValueOnce({ connectionString: `mongodb://${host}/`, options: {}, + verifiedIdentity, }); await ClustersClient.getClient(clusterId); expect(vi.mocked(MongoClient).mock.calls[0]?.[1]?.appName).toBe(appName); @@ -393,7 +522,7 @@ describe('regular connection startup diagnostics', () => { vi.mocked(MicrosoftEntraIDAuthHandler.prototype.configureAuth).mockImplementationOnce( async (_timings, context) => { traceContext = context; - return { connectionString: 'mongodb://private-host:27017', options: {} }; + return { connectionString: 'mongodb://private-host:27017', options: {}, verifiedIdentity }; }, ); const client = await ClustersClient.getClient(clusterId); @@ -496,7 +625,7 @@ describe('regular connection startup diagnostics', () => { const stop = timings?.startTokenAcquire(); vi.advanceTimersByTime(20); stop?.(); - return { connectionString: 'mongodb://private-host:27017', options: {} }; + return { connectionString: 'mongodb://private-host:27017', options: {}, verifiedIdentity }; }); await ClustersClient.getClient(clusterId); expect(startupEvent().telemetry.measurements).toMatchObject({ @@ -638,6 +767,7 @@ describe('regular connection startup diagnostics', () => { vi.mocked(MicrosoftEntraIDAuthHandler.prototype.configureAuth).mockResolvedValueOnce({ connectionString: original, options: {}, + verifiedIdentity, }); vi.mocked(prepareDriverConnectionString).mockResolvedValueOnce({ connectionString: rewritten, @@ -663,6 +793,7 @@ describe('regular connection startup diagnostics', () => { vi.mocked(MicrosoftEntraIDAuthHandler.prototype.configureAuth).mockResolvedValueOnce({ connectionString: original, options: {}, + verifiedIdentity, }); vi.mocked(prepareDriverConnectionString).mockResolvedValueOnce({ connectionString: 'mongodb://resolved.example.com/', diff --git a/src/documentdb/ClustersClient.ts b/src/documentdb/ClustersClient.ts index 40c785b73..529f8f3a6 100644 --- a/src/documentdb/ClustersClient.ts +++ b/src/documentdb/ClustersClient.ts @@ -42,10 +42,13 @@ import { Links } from '../constants'; 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 { createAuthHandler } from './auth/createAuthHandler'; import { getAzureHostSuffix } from './auth/oidcAllowedHosts'; import { QueryInsightsApis, type ExplainVerbosity } from './client/QueryInsightsApis'; +import { computeConnectionFingerprint, type ConnectionPrincipal } from './connectionFingerprint'; import { CredentialCache, type CachedClusterCredentials } from './CredentialCache'; import { QueryError } from './errors/QueryError'; import { @@ -62,7 +65,7 @@ import { SchemaStore } from './SchemaStore'; import { prepareDriverConnectionString } from './srv/prepareDriverConnectionString'; import { type SrvResolutionSummary } from './srv/srvResolutionSummary'; import { ConnectionStartupTimings } from './utils/ConnectionStartupTimings'; -import { getHostsFromConnectionString } from './utils/connectionStringHelpers'; +import { getHostsFromConnectionString, getUserNameFromConnectionString } from './utils/connectionStringHelpers'; import { fixupDocumentDbExplain } from './utils/fixupDocumentDbExplain'; import { getClusterMetadata, type ClusterMetadata } from './utils/getClusterMetadata'; import { parseDocumentId } from './utils/parseDocumentId'; @@ -76,6 +79,12 @@ export interface DatabaseItemModel { empty?: boolean; } +export interface ConnectionBinding { + readonly clusterId: string; + readonly fingerprint: string; + readonly generation: number; +} + export interface CollectionItemModel { name: string; type?: string; @@ -182,6 +191,24 @@ function assertDocumentObject(value: unknown, errorCode: 'INVALID_PROJECTION' | return value as Document; } +function getConnectionPrincipal( + authMethod: AuthMethodId, + credentials: CachedClusterCredentials, + configuredUri: string, + verifiedIdentity: VerifiedEntraIdentity | undefined, +): ConnectionPrincipal { + switch (authMethod) { + case AuthMethodId.NativeAuth: + return { kind: 'native', username: getUserNameFromConnectionString(configuredUri) }; + case AuthMethodId.ManagedIdentity: + return { kind: 'managedIdentity', clientId: credentials.managedIdentityConfig?.clientId }; + case AuthMethodId.MicrosoftEntraID: + return nonNullValue(verifiedIdentity, 'verifiedIdentity', 'ClustersClient.ts'); + case AuthMethodId.NoAuth: + return { kind: 'none' }; + } +} + export class ClustersClient { /** * Cache of active MongoDB clients, keyed by clusterId. @@ -198,6 +225,12 @@ export class ClustersClient { */ static _clients: Map = new Map(); + private static readonly _generations = new Map(); + + #startupCredentials: Readonly; + private _fingerprint: string; + private _binding: ConnectionBinding; + private _createdAt: number; private _mongoClient: MongoClient; private _interactiveEntraStartupId?: string; private _llmEnhancedFeatureApis: llmEnhancedFeatureApis | null = null; @@ -238,6 +271,26 @@ export class ClustersClient { return; } + public get binding(): ConnectionBinding { + return this._binding; + } + + public get createdAt(): number { + return this._createdAt; + } + + public get generation(): number { + return this.binding.generation; + } + + public get fingerprint(): string { + return this.binding.fingerprint; + } + + public get authMethod(): AuthMethodId { + return this.#startupCredentials.authMechanism ?? AuthMethodId.NativeAuth; + } + // TODO: add support for single databases via connection string. // // const databaseInConnectionString = getDatabaseNameFromConnectionString(this.account.connectionString); @@ -364,14 +417,16 @@ export class ClustersClient { } private async initializeClient(startup: ClientStartup, abortSignal?: AbortSignal): Promise { - const credentials = CredentialCache.getCredentials(this.clusterId); - if (!credentials) { + const cachedCredentials = CredentialCache.getCredentials(this.clusterId); + if (!cachedCredentials) { startup.credentialsMissing = true; throw new Error(l10n.t('No credentials found for id {clusterId}', { clusterId: this.clusterId })); } + const credentials = structuredClone(cachedCredentials); + this.#startupCredentials = credentials; // default to NativeAuth if nothing is configured - const authMethod = credentials?.authMechanism ?? AuthMethodId.NativeAuth; + const authMethod = this.authMethod; startup.telemetry.properties.authMethod = authMethod; // Ordinary connects may prompt (for example, Microsoft Entra ID sign-in). @@ -379,13 +434,17 @@ export class ClustersClient { // Configure auth and get connection options this.advanceClientStartup(startup, 'stage02ConfiguringAuth'); - const { connectionString, options } = await authHandler.configureAuth(startup.costTimings, { + const { connectionString, options, verifiedIdentity } = await authHandler.configureAuth(startup.costTimings, { startupCorrelationId: startup.id, surface: 'extension', startupProperties: startup.telemetry.properties, }); this.advanceClientStartup(startup, 'stage03PreparingClient'); + this._fingerprint = computeConnectionFingerprint({ + connectionString: credentials.connectionString, + principal: getConnectionPrincipal(authMethod, credentials, connectionString, verifiedIdentity), + }); const hosts = getHostsFromConnectionString(connectionString); const userAgentString = hosts.some((host) => getAzureHostSuffix(host)) ? appendExtensionUserAgent() : undefined; if (userAgentString) { @@ -595,8 +654,8 @@ export class ClustersClient { * * @param clusterId - A required string used to find the cached connection string to connect. * It is also used as a key to reuse existing clients. - * @param abortSignal - Optional signal to abort the connection attempt. When aborted, - * the in-progress connection is closed and a `UserCancelledError` is thrown. + * @param abortSignal - Optional signal that rejects the call with `UserCancelledError` on abort. + * A cold startup closes its in-progress connection; a cached reuse cancels only this caller's wait. * @param onStartup - Called with the startup correlation ID of the attempt this call joins. * @param trigger - Which code path asks for the client; recorded as `startupTrigger` when this * call starts a new `connect.startup`. Callers that do not pass it are recorded as `other`. @@ -614,33 +673,27 @@ export class ClustersClient { onStartup?.(client.connectionCorrelationId); } - // Wire up abort for cached client reconnection so the cancellable - // progress UI can also cancel a reconnection attempt. if (abortSignal?.aborted) { throw new UserCancelledError('abortConnection'); } - const onAbort = (): void => { - void client._mongoClient.close().catch(() => { - // Ignore close errors when aborting during reconnect - }); - }; - abortSignal?.addEventListener('abort', onAbort, { once: true }); - - try { - // if the client is already connected, it's a NOOP. - // Note: connectionCorrelationId retains the value from the initial - // connection (set in initClient). This is by design — the correlation - // ID links the original connect/staticmetadata/getmetadata events. - // Cached reconnects don't emit new metadata events, so no new ID is needed. + // Preserve the original startup correlation ID on cached reuse. + if (!abortSignal) { await client._mongoClient.connect(); - } catch (error) { - if (abortSignal?.aborted) { - throw new UserCancelledError('abortConnection'); - } - throw error; + return client; + } + let onAbort: (() => void) | undefined; + try { + await new Promise((resolve, reject) => { + onAbort = (): void => reject(new UserCancelledError('abortConnection')); + abortSignal.addEventListener('abort', onAbort, { once: true }); + // Keep observing the driver promise even if the caller stops waiting. + void client._mongoClient.connect().then(resolve, reject); + }); } finally { - abortSignal?.removeEventListener('abort', onAbort); + if (onAbort) { + abortSignal.removeEventListener('abort', onAbort); + } } return client; @@ -650,6 +703,10 @@ export class ClustersClient { try { // Cluster metadata is set in initClient await client.initClient(abortSignal, onStartup, trigger); + const generation = (ClustersClient._generations.get(clusterId) ?? 0) + 1; + client._binding = Object.freeze({ clusterId, fingerprint: client._fingerprint, generation }); + client._createdAt = Date.now(); + ClustersClient._generations.set(clusterId, generation); ClustersClient._clients.set(clusterId, client); ClustersClient._lastFailedStartups.delete(clusterId); } catch (error) { @@ -698,6 +755,10 @@ export class ClustersClient { return ClustersClient._clients.get(clusterId); } + public static getBinding(clusterId: string): ConnectionBinding | undefined { + return ClustersClient.getExistingClient(clusterId)?.binding; + } + public static getSrvResolution(clusterId: string): SrvResolutionSummary | undefined { return ClustersClient._clients.get(clusterId)?._srvResolution; } @@ -1526,3 +1587,15 @@ export class ClustersClient { return this._llmEnhancedFeatureApis.unhideIndex(databaseName, collectionName, indexName); } } + +export function addEstablishedConnectionContext(context: ITelemetryContext, cluster: string | ClustersClient): void { + const client = typeof cluster === 'string' ? ClustersClient.getExistingClient(cluster) : cluster; + if (!client || ClustersClient.getExistingClient(client.binding.clusterId) !== client) { + return; + } + + context.properties.authMethod = client.authMethod; + context.properties.connectionCorrelationId = client.connectionCorrelationId; + context.measurements.connectionAgeMs = Math.max(0, Date.now() - client.createdAt); + context.measurements.clientGeneration = client.generation; +} From 9a4d28dfa5228c20e16b3523b016e06088c72d99 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 12:45:54 +0000 Subject: [PATCH 052/380] docs: record WI-4b binding and cancellation integration Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../features/connection-lifecycle/iterations/01-dev-plan.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index 2a966ddf6..7792c3e92 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 @@ -1028,6 +1028,12 @@ shim (0005). fingerprint comparison winner onto the actual PR3 base. The blind advisor scored it 94/100 against 88/100 for `mai-code-2` (80% confidence). It hashes the stored URI without its password and the principal, preserving all other URI bytes. The build and 13 fingerprint tests passed. +- **Done (2026-11-20), commit `a9a8d5103` (WI-4b, `gpt-6.2-sol`):** Integrated the client + generation, binding, isolated cached-waiter cancellation, and telemetry context helper. + The blind scores were 89/100 and 74/100; the selection was provisional until the advisor + (`claude-opus-5.5`) approved the staged winner on the actual PR3 base at 85% confidence. + The build and 121 focused tests passed. Generations advance only on successful establishment; + cancelling one waiter no longer closes the client shared by other callers. --- From 7a7c0909a29b0a996f5514acead2db8002e4d33e Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 12:49:00 +0000 Subject: [PATCH 053/380] docs: record WI-4c trial decision gate Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../connection-lifecycle/iterations/01-dev-plan.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index 7792c3e92..adbb5f20d 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 @@ -1034,6 +1034,14 @@ shim (0005). (`claude-opus-5.5`) approved the staged winner on the actual PR3 base at 85% confidence. The build and 121 focused tests passed. Generations advance only on successful establishment; cancelling one waiter no longer closes the client shared by other callers. +- **WI-4c deferred, escalated (2026-11-20):** The plan allows one retry after a stale startup + and specifies the result when a latch is set. It does not specify the unlatched result when + that retry is also invalidated. Recommendation: use a neutral retryable error, “The connection + changed while it was opening. Try again.” The advisor suggested `credentialsChanged`, which + fits the existing enum but can imply a credential change after a plain eviction. Confirm + the changes to the existing cancellation tests as well: cancelling a wait must not cancel + or misreport the physical startup, and a real startup failure must still be logged and cleaned + up. Neither choice was assumed. The two worktrees are ready; no coding variants have run. --- From eff2070fba2f530097b4d6eb740d3f93c547af4c Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 13:10:01 +0000 Subject: [PATCH 054/380] docs: record the WI-4c retry outcome decision Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../features/connection-lifecycle/iterations/01-dev-plan.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index adbb5f20d..e8bbb4dab 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 @@ -1042,6 +1042,11 @@ shim (0005). the changes to the existing cancellation tests as well: cancelling a wait must not cancel or misreport the physical startup, and a real startup failure must still be logged and cleaned up. Neither choice was assumed. The two worktrees are ready; no coding variants have run. +- **WI-4c operator decision (2026-11-20):** Use the neutral retryable error “The connection + changed while it was opening. Try again.” if the one retry is also superseded and no latch + is set. Do not add a new unavailable reason or a third attempt. A latch takes precedence. + Cancellation assertions continue to follow the approved waiter-only behavior and retain + coverage of actual startup failures, telemetry and cleanup. --- From 61e9cd4f53678128c87286dd76146722c497a6e0 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 14:01:02 +0000 Subject: [PATCH 055/380] fix: share client startups and reject superseded clients (WI-4c) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/documentdb/ClustersClient.test.ts | 277 +++++++++++++++++-- src/documentdb/ClustersClient.ts | 250 ++++++++++------- src/documentdb/ConnectionUnavailableError.ts | 29 ++ 3 files changed, 430 insertions(+), 126 deletions(-) create mode 100644 src/documentdb/ConnectionUnavailableError.ts diff --git a/src/documentdb/ClustersClient.test.ts b/src/documentdb/ClustersClient.test.ts index dfb7b61cc..a84b915ca 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -25,6 +25,7 @@ import { type IndexItemModel, } from './ClustersClient'; import { computeConnectionFingerprint } from './connectionFingerprint'; +import { ConnectionUnavailableError } from './ConnectionUnavailableError'; import { CredentialCache } from './CredentialCache'; import { prepareDriverConnectionString } from './srv/prepareDriverConnectionString'; import { type SrvResolutionSummary } from './srv/srvResolutionSummary'; @@ -39,6 +40,16 @@ interface RecordedTelemetry { const mockTelemetryEvents: RecordedTelemetry[] = []; +function deferred(): { promise: Promise; resolve: () => void; reject: (error: Error) => void } { + let resolve!: () => void; + let reject!: (error: Error) => void; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve, reject }; +} + vi.mock('@microsoft/vscode-azext-utils', async () => { const actual = await vi.importActual<{ UserCancelledError: typeof UserCancelledError }>( '@microsoft/vscode-azext-utils', @@ -138,6 +149,16 @@ describe('regular connection startup diagnostics', () => { const mockListDatabases = vi.fn<() => Promise>(); let poolEvents: EventEmitter; + function pauseNextConnect(): { started: Promise; resolve: () => void; reject: (error: Error) => void } { + const started = deferred(); + const finish = deferred(); + mockConnect.mockImplementationOnce(() => { + started.resolve(); + return finish.promise; + }); + return { started: started.promise, resolve: finish.resolve, reject: finish.reject }; + } + beforeEach(() => { vi.clearAllMocks(); vi.useFakeTimers(); @@ -264,6 +285,183 @@ describe('regular connection startup diagnostics', () => { expect(mockClose).not.toHaveBeenCalled(); }); + it('shares one cold startup even with a caller re-entering from onStartup', async () => { + const onJoin = vi.fn(); + let joined!: Promise; + const onStart = vi.fn(() => { + joined = ClustersClient.getClient(clusterId, undefined, onJoin); + }); + const first = ClustersClient.getClient(clusterId, undefined, onStart, 'treeConnect'); + const [client, same] = await Promise.all([first, joined]); + expect(same).toBe(client); + expect(onStart).toHaveBeenCalledExactlyOnceWith(client.connectionCorrelationId); + expect(onJoin).toHaveBeenCalledExactlyOnceWith(client.connectionCorrelationId); + expect(mockConnect).toHaveBeenCalledTimes(1); + expect(getClusterMetadata).toHaveBeenCalledTimes(1); + expect(startupEvent().telemetry.properties.startupTrigger).toBe('treeConnect'); + }); + + it.each([0, 1])('canceling cold waiter %i leaves the other waiter connected', async (index) => { + const handshake = pauseNextConnect(); + const controllers = [new AbortController(), new AbortController()]; + const waits = controllers.map(({ signal }) => ClustersClient.getClient(clusterId, signal)); + await handshake.started; + controllers[index].abort(); + await expect(waits[index]).rejects.toBeInstanceOf(UserCancelledError); + expect(vi.mocked(prepareDriverConnectionString).mock.calls[0][0].abortSignal).toBeUndefined(); + expect(mockClose).not.toHaveBeenCalled(); + handshake.resolve(); + const client = await waits[1 - index]; + expect(ClustersClient.getBinding(clusterId)).toBe(client.binding); + expect(mockConnect).toHaveBeenCalledTimes(1); + expect(mockClose).not.toHaveBeenCalled(); + }); + + it('closes the superseded driver without publishing it or removing the newer pending startup', async () => { + const baseline = await ClustersClient.getClient(clusterId); + await ClustersClient.deleteClient(clusterId); + mockClose.mockClear(); + const closing = deferred(); + mockClose.mockReturnValueOnce(closing.promise); + + const first = pauseNextConnect(); + const retried = deferred(); + const onStartup = vi.fn().mockImplementationOnce(() => undefined).mockImplementationOnce(retried.resolve); + const waiter = ClustersClient.getClient(clusterId, undefined, onStartup); + await first.started; + await ClustersClient.deleteClient(clusterId); + const second = pauseNextConnect(); + const replacement = ClustersClient.getClient(clusterId); + await second.started; + + first.resolve(); + await retried.promise; + expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); + expect(mockClose).toHaveBeenCalledTimes(1); + expect(mockClose.mock.contexts[0]).toBe(mockConnect.mock.contexts[1]); + second.resolve(); + const client = await replacement; + await expect(waiter).resolves.toBe(client); + expect(onStartup.mock.calls[0][0]).not.toBe(client.connectionCorrelationId); + expect(onStartup.mock.calls[1][0]).toBe(client.connectionCorrelationId); + expect(client.generation).toBe(baseline.generation + 1); + expect(ClustersClient.getBinding(clusterId)).toBe(client.binding); + expect(mockConnect).toHaveBeenCalledTimes(3); + closing.reject(new Error('private cleanup detail')); + await Promise.resolve(); + expect(ext.outputChannel.debug).toHaveBeenCalledWith( + `[ClustersClient] startup=${onStartup.mock.calls[0][0]} superseded client cleanup failed surface=extension`, + ); + }); + + it('reports the latch instead of a failed superseded handshake', async () => { + const handshake = pauseNextConnect(); + const waiter = ClustersClient.getClient(clusterId); + await handshake.started; + ClustersClient.latch(clusterId, 'userDisconnected'); + handshake.reject(new Error('superseded failure')); + + await expect(waiter).rejects.toMatchObject({ name: 'ConnectionUnavailableError', reason: 'userDisconnected' }); + expect(mockConnect).toHaveBeenCalledOnce(); + expect(mockClose).toHaveBeenCalledOnce(); + expect(ClustersClient.getExistingClient(clusterId)).toBeUndefined(); + }); + + it('a stale driver failure does not replace the correlation ID of a newer failure', async () => { + const stale = pauseNextConnect(); + const waiter = ClustersClient.getClient(clusterId); + await stale.started; + ClustersClient.invalidate(clusterId); + mockConnect.mockRejectedValueOnce(new Error('current failure')); + await expect(ClustersClient.getClient(clusterId)).rejects.toThrow('current failure'); + const failedId = startupEvent().telemetry.properties.startupCorrelationId; + expect(ClustersClient.getLastFailedStartupCorrelationId(clusterId)).toBe(failedId); + stale.reject(new Error('superseded failure')); + const client = await waiter; + const retry = mockTelemetryEvents.find( + (event) => + event.eventName === 'connect.startup' && + event.telemetry.properties.startupCorrelationId === client.connectionCorrelationId, + ); + expect(retry?.telemetry.properties.previousFailedStartupCorrelationId).toBe(failedId); + expect(ClustersClient.getLastFailedStartupCorrelationId(clusterId)).toBeUndefined(); + }); + + it('removes the cached entry before closing and leaves a racing replacement alone', async () => { + const old = await ClustersClient.getClient(clusterId); + const epoch = ClustersClient.getEpoch(clusterId); + const closing = deferred(); + mockClose.mockReturnValueOnce(closing.promise); + const deletion = ClustersClient.deleteClient(clusterId); + expect(ClustersClient.getEpoch(clusterId)).toBe(epoch + 1); + expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); + const replacement = await ClustersClient.getClient(clusterId); + closing.resolve(); + await deletion; + expect(mockClose).toHaveBeenCalledTimes(1); + expect(mockClose.mock.contexts[0]).toBe(old.getMongoClient()); + expect(ClustersClient.getBinding(clusterId)).toBe(replacement.binding); + }); + + it.each([false, true])('a stale cached waiter has only one retry (latched: %s)', async (latch) => { + const cached = await ClustersClient.getClient(clusterId); + const cachedConnect = pauseNextConnect(); + const onStartup = vi.fn(); + const waiter = ClustersClient.getClient(clusterId, undefined, onStartup); + await cachedConnect.started; + await ClustersClient.deleteClient(clusterId); + const retry = pauseNextConnect(); + cachedConnect.reject(new Error('old client closed')); + await retry.started; + if (latch) { + ClustersClient.latch(clusterId, 'connectionRemoved'); + } else { + ClustersClient.invalidate(clusterId); + } + retry.resolve(); + if (latch) { + await expect(waiter).rejects.toMatchObject({ + name: 'ConnectionUnavailableError', + reason: 'connectionRemoved', + }); + } else { + await expect(waiter).rejects.toMatchObject({ + constructor: Error, + message: 'The connection changed while it was opening. Try again.', + }); + } + expect(onStartup).toHaveBeenCalledTimes(2); + expect(onStartup.mock.calls[0][0]).toBe(cached.connectionCorrelationId); + expect(onStartup.mock.calls[1][0]).not.toBe(cached.connectionCorrelationId); + expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); + expect(MongoClient).toHaveBeenCalledTimes(2); + }); + + it('latch blocks cold and cached calls before startup or driver reuse', async () => { + const epoch = ClustersClient.getEpoch(clusterId); + ClustersClient.latch(clusterId, 'userDisconnected'); + expect(ClustersClient.getEpoch(clusterId)).toBe(epoch + 1); + expect(ClustersClient.getLatchReason(clusterId)).toBe('userDisconnected'); + const onStartup = vi.fn(); + await expect(ClustersClient.getClient(clusterId, undefined, onStartup)).rejects.toMatchObject({ + name: 'ConnectionUnavailableError', + reason: 'userDisconnected', + message: 'The connection is unavailable.', + }); + expect(MongoClient).not.toHaveBeenCalled(); + ClustersClient.unlatch(clusterId); + expect(ClustersClient.getEpoch(clusterId)).toBe(epoch + 2); + expect(ClustersClient.getLatchReason(clusterId)).toBeUndefined(); + + await ClustersClient.getClient(clusterId); + ClustersClient.latch(clusterId, 'credentialsChanged'); + await expect(ClustersClient.getClient(clusterId, undefined, onStartup)).rejects.toMatchObject({ + reason: 'credentialsChanged', + }); + expect(mockConnect).toHaveBeenCalledTimes(1); + expect(onStartup).not.toHaveBeenCalled(); + }); + it('adds only bounded established-connection context by ID or client and does nothing without one', async () => { const context: ITelemetryContext = { properties: { existing: 'kept' }, measurements: { existing: 1 } }; addEstablishedConnectionContext(context, clusterId); @@ -294,6 +492,10 @@ describe('regular connection startup diagnostics', () => { }); afterEach(() => { + if (ClustersClient.getLatchReason(clusterId)) { + ClustersClient.unlatch(clusterId); + } + ClustersClient['_pendingStartups'].clear(); CredentialCache.deleteCredentials(clusterId); ClustersClient._clients.clear(); ClustersClient._lastFailedStartups.clear(); @@ -671,48 +873,83 @@ describe('regular connection startup diagnostics', () => { expect(client.connectionCorrelationId).not.toBe(firstEvent.telemetry.properties.connectionCorrelationId); }); - it('reports cancellation without swallowing the caller cancellation error', async () => { + it('does not start a connection for an already canceled waiter', async () => { const controller = new AbortController(); controller.abort(); - await expect(ClustersClient.getClient(clusterId, controller.signal)).rejects.toBeInstanceOf(UserCancelledError); - expect(startupEvent().telemetry.properties).toMatchObject({ result: 'Canceled', startupOutcome: 'canceled' }); + const onStartup = vi.fn(); + await expect(ClustersClient.getClient(clusterId, controller.signal, onStartup)).rejects.toBeInstanceOf( + UserCancelledError, + ); + expect(onStartup).not.toHaveBeenCalled(); + expect(mockTelemetryEvents.filter((e) => e.eventName === 'connect.startup')).toHaveLength(0); expect(ext.outputChannel.error).not.toHaveBeenCalled(); expect(mockConnect).not.toHaveBeenCalled(); }); - it('records cancellation during the driver handshake and retains cleanup', async () => { + it('records a canceled wait during the handshake but publishes the abandoned successful startup', async () => { const controller = new AbortController(); - mockConnect.mockImplementationOnce(async (): Promise => { - vi.advanceTimersByTime(25); - controller.abort(); - throw new Error('private-driver-abort'); - }); + const handshake = pauseNextConnect(); + const waiter = ClustersClient.getClient(clusterId, controller.signal); + await handshake.started; + vi.advanceTimersByTime(25); + controller.abort(); + await expect(waiter).rejects.toBeInstanceOf(UserCancelledError); + handshake.resolve(); + await vi.advanceTimersByTimeAsync(0); - await expect(ClustersClient.getClient(clusterId, controller.signal)).rejects.toBeInstanceOf(UserCancelledError); expect(startupEvent().telemetry.properties).toMatchObject({ - result: 'Canceled', - startupOutcome: 'canceled', - lastStage: 'stage04ConnectingAndAuthenticating', + result: 'Succeeded', + startupOutcome: 'succeeded', + lastStage: 'stage05InitializingApis', }); expect(startupEvent().telemetry.measurements.stage04ConnectingAndAuthenticatingDurationMs).toBe(25); - expect(mockClose).toHaveBeenCalled(); + expect(mockClose).not.toHaveBeenCalled(); expect(ext.outputChannel.error).not.toHaveBeenCalled(); - expect(ClustersClient._clients.has(clusterId)).toBe(false); const startupId = startupEvent().telemetry.properties.startupCorrelationId as string; + expect(ClustersClient.getExistingClient(clusterId)?.connectionCorrelationId).toBe(startupId); expect(startupId).toMatch(/^[0-9a-f-]{36}$/); expect(ext.outputChannel.debug).toHaveBeenCalledWith( - `[ClustersClient] startup=${startupId} canceled by user surface=extension`, + `[ClustersClient] startup=${startupId} wait canceled by user surface=extension`, ); }); + it('reports and cleans up a genuine driver failure after both cold waiters leave', async () => { + const handshake = pauseNextConnect(); + const controllers = [new AbortController(), new AbortController()]; + const waits = controllers.map(({ signal }) => ClustersClient.getClient(clusterId, signal)); + await handshake.started; + controllers.forEach((controller) => controller.abort()); + await Promise.all(waits.map((wait) => expect(wait).rejects.toBeInstanceOf(UserCancelledError))); + expect(mockClose).not.toHaveBeenCalled(); + handshake.reject(new MongoNetworkError('private-driver-failure')); + await vi.advanceTimersByTimeAsync(0); + expect(startupEvent().telemetry.properties).toMatchObject({ + result: 'Failed', + startupOutcome: 'failed', + startupFailureCategory: 'network', + lastStage: 'stage04ConnectingAndAuthenticating', + }); + const failedId = startupEvent().telemetry.properties.startupCorrelationId; + expect(ClustersClient.getLastFailedStartupCorrelationId(clusterId)).toBe(failedId); + expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); + expect(mockClose).toHaveBeenCalledTimes(1); + expect((await ClustersClient.getClient(clusterId)).connectionCorrelationId).not.toBe(failedId); + }); + it('records a credentials failure before auth configuration', async () => { CredentialCache.deleteCredentials(clusterId); - await expect(ClustersClient.getClient(clusterId)).rejects.toThrow('No credentials found'); + const waiter = ClustersClient.getClient(clusterId); + await expect(waiter).rejects.toBeInstanceOf(ConnectionUnavailableError); + await expect(waiter).rejects.toMatchObject({ + name: 'ConnectionUnavailableError', + reason: 'credentialsMissing', + message: 'No credentials found.', + }); expect(startupEvent().telemetry.properties).toMatchObject({ result: 'Failed', lastStage: 'stage01PreparingCredentials', - startupFailureType: 'Error', + startupFailureType: 'ConnectionUnavailableError', startupFailureCategory: 'credentialsUnavailable', startupTrigger: 'other', }); @@ -744,7 +981,7 @@ describe('regular connection startup diagnostics', () => { expect(JSON.stringify(startupEvent())).not.toContain('private-'); }); - it('records no failure properties on a successful or cancelled startup', async () => { + it('records no failure properties on success and no startup event for pre-cancellation', async () => { await ClustersClient.getClient(clusterId, undefined, undefined, 'clusterDashboardPoll'); expect(startupEvent().telemetry.properties).toMatchObject({ startupTrigger: 'clusterDashboardPoll' }); expect(startupEvent().telemetry.properties.startupFailureType).toBeUndefined(); @@ -755,7 +992,7 @@ describe('regular connection startup diagnostics', () => { const controller = new AbortController(); controller.abort(); await expect(ClustersClient.getClient(clusterId, controller.signal)).rejects.toBeInstanceOf(UserCancelledError); - expect(startupEvent().telemetry.properties.startupFailureCategory).toBeUndefined(); + expect(mockTelemetryEvents.filter((event) => event.eventName === 'connect.startup')).toHaveLength(0); }); it('hands the transient URI to the driver while metadata and credentials keep the original', async () => { diff --git a/src/documentdb/ClustersClient.ts b/src/documentdb/ClustersClient.ts index 529f8f3a6..4523f8388 100644 --- a/src/documentdb/ClustersClient.ts +++ b/src/documentdb/ClustersClient.ts @@ -49,6 +49,7 @@ import { createAuthHandler } from './auth/createAuthHandler'; import { getAzureHostSuffix } from './auth/oidcAllowedHosts'; import { QueryInsightsApis, type ExplainVerbosity } from './client/QueryInsightsApis'; import { computeConnectionFingerprint, type ConnectionPrincipal } from './connectionFingerprint'; +import { ConnectionUnavailableError, type ConnectionUnavailableReason } from './ConnectionUnavailableError'; import { CredentialCache, type CachedClusterCredentials } from './CredentialCache'; import { QueryError } from './errors/QueryError'; import { @@ -180,6 +181,40 @@ interface ClientStartup { credentialsMissing?: boolean; } +interface PendingStartup { + readonly id: string; + readonly epoch: number; + readonly promise: Promise; +} + +async function waitForClient( + promise: Promise, + signal: AbortSignal | undefined, + startupId: string | undefined, +): Promise { + if (!signal) { + return promise; + } + let onAbort!: () => void; + try { + return await new Promise((resolve, reject) => { + onAbort = (): void => { + ext.outputChannel.debug(`[ClustersClient] startup=${startupId} wait canceled by user surface=extension`); + reject(new UserCancelledError('abortConnection')); + }; + // Observe settlement even if this caller has already left. + void promise.then(resolve, reject); + if (signal.aborted) { + onAbort(); + } else { + signal.addEventListener('abort', onAbort, { once: true }); + } + }); + } finally { + signal.removeEventListener('abort', onAbort); + } +} + /** * Validates that a parsed BSON value is a plain object (not a scalar, array, or null). * Throws a QueryError if the value is not a plain object. @@ -226,6 +261,33 @@ export class ClustersClient { static _clients: Map = new Map(); private static readonly _generations = new Map(); + private static readonly _epochs = new Map(); + private static readonly _latches = new Map(); + private static readonly _pendingStartups = new Map(); + + public static getEpoch(clusterId: string): number { + return ClustersClient._epochs.get(clusterId) ?? 0; + } + + public static invalidate(clusterId: string): number { + const epoch = ClustersClient.getEpoch(clusterId) + 1; + ClustersClient._epochs.set(clusterId, epoch); + return epoch; + } + + public static latch(clusterId: string, reason: ConnectionUnavailableReason): void { + ClustersClient._latches.set(clusterId, reason); + ClustersClient.invalidate(clusterId); + } + + public static unlatch(clusterId: string): void { + ClustersClient._latches.delete(clusterId); + ClustersClient.invalidate(clusterId); + } + + public static getLatchReason(clusterId: string): ConnectionUnavailableReason | undefined { + return ClustersClient._latches.get(clusterId); + } #startupCredentials: Readonly; private _fingerprint: string; @@ -245,7 +307,7 @@ export class ClustersClient { /** * This client's startup ID, also published as `startupCorrelationId`. Links `connect.startup`, - * `connect.staticmetadata`, `connect.getmetadata` and SRV events. Generated once per `initClient` call. + * `connect.staticmetadata`, `connect.getmetadata` and SRV events. Generated once per cold startup. */ public connectionCorrelationId?: string; @@ -323,14 +385,8 @@ export class ClustersClient { return CredentialCache.getCredentials(this.clusterId)?.localQuickStartInstance === true; } - private async initClient( - abortSignal: AbortSignal | undefined, - onStartup: ((id: string) => void) | undefined, - trigger: ClientStartupTrigger, - ): Promise { - const startupId = randomUUID(); + private async initClient(startupId: string, trigger: ClientStartupTrigger): Promise { this.connectionCorrelationId = startupId; - onStartup?.(startupId); let originalFailure: { error: unknown } | undefined; try { @@ -361,7 +417,7 @@ export class ClustersClient { }; try { - await this.initializeClient(startup, abortSignal); + await this.initializeClient(startup); this.finishClientStartup(startup, 'succeeded'); } catch (error) { const canceled = error instanceof UserCancelledError; @@ -416,11 +472,11 @@ export class ClustersClient { ); } - private async initializeClient(startup: ClientStartup, abortSignal?: AbortSignal): Promise { + private async initializeClient(startup: ClientStartup): Promise { const cachedCredentials = CredentialCache.getCredentials(this.clusterId); if (!cachedCredentials) { startup.credentialsMissing = true; - throw new Error(l10n.t('No credentials found for id {clusterId}', { clusterId: this.clusterId })); + throw new ConnectionUnavailableError('credentialsMissing'); } const credentials = structuredClone(cachedCredentials); this.#startupCredentials = credentials; @@ -475,7 +531,6 @@ export class ClustersClient { startupCorrelationId: startup.id, connectionCorrelationId: startup.id, }, - abortSignal, startupTelemetry: startup.telemetry, }); this._srvResolution = prepared.summary; @@ -485,7 +540,6 @@ export class ClustersClient { prepared.options, authMethod === AuthMethodId.MicrosoftEntraID, credentials.emulatorConfiguration, - abortSignal, connectionString, ); @@ -536,49 +590,14 @@ export class ClustersClient { options: MongoClientOptions, interactiveEntra: boolean, emulatorConfiguration?: EmulatorConfiguration, - abortSignal?: AbortSignal, originalConnectionString: string = connectionString, ): Promise { - // Create the client instance first so we hold a reference during connection. - // This allows callers to abort via abortSignal by closing the underlying client. this._mongoClient = new MongoClient(connectionString, options); if (interactiveEntra) { this._interactiveEntraStartupId = startup.id; this.traceInteractiveEntraPool(startup.id); } - if (abortSignal?.aborted) { - ext.outputChannel.debug( - `[ClustersClient] startup=${startup.id} canceled before connecting (already aborted signal) surface=extension`, - ); - await this._mongoClient.close(); - throw new UserCancelledError('abortConnection'); - } - - // Track whether connect() has resolved so the abort handler can avoid - // closing an already-connected client during the micro window between - // connect() resolving and removeEventListener firing. This window exists - // because abort events are dispatched synchronously when abort() is - // called: if abort() fires during the synchronous continuation after - // connect() resolves but before the listener is removed, the handler - // would close the now-connected client without this guard. - let connected = false; - - // Wire up abort: closing the client causes the pending connect() to reject - const onAbort = (): void => { - if (connected) { - // connect() already resolved — do not close the connected client. - return; - } - ext.outputChannel.debug( - `[ClustersClient] startup=${startup.id} abort requested; closing client to interrupt connection handshake surface=extension`, - ); - void this._mongoClient.close().catch(() => { - // Ignore close errors during abort cleanup - }); - }; - abortSignal?.addEventListener('abort', onAbort, { once: true }); - try { this.advanceClientStartup(startup, 'stage04ConnectingAndAuthenticating'); const stopDatabaseConnect = startup.costTimings.startDatabaseConnect(); @@ -587,24 +606,10 @@ export class ClustersClient { } finally { stopDatabaseConnect(); } - connected = true; - - // Remove the abort listener immediately after connect() resolves so - // that a late cancellation during synchronous API init below cannot - // close an already-connected client while the method continues as - // "successful". The connected flag above serves as a belt-and-suspenders - // guard in case abort fires between the assignment and this removal. - abortSignal?.removeEventListener('abort', onAbort); - this.advanceClientStartup(startup, 'stage05InitializingApis'); this._llmEnhancedFeatureApis = new llmEnhancedFeatureApis(this._mongoClient); this._queryInsightsApis = new QueryInsightsApis(this._mongoClient); } catch (error) { - if (abortSignal?.aborted) { - ext.outputChannel.debug(`[ClustersClient] startup=${startup.id} canceled by user surface=extension`); - throw new UserCancelledError('abortConnection'); - } - const message = parseError(error).message; // Surface the friendly local-connection tips only for a genuinely local-ish connection // (emulator, OR a local connection that opted into the TLS exception — host-gated the @@ -630,13 +635,6 @@ export class ClustersClient { ); } throw error; - } finally { - // Clean up the abort listener if we didn't already remove it in the - // success path (i.e., connect() failed). In the success path the - // listener was already removed above. - if (abortSignal && !connected) { - abortSignal.removeEventListener('abort', onAbort); - } } } @@ -655,7 +653,7 @@ export class ClustersClient { * @param clusterId - A required string used to find the cached connection string to connect. * It is also used as a key to reuse existing clients. * @param abortSignal - Optional signal that rejects the call with `UserCancelledError` on abort. - * A cold startup closes its in-progress connection; a cached reuse cancels only this caller's wait. + * Cancellation stops only this caller's wait, not the underlying connection. * @param onStartup - Called with the startup correlation ID of the attempt this call joins. * @param trigger - Which code path asks for the client; recorded as `startupTrigger` when this * call starts a new `connect.startup`. Callers that do not pass it are recorded as `other`. @@ -667,59 +665,100 @@ export class ClustersClient { onStartup?: (id: string) => void, trigger: ClientStartupTrigger = 'other', ): Promise { - if (ClustersClient._clients.has(clusterId)) { - const client = ClustersClient._clients.get(clusterId) as ClustersClient; - if (client.connectionCorrelationId) { - onStartup?.(client.connectionCorrelationId); + for (let attempt = 0; ; attempt++) { + const reason = ClustersClient.getLatchReason(clusterId); + if (reason) { + throw new ConnectionUnavailableError(reason); } - if (abortSignal?.aborted) { throw new UserCancelledError('abortConnection'); } + if (attempt === 2) { + throw new Error(l10n.t('The connection changed while it was opening. Try again.')); + } - // Preserve the original startup correlation ID on cached reuse. - if (!abortSignal) { - await client._mongoClient.connect(); - return client; + const epoch = ClustersClient.getEpoch(clusterId); + const cached = ClustersClient._clients.get(clusterId); + let promise: Promise; + let id: string | undefined; + if (cached) { + id = cached.connectionCorrelationId; + if (id) { + onStartup?.(id); + } + promise = cached._mongoClient.connect().then(() => cached); + } else { + const pending = ClustersClient.getOrStartClient(clusterId, epoch, trigger); + id = pending.id; + onStartup?.(id); + promise = pending.promise; } - let onAbort: (() => void) | undefined; + try { - await new Promise((resolve, reject) => { - onAbort = (): void => reject(new UserCancelledError('abortConnection')); - abortSignal.addEventListener('abort', onAbort, { once: true }); - // Keep observing the driver promise even if the caller stops waiting. - void client._mongoClient.connect().then(resolve, reject); - }); - } finally { - if (onAbort) { - abortSignal.removeEventListener('abort', onAbort); + const client = await waitForClient(promise, abortSignal, id); + if (epoch === ClustersClient.getEpoch(clusterId)) { + return client; + } + } catch (error) { + if (epoch === ClustersClient.getEpoch(clusterId)) { + throw error; } } + // Both a stale success and a stale failure use the same retry, after checking the latch. + } + } - return client; + private static getOrStartClient(clusterId: string, epoch: number, trigger: ClientStartupTrigger): PendingStartup { + const existing = ClustersClient._pendingStartups.get(clusterId); + if (existing?.epoch === epoch) { + return existing; } + 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)); + const pending = { id, epoch, promise }; + ClustersClient._pendingStartups.set(clusterId, pending); + const clear = (): void => { + if (ClustersClient._pendingStartups.get(clusterId) === pending) { + ClustersClient._pendingStartups.delete(clusterId); + } + }; + void promise.then(clear, clear); + return pending; + } + + private static async establishClient( + clusterId: string, + epoch: number, + id: string, + trigger: ClientStartupTrigger, + ): Promise { const client = new ClustersClient(clusterId); try { - // Cluster metadata is set in initClient - await client.initClient(abortSignal, onStartup, trigger); - const generation = (ClustersClient._generations.get(clusterId) ?? 0) + 1; - client._binding = Object.freeze({ clusterId, fingerprint: client._fingerprint, generation }); - client._createdAt = Date.now(); - ClustersClient._generations.set(clusterId, generation); - ClustersClient._clients.set(clusterId, client); - ClustersClient._lastFailedStartups.delete(clusterId); + await client.initClient(id, trigger); } catch (error) { - if (!(error instanceof UserCancelledError) && !abortSignal?.aborted && client.connectionCorrelationId) { - ClustersClient._lastFailedStartups.set(clusterId, client.connectionCorrelationId); + if (!(error instanceof UserCancelledError) && epoch === ClustersClient.getEpoch(clusterId)) { + ClustersClient._lastFailedStartups.set(clusterId, id); } - // On failure (including abort), clean up the partially-created client void client._mongoClient?.close().catch(() => { // Ignore close errors during cleanup }); throw error; } + if (epoch !== ClustersClient.getEpoch(clusterId)) { + void client._mongoClient.close().catch(() => { + ext.outputChannel.debug(`[ClustersClient] startup=${id} superseded client cleanup failed surface=extension`); + }); + } else { + const generation = (ClustersClient._generations.get(clusterId) ?? 0) + 1; + client._binding = Object.freeze({ clusterId, fingerprint: client._fingerprint, generation }); + client._createdAt = Date.now(); + ClustersClient._generations.set(clusterId, generation); + ClustersClient._clients.set(clusterId, client); + ClustersClient._lastFailedStartups.delete(clusterId); + } return client; } @@ -764,13 +803,12 @@ export class ClustersClient { } public static async deleteClient(clusterId: string): Promise { - if (ClustersClient._clients.has(clusterId)) { - const client = ClustersClient._clients.get(clusterId) as ClustersClient; - await client._mongoClient.close(true); + ClustersClient.invalidate(clusterId); + const client = ClustersClient._clients.get(clusterId); + if (client) { ClustersClient._clients.delete(clusterId); - - // Clear cached schema data for this cluster SchemaStore.getInstance().clearCluster(clusterId); + await client._mongoClient.close(true); } } diff --git a/src/documentdb/ConnectionUnavailableError.ts b/src/documentdb/ConnectionUnavailableError.ts new file mode 100644 index 000000000..ac6765a7a --- /dev/null +++ b/src/documentdb/ConnectionUnavailableError.ts @@ -0,0 +1,29 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as l10n from '@vscode/l10n'; + +export type ConnectionUnavailableReason = + | 'signInRequired' + | 'credentialsRejected' + | 'credentialsMissing' + | 'credentialsChanged' + | 'identityChanged' + | 'userDisconnected' + | 'connectionRemoved' + | 'unreachable'; + +export class ConnectionUnavailableError extends Error { + constructor( + readonly reason: ConnectionUnavailableReason, + options?: ErrorOptions, + ) { + super( + reason === 'credentialsMissing' ? l10n.t('No credentials found.') : l10n.t('The connection is unavailable.'), + options, + ); + this.name = 'ConnectionUnavailableError'; + } +} From 7185c387d48e36fe0c7f82bab4a37695d49b7baa Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 14:02:52 +0000 Subject: [PATCH 056/380] docs: record WI-4c delivery and blind trial results Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iterations/01-dev-plan.md | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index e8bbb4dab..7383fbf0a 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 @@ -1047,6 +1047,37 @@ shim (0005). is set. Do not add a new unavailable reason or a third attempt. A latch takes precedence. Cancellation assertions continue to follow the approved waiter-only behavior and retain coverage of actual startup failures, telemetry and cleanup. +- **Done (2026-11-20), commit `61e9cd4f5` (WI-4c, `gpt-6.2-astra`, High, large context):** + Integrated the top blind-review candidate with bounded follow-up changes. Concurrent callers + share a startup for the current epoch; cancellation only ends a caller's wait. A superseded + client cannot publish or delay a retry while closing. Added the stale-handshake failure and + latch regression; the build and 108 focused tests passed on the delivery branch. The operator + chose the neutral second-invalidation message. The advisor (`claude-opus-5.5`) approved the + corrected candidate for delivery at 85% confidence. Full Case 2 and localization generation + remain deferred to PR3 handoff. + + **WI-4c blind comparison:** Same baseline (`9a4d28dfa`), accepted behavior, build and focused + selectors. Scores describe the original candidates, not the corrected delivery commit. The + ranking had 60–65% confidence. Test counts differ because candidates authored their own tests. + Fusion ran alone via the Copilot CLI; its AI credits are reported separately from AIU. + + | Variant | Candidate | Score | Elapsed | Input / output tokens | Tool calls | Usage | + | --- | --- | ---: | ---: | ---: | ---: | ---: | + | `gpt-6.2-astra`, High, large context | `89d642e66` | 92 | 4m03s | 737k / 12k | 27 | 254.7 AIU | + | `gpt-6.1-sol`, High | `18e933d13` | 89 | 8m16s | 1.1M / 24k | 33 | 55.8 AIU | + | `gpt-6.1-sol`, Extra High | `7a1845af5` | 88 | 6m56s | 918k / 21k | 31 | 51.2 AIU | + | `gpt-6.2-sol`, default | `eb388ef45` | 88 | 5m04s | 1.0M / 13k | 28 | 78.5 AIU | + | Copilot Fusion Standard (`gpt-6.1-terra`) | `4ac6c4765` | 86 | 3m07s | 911.6k / 12.5k | Not reported | 13.55 AI credits | + | `gpt-6.2-sol`, High | `f80f3a325` | 84 | 4m41s | 1.1M / 15k | 28 | 79.6 AIU | + | `gpt-6.2-sol`, Extra High | `aeabaabd2` | 84 | 7m01s | 1.1M / 18k | 33 | 87.6 AIU | + | `mai-code-2`, default | `1978a3c80` | 74 | 8m06s | 1.6M / 21k | 41 | 17.0 AIU | + | `gpt-6.1-sol`, Medium | `2cb904a18` | 73, fix required | 5m46s | 982k / 14k | 28 | 41.3 AIU | + | `claude-opus-5.5`, default, large context | `a0b581b07` | Disqualified | 7m53s | 2.5M / 44k | 29 | 201.1 AIU | + + The medium-effort candidate could replace a cached client without closing it. The Opus + candidate did not honor the retry or latch on an obsolete startup failure. Astra led on + simplicity among the correct candidates; Sol 6.1 High had the strongest tests. This was + one trial per configuration, not a general model ranking. --- From 0868ad85784220796f8e7b56acd981b24ac0741b Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 14:11:50 +0000 Subject: [PATCH 057/380] docs: record pending silent reconnect decisions (WI-4d/e) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iterations/01-dev-plan.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index 7383fbf0a..715af3999 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 @@ -1079,6 +1079,23 @@ shim (0005). simplicity among the correct candidates; Sol 6.1 High had the strongest tests. This was one trial per configuration, not a general model ranking. +- **WI-4d/e deferred, escalated (2026-11-20):** The advisor reviewed the split between silent + reconnect and closed-client replacement. Before implementing, confirm these reconnect rules: + 1. Reject a silent Entra startup without a verified account before asking VS Code for a + session. Only a deliberate first connect may prompt. + 2. Let background callers use a healthy cached client or join an existing startup, but not + start or replace one. + 3. Keep the verified account for Discovery and Azure Resources connections. Those items have + no Remove action, so switching accounts may require a reload until there is an explicit + account-switch flow. + 4. Reject a closed-client replacement with a different identity and retain the closed entry, + so the next ordinary call cannot start as the new identity. + 5. Pin account, provider, and tenant for automatic reconnect. Use changed tenant credentials + only after an explicit credentials change. + + These are recommendations, not approvals. The decision request went unanswered, and no + WI-4d/e code was started. PR2 author sign-off is a separate gate. + --- ## WI-5: Classify failures and recover: host and tree (PR 4) From 4858e97d0caede51131286afe6515708c357172f Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 14:50:47 +0000 Subject: [PATCH 058/380] docs: record operator acceptance of PR2 pre-review Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iterations/01-pr2-azureauth-review.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr2-azureauth-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr2-azureauth-review.md index 879c05b8a..7fa973c18 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr2-azureauth-review.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr2-azureauth-review.md @@ -34,8 +34,9 @@ events. Tenant and subscription caches remain intact. Added two focused regressi cloud-invalidation and listener-disposal coverage. The three affected suites (55 tests), root type-check, and targeted formatting check passed. -The other three findings remain unchanged as recommended above. Author review of those -dispositions is pending. +**Author sign-off (2026-11-20):** The operator accepted the recorded dispositions: keep the +account-inventory fix, leave the existing Refresh/Retry and filter-wizard behavior unchanged, +and keep the one-shot freshness design unless the overlap race reproduces. ## OP-2 and CP-W3 From 26eaa166a6ff98f6fd0fbf01f56e0d2743067856 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 14:51:32 +0000 Subject: [PATCH 059/380] docs: record approved WI-4d/e reconnect rules Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../connection-lifecycle/iterations/01-dev-plan.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index 715af3999..30115ef8e 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 @@ -1093,8 +1093,12 @@ shim (0005). 5. Pin account, provider, and tenant for automatic reconnect. Use changed tenant credentials only after an explicit credentials change. - These are recommendations, not approvals. The decision request went unanswered, and no - WI-4d/e code was started. PR2 author sign-off is a separate gate. + The initial request went unanswered, so implementation did not start at that checkpoint. +- **WI-4d/e approved (2026-11-20), operator decision:** The operator accepted all five rules above. + For rule 1, the operator preferred requiring an explicit first connect to silently picking + an account. For rule 3, the operator accepted the reload limitation as an edge case. Finish + silent reconnect first, then closed-client replacement. PR2's pre-review was signed off + separately and does not block this work. --- From 6a53cf19e071c1459d6ccf1519cb5eb79979073b Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 15:02:01 +0000 Subject: [PATCH 060/380] fix: reconnect silently using the verified identity (WI-4d) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/documentdb/ClustersClient.test.ts | 214 ++++++++++++++---- src/documentdb/ClustersClient.ts | 118 ++++++++-- .../auth/MicrosoftEntraIDAuthHandler.test.ts | 55 +++++ .../auth/MicrosoftEntraIDAuthHandler.ts | 27 ++- src/documentdb/auth/authCallerPolicy.ts | 6 +- .../CollectionNameCache.ts | 4 +- .../discovery-tree/AtlasClusterItem.test.ts | 2 +- .../documentdb/KubernetesResourceItem.test.ts | 2 +- .../azureResourceAuthentication.test.ts | 6 +- .../DocumentDBClusterItem.test.ts | 18 +- .../LocalQuickStartItem.credentials.test.ts | 2 +- src/tree/documentdb/ClusterItemBase.test.ts | 38 ++-- src/tree/documentdb/ClusterItemBase.ts | 4 +- src/tree/documentdb/CollectionItem.test.ts | 20 ++ src/tree/documentdb/CollectionItem.ts | 4 +- src/tree/documentdb/DatabaseItem.test.ts | 14 ++ src/tree/documentdb/DatabaseItem.ts | 4 +- .../clusterDashboardRouter.test.ts | 18 ++ .../clusterDashboardRouter.ts | 4 +- 19 files changed, 457 insertions(+), 103 deletions(-) diff --git a/src/documentdb/ClustersClient.test.ts b/src/documentdb/ClustersClient.test.ts index a84b915ca..0ec1a6c49 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -8,7 +8,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { UserCancelledError, type IActionContext, type ITelemetryContext } from '@microsoft/vscode-azext-utils'; import { EventEmitter } from 'events'; import type * as Mongodb from 'mongodb'; -import { MongoClient, MongoNetworkError, MongoServerError, type MongoClientOptions } from 'mongodb'; +import { + MongoClient, + MongoNetworkError, + MongoNotConnectedError, + MongoServerError, + type MongoClientOptions, +} from 'mongodb'; import { ext } from '../extensionVariables'; import { traceAuthFlow, type AuthTraceContext } from '../utils/authTrace'; import { type VerifiedEntraIdentity } from './auth/AuthHandler'; @@ -136,7 +142,8 @@ describe('ClustersClient', () => { }); describe('regular connection startup diagnostics', () => { - const clusterId = 'private-cluster'; + let clusterId: string; + let clusterNumber = 0; const verifiedIdentity: VerifiedEntraIdentity = { kind: 'entra', providerId: 'microsoft', @@ -160,6 +167,7 @@ describe('regular connection startup diagnostics', () => { } beforeEach(() => { + clusterId = `private-cluster-${++clusterNumber}`; vi.clearAllMocks(); vi.useFakeTimers(); mockTelemetryEvents.length = 0; @@ -206,7 +214,7 @@ describe('regular connection startup diagnostics', () => { it('publishes a new binding only on successful establishment and advances generations across deletion', async () => { expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); - const first = await ClustersClient.getClient(clusterId); + const first = await ClustersClient.connectInteractive(clusterId); expect(first.binding).toEqual({ clusterId, fingerprint: first.fingerprint, generation: first.generation }); expect(first.createdAt).toBe(Date.now()); expect(await ClustersClient.getClient(clusterId)).toBe(first); @@ -225,6 +233,111 @@ describe('regular connection startup diagnostics', () => { expect(second.createdAt).toBeGreaterThan(first.createdAt); }); + it('never hydrates unpinned Entra silently, even after a native connection', async () => { + const expectNoSession = async (): Promise => { + await expect(ClustersClient.getClient(clusterId, undefined, undefined, 'treeConnect')).rejects.toMatchObject({ + name: 'EntraSignInRequiredError', + reason: 'noSession', + }); + }; + await expectNoSession(); + expect(authHandlerFactory.createAuthHandler).not.toHaveBeenCalled(); + + const uri = 'mongodb://private-user@private-host:27017'; + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.NativeAuth, uri); + vi.mocked(NativeAuthHandler.prototype.configureAuth).mockResolvedValueOnce({ + connectionString: uri, + options: {}, + }); + await ClustersClient.getClient(clusterId); + expect(ClustersClient.getLastVerifiedIdentity(clusterId)).toEqual({ kind: 'native', username: 'private-user' }); + await ClustersClient.deleteClient(clusterId); + + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.MicrosoftEntraID, 'mongodb://private-host:27017'); + await expectNoSession(); + expect(MicrosoftEntraIDAuthHandler.prototype.configureAuth).not.toHaveBeenCalled(); + await ClustersClient.connectInteractive(clusterId); + expect(authHandlerFactory.createAuthHandler).toHaveBeenLastCalledWith( + AuthMethodId.MicrosoftEntraID, + expect.objectContaining({ clusterId }), + { interactive: true }, + ); + expect(ClustersClient.getLastVerifiedIdentity(clusterId)).toEqual(verifiedIdentity); + }); + + it('records only the current publication and retains its pin across eviction and reconnect', async () => { + const staleHandshake = pauseNextConnect(); + const staleWaiter = ClustersClient.connectInteractive(clusterId); + await staleHandshake.started; + expect(ClustersClient.getLastVerifiedIdentity(clusterId)).toBeUndefined(); + await ClustersClient.deleteClient(clusterId); + const currentIdentity = { ...verifiedIdentity, accountId: 'private-current-account' }; + vi.mocked(MicrosoftEntraIDAuthHandler.prototype.configureAuth).mockResolvedValueOnce({ + connectionString: 'mongodb://private-host:27017', + options: {}, + verifiedIdentity: currentIdentity, + }); + const current = await ClustersClient.connectInteractive(clusterId); + const published = ClustersClient.getLastVerifiedIdentity(clusterId); + expect(published).toEqual(currentIdentity); + staleHandshake.resolve(); + await expect(staleWaiter).resolves.toBe(current); + expect(ClustersClient.getLastVerifiedIdentity(clusterId)).toBe(published); + + await ClustersClient.deleteClient(clusterId); + expect(ClustersClient.getLastVerifiedIdentity(clusterId)).toBe(published); + const configureAuth = vi.mocked(MicrosoftEntraIDAuthHandler.prototype.configureAuth); + for (const connect of [ClustersClient.getClient, ClustersClient.connectInteractive]) { + configureAuth.mockRejectedValueOnce(new Error('pinned startup failed')); + await expect(connect(clusterId)).rejects.toThrow('pinned startup failed'); + expect(authHandlerFactory.createAuthHandler).toHaveBeenLastCalledWith( + AuthMethodId.MicrosoftEntraID, + expect.objectContaining({ clusterId }), + { interactive: false, pinnedEntraIdentity: currentIdentity }, + ); + expect(ClustersClient.getLastVerifiedIdentity(clusterId)).toBe(published); + } + }); + + it('rechecks silent authorization using the credentials cloned during initialization', async () => { + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.NativeAuth, 'mongodb://private-host:27017'); + const waiter = ClustersClient.getClient(clusterId, undefined, () => { + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.MicrosoftEntraID, 'mongodb://private-host:27017'); + }); + await expect(waiter).rejects.toMatchObject({ name: 'EntraSignInRequiredError', reason: 'noSession' }); + expect(authHandlerFactory.createAuthHandler).not.toHaveBeenCalled(); + expect(MongoClient).not.toHaveBeenCalled(); + }); + + it('background calls never start a client, but can reuse a cached one', async () => { + const onStartup = vi.fn(); + const background = (): Promise => + ClustersClient.getClient(clusterId, undefined, onStartup, 'clusterDashboardPoll', { background: true }); + + await expect(background()).rejects.toBeInstanceOf(MongoNotConnectedError); + CredentialCache.deleteCredentials(clusterId); + await expect(background()).rejects.toMatchObject({ + name: 'ConnectionUnavailableError', + reason: 'credentialsMissing', + }); + ClustersClient.latch(clusterId, 'userDisconnected'); + await expect(background()).rejects.toMatchObject({ + name: 'ConnectionUnavailableError', + reason: 'userDisconnected', + }); + expect(onStartup).not.toHaveBeenCalled(); + expect(authHandlerFactory.createAuthHandler).not.toHaveBeenCalled(); + expect(MongoClient).not.toHaveBeenCalled(); + expect(mockTelemetryEvents).toHaveLength(0); + + ClustersClient.unlatch(clusterId); + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.NoAuth, 'mongodb://private-host:27017'); + const client = await ClustersClient.getClient(clusterId); + await expect(background()).resolves.toBe(client); + expect(onStartup).toHaveBeenCalledExactlyOnceWith(client.connectionCorrelationId); + expect(MongoClient).toHaveBeenCalledOnce(); + }); + 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'; @@ -243,7 +356,7 @@ describe('regular connection startup diagnostics', () => { srvResolution: 'fallback', }); - const client = await ClustersClient.getClient(clusterId); + const client = await ClustersClient.connectInteractive(clusterId); expect(MongoClient).toHaveBeenCalledWith(driverUri, {}); expect(client.fingerprint).toBe( computeConnectionFingerprint({ connectionString: originalUri, principal: verifiedIdentity }), @@ -258,13 +371,13 @@ describe('regular connection startup diagnostics', () => { options: {}, }); - await expect(ClustersClient.getClient(clusterId)).rejects.toThrow('verifiedIdentity'); + await expect(ClustersClient.connectInteractive(clusterId)).rejects.toThrow('verifiedIdentity'); expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); expect(MongoClient).not.toHaveBeenCalled(); }); it('aborts only one cached waiter while both are waiting for the same driver connection', async () => { - const client = await ClustersClient.getClient(clusterId); + const client = await ClustersClient.connectInteractive(clusterId); let finishConnect!: () => void; const pendingConnect = new Promise((resolve) => { finishConnect = resolve; @@ -291,7 +404,7 @@ describe('regular connection startup diagnostics', () => { const onStart = vi.fn(() => { joined = ClustersClient.getClient(clusterId, undefined, onJoin); }); - const first = ClustersClient.getClient(clusterId, undefined, onStart, 'treeConnect'); + const first = ClustersClient.connectInteractive(clusterId, undefined, onStart); const [client, same] = await Promise.all([first, joined]); expect(same).toBe(client); expect(onStart).toHaveBeenCalledExactlyOnceWith(client.connectionCorrelationId); @@ -304,7 +417,12 @@ describe('regular connection startup diagnostics', () => { it.each([0, 1])('canceling cold waiter %i leaves the other waiter connected', async (index) => { const handshake = pauseNextConnect(); const controllers = [new AbortController(), new AbortController()]; - const waits = controllers.map(({ signal }) => ClustersClient.getClient(clusterId, signal)); + const waits = [ + ClustersClient.connectInteractive(clusterId, controllers[0].signal), + ClustersClient.getClient(clusterId, controllers[1].signal, undefined, 'clusterDashboardPoll', { + background: true, + }), + ]; await handshake.started; controllers[index].abort(); await expect(waits[index]).rejects.toBeInstanceOf(UserCancelledError); @@ -318,7 +436,7 @@ describe('regular connection startup diagnostics', () => { }); it('closes the superseded driver without publishing it or removing the newer pending startup', async () => { - const baseline = await ClustersClient.getClient(clusterId); + const baseline = await ClustersClient.connectInteractive(clusterId); await ClustersClient.deleteClient(clusterId); mockClose.mockClear(); const closing = deferred(); @@ -356,7 +474,7 @@ describe('regular connection startup diagnostics', () => { it('reports the latch instead of a failed superseded handshake', async () => { const handshake = pauseNextConnect(); - const waiter = ClustersClient.getClient(clusterId); + const waiter = ClustersClient.connectInteractive(clusterId); await handshake.started; ClustersClient.latch(clusterId, 'userDisconnected'); handshake.reject(new Error('superseded failure')); @@ -369,11 +487,11 @@ describe('regular connection startup diagnostics', () => { it('a stale driver failure does not replace the correlation ID of a newer failure', async () => { const stale = pauseNextConnect(); - const waiter = ClustersClient.getClient(clusterId); + const waiter = ClustersClient.connectInteractive(clusterId); await stale.started; ClustersClient.invalidate(clusterId); mockConnect.mockRejectedValueOnce(new Error('current failure')); - await expect(ClustersClient.getClient(clusterId)).rejects.toThrow('current failure'); + await expect(ClustersClient.connectInteractive(clusterId)).rejects.toThrow('current failure'); const failedId = startupEvent().telemetry.properties.startupCorrelationId; expect(ClustersClient.getLastFailedStartupCorrelationId(clusterId)).toBe(failedId); stale.reject(new Error('superseded failure')); @@ -388,7 +506,7 @@ describe('regular connection startup diagnostics', () => { }); it('removes the cached entry before closing and leaves a racing replacement alone', async () => { - const old = await ClustersClient.getClient(clusterId); + const old = await ClustersClient.connectInteractive(clusterId); const epoch = ClustersClient.getEpoch(clusterId); const closing = deferred(); mockClose.mockReturnValueOnce(closing.promise); @@ -404,7 +522,7 @@ describe('regular connection startup diagnostics', () => { }); it.each([false, true])('a stale cached waiter has only one retry (latched: %s)', async (latch) => { - const cached = await ClustersClient.getClient(clusterId); + const cached = await ClustersClient.connectInteractive(clusterId); const cachedConnect = pauseNextConnect(); const onStartup = vi.fn(); const waiter = ClustersClient.getClient(clusterId, undefined, onStartup); @@ -453,7 +571,7 @@ describe('regular connection startup diagnostics', () => { expect(ClustersClient.getEpoch(clusterId)).toBe(epoch + 2); expect(ClustersClient.getLatchReason(clusterId)).toBeUndefined(); - await ClustersClient.getClient(clusterId); + await ClustersClient.connectInteractive(clusterId); ClustersClient.latch(clusterId, 'credentialsChanged'); await expect(ClustersClient.getClient(clusterId, undefined, onStartup)).rejects.toMatchObject({ reason: 'credentialsChanged', @@ -467,7 +585,7 @@ describe('regular connection startup diagnostics', () => { addEstablishedConnectionContext(context, clusterId); expect(context).toEqual({ properties: { existing: 'kept' }, measurements: { existing: 1 } }); - const client = await ClustersClient.getClient(clusterId); + const client = await ClustersClient.connectInteractive(clusterId); CredentialCache.setAuthCredentials(clusterId, AuthMethodId.NoAuth, 'mongodb://replacement.example.com'); vi.advanceTimersByTime(125); addEstablishedConnectionContext(context, clusterId); @@ -509,7 +627,7 @@ describe('regular connection startup diagnostics', () => { poolEvents.emit('connectionCreated', { connectionId: 7, ...privateFields }); poolEvents.emit('connectionReady', { connectionId: 7, ...privateFields }); }); - const client = await ClustersClient.getClient(clusterId); + const client = await ClustersClient.connectInteractive(clusterId); poolEvents.emit('connectionClosed', { connectionId: 7, reason: 'idle', ...privateFields }); poolEvents.emit('connectionCheckOutFailed', { reason: 'connectionError', ...privateFields }); poolEvents.emit('connectionClosed', { connectionId: '', reason: 'private-reason', ...privateFields }); @@ -527,7 +645,7 @@ describe('regular connection startup diagnostics', () => { }); it('logs only bounded listDatabases error details for Entra and rethrows each original error', async () => { - const client = await ClustersClient.getClient(clusterId); + const client = await ClustersClient.connectInteractive(clusterId); const serverError = new MongoServerError({ code: 18, errmsg: 'private-server-message' }); const networkError = new MongoNetworkError('private-network-message'); networkError.code = 'private-code'; @@ -584,7 +702,7 @@ describe('regular connection startup diagnostics', () => { options: {}, verifiedIdentity, }); - await ClustersClient.getClient(clusterId); + await ClustersClient.connectInteractive(clusterId); expect(vi.mocked(MongoClient).mock.calls[0]?.[1]?.appName).toBe(appName); }); @@ -609,7 +727,7 @@ describe('regular connection startup diagnostics', () => { AuthMethodId.NoAuth, ])('summarizes a fresh %s connection with numbered stage timings', async (authMethod) => { CredentialCache.setAuthCredentials(clusterId, authMethod, 'mongodb://private-host:27017'); - const client = await ClustersClient.getClient(clusterId); + const client = await ClustersClient.connectInteractive(clusterId, undefined, undefined, 'other'); expect(startupEvent().telemetry).toMatchObject({ maskEntireErrorMessage: true, @@ -680,7 +798,7 @@ describe('regular connection startup diagnostics', () => { undefined, { localQuickStartInstance }, ); - await ClustersClient.getClient(clusterId); + await ClustersClient.connectInteractive(clusterId); await vi.dynamicImportSettled(); await vi.waitFor(() => expect(mockTelemetryEvents.map((event) => event.eventName)).toEqual( @@ -702,19 +820,24 @@ describe('regular connection startup diagnostics', () => { [AuthMethodId.NativeAuth, NativeAuthHandler], [AuthMethodId.NoAuth, NoAuthHandler], ] as const)( - 'constructs the %s handler through the factory with the interactive policy', + 'constructs the %s handler through the factory with the caller policy', async (authMethod, handlerClass): Promise => { CredentialCache.setAuthCredentials(clusterId, authMethod, 'mongodb://private-host:27017'); - await ClustersClient.getClient(clusterId); + const interactive = authMethod === AuthMethodId.MicrosoftEntraID; + if (interactive) { + await ClustersClient.connectInteractive(clusterId); + } else { + await ClustersClient.getClient(clusterId); + } const factory = vi.mocked(authHandlerFactory.createAuthHandler); expect(factory).toHaveBeenCalledTimes(1); expect(factory).toHaveBeenCalledWith(authMethod, expect.objectContaining({ clusterId }), { - interactive: true, + interactive, }); const handler = factory.mock.results[0]?.value as unknown; expect(handler).toBeInstanceOf(handlerClass); - expect(handler).toHaveProperty('policy', { interactive: true }); + expect(handler).toHaveProperty('policy', { interactive }); expect(handlerClass.prototype.configureAuth).toHaveBeenCalledTimes(1); }, ); @@ -727,7 +850,7 @@ describe('regular connection startup diagnostics', () => { return { connectionString: 'mongodb://private-host:27017', options: {}, verifiedIdentity }; }, ); - const client = await ClustersClient.getClient(clusterId); + const client = await ClustersClient.connectInteractive(clusterId); expect(traceContext).toEqual({ startupCorrelationId: client.connectionCorrelationId, surface: 'extension', @@ -739,12 +862,12 @@ describe('regular connection startup diagnostics', () => { vi.mocked(MicrosoftEntraIDAuthHandler.prototype.configureAuth).mockRejectedValueOnce( new Error('private-failure'), ); - await expect(ClustersClient.getClient(clusterId)).rejects.toThrow('private-failure'); + await expect(ClustersClient.connectInteractive(clusterId)).rejects.toThrow('private-failure'); const failedId = startupEvent().telemetry.properties.startupCorrelationId; expect(failedId).toEqual(expect.any(String)); expect(ClustersClient.getLastFailedStartupCorrelationId(clusterId)).toBe(failedId); - const client = await ClustersClient.getClient(clusterId); + const client = await ClustersClient.connectInteractive(clusterId); const events = mockTelemetryEvents.filter((event) => event.eventName === 'connect.startup'); expect(events[0].telemetry.properties.previousFailedStartupCorrelationId).toBeUndefined(); expect(events[1].telemetry.properties).toMatchObject({ @@ -756,7 +879,7 @@ describe('regular connection startup diagnostics', () => { it('does not record a cancelled startup as a failure to follow up on', async () => { vi.mocked(MicrosoftEntraIDAuthHandler.prototype.configureAuth).mockRejectedValueOnce(new UserCancelledError()); - await expect(ClustersClient.getClient(clusterId)).rejects.toBeInstanceOf(UserCancelledError); + await expect(ClustersClient.connectInteractive(clusterId)).rejects.toBeInstanceOf(UserCancelledError); expect(ClustersClient.getLastFailedStartupCorrelationId(clusterId)).toBeUndefined(); }); @@ -782,9 +905,9 @@ describe('regular connection startup diagnostics', () => { ); throw new Error('private-resolution-failure'); }); - await expect(ClustersClient.getClient(clusterId)).rejects.toThrow('private-resolution-failure'); + await expect(ClustersClient.connectInteractive(clusterId)).rejects.toThrow('private-resolution-failure'); const failedProperties = { ...startupEvent().telemetry.properties }; - await ClustersClient.getClient(clusterId); + await ClustersClient.connectInteractive(clusterId); const events = mockTelemetryEvents.filter((event) => event.eventName === 'connect.startup'); expect(events[0].telemetry.properties).toEqual(failedProperties); expect(failedProperties).toMatchObject({ @@ -807,7 +930,7 @@ describe('regular connection startup diagnostics', () => { throw originalError; }); - await expect(ClustersClient.getClient(clusterId, undefined, onStartup)).rejects.toBe(originalError); + await expect(ClustersClient.connectInteractive(clusterId, undefined, onStartup)).rejects.toBe(originalError); expect(onStartup).toHaveBeenCalledExactlyOnceWith(startupEvent().telemetry.properties.connectionCorrelationId); expect(startupEvent().telemetry.properties).toMatchObject({ result: 'Failed', @@ -829,7 +952,7 @@ describe('regular connection startup diagnostics', () => { stop?.(); return { connectionString: 'mongodb://private-host:27017', options: {}, verifiedIdentity }; }); - await ClustersClient.getClient(clusterId); + await ClustersClient.connectInteractive(clusterId); expect(startupEvent().telemetry.measurements).toMatchObject({ tokenAcquireDurationMs: 20, databaseConnectDurationMs: 30, @@ -861,13 +984,13 @@ describe('regular connection startup diagnostics', () => { it('preserves driver failures and gives the retry a new correlation ID', async () => { const originalError = new Error('private-driver-error'); mockConnect.mockRejectedValueOnce(originalError); - await expect(ClustersClient.getClient(clusterId)).rejects.toBe(originalError); + await expect(ClustersClient.connectInteractive(clusterId)).rejects.toBe(originalError); const firstEvent = startupEvent(); expect(firstEvent.telemetry.properties.lastStage).toBe('stage04ConnectingAndAuthenticating'); expect(JSON.stringify(firstEvent)).not.toContain('private-'); expect(mockClose).toHaveBeenCalled(); - const client = await ClustersClient.getClient(clusterId); + const client = await ClustersClient.connectInteractive(clusterId); const events = mockTelemetryEvents.filter((event) => event.eventName === 'connect.startup'); expect(events).toHaveLength(2); expect(client.connectionCorrelationId).not.toBe(firstEvent.telemetry.properties.connectionCorrelationId); @@ -890,7 +1013,7 @@ describe('regular connection startup diagnostics', () => { it('records a canceled wait during the handshake but publishes the abandoned successful startup', async () => { const controller = new AbortController(); const handshake = pauseNextConnect(); - const waiter = ClustersClient.getClient(clusterId, controller.signal); + const waiter = ClustersClient.connectInteractive(clusterId, controller.signal); await handshake.started; vi.advanceTimersByTime(25); controller.abort(); @@ -917,7 +1040,10 @@ describe('regular connection startup diagnostics', () => { it('reports and cleans up a genuine driver failure after both cold waiters leave', async () => { const handshake = pauseNextConnect(); const controllers = [new AbortController(), new AbortController()]; - const waits = controllers.map(({ signal }) => ClustersClient.getClient(clusterId, signal)); + const waits = [ + ClustersClient.connectInteractive(clusterId, controllers[0].signal), + ClustersClient.getClient(clusterId, controllers[1].signal), + ]; await handshake.started; controllers.forEach((controller) => controller.abort()); await Promise.all(waits.map((wait) => expect(wait).rejects.toBeInstanceOf(UserCancelledError))); @@ -934,7 +1060,7 @@ describe('regular connection startup diagnostics', () => { expect(ClustersClient.getLastFailedStartupCorrelationId(clusterId)).toBe(failedId); expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); expect(mockClose).toHaveBeenCalledTimes(1); - expect((await ClustersClient.getClient(clusterId)).connectionCorrelationId).not.toBe(failedId); + expect((await ClustersClient.connectInteractive(clusterId)).connectionCorrelationId).not.toBe(failedId); }); it('records a credentials failure before auth configuration', async () => { @@ -963,9 +1089,7 @@ describe('regular connection startup diagnostics', () => { const serverError = new MongoServerError({ message: 'private-user authentication failed', code: 18 }); mockConnect.mockRejectedValueOnce(serverError); - await expect(ClustersClient.getClient(clusterId, undefined, undefined, 'treeConnect')).rejects.toBe( - serverError, - ); + await expect(ClustersClient.connectInteractive(clusterId)).rejects.toBe(serverError); const properties = startupEvent().telemetry.properties; expect(properties).toMatchObject({ startupFailureType: '18', @@ -982,7 +1106,7 @@ describe('regular connection startup diagnostics', () => { }); it('records no failure properties on success and no startup event for pre-cancellation', async () => { - await ClustersClient.getClient(clusterId, undefined, undefined, 'clusterDashboardPoll'); + await ClustersClient.connectInteractive(clusterId, undefined, undefined, 'clusterDashboardPoll'); expect(startupEvent().telemetry.properties).toMatchObject({ startupTrigger: 'clusterDashboardPoll' }); expect(startupEvent().telemetry.properties.startupFailureType).toBeUndefined(); expect(startupEvent().telemetry.properties.startupFailureCategory).toBeUndefined(); @@ -1012,7 +1136,7 @@ describe('regular connection startup diagnostics', () => { srvResolution: 'fallback', summary, }); - const client = await ClustersClient.getClient(clusterId); + const client = await ClustersClient.connectInteractive(clusterId); expect(MongoClient).toHaveBeenCalledWith(rewritten, preparedOptions); expect(CredentialCache.getCredentials(clusterId)?.connectionString).toBe(original); const hosts = ['original.global.mongocluster.cosmos.azure.com']; @@ -1039,14 +1163,14 @@ describe('regular connection startup diagnostics', () => { }); const failure = new Error('ECONNREFUSED'); mockConnect.mockRejectedValueOnce(failure); - await expect(ClustersClient.getClient(clusterId)).rejects.toBe(failure); + await expect(ClustersClient.connectInteractive(clusterId)).rejects.toBe(failure); expect(policy).toHaveBeenCalledWith(undefined, original); }); it('rethrows an SRV preparation failure without constructing a driver', async (): Promise => { const failure = new Error('original resolution failure'); vi.mocked(prepareDriverConnectionString).mockRejectedValueOnce(failure); - await expect(ClustersClient.getClient(clusterId)).rejects.toBe(failure); + await expect(ClustersClient.connectInteractive(clusterId)).rejects.toBe(failure); expect(MongoClient).not.toHaveBeenCalled(); expect(startupEvent().telemetry.properties).toMatchObject({ startupOutcome: 'failed', diff --git a/src/documentdb/ClustersClient.ts b/src/documentdb/ClustersClient.ts index 4523f8388..427d526c9 100644 --- a/src/documentdb/ClustersClient.ts +++ b/src/documentdb/ClustersClient.ts @@ -24,6 +24,7 @@ import { MongoClient, MongoError, MongoNetworkError, + MongoNotConnectedError, MongoServerError, ObjectId, type ClientSession, @@ -46,6 +47,7 @@ import { nonNullValue } from '../utils/nonNull'; import { type VerifiedEntraIdentity } from './auth/AuthHandler'; import { AuthMethodId } from './auth/AuthMethod'; import { createAuthHandler } from './auth/createAuthHandler'; +import { EntraSignInRequiredError } from './auth/entraErrors/entraCallbackErrors'; import { getAzureHostSuffix } from './auth/oidcAllowedHosts'; import { QueryInsightsApis, type ExplainVerbosity } from './client/QueryInsightsApis'; import { computeConnectionFingerprint, type ConnectionPrincipal } from './connectionFingerprint'; @@ -86,6 +88,8 @@ export interface ConnectionBinding { readonly generation: number; } +export type VerifiedIdentity = VerifiedEntraIdentity | Exclude; + export interface CollectionItemModel { name: string; type?: string; @@ -226,12 +230,12 @@ function assertDocumentObject(value: unknown, errorCode: 'INVALID_PROJECTION' | return value as Document; } -function getConnectionPrincipal( +function getVerifiedIdentity( authMethod: AuthMethodId, credentials: CachedClusterCredentials, configuredUri: string, verifiedIdentity: VerifiedEntraIdentity | undefined, -): ConnectionPrincipal { +): VerifiedIdentity { switch (authMethod) { case AuthMethodId.NativeAuth: return { kind: 'native', username: getUserNameFromConnectionString(configuredUri) }; @@ -264,6 +268,17 @@ export class ClustersClient { private static readonly _epochs = new Map(); private static readonly _latches = new Map(); private static readonly _pendingStartups = new Map(); + private static readonly _lastVerifiedIdentities = new Map>(); + + /** Last successfully published identity, retained when the client is evicted. */ + public static getLastVerifiedIdentity(clusterId: string): VerifiedIdentity | undefined { + return ClustersClient._lastVerifiedIdentities.get(clusterId); + } + + private static getEntraPin(clusterId: string): VerifiedEntraIdentity | undefined { + const identity = ClustersClient.getLastVerifiedIdentity(clusterId); + return identity?.kind === 'entra' ? identity : undefined; + } public static getEpoch(clusterId: string): number { return ClustersClient._epochs.get(clusterId) ?? 0; @@ -290,6 +305,7 @@ export class ClustersClient { } #startupCredentials: Readonly; + #verifiedIdentity: VerifiedIdentity; private _fingerprint: string; private _binding: ConnectionBinding; private _createdAt: number; @@ -385,7 +401,12 @@ export class ClustersClient { return CredentialCache.getCredentials(this.clusterId)?.localQuickStartInstance === true; } - private async initClient(startupId: string, trigger: ClientStartupTrigger): Promise { + private async initClient( + startupId: string, + trigger: ClientStartupTrigger, + epoch: number, + allowInteractive: boolean, + ): Promise { this.connectionCorrelationId = startupId; let originalFailure: { error: unknown } | undefined; @@ -417,7 +438,7 @@ export class ClustersClient { }; try { - await this.initializeClient(startup); + await this.initializeClient(startup, epoch, allowInteractive); this.finishClientStartup(startup, 'succeeded'); } catch (error) { const canceled = error instanceof UserCancelledError; @@ -472,7 +493,7 @@ export class ClustersClient { ); } - private async initializeClient(startup: ClientStartup): Promise { + private async initializeClient(startup: ClientStartup, epoch: number, allowInteractive: boolean): Promise { const cachedCredentials = CredentialCache.getCredentials(this.clusterId); if (!cachedCredentials) { startup.credentialsMissing = true; @@ -481,12 +502,27 @@ export class ClustersClient { const credentials = structuredClone(cachedCredentials); this.#startupCredentials = credentials; + const reason = ClustersClient.getLatchReason(this.clusterId); + if (reason) { + throw new ConnectionUnavailableError(reason); + } + if (epoch !== ClustersClient.getEpoch(this.clusterId)) { + throw new Error(l10n.t('The connection changed while it was opening. Try again.')); + } + // default to NativeAuth if nothing is configured const authMethod = this.authMethod; startup.telemetry.properties.authMethod = authMethod; - // Ordinary connects may prompt (for example, Microsoft Entra ID sign-in). - const authHandler = createAuthHandler(authMethod, credentials, { interactive: true }); + const pinnedEntraIdentity = + authMethod === AuthMethodId.MicrosoftEntraID ? ClustersClient.getEntraPin(this.clusterId) : undefined; + if (authMethod === AuthMethodId.MicrosoftEntraID && !pinnedEntraIdentity && !allowInteractive) { + throw new EntraSignInRequiredError('noSession'); + } + const authHandler = createAuthHandler(authMethod, credentials, { + interactive: allowInteractive && !pinnedEntraIdentity, + ...(pinnedEntraIdentity ? { pinnedEntraIdentity } : {}), + }); // Configure auth and get connection options this.advanceClientStartup(startup, 'stage02ConfiguringAuth'); @@ -497,9 +533,10 @@ export class ClustersClient { }); this.advanceClientStartup(startup, 'stage03PreparingClient'); + this.#verifiedIdentity = getVerifiedIdentity(authMethod, credentials, connectionString, verifiedIdentity); this._fingerprint = computeConnectionFingerprint({ connectionString: credentials.connectionString, - principal: getConnectionPrincipal(authMethod, credentials, connectionString, verifiedIdentity), + principal: this.#verifiedIdentity, }); const hosts = getHostsFromConnectionString(connectionString); const userAgentString = hosts.some((host) => getAzureHostSuffix(host)) ? appendExtensionUserAgent() : undefined; @@ -648,7 +685,7 @@ export class ClustersClient { } /** - * Retrieves an instance of `ClustersClient` based on the provided `clusterId`. + * Retrieves an instance of `ClustersClient` without opening sign-in UI. * * @param clusterId - A required string used to find the cached connection string to connect. * It is also used as a key to reuse existing clients. @@ -657,6 +694,7 @@ export class ClustersClient { * @param onStartup - Called with the startup correlation ID of the attempt this call joins. * @param trigger - Which code path asks for the client; recorded as `startupTrigger` when this * call starts a new `connect.startup`. Callers that do not pass it are recorded as `other`. + * @param options - Background callers may reuse a client or join a startup, but never start one. * @returns A promise that resolves to an instance of `ClustersClient`. */ public static async getClient( @@ -664,6 +702,35 @@ export class ClustersClient { abortSignal?: AbortSignal, onStartup?: (id: string) => void, trigger: ClientStartupTrigger = 'other', + options?: { readonly background?: boolean }, + ): Promise { + return ClustersClient.acquireClient( + clusterId, + abortSignal, + onStartup, + trigger, + false, + options?.background === true, + ); + } + + /** A deliberate connect may open sign-in only when there is no verified Entra identity. */ + public static async connectInteractive( + clusterId: string, + abortSignal?: AbortSignal, + onStartup?: (id: string) => void, + trigger: ClientStartupTrigger = 'treeConnect', + ): Promise { + return ClustersClient.acquireClient(clusterId, abortSignal, onStartup, trigger, true, false); + } + + private static async acquireClient( + clusterId: string, + abortSignal: AbortSignal | undefined, + onStartup: ((id: string) => void) | undefined, + trigger: ClientStartupTrigger, + allowInteractive: boolean, + background: boolean, ): Promise { for (let attempt = 0; ; attempt++) { const reason = ClustersClient.getLatchReason(clusterId); @@ -688,7 +755,7 @@ export class ClustersClient { } promise = cached._mongoClient.connect().then(() => cached); } else { - const pending = ClustersClient.getOrStartClient(clusterId, epoch, trigger); + const pending = ClustersClient.getOrStartClient(clusterId, epoch, trigger, allowInteractive, background); id = pending.id; onStartup?.(id); promise = pending.promise; @@ -708,15 +775,38 @@ export class ClustersClient { } } - private static getOrStartClient(clusterId: string, epoch: number, trigger: ClientStartupTrigger): PendingStartup { + private static getOrStartClient( + clusterId: string, + epoch: number, + trigger: ClientStartupTrigger, + allowInteractive: boolean, + background: boolean, + ): PendingStartup { const existing = ClustersClient._pendingStartups.get(clusterId); if (existing?.epoch === epoch) { return existing; } + const credentials = CredentialCache.getCredentials(clusterId); + if (background) { + if (!credentials) { + throw new ConnectionUnavailableError('credentialsMissing'); + } + throw new MongoNotConnectedError(l10n.t('The connection is unavailable.')); + } + if ( + !allowInteractive && + credentials?.authMechanism === AuthMethodId.MicrosoftEntraID && + !ClustersClient.getEntraPin(clusterId) + ) { + throw new EntraSignInRequiredError('noSession'); + } + 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)); + const promise = Promise.resolve().then(() => + ClustersClient.establishClient(clusterId, epoch, id, trigger, allowInteractive), + ); const pending = { id, epoch, promise }; ClustersClient._pendingStartups.set(clusterId, pending); const clear = (): void => { @@ -733,10 +823,11 @@ export class ClustersClient { epoch: number, id: string, trigger: ClientStartupTrigger, + allowInteractive: boolean, ): Promise { const client = new ClustersClient(clusterId); try { - await client.initClient(id, trigger); + await client.initClient(id, trigger, epoch, allowInteractive); } catch (error) { if (!(error instanceof UserCancelledError) && epoch === ClustersClient.getEpoch(clusterId)) { ClustersClient._lastFailedStartups.set(clusterId, id); @@ -756,6 +847,7 @@ export class ClustersClient { client._binding = Object.freeze({ clusterId, fingerprint: client._fingerprint, generation }); client._createdAt = Date.now(); ClustersClient._generations.set(clusterId, generation); + ClustersClient._lastVerifiedIdentities.set(clusterId, Object.freeze({ ...client.#verifiedIdentity })); ClustersClient._clients.set(clusterId, client); ClustersClient._lastFailedStartups.delete(clusterId); } diff --git a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts index d95ac2972..0e187df01 100644 --- a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts +++ b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts @@ -47,6 +47,7 @@ import { type CachedClusterCredentials } from '../CredentialCache'; import { ConnectionStartupTimings } from '../utils/ConnectionStartupTimings'; import { AuthInputUnavailableError, type AuthPhaseObserver } from './authCallerPolicy'; import { buildAuthConnectionTarget } from './authConnectionTarget'; +import { type VerifiedEntraIdentity } from './AuthHandler'; import { AuthMethodId } from './AuthMethod'; import { resolveInteractiveTokenResource, TokenResourceResolutionError } from './documentdbTokenResource'; import { @@ -74,6 +75,14 @@ function buildCredentials(connectionString: string): CachedClusterCredentials { } describe('MicrosoftEntraIDAuthHandler', () => { + const pinnedEntraIdentity: VerifiedEntraIdentity = { + kind: 'entra', + providerId: 'microsoft', + accountId: account.id, + accountLabel: account.label, + tenantId: 'pinned-tenant', + }; + beforeEach(() => { vi.clearAllMocks(); resetEntraTokenFailuresForTests(); @@ -104,6 +113,52 @@ describe('MicrosoftEntraIDAuthHandler', () => { resetEntraTokenFailuresForTests(); }); + it.each(['pinned-tenant', undefined])('uses the pinned tenant %s, never the cached tenant', async (tenantId) => { + const pin = { ...pinnedEntraIdentity, tenantId }; + const result = await new MicrosoftEntraIDAuthHandler( + buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'), + { interactive: true, pinnedEntraIdentity: pin }, + ).configureAuth(); + + const scopes = ['https://ossrdbms-aad.database.windows.net/.default']; + if (tenantId !== undefined) { + scopes.push(`VSCODE_TENANT:${tenantId}`); + } + expect(getSessionFromVSCode).toHaveBeenCalledExactlyOnceWith(pin.providerId, scopes, { silent: true, account }); + expect(result.verifiedIdentity).toEqual(pin); + }); + + it.each(['providerChanged', 'noSession', 'identityMismatch'] as const)( + 'fails closed on a pinned %s without changing the existing failure context', + async (failure) => { + const credentials = buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'); + recordEntraTokenFailure(credentials.clusterId, { cloudCategory: 'public', authMethod: 'interactive' }); + const previousFailure = getRecentEntraTokenFailure(credentials.clusterId); + const startupProperties: Record = {}; + if (failure === 'providerChanged') { + getConfiguredAuthProviderId.mockReturnValue('different-provider'); + } else if (failure === 'noSession') { + getSessionFromVSCode.mockResolvedValue(undefined); + } else { + getSessionFromVSCode.mockResolvedValue({ ...session, account: { ...account, id: 'different-account' } }); + } + + const configuring = new MicrosoftEntraIDAuthHandler(credentials, { + interactive: false, + pinnedEntraIdentity, + }).configureAuth(undefined, { startupCorrelationId: 'startup', surface: 'extension', startupProperties }); + if (failure === 'identityMismatch') { + await expect(configuring).rejects.toBeInstanceOf(EntraIdentityMismatchError); + } else { + await expect(configuring).rejects.toBeInstanceOf(EntraSignInRequiredError); + await expect(configuring).rejects.toMatchObject({ reason: failure }); + } + expect(getSessionFromVSCode).toHaveBeenCalledTimes(failure === 'providerChanged' ? 0 : 1); + expect(getRecentEntraTokenFailure(credentials.clusterId)).toBe(previousFailure); + expect(startupProperties.entraFailureKind).not.toBe('tokenAcquisitionFailed'); + }, + ); + it.each([ 'mongodb://attacker.cloudapp.azure.com/', 'mongodb://cluster.mongocluster.cosmos.azure.com,attacker.example.com/', diff --git a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts index f004d560e..cda5b17d7 100644 --- a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts +++ b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts @@ -62,8 +62,8 @@ function assertEntraSignInEnvironment(expected: EntraSignInEnvironment | undefin /** * Handler for Microsoft Entra ID authentication via OIDC. * - * An interactive policy may open sign-in (`createIfNone`). A non-interactive policy only looks up - * an existing session silently and reports a missing one as {@link AuthInputUnavailableError}. + * An interactive policy may open sign-in (`createIfNone`) only without a pin. Pinned lookups and + * diagnostics are silent; only diagnostics report a missing session as {@link AuthInputUnavailableError}. */ export class MicrosoftEntraIDAuthHandler implements AuthHandler { constructor( @@ -81,7 +81,8 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { ): Promise { const authCorrelationId = randomUUID(); const { connectionString, clusterId } = this.clusterCredentials; - const tenantId = this.clusterCredentials.entraIdConfig?.tenantId; + const pin = this.policy.pinnedEntraIdentity; + const tenantId = pin ? pin.tenantId : this.clusterCredentials.entraIdConfig?.tenantId; const decision = evaluateEntraDestinationFromSettings(connectionString); traceEntraDestination(decision, authCorrelationId, traceContext); if (!decision.allowed) { @@ -123,7 +124,7 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { // Get Microsoft Entra ID token. Only an interactive caller may open sign-in; a non-interactive // caller looks up an existing session silently and never forces a new one. - const interactive = this.policy.interactive; + const interactive = this.policy.interactive && !pin; let session: vscode.AuthenticationSession | undefined; let signInEnvironment: EntraSignInEnvironment; const resource = resolved.scope; @@ -134,11 +135,15 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { () => withTokenAcquisitionTiming(timings, async () => { const signInEnvironment = assertEntraSignInEnvironment(environmentBeforeResolution); + if (pin && pin.providerId !== signInEnvironment.providerId) { + throw new EntraSignInRequiredError('providerChanged'); + } try { const session = await getEntraSession({ - providerId: signInEnvironment.providerId, + providerId: pin?.providerId ?? signInEnvironment.providerId, resource, tenantId, + account: pin ? { id: pin.accountId, label: pin.accountLabel } : undefined, mode: interactive ? 'interactive' : 'silent', }); return { session, signInEnvironment }; @@ -163,14 +168,24 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { authCorrelationId, traceContext, ); + if (pin) { + throw new EntraSignInRequiredError('noSession'); + } if (!interactive) { throw new AuthInputUnavailableError('entraSession'); } throw new Error(l10n.t('Failed to obtain Entra ID token.')); } + if (pin && session.account.id !== pin.accountId) { + throw new EntraIdentityMismatchError(); + } } catch (error) { // Missing input or configuration drift must not alter the next connect's failure context. - if (!(error instanceof AuthInputUnavailableError || error instanceof EntraSignInRequiredError)) { + if ( + !(error instanceof AuthInputUnavailableError) && + !(error instanceof EntraSignInRequiredError) && + !(error instanceof EntraIdentityMismatchError) + ) { if (traceContext?.startupProperties) { traceContext.startupProperties.entraFailureKind = 'tokenAcquisitionFailed'; } diff --git a/src/documentdb/auth/authCallerPolicy.ts b/src/documentdb/auth/authCallerPolicy.ts index 52b1e5764..b357a2db2 100644 --- a/src/documentdb/auth/authCallerPolicy.ts +++ b/src/documentdb/auth/authCallerPolicy.ts @@ -3,6 +3,8 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import { type VerifiedEntraIdentity } from './AuthHandler'; + /** * Host-only callbacks that report the authentication phases in the order they really happen. * @@ -36,11 +38,11 @@ export interface AuthPhaseObserver { } /** - * How the caller wants authentication to behave. Ordinary connects are interactive; connection - * diagnostics are not, and never open sign-in UI. + * Whether the caller can open sign-in UI and, for Entra reconnect, which identity must be used. */ export interface AuthCallerPolicy { readonly interactive: boolean; + readonly pinnedEntraIdentity?: VerifiedEntraIdentity; readonly observer?: AuthPhaseObserver; } diff --git a/src/documentdb/query-language/playground-completions/CollectionNameCache.ts b/src/documentdb/query-language/playground-completions/CollectionNameCache.ts index e69fc0bd7..dd11c0ba3 100644 --- a/src/documentdb/query-language/playground-completions/CollectionNameCache.ts +++ b/src/documentdb/query-language/playground-completions/CollectionNameCache.ts @@ -128,7 +128,9 @@ export class CollectionNameCache implements vscode.Disposable { const fetchPromise = (async (): Promise => { try { - const client = await ClustersClient.getClient(clusterId, undefined, undefined, 'playgroundCompletion'); + const client = await ClustersClient.getClient(clusterId, undefined, undefined, 'playgroundCompletion', { + background: true, + }); // This call populates ClustersClient._collectionsCache await client.listCollections(databaseName); } catch (error) { 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 85b124707..a8340f9dc 100644 --- a/src/plugins/service-atlas-mongodb/discovery-tree/AtlasClusterItem.test.ts +++ b/src/plugins/service-atlas-mongodb/discovery-tree/AtlasClusterItem.test.ts @@ -109,7 +109,7 @@ vi.mock('../../../documentdb/CredentialCache', () => ({ vi.mock('../../../documentdb/ClustersClient', () => ({ ClustersClient: { - getClient: vi.fn(), + connectInteractive: vi.fn(), deleteClient: vi.fn(), }, })); 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 f06310bd3..4e6c066a9 100644 --- a/src/plugins/service-kubernetes/discovery-tree/documentdb/KubernetesResourceItem.test.ts +++ b/src/plugins/service-kubernetes/discovery-tree/documentdb/KubernetesResourceItem.test.ts @@ -128,7 +128,7 @@ vi.mock('../../../../documentdb/CredentialCache', () => ({ vi.mock('../../../../documentdb/ClustersClient', () => ({ ClustersClient: { exists: vi.fn().mockReturnValue(false), - getClient: (...args: unknown[]) => mockGetClient(...args), + connectInteractive: (...args: unknown[]) => mockGetClient(...args), deleteClient: vi.fn(), }, })); diff --git a/src/tree/azure-resources-view/documentdb/azureResourceAuthentication.test.ts b/src/tree/azure-resources-view/documentdb/azureResourceAuthentication.test.ts index 3e8b8c631..93db00959 100644 --- a/src/tree/azure-resources-view/documentdb/azureResourceAuthentication.test.ts +++ b/src/tree/azure-resources-view/documentdb/azureResourceAuthentication.test.ts @@ -71,7 +71,7 @@ vi.mock('../../../utils/azureClients', () => ({ createMongoClustersManagementClient: vi.fn(() => ({ mongoClusters: { get: getCluster } })), })); vi.mock('../../../documentdb/ClustersClient', () => ({ - ClustersClient: { getClient: vi.fn(), deleteClient: vi.fn() }, + ClustersClient: { connectInteractive: vi.fn(), deleteClient: vi.fn() }, })); vi.mock('../../../documentdb/CredentialCache', () => ({ CredentialCache: { hasCredentials: vi.fn(), setAuthCredentials: vi.fn(), deleteCredentials: vi.fn() }, @@ -116,7 +116,9 @@ describe.each([ beforeEach((): void => { vi.clearAllMocks(); vi.mocked(CredentialCache.hasCredentials).mockReturnValue(false); - vi.mocked(ClustersClient.getClient).mockResolvedValue({ connectionCorrelationId: 'attempt' } as ClustersClient); + vi.mocked(ClustersClient.connectInteractive).mockResolvedValue({ + connectionCorrelationId: 'attempt', + } as ClustersClient); vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ inspect: vi.fn(), } as unknown as vscode.WorkspaceConfiguration); diff --git a/src/tree/connections-view/DocumentDBClusterItem.test.ts b/src/tree/connections-view/DocumentDBClusterItem.test.ts index ac8c75c23..9d0f8e0f4 100644 --- a/src/tree/connections-view/DocumentDBClusterItem.test.ts +++ b/src/tree/connections-view/DocumentDBClusterItem.test.ts @@ -84,7 +84,7 @@ vi.mock('../../services/connectionStorageService', async (importOriginal) => ({ ConnectionStorageService: { get: vi.fn(), save: vi.fn() }, })); vi.mock('../../documentdb/ClustersClient', () => ({ - ClustersClient: { getClient: vi.fn(), deleteClient: vi.fn(), exists: vi.fn() }, + ClustersClient: { connectInteractive: vi.fn(), deleteClient: vi.fn(), exists: vi.fn() }, })); vi.mock('../../documentdb/CredentialCache', () => ({ CredentialCache: { hasCredentials: vi.fn(), setAuthCredentials: vi.fn(), deleteCredentials: vi.fn() }, @@ -120,7 +120,9 @@ describe('saved connection destination authentication', () => { beforeEach((): void => { vi.clearAllMocks(); vi.mocked(CredentialCache.hasCredentials).mockReturnValue(false); - vi.mocked(ClustersClient.getClient).mockResolvedValue({ connectionCorrelationId: 'attempt' } as ClustersClient); + vi.mocked(ClustersClient.connectInteractive).mockResolvedValue({ + connectionCorrelationId: 'attempt', + } as ClustersClient); vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ inspect: vi.fn(), } as unknown as vscode.WorkspaceConfiguration); @@ -137,7 +139,7 @@ describe('saved connection destination authentication', () => { async (method): Promise => { const connection = makeConnection('mongodb://other.example.com/', method); vi.mocked(ConnectionStorageService.get).mockResolvedValue(connection); - vi.mocked(ClustersClient.getClient).mockRejectedValue( + vi.mocked(ClustersClient.connectInteractive).mockRejectedValue( new EntraDestinationRejectedError(evaluateEntraDestination(connection.secrets.connectionString)), ); const item = makeItem(); @@ -147,7 +149,7 @@ describe('saved connection destination authentication', () => { expect(wizardCreated).not.toHaveBeenCalled(); expect(prompt).not.toHaveBeenCalled(); expect(showQuickPick).not.toHaveBeenCalled(); - expect(ClustersClient.getClient).toHaveBeenCalledTimes(1); + expect(ClustersClient.connectInteractive).toHaveBeenCalledTimes(1); expect(CredentialCache.setAuthCredentials).toHaveBeenCalledWith( 'stable-id', method, @@ -216,7 +218,7 @@ describe('saved connection destination authentication', () => { const error = new EntraDestinationRejectedError( evaluateEntraDestination(connection.secrets.connectionString), ); - vi.mocked(ClustersClient.getClient).mockRejectedValue(error); + vi.mocked(ClustersClient.connectInteractive).mockRejectedValue(error); showErrorMessage.mockResolvedValueOnce('Learn More'); if (outcome === 'false') { vi.mocked(vscode.env.openExternal).mockResolvedValueOnce(false); @@ -259,7 +261,7 @@ describe('connect request telemetry', () => { // The request returns no client after a failed connection, which the wrapper reports as // Succeeded; the outcome and the failed attempt's ID must be explicit. it('reports a failed connection with the ID of the attempt that failed', async (): Promise => { - vi.mocked(ClustersClient.getClient).mockImplementation(async (_clusterId, _signal, onStartup) => { + vi.mocked(ClustersClient.connectInteractive).mockImplementation(async (_clusterId, _signal, onStartup) => { onStartup?.('failed-attempt'); throw new Error('Authentication failed.'); }); @@ -270,7 +272,9 @@ describe('connect request telemetry', () => { }); it('reports a successful connection with its connection ID', async (): Promise => { - vi.mocked(ClustersClient.getClient).mockResolvedValue({ connectionCorrelationId: 'attempt' } as ClustersClient); + vi.mocked(ClustersClient.connectInteractive).mockResolvedValue({ + connectionCorrelationId: 'attempt', + } as ClustersClient); await expect(makeItem().connect()).resolves.toMatchObject({ connectionCorrelationId: 'attempt' }); diff --git a/src/tree/connections-view/LocalQuickStart/LocalQuickStartItem.credentials.test.ts b/src/tree/connections-view/LocalQuickStart/LocalQuickStartItem.credentials.test.ts index 8fe35a74d..f45687f83 100644 --- a/src/tree/connections-view/LocalQuickStart/LocalQuickStartItem.credentials.test.ts +++ b/src/tree/connections-view/LocalQuickStart/LocalQuickStartItem.credentials.test.ts @@ -79,7 +79,7 @@ const mockGetClient = vi.fn(); vi.mock('../../../documentdb/ClustersClient', () => ({ ClustersClient: { exists: vi.fn().mockReturnValue(false), - getClient: (...args: unknown[]) => mockGetClient(...args), + connectInteractive: (...args: unknown[]) => mockGetClient(...args), }, })); diff --git a/src/tree/documentdb/ClusterItemBase.test.ts b/src/tree/documentdb/ClusterItemBase.test.ts index fac610fa9..01e8663a4 100644 --- a/src/tree/documentdb/ClusterItemBase.test.ts +++ b/src/tree/documentdb/ClusterItemBase.test.ts @@ -71,7 +71,7 @@ vi.mock('../../documentdb/CredentialCache', () => ({ })); vi.mock('../../documentdb/ClustersClient', () => ({ - ClustersClient: { getClient: vi.fn(), exists: vi.fn().mockReturnValue(false), getExistingClient: vi.fn() }, + ClustersClient: { connectInteractive: vi.fn(), exists: vi.fn().mockReturnValue(false), getExistingClient: vi.fn() }, })); vi.mock('../../extensionVariables', () => ({ @@ -348,7 +348,7 @@ describe('ClusterItemBase.getChildren — listDatabases failure handling', () => it('does not reopen the dashboard on refresh or when the tree node is recreated', async () => { mockGetSetting.mockReturnValue(true); const client = makeClient(vi.fn().mockResolvedValue([{ name: 'database' }])); - ClustersClientMock.getClient.mockResolvedValue(client); + ClustersClientMock.connectInteractive.mockResolvedValue(client); const item = new TestClusterItem(makeCluster(), client); await item.getChildren(); @@ -365,7 +365,7 @@ describe('ClusterItemBase.getChildren — listDatabases failure handling', () => mockGetSetting.mockReturnValue(true); mockHasCredentials.mockReturnValue(true); const client = makeClient(vi.fn().mockResolvedValue([{ name: 'database' }])); - ClustersClientMock.getClient.mockResolvedValue(client); + ClustersClientMock.connectInteractive.mockResolvedValue(client); ClustersClientMock.exists.mockReturnValueOnce(true).mockReturnValueOnce(false); const item = new TestClusterItem(makeCluster(), client); @@ -424,7 +424,7 @@ describe('ClusterItemBase.getChildren — cached client connection failure handl mockHasCredentials.mockReturnValue(true); // jest-mock-vscode's withProgress is a no-op vi.fn(); make it actually run the task so - // getClientWithProgress() exercises ClustersClient.getClient() and surfaces its rejection. + // getClientWithProgress() exercises ClustersClient.connectInteractive() and surfaces its rejection. (vscode.window.withProgress as unknown as Mock).mockImplementation( ( _options: unknown, @@ -437,7 +437,7 @@ describe('ClusterItemBase.getChildren — cached client connection failure handl }); it('returns a retry node when reusing the cached client fails (without listing databases)', async () => { - (ClustersClientMock.getClient as Mock).mockRejectedValue(new Error('server down')); + (ClustersClientMock.connectInteractive as Mock).mockRejectedValue(new Error('server down')); // listDatabases must never be reached when the cached client cannot connect. const listDatabases = vi.fn(); @@ -456,7 +456,7 @@ describe('ClusterItemBase.getChildren — cached client connection failure handl }); it('uses the trusted-server modal and preserves action-only recovery for a cached rejection', async (): Promise => { - ClustersClientMock.getClient.mockRejectedValue( + ClustersClientMock.connectInteractive.mockRejectedValue( new EntraDestinationRejectedError({ firstHost: 'other.example.com:27017', hostCount: 2 }), ); const cluster = makeCluster(); @@ -465,7 +465,7 @@ describe('ClusterItemBase.getChildren — cached client connection failure handl const children = await item.getChildren(); - expect(ClustersClientMock.getClient).toHaveBeenCalledWith( + expect(ClustersClientMock.connectInteractive).toHaveBeenCalledWith( 'cluster-1', expect.anything(), expect.any(Function), @@ -499,12 +499,12 @@ describe('ClusterItemBase.getChildren — cached client connection failure handl it('clears the destination rejection reason after a successful cached retry', async (): Promise => { const item = new TestClusterItem(makeCluster(), null); - ClustersClientMock.getClient.mockRejectedValueOnce( + ClustersClientMock.connectInteractive.mockRejectedValueOnce( new EntraDestinationRejectedError({ firstHost: 'other.example.com', hostCount: 1 }), ); await item.getChildren(); expect(item.lastConnectionFailureReason).toBe('entraDestinationRejected'); - ClustersClientMock.getClient.mockResolvedValueOnce(makeClient(vi.fn().mockResolvedValue([]))); + ClustersClientMock.connectInteractive.mockResolvedValueOnce(makeClient(vi.fn().mockResolvedValue([]))); await item.getChildren(); @@ -513,7 +513,7 @@ describe('ClusterItemBase.getChildren — cached client connection failure handl }); it('surfaces a modal and records telemetry with failurePhase=cachedClientConnect', async () => { - (ClustersClientMock.getClient as Mock).mockRejectedValue(new Error('server down')); + (ClustersClientMock.connectInteractive as Mock).mockRejectedValue(new Error('server down')); const item = new TestClusterItem(makeCluster(), makeClient(vi.fn())); @@ -536,7 +536,7 @@ describe('ClusterItemBase.getChildren — cached client connection failure handl }); it('returns an empty array (no retry node) when the user cancels the cached connection', async () => { - (ClustersClientMock.getClient as Mock).mockRejectedValue(new UserCancelledError()); + (ClustersClientMock.connectInteractive as Mock).mockRejectedValue(new UserCancelledError()); const item = new TestClusterItem(makeCluster(), makeClient(vi.fn())); @@ -601,7 +601,7 @@ describe('ClusterItemBase.connect', () => { mockTelemetryEvents.length = 0; // jest-mock-vscode's withProgress is a no-op vi.fn(); make it run the task so the - // cached path actually reaches ClustersClient.getClient(). + // cached path actually reaches ClustersClient.connectInteractive(). (vscode.window.withProgress as unknown as Mock).mockImplementation( ( _options: unknown, @@ -619,7 +619,7 @@ describe('ClusterItemBase.connect', () => { const item = new ConnectTestClusterItem(makeCluster(), null); item.lastConnectionOutcome = 'canceled'; item.lastConnectionCorrelationId = 'previous-attempt'; - ClustersClientMock.getClient.mockImplementationOnce( + ClustersClientMock.connectInteractive.mockImplementationOnce( async (_clusterId, _signal, onAttempt): Promise => { expect(item.lastConnectionOutcome).toBeUndefined(); expect(item.lastConnectionCorrelationId).toBeUndefined(); @@ -640,7 +640,7 @@ describe('ClusterItemBase.connect', () => { it('keys the credential cache and the client on clusterId, never on the tree position', async () => { mockHasCredentials.mockReturnValue(true); const cached = makeClient(vi.fn()); - (ClustersClientMock.getClient as Mock).mockResolvedValue(cached); + (ClustersClientMock.connectInteractive as Mock).mockResolvedValue(cached); const cluster = makeMovedCluster(); const item = new ConnectTestClusterItem(cluster, null); @@ -651,7 +651,7 @@ describe('ClusterItemBase.connect', () => { // Keying either lookup on the tree position opens a second, duplicate connection. expect(mockHasCredentials).toHaveBeenCalledWith(cluster.clusterId); expect(mockHasCredentials).not.toHaveBeenCalledWith(cluster.treeId); - expect(ClustersClientMock.getClient).toHaveBeenCalledWith( + expect(ClustersClientMock.connectInteractive).toHaveBeenCalledWith( cluster.clusterId, expect.anything(), expect.any(Function), @@ -667,12 +667,12 @@ describe('ClusterItemBase.connect', () => { await expect(item.connect()).resolves.toBe(fresh); expect(item.authenticateCalls).toBe(1); expect(item.beforeCachedCalls).toBe(0); - expect(ClustersClientMock.getClient).not.toHaveBeenCalled(); + expect(ClustersClientMock.connectInteractive).not.toHaveBeenCalled(); }); it('returns null when the user cancels the progress notification on the cached path', async () => { mockHasCredentials.mockReturnValue(true); - (ClustersClientMock.getClient as Mock).mockRejectedValue(new UserCancelledError()); + (ClustersClientMock.connectInteractive as Mock).mockRejectedValue(new UserCancelledError()); const item = new ConnectTestClusterItem(makeCluster(), null); @@ -684,7 +684,7 @@ describe('ClusterItemBase.connect', () => { it('propagates a genuine failure on the cached path so the command can report it', async () => { mockHasCredentials.mockReturnValue(true); - (ClustersClientMock.getClient as Mock).mockRejectedValue(new Error('server down')); + (ClustersClientMock.connectInteractive as Mock).mockRejectedValue(new Error('server down')); const item = new ConnectTestClusterItem(makeCluster(), null); @@ -694,7 +694,7 @@ describe('ClusterItemBase.connect', () => { it('reports a cached destination rejection through the same modal without reauthenticating', async (): Promise => { mockHasCredentials.mockReturnValue(true); - ClustersClientMock.getClient.mockRejectedValue( + ClustersClientMock.connectInteractive.mockRejectedValue( new EntraDestinationRejectedError({ firstHost: 'other.example.com', hostCount: 1 }), ); const item = new ConnectTestClusterItem(makeMovedCluster(), null); diff --git a/src/tree/documentdb/ClusterItemBase.ts b/src/tree/documentdb/ClusterItemBase.ts index c743a61bb..7aeab3a49 100644 --- a/src/tree/documentdb/ClusterItemBase.ts +++ b/src/tree/documentdb/ClusterItemBase.ts @@ -222,7 +222,7 @@ export abstract class ClusterItemBase { const abortController = new AbortController(); - const clientPromise = ClustersClient.getClient( + const clientPromise = ClustersClient.connectInteractive( clusterId, abortController.signal, (id) => { diff --git a/src/tree/documentdb/CollectionItem.test.ts b/src/tree/documentdb/CollectionItem.test.ts index fb7a2bd24..88afa1a8f 100644 --- a/src/tree/documentdb/CollectionItem.test.ts +++ b/src/tree/documentdb/CollectionItem.test.ts @@ -5,6 +5,7 @@ import { describe, expect, it, vi } from 'vitest'; +import { ClustersClient } from '../../documentdb/ClustersClient'; import { CollectionItem } from './CollectionItem'; vi.mock('@vscode/l10n', () => ({ @@ -90,6 +91,25 @@ describe('CollectionItem', () => { expect(children[1].id).toBe('connectionsView/cluster-1/db1/coll1/indexes'); }); + it('loads the count in the background using the stable cluster ID', async () => { + const estimateDocumentCount = vi.fn().mockResolvedValue(0); + vi.mocked(ClustersClient.getClient) + .mockClear() + .mockResolvedValueOnce({ estimateDocumentCount } as unknown as ClustersClient); + const item = new CollectionItem(cluster as never, databaseInfo as never, collectionInfo as never); + + item.loadDocumentCount(); + + await vi.waitFor(() => expect(estimateDocumentCount).toHaveBeenCalledExactlyOnceWith('db1', 'coll1')); + expect(ClustersClient.getClient).toHaveBeenCalledExactlyOnceWith( + 'cluster-1', + undefined, + undefined, + 'treeChildren', + { background: true }, + ); + }); + it('keeps shard key fields with backticks inside their code span', () => { const item = new CollectionItem( cluster as never, diff --git a/src/tree/documentdb/CollectionItem.ts b/src/tree/documentdb/CollectionItem.ts index d7f957124..83e5b031e 100644 --- a/src/tree/documentdb/CollectionItem.ts +++ b/src/tree/documentdb/CollectionItem.ts @@ -132,7 +132,9 @@ export class CollectionItem implements TreeElement, TreeElementWithExperience, T if (!isCurrent()) { return null; } - const client = await ClustersClient.getClient(clusterId, undefined, undefined, 'treeChildren'); + const client = await ClustersClient.getClient(clusterId, undefined, undefined, 'treeChildren', { + background: true, + }); return client.estimateDocumentCount(dbName, collName); }); } catch { diff --git a/src/tree/documentdb/DatabaseItem.test.ts b/src/tree/documentdb/DatabaseItem.test.ts index 6c40addd4..896a2524c 100644 --- a/src/tree/documentdb/DatabaseItem.test.ts +++ b/src/tree/documentdb/DatabaseItem.test.ts @@ -81,6 +81,13 @@ describe('DatabaseItem - async collection count loading', () => { item.loadCollectionCount(); await flushAsync(); + expect(ClustersClient.getClient).toHaveBeenCalledExactlyOnceWith( + cluster.clusterId, + undefined, + undefined, + 'treeChildren', + { background: true }, + ); expect(countCollectionsMock).toHaveBeenCalledWith('testdb', COLLECTION_COUNT_LIMIT); expect(listCollectionsMock).not.toHaveBeenCalled(); expect(notifyChildrenChangedMock).toHaveBeenCalledWith(item.id); @@ -124,6 +131,13 @@ describe('DatabaseItem - async collection count loading', () => { // Now expand the node, which fetches the full list const children = await item.getChildren(); + expect(ClustersClient.getClient).toHaveBeenNthCalledWith( + 2, + cluster.clusterId, + undefined, + undefined, + 'treeChildren', + ); expect(listCollectionsMock).toHaveBeenCalledTimes(1); expect(children).toHaveLength(3); // Description now shows exact count, no "+" diff --git a/src/tree/documentdb/DatabaseItem.ts b/src/tree/documentdb/DatabaseItem.ts index 1c9536726..8d05b7e37 100644 --- a/src/tree/documentdb/DatabaseItem.ts +++ b/src/tree/documentdb/DatabaseItem.ts @@ -136,7 +136,9 @@ export class DatabaseItem implements TreeElement, TreeElementWithExperience, Tre private async fetchAndUpdateCount(): Promise { try { - const client = await ClustersClient.getClient(this.cluster.clusterId, undefined, undefined, 'treeChildren'); + const client = await ClustersClient.getClient(this.cluster.clusterId, undefined, undefined, 'treeChildren', { + background: true, + }); const { count, hasMore } = await client.countCollections(this.databaseInfo.name, COLLECTION_COUNT_LIMIT); // `getChildren()` may have run while this request was in flight and // established the exact count. Never replace an exact count with diff --git a/src/webviews/documentdb/clusterDashboard/clusterDashboardRouter.test.ts b/src/webviews/documentdb/clusterDashboard/clusterDashboardRouter.test.ts index 9964ab31c..dc128f009 100644 --- a/src/webviews/documentdb/clusterDashboard/clusterDashboardRouter.test.ts +++ b/src/webviews/documentdb/clusterDashboard/clusterDashboardRouter.test.ts @@ -11,6 +11,7 @@ import { type initWebviewTrpc as InitWebviewTrpc } from '@microsoft/vscode-ext-w import { type Document, type MongoClient } from 'mongodb'; import * as vscode from 'vscode'; +import { ClustersClient } from '../../../documentdb/ClustersClient'; import { API } from '../../../DocumentDBExperiences'; const mockResolveClusterNode = vi.fn(); @@ -130,6 +131,23 @@ describe('clusterDashboardRouter create actions', () => { vi.clearAllMocks(); }); + describe('clusterDashboardRouter health poll', () => { + it('requests a background client for the sampled cluster', async () => { + const unavailable = new Error('test connection unavailable'); + vi.mocked(ClustersClient.getClient).mockRejectedValueOnce(unavailable); + const caller = createCallerFactory(clusterDashboardRouter)(createContext()); + + await expect(caller.measureRtt()).rejects.toMatchObject({ cause: unavailable }); + expect(ClustersClient.getClient).toHaveBeenCalledExactlyOnceWith( + 'cluster-id', + undefined, + undefined, + 'clusterDashboardPoll', + { background: true }, + ); + }); + }); + it('opens the shell with the default database', async () => { const caller = createCallerFactory(clusterDashboardRouter)(createContext()); diff --git a/src/webviews/documentdb/clusterDashboard/clusterDashboardRouter.ts b/src/webviews/documentdb/clusterDashboard/clusterDashboardRouter.ts index 1107d1a1b..18ef9ab59 100644 --- a/src/webviews/documentdb/clusterDashboard/clusterDashboardRouter.ts +++ b/src/webviews/documentdb/clusterDashboard/clusterDashboardRouter.ts @@ -222,7 +222,9 @@ export const clusterDashboardRouter = router({ const myCtx = ctx as WithTelemetry; myCtx.actionContext.telemetry.suppressAll = true; - const client = await ClustersClient.getClient(myCtx.clusterId, undefined, undefined, 'clusterDashboardPoll'); + const client = await ClustersClient.getClient(myCtx.clusterId, undefined, undefined, 'clusterDashboardPoll', { + background: true, + }); return sampleClusterHealth(client.getMongoClient()); }), From 30bed635311e2febf3c8e378879d89a90a040aa8 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 15:03:10 +0000 Subject: [PATCH 061/380] docs: record WI-4d verification and tenant change handoff Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../connection-lifecycle/iterations/01-dev-plan.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index 30115ef8e..17af5d355 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 @@ -1099,6 +1099,12 @@ shim (0005). an account. For rule 3, the operator accepted the reload limitation as an edge case. Finish silent reconnect first, then closed-client replacement. PR2's pre-review was signed off separately and does not block this work. +- **Done (2026-11-20), commit `6a53cf19e` (WI-4d, `gpt-6.2-sol`):** Reconnect silently with the + verified provider, account and tenant. Only a deliberate first connect may prompt, and + background calls cannot start a client. The shared tree helper uses `connectInteractive`; + the positional `getClient` signature remains compatible, with an optional background flag. + The advisor (`claude-opus-5.5`, 85% confidence) approved the implementation. All 372 focused + tests across 13 files and the TypeScript check passed. WI-4e will handle closed topology. --- @@ -1557,6 +1563,10 @@ behave as today. **Progress:** +- **Carry-forward from WI-4d:** An explicit Update Credentials that changes the tenant must + replace or clear the old verified Entra identity so the next connect can use the saved + tenant (decision 0011). Automatic reconnect remains pinned until that explicit update. + --- ## WI-8: Cluster Dashboard health polling (PR 6) From ed2d2616872b535101724d07c4e4a40d72f3d48a Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 15:14:12 +0000 Subject: [PATCH 062/380] docs: record the WI-4c Fusion High timeout Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../features/connection-lifecycle/iterations/01-dev-plan.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index 17af5d355..a88537ecd 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 @@ -1068,6 +1068,7 @@ shim (0005). | `gpt-6.1-sol`, Extra High | `7a1845af5` | 88 | 6m56s | 918k / 21k | 31 | 51.2 AIU | | `gpt-6.2-sol`, default | `eb388ef45` | 88 | 5m04s | 1.0M / 13k | 28 | 78.5 AIU | | Copilot Fusion Standard (`gpt-6.1-terra`) | `4ac6c4765` | 86 | 3m07s | 911.6k / 12.5k | Not reported | 13.55 AI credits | + | Copilot Fusion High | No complete candidate | Not scored | 9m55s reported | 2.0M / 77.1k | Not reported | 184.43 AI credits | | `gpt-6.2-sol`, High | `f80f3a325` | 84 | 4m41s | 1.1M / 15k | 28 | 79.6 AIU | | `gpt-6.2-sol`, Extra High | `aeabaabd2` | 84 | 7m01s | 1.1M / 18k | 33 | 87.6 AIU | | `mai-code-2`, default | `1978a3c80` | 74 | 8m06s | 1.6M / 21k | 41 | 17.0 AIU | @@ -1078,6 +1079,9 @@ shim (0005). candidate did not honor the retry or latch on an obsolete startup failure. Astra led on simplicity among the correct candidates; Sol 6.1 High had the strongest tests. This was one trial per configuration, not a general model ranking. + Fusion High ran alone on the same baseline and hit the 10-minute limit. It left partial + implementation changes but no test changes. The partial result was not verified or scored + and does not change the delivery selection. - **WI-4d/e deferred, escalated (2026-11-20):** The advisor reviewed the split between silent reconnect and closed-client replacement. Before implementing, confirm these reconnect rules: From 64f7a07916c000cfcec47dfbbdb332f6c3a57c26 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 15:17:01 +0000 Subject: [PATCH 063/380] docs: record PR2 final review checks Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iterations/01-pr2-azureauth-review.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr2-azureauth-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr2-azureauth-review.md index 7fa973c18..b2d368818 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr2-azureauth-review.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr2-azureauth-review.md @@ -48,3 +48,12 @@ accepted the untested deep-link URLs; partial failures were not reproducible liv CP-W3 retains L2 (Claude Opus 5.5, 85% confidence). L1 uses the same azureauth and Azure Resources API versions, so stepping down does not reduce the remaining risk. + +## Final review handoff (2026-11-20) + +Case 2 verification at `4858e97d0` passed formatting, localization check, build, test +type-check, full Vitest (9,684 passed, one skipped), and VSIX packaging. Lint initially +reported unresolved types in the fresh worktree; it passed when rerun after the workspace +build generated the package declarations. No source changes were needed. Automated VSIX +activation remains unavailable on this host; the operator accepted the manual OP-2 result +and its coverage gaps above. From 4680b459ff3e821cdd24fa5fd9d0eb8587a4cb2d Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 15:21:38 +0000 Subject: [PATCH 064/380] fix: replace closed clients without changing identity (WI-4e) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/documentdb/ClustersClient.test.ts | 134 ++++++++++++++++++++++---- src/documentdb/ClustersClient.ts | 51 +++++++--- 2 files changed, 156 insertions(+), 29 deletions(-) diff --git a/src/documentdb/ClustersClient.test.ts b/src/documentdb/ClustersClient.test.ts index 0ec1a6c49..944962490 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -336,6 +336,101 @@ describe('regular connection startup diagnostics', () => { await expect(background()).resolves.toBe(client); expect(onStartup).toHaveBeenCalledExactlyOnceWith(client.connectionCorrelationId); expect(MongoClient).toHaveBeenCalledOnce(); + expect(mockConnect).toHaveBeenCalledOnce(); + }); + + it('rechecks cancellation and the latch after a cached reuse callback', async () => { + const client = await ClustersClient.connectInteractive(clusterId); + const controller = new AbortController(); + const abort = vi.fn(() => controller.abort()); + await expect(ClustersClient.getClient(clusterId, controller.signal, abort)).rejects.toBeInstanceOf( + UserCancelledError, + ); + expect(abort).toHaveBeenCalledExactlyOnceWith(client.connectionCorrelationId); + + const latchedController = new AbortController(); + const latch = vi.fn(() => { + ClustersClient.latch(clusterId, 'userDisconnected'); + latchedController.abort(); + }); + await expect(ClustersClient.getClient(clusterId, latchedController.signal, latch)).rejects.toMatchObject({ + name: 'ConnectionUnavailableError', + reason: 'userDisconnected', + }); + expect(latch).toHaveBeenCalledExactlyOnceWith(client.connectionCorrelationId); + expect(ClustersClient.getBinding(clusterId)).toBe(client.binding); + expect(mockConnect).toHaveBeenCalledOnce(); + expect(mockClose).not.toHaveBeenCalled(); + }); + + it('retries instead of returning a cached client evicted by the startup callback', async () => { + const client = await ClustersClient.connectInteractive(clusterId); + const onStartup = vi.fn().mockImplementationOnce((): void => { + void ClustersClient.deleteClient(clusterId); + }); + const next = await ClustersClient.getClient(clusterId, undefined, onStartup); + expect(next.generation).toBe(client.generation + 1); + expect(onStartup.mock.calls).toEqual([[client.connectionCorrelationId], [next.connectionCorrelationId]]); + expect(mockConnect).toHaveBeenCalledTimes(2); + }); + + it('shares one same-identity replacement after topology closure, including a background joiner', async () => { + const old = await ClustersClient.connectInteractive(clusterId); + const epoch = ClustersClient.getEpoch(clusterId); + poolEvents.emit('topologyClosed'); + const onBackground = vi.fn(); + const background = (): Promise => + ClustersClient.getClient(clusterId, undefined, onBackground, 'clusterDashboardPoll', { background: true }); + + await expect(background()).rejects.toBeInstanceOf(MongoNotConnectedError); + expect(onBackground).not.toHaveBeenCalled(); + expect(mockConnect).toHaveBeenCalledOnce(); + expect(MongoClient).toHaveBeenCalledOnce(); + expect(ClustersClient.getBinding(clusterId)).toBe(old.binding); + + const handshake = pauseNextConnect(); + const onForeground = vi.fn(); + const first = ClustersClient.getClient(clusterId, undefined, onForeground); + await handshake.started; + const second = ClustersClient.getClient(clusterId); + const joined = background(); + expect(ClustersClient.getBinding(clusterId)).toBe(old.binding); + handshake.resolve(); + const [replacement, other, polled] = await Promise.all([first, second, joined]); + expect(other).toBe(replacement); + expect(polled).toBe(replacement); + expect(replacement.generation).toBe(old.generation + 1); + expect(replacement.fingerprint).toBe(old.fingerprint); + expect(replacement.connectionCorrelationId).not.toBe(old.connectionCorrelationId); + expect(onForeground).toHaveBeenCalledExactlyOnceWith(replacement.connectionCorrelationId); + expect(onBackground).toHaveBeenCalledExactlyOnceWith(replacement.connectionCorrelationId); + expect(ClustersClient.getBinding(clusterId)).toBe(replacement.binding); + expect(ClustersClient.getEpoch(clusterId)).toBe(epoch); + expect(mockConnect).toHaveBeenCalledTimes(2); + expect(MongoClient).toHaveBeenCalledTimes(2); + }); + + it('keeps the closed binding when repeated replacements would change identity', async () => { + const client = await ClustersClient.connectInteractive(clusterId); + const epoch = ClustersClient.getEpoch(clusterId); + poolEvents.emit('topologyClosed'); + vi.mocked(MicrosoftEntraIDAuthHandler.prototype.configureAuth).mockResolvedValue({ + connectionString: 'mongodb://private-host:27017', + options: {}, + verifiedIdentity: { ...verifiedIdentity, accountId: 'private-different-account' }, + }); + + for (let attempt = 0; attempt < 2; attempt++) { + await expect(ClustersClient.getClient(clusterId)).rejects.toMatchObject({ + name: 'ConnectionUnavailableError', + reason: 'identityChanged', + }); + expect(ClustersClient.getBinding(clusterId)).toBe(client.binding); + expect(ClustersClient.getEpoch(clusterId)).toBe(epoch); + } + expect(ClustersClient.getLastVerifiedIdentity(clusterId)).toEqual(verifiedIdentity); + expect(MongoClient).toHaveBeenCalledOnce(); + expect(mockConnect).toHaveBeenCalledOnce(); }); it('binds Entra to the original cached URI and the verified identity, even if credentials change during startup', async () => { @@ -376,25 +471,25 @@ describe('regular connection startup diagnostics', () => { expect(MongoClient).not.toHaveBeenCalled(); }); - it('aborts only one cached waiter while both are waiting for the same driver connection', async () => { + it('aborts only one waiter while both are waiting for the same replacement', async () => { const client = await ClustersClient.connectInteractive(clusterId); - let finishConnect!: () => void; - const pendingConnect = new Promise((resolve) => { - finishConnect = resolve; - }); - mockConnect.mockReturnValue(pendingConnect); + poolEvents.emit('topologyClosed'); + const handshake = pauseNextConnect(); const controller = new AbortController(); const cancelled = ClustersClient.getClient(clusterId, controller.signal); const other = ClustersClient.getClient(clusterId, new AbortController().signal); - expect(mockConnect).toHaveBeenCalledTimes(3); + await handshake.started; + expect(mockConnect).toHaveBeenCalledTimes(2); controller.abort(); await expect(cancelled).rejects.toBeInstanceOf(UserCancelledError); expect(mockClose).not.toHaveBeenCalled(); - - finishConnect(); - await expect(other).resolves.toBe(client); expect(ClustersClient.getBinding(clusterId)).toBe(client.binding); + + handshake.resolve(); + const replacement = await other; + expect(replacement.generation).toBe(client.generation + 1); + expect(ClustersClient.getBinding(clusterId)).toBe(replacement.binding); expect(mockClose).not.toHaveBeenCalled(); }); @@ -521,15 +616,16 @@ describe('regular connection startup diagnostics', () => { expect(ClustersClient.getBinding(clusterId)).toBe(replacement.binding); }); - it.each([false, true])('a stale cached waiter has only one retry (latched: %s)', async (latch) => { + it.each([false, true])('a stale replacement waiter has only one retry (latched: %s)', async (latch) => { const cached = await ClustersClient.connectInteractive(clusterId); - const cachedConnect = pauseNextConnect(); + poolEvents.emit('topologyClosed'); + const replacement = pauseNextConnect(); const onStartup = vi.fn(); const waiter = ClustersClient.getClient(clusterId, undefined, onStartup); - await cachedConnect.started; + await replacement.started; await ClustersClient.deleteClient(clusterId); const retry = pauseNextConnect(); - cachedConnect.reject(new Error('old client closed')); + replacement.reject(new Error('superseded replacement failed')); await retry.started; if (latch) { ClustersClient.latch(clusterId, 'connectionRemoved'); @@ -549,10 +645,14 @@ describe('regular connection startup diagnostics', () => { }); } expect(onStartup).toHaveBeenCalledTimes(2); - expect(onStartup.mock.calls[0][0]).toBe(cached.connectionCorrelationId); + expect(onStartup.mock.calls[0][0]).not.toBe(cached.connectionCorrelationId); expect(onStartup.mock.calls[1][0]).not.toBe(cached.connectionCorrelationId); + expect(onStartup.mock.calls[1][0]).not.toBe(onStartup.mock.calls[0][0]); expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); - expect(MongoClient).toHaveBeenCalledTimes(2); + expect(MongoClient).toHaveBeenCalledTimes(3); + expect(mockClose).toHaveBeenCalledTimes(3); + expect(mockClose.mock.contexts[1]).toBe(mockConnect.mock.contexts[1]); + expect(mockClose.mock.contexts[2]).toBe(mockConnect.mock.contexts[2]); }); it('latch blocks cold and cached calls before startup or driver reuse', async () => { @@ -674,7 +774,7 @@ describe('regular connection startup diagnostics', () => { const error = new MongoServerError({ code: 18, errmsg: 'private-server-message' }); mockListDatabases.mockRejectedValueOnce(error); - expect(poolEvents.eventNames()).toEqual([]); + expect(poolEvents.eventNames()).toEqual(['topologyClosed']); await expect(client.listDatabases()).rejects.toBe(error); expect(ext.outputChannel.debug).not.toHaveBeenCalled(); }); diff --git a/src/documentdb/ClustersClient.ts b/src/documentdb/ClustersClient.ts index 427d526c9..ef62fe0f7 100644 --- a/src/documentdb/ClustersClient.ts +++ b/src/documentdb/ClustersClient.ts @@ -175,6 +175,7 @@ type ClientStartupStage = interface ClientStartup { readonly id: string; + readonly expectedFingerprint?: string; readonly startedAt: number; readonly costTimings: ConnectionStartupTimings; readonly telemetry: ITelemetryContext; @@ -310,6 +311,7 @@ export class ClustersClient { private _binding: ConnectionBinding; private _createdAt: number; private _mongoClient: MongoClient; + private _closed = false; private _interactiveEntraStartupId?: string; private _llmEnhancedFeatureApis: llmEnhancedFeatureApis | null = null; private _queryInsightsApis: QueryInsightsApis | null = null; @@ -406,6 +408,7 @@ export class ClustersClient { trigger: ClientStartupTrigger, epoch: number, allowInteractive: boolean, + expectedFingerprint?: string, ): Promise { this.connectionCorrelationId = startupId; let originalFailure: { error: unknown } | undefined; @@ -429,6 +432,7 @@ export class ClustersClient { const startedAt = Date.now(); const startup: ClientStartup = { id: startupId, + expectedFingerprint, startedAt, costTimings: new ConnectionStartupTimings(), telemetry: context.telemetry, @@ -538,6 +542,9 @@ export class ClustersClient { connectionString: credentials.connectionString, principal: this.#verifiedIdentity, }); + if (startup.expectedFingerprint !== undefined && this._fingerprint !== startup.expectedFingerprint) { + throw new ConnectionUnavailableError('identityChanged'); + } const hosts = getHostsFromConnectionString(connectionString); const userAgentString = hosts.some((host) => getAzureHostSuffix(host)) ? appendExtensionUserAgent() : undefined; if (userAgentString) { @@ -630,6 +637,9 @@ export class ClustersClient { originalConnectionString: string = connectionString, ): Promise { this._mongoClient = new MongoClient(connectionString, options); + this._mongoClient.once('topologyClosed', (): void => { + this._closed = true; + }); if (interactiveEntra) { this._interactiveEntraStartupId = startup.id; this.traceInteractiveEntraPool(startup.id); @@ -746,21 +756,33 @@ export class ClustersClient { const epoch = ClustersClient.getEpoch(clusterId); const cached = ClustersClient._clients.get(clusterId); - let promise: Promise; - let id: string | undefined; - if (cached) { - id = cached.connectionCorrelationId; + if (cached && !cached._closed) { + const id = cached.connectionCorrelationId; if (id) { onStartup?.(id); } - promise = cached._mongoClient.connect().then(() => cached); - } else { - const pending = ClustersClient.getOrStartClient(clusterId, epoch, trigger, allowInteractive, background); - id = pending.id; - onStartup?.(id); - promise = pending.promise; + if (epoch !== ClustersClient.getEpoch(clusterId)) { + continue; + } + if (abortSignal?.aborted) { + ext.outputChannel.debug(`[ClustersClient] startup=${id} wait canceled by user surface=extension`); + throw new UserCancelledError('abortConnection'); + } + if (!cached._closed) { + return cached; + } } + // Until a replacement succeeds, the closed entry still pins the connection identity. + const { id, promise } = ClustersClient.getOrStartClient( + clusterId, + epoch, + trigger, + allowInteractive, + background, + cached?.fingerprint, + ); + onStartup?.(id); try { const client = await waitForClient(promise, abortSignal, id); if (epoch === ClustersClient.getEpoch(clusterId)) { @@ -781,6 +803,7 @@ export class ClustersClient { trigger: ClientStartupTrigger, allowInteractive: boolean, background: boolean, + expectedFingerprint?: string, ): PendingStartup { const existing = ClustersClient._pendingStartups.get(clusterId); if (existing?.epoch === epoch) { @@ -805,7 +828,7 @@ export class ClustersClient { const id = randomUUID(); // Register before initialization or a caller's onStartup callback can re-enter getClient. const promise = Promise.resolve().then(() => - ClustersClient.establishClient(clusterId, epoch, id, trigger, allowInteractive), + ClustersClient.establishClient(clusterId, epoch, id, trigger, allowInteractive, expectedFingerprint), ); const pending = { id, epoch, promise }; ClustersClient._pendingStartups.set(clusterId, pending); @@ -824,14 +847,16 @@ export class ClustersClient { id: string, trigger: ClientStartupTrigger, allowInteractive: boolean, + expectedFingerprint?: string, ): Promise { const client = new ClustersClient(clusterId); try { - await client.initClient(id, trigger, epoch, allowInteractive); + await client.initClient(id, trigger, epoch, allowInteractive, expectedFingerprint); } catch (error) { if (!(error instanceof UserCancelledError) && epoch === ClustersClient.getEpoch(clusterId)) { ClustersClient._lastFailedStartups.set(clusterId, id); } + client._closed = true; void client._mongoClient?.close().catch(() => { // Ignore close errors during cleanup }); @@ -839,6 +864,7 @@ export class ClustersClient { } if (epoch !== ClustersClient.getEpoch(clusterId)) { + client._closed = true; void client._mongoClient.close().catch(() => { ext.outputChannel.debug(`[ClustersClient] startup=${id} superseded client cleanup failed surface=extension`); }); @@ -900,6 +926,7 @@ export class ClustersClient { if (client) { ClustersClient._clients.delete(clusterId); SchemaStore.getInstance().clearCluster(clusterId); + client._closed = true; await client._mongoClient.close(true); } } From 657c9b2cf48019b477a8da9fb0557d67e22e8854 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Fri, 20 Nov 2026 15:22:10 +0000 Subject: [PATCH 065/380] docs: record WI-4e checks and Fusion High timing Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../connection-lifecycle/iterations/01-dev-plan.md | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index a88537ecd..150197987 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 @@ -1068,7 +1068,7 @@ shim (0005). | `gpt-6.1-sol`, Extra High | `7a1845af5` | 88 | 6m56s | 918k / 21k | 31 | 51.2 AIU | | `gpt-6.2-sol`, default | `eb388ef45` | 88 | 5m04s | 1.0M / 13k | 28 | 78.5 AIU | | Copilot Fusion Standard (`gpt-6.1-terra`) | `4ac6c4765` | 86 | 3m07s | 911.6k / 12.5k | Not reported | 13.55 AI credits | - | Copilot Fusion High | No complete candidate | Not scored | 9m55s reported | 2.0M / 77.1k | Not reported | 184.43 AI credits | + | Copilot Fusion High | No complete candidate | Not scored | 9m55s reported | 2.0M / 77.1k | 40 | 184.43 AI credits | | `gpt-6.2-sol`, High | `f80f3a325` | 84 | 4m41s | 1.1M / 15k | 28 | 79.6 AIU | | `gpt-6.2-sol`, Extra High | `aeabaabd2` | 84 | 7m01s | 1.1M / 18k | 33 | 87.6 AIU | | `mai-code-2`, default | `1978a3c80` | 74 | 8m06s | 1.6M / 21k | 41 | 17.0 AIU | @@ -1081,7 +1081,9 @@ shim (0005). one trial per configuration, not a general model ranking. Fusion High ran alone on the same baseline and hit the 10-minute limit. It left partial implementation changes but no test changes. The partial result was not verified or scored - and does not change the delivery selection. + and does not change the delivery selection. Fusion chose Critique mode but never finished + the Opus 5.5 draft. The first request took 5m15s and reached its 48,000-output-token limit. + The draft then made further requests until the timeout; the critic and revision never ran. - **WI-4d/e deferred, escalated (2026-11-20):** The advisor reviewed the split between silent reconnect and closed-client replacement. Before implementing, confirm these reconnect rules: @@ -1109,6 +1111,13 @@ shim (0005). the positional `getClient` signature remains compatible, with an optional background flag. The advisor (`claude-opus-5.5`, 85% confidence) approved the implementation. All 372 focused tests across 13 files and the TypeScript check passed. WI-4e will handle closed topology. +- **Done (2026-11-20), commit `4680b459f` (WI-4e, `gpt-6.2-sol`):** Reuse open clients without + calling driver `connect()` again. A foreground caller can replace a closed client; concurrent + callers share that replacement, including background callers that join it. Reject a different + fingerprint before constructing a driver and retain the closed binding, as the operator + approved. The leader checked the topology event and caller, epoch, and latch checks against + the advised WI-4e contract. Build and 116 focused tests passed. The cancellation and stale + retry tests now exercise a pending replacement rather than an obsolete cached `connect()` call. --- From 8de2a67dadd692839af61f39f222dda4267f2861 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 09:40:47 +0000 Subject: [PATCH 066/380] fix: distinguish Azure access denial from sign-in requirements (PR2-R1) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../checks/resolveTarget.test.ts | 11 +++++++++++ src/connectionDiagnostics/checks/resolveTarget.ts | 2 +- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/connectionDiagnostics/checks/resolveTarget.test.ts b/src/connectionDiagnostics/checks/resolveTarget.test.ts index b8f2819a4..264f393e2 100644 --- a/src/connectionDiagnostics/checks/resolveTarget.test.ts +++ b/src/connectionDiagnostics/checks/resolveTarget.test.ts @@ -188,6 +188,17 @@ describe('resolveTarget check (review R2, option A)', (): void => { 'target.sourceInaccessible', { source: 'azure', reason: 'accessDenied', errorName: 'Error', statusCode: 403 }, ], + ...['AADSTS53003', 'AADSTS700016'].map( + (code) => + [ + new ConnectionSourceUnavailableError( + 'azure', + withStatus(new Error('secret authority detail'), { code, statusCode: 403 }), + ), + 'target.sourceInaccessible', + { source: 'azure', reason: 'accessDenied', errorName: 'Error', statusCode: 403 }, + ] as const, + ), [ new ConnectionSourceUnavailableError( 'kubernetes', diff --git a/src/connectionDiagnostics/checks/resolveTarget.ts b/src/connectionDiagnostics/checks/resolveTarget.ts index 7d805654e..0a15f5a87 100644 --- a/src/connectionDiagnostics/checks/resolveTarget.ts +++ b/src/connectionDiagnostics/checks/resolveTarget.ts @@ -35,7 +35,7 @@ function isAzureSignInSignal(error: unknown): boolean { } const code = 'code' in error ? error.code : undefined; return [error.name, code].some( - (value) => typeof value === 'string' && (value === 'interaction_required' || /^AADSTS\d{5,9}$/.test(value)), + (value) => value === 'interaction_required' || value === 'AADSTS50076' || value === 'AADSTS50079', ); } From df66e017239980e053d96b01406ce77a20bb73d7 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 09:40:47 +0000 Subject: [PATCH 067/380] fix: refresh subscriptions after a deep-link cache miss (PR2-R2) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/deepLinks/azureSubscription.test.ts | 76 ++++++++++++++++++++----- src/deepLinks/azureSubscription.ts | 29 ++++++---- 2 files changed, 80 insertions(+), 25 deletions(-) diff --git a/src/deepLinks/azureSubscription.test.ts b/src/deepLinks/azureSubscription.test.ts index 0bbcc5688..2a9efcef4 100644 --- a/src/deepLinks/azureSubscription.test.ts +++ b/src/deepLinks/azureSubscription.test.ts @@ -46,6 +46,7 @@ const azureSubscriptionProvider = { getAvailableSubscriptions: vi.fn(), }; const listingOptions = { filter: false, maximumTenants: Number.POSITIVE_INFINITY }; +const freshListingOptions = { ...listingOptions, noCache: true }; const session: vscode.AuthenticationSession = { id: 'session-id', @@ -134,6 +135,7 @@ describe('resolveAzureSubscription', (): void => { }); expect(azureSubscriptionProvider.signIn).toHaveBeenCalledTimes(2); expect(azureSubscriptionProvider.getAvailableSubscriptions).toHaveBeenCalledExactlyOnceWith(listingOptions); + expect(context.telemetry.measurements.subscriptionLookupAttempts).toBe(1); expect(ext.outputChannel.trace).toHaveBeenCalledWith('[DeepLink] Azure sign-in: sign-in required'); expect(ext.outputChannel.trace).toHaveBeenCalledWith('[DeepLink] Azure sign-in confirmation: accepted'); expect(ext.outputChannel.trace).toHaveBeenCalledWith('[DeepLink] 1 matching subscription(s) found'); @@ -235,10 +237,34 @@ describe('resolveAzureSubscription', (): void => { expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); }); - it('signs into the hinted tenant and retries unfiltered subscription resolution exactly once', async (): Promise => { - const report = vi.fn<(message: string) => void>(); + it.each([ + { hint: 'without a tenant hint', tenantId: undefined }, + { hint: 'with a tenant hint', tenantId: 'TENANT-ID' }, + ])('resolves a fresh hit without prompting $hint', async ({ tenantId }): Promise => { const found = subscription('tenant-id', 'account-id'); azureSubscriptionProvider.getAvailableSubscriptions.mockResolvedValueOnce([]).mockResolvedValueOnce([found]); + const lookupRequest = tenantId === undefined ? request : { ...request, tenantId }; + + await expect(resolveAzureSubscription(context, lookupRequest)).resolves.toBe(found); + + expect(azureSubscriptionProvider.getAvailableSubscriptions.mock.calls).toEqual([ + [listingOptions], + [freshListingOptions], + ]); + expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); + expect(getSessionFromVSCode).not.toHaveBeenCalled(); + expect(context.telemetry.properties.tenantSignInRequired).toBe('false'); + expect(context.telemetry.measurements.subscriptionLookupAttempts).toBe(2); + expect(context.telemetry.measurements.subscriptionAccountCount).toBe(1); + }); + + it('offers hinted tenant sign-in after a fresh miss and refreshes exactly once after sign-in', async (): Promise => { + const report = vi.fn<(message: string) => void>(); + const found = subscription('tenant-id', 'account-id'); + azureSubscriptionProvider.getAvailableSubscriptions + .mockResolvedValueOnce([]) + .mockResolvedValueOnce([]) + .mockResolvedValueOnce([found]); (vscode.window.showInformationMessage as Mock).mockImplementation(async (): Promise => { expect(report).not.toHaveBeenCalledWith('Signing in to tenant…'); return 'Sign in to tenant'; @@ -255,6 +281,7 @@ describe('resolveAzureSubscription', (): void => { expect(report.mock.calls).toEqual([ ['Checking Azure sign-in…'], ['Looking for the subscription…'], + ['Looking for the subscription…'], ['Signing in to tenant…'], ['Looking for the subscription…'], ]); @@ -271,12 +298,22 @@ describe('resolveAzureSubscription', (): void => { createIfNone: true, clearSessionPreference: true, }); - expect(azureSubscriptionProvider.getAvailableSubscriptions).toHaveBeenCalledTimes(2); - expect(azureSubscriptionProvider.getAvailableSubscriptions).toHaveBeenNthCalledWith(1, listingOptions); - expect(azureSubscriptionProvider.getAvailableSubscriptions).toHaveBeenNthCalledWith(2, { - ...listingOptions, - noCache: true, - }); + expect(azureSubscriptionProvider.getAvailableSubscriptions.mock.calls).toEqual([ + [listingOptions], + [freshListingOptions], + [freshListingOptions], + ]); + const [cachedList, freshList, tenantList] = + azureSubscriptionProvider.getAvailableSubscriptions.mock.invocationCallOrder; + const order = [ + cachedList, + freshList, + vi.mocked(vscode.window.showInformationMessage).mock.invocationCallOrder[0], + vi.mocked(getSessionFromVSCode).mock.invocationCallOrder[0], + tenantList, + ]; + expect(order).toEqual([...order].sort((a, b): number => a - b)); + expect(context.telemetry.measurements.subscriptionLookupAttempts).toBe(3); expect(context.telemetry.properties).toEqual({ failureStage: 'resolveSubscription', azureSignInRequired: 'false', @@ -284,7 +321,7 @@ describe('resolveAzureSubscription', (): void => { }); }); - it('treats a false tenant sign-in result as cancellation without retrying subscription lookup', async (): Promise => { + it('treats a false tenant sign-in result as cancellation without listing again after sign-in', async (): Promise => { vi.mocked(getSessionFromVSCode).mockResolvedValue(undefined); (vscode.window.showInformationMessage as Mock).mockResolvedValue('Sign in to tenant'); @@ -294,7 +331,11 @@ describe('resolveAzureSubscription', (): void => { createIfNone: true, clearSessionPreference: true, }); - expect(azureSubscriptionProvider.getAvailableSubscriptions).toHaveBeenCalledExactlyOnceWith(listingOptions); + expect(azureSubscriptionProvider.getAvailableSubscriptions.mock.calls).toEqual([ + [listingOptions], + [freshListingOptions], + ]); + expect(context.telemetry.measurements.subscriptionLookupAttempts).toBe(2); expect(context.telemetry.properties).toMatchObject({ tenantSignInRequired: 'true', deepLinkOutcome: 'canceled', @@ -317,7 +358,8 @@ describe('resolveAzureSubscription', (): void => { 'We could not find subscription Subscription-ID among your signed-in Azure accounts. Check that you are signed in with the right account and to the right Azure cloud.', ); - expect(azureSubscriptionProvider.getAvailableSubscriptions).toHaveBeenCalledTimes(2); + expect(azureSubscriptionProvider.getAvailableSubscriptions).toHaveBeenCalledTimes(3); + expect(context.telemetry.measurements.subscriptionLookupAttempts).toBe(3); expect(getSessionFromVSCode).toHaveBeenCalledExactlyOnceWith(undefined, 'tenant-id', { createIfNone: true, clearSessionPreference: true, @@ -353,7 +395,11 @@ describe('resolveAzureSubscription', (): void => { expect(context.telemetry.properties.userCancelledAtStep).toBe('AzureTenantSignIn'); expect(context.telemetry.properties.tenantSignInRequired).toBe('true'); - expect(azureSubscriptionProvider.getAvailableSubscriptions).toHaveBeenCalledExactlyOnceWith(listingOptions); + expect(azureSubscriptionProvider.getAvailableSubscriptions.mock.calls).toEqual([ + [listingOptions], + [freshListingOptions], + ]); + expect(context.telemetry.measurements.subscriptionLookupAttempts).toBe(2); expect(azureSubscriptionProvider.signIn).toHaveBeenCalledExactlyOnceWith(undefined, { promptIfNeeded: false }); expect(getSessionFromVSCode).not.toHaveBeenCalled(); expect(context.errorHandling.buttons).toBeUndefined(); @@ -371,8 +417,12 @@ describe('resolveAzureSubscription', (): void => { expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); expect(azureSubscriptionProvider.signIn).toHaveBeenCalledExactlyOnceWith(undefined, { promptIfNeeded: false }); expect(getSessionFromVSCode).not.toHaveBeenCalled(); - expect(azureSubscriptionProvider.getAvailableSubscriptions).toHaveBeenCalledExactlyOnceWith(listingOptions); + expect(azureSubscriptionProvider.getAvailableSubscriptions.mock.calls).toEqual([ + [listingOptions], + [freshListingOptions], + ]); expect(context.telemetry.properties.tenantSignInRequired).toBe('false'); + expect(context.telemetry.measurements.subscriptionLookupAttempts).toBe(2); expect(context.telemetry.measurements.subscriptionAccountCount).toBe(0); expect(context.errorHandling.buttons?.[0].title).toBe('Manage Azure accounts'); }); diff --git a/src/deepLinks/azureSubscription.ts b/src/deepLinks/azureSubscription.ts index ee1f23906..063617df9 100644 --- a/src/deepLinks/azureSubscription.ts +++ b/src/deepLinks/azureSubscription.ts @@ -85,14 +85,16 @@ export async function resolveAzureSubscription( context.telemetry.properties.failureStage = 'resolveSubscription'; context.telemetry.properties.tenantSignInRequired = 'false'; - for (let attempt = 0; attempt < 2; attempt++) { + let lookupAttempts = 0; + async function lookupSubscription(noCache = false): Promise { ext.outputChannel.trace('[DeepLink] Listing subscriptions'); report?.(vscode.l10n.t('Looking for the subscription…')); + context.telemetry.measurements.subscriptionLookupAttempts = ++lookupAttempts; const subscriptions = await measureDeepLinkPhase(context, 'subscriptionLookup', () => azureSubscriptionProvider.getAvailableSubscriptions({ filter: false, maximumTenants: Number.POSITIVE_INFINITY, - ...(attempt === 1 ? { noCache: true } : {}), + ...(noCache ? { noCache: true } : {}), }), ); const candidates = subscriptions.filter( @@ -103,18 +105,17 @@ export async function resolveAzureSubscription( ); ext.outputChannel.trace(`[DeepLink] ${candidates.length} matching subscription(s) found`); context.telemetry.measurements.subscriptionAccountCount = candidates.length; - context.telemetry.measurements.subscriptionLookupAttempts = attempt + 1; - const subscription = + return ( candidates.find((candidate) => !isTenantFilteredOut(candidate.tenantId, candidate.account.id)) ?? - candidates[0]; - if (subscription) { - return subscription; - } - - if (attempt > 0 || request.tenantId === undefined) { - break; - } + candidates[0] + ); + } + const subscription = (await lookupSubscription()) ?? (await lookupSubscription(true)); + if (subscription) { + return subscription; + } + if (request.tenantId !== undefined) { context.telemetry.properties.tenantSignInRequired = 'true'; const tenantId = request.tenantId; ext.outputChannel.trace('[DeepLink] Tenant sign-in offered'); @@ -147,6 +148,10 @@ export async function resolveAzureSubscription( cancelDeepLink(context, 'AzureTenantSignIn'); return undefined; } + const tenantSubscription = await lookupSubscription(true); + if (tenantSubscription) { + return tenantSubscription; + } } ext.outputChannel.trace('[DeepLink] Subscription not found'); From 9805b7e259c767b87c364eca2c48e7f8e9077105 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 09:41:21 +0000 Subject: [PATCH 068/380] test: verify retained Azure subscriptions renew across ARM operations (PR2-R3) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/utils/azureClients.test.ts | 167 +++++++++++++++++++++++++++++++++ 1 file changed, 167 insertions(+) create mode 100644 src/utils/azureClients.test.ts diff --git a/src/utils/azureClients.test.ts b/src/utils/azureClients.test.ts new file mode 100644 index 000000000..46aba7969 --- /dev/null +++ b/src/utils/azureClients.test.ts @@ -0,0 +1,167 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { createHttpHeaders } from '@azure/core-rest-pipeline'; +import { getConfiguredAzureEnv } from '@microsoft/vscode-azext-azureauth'; +import { registerAzureUtilsExtensionVariables } from '@microsoft/vscode-azext-azureutils'; +import { TestOutputChannel, TestUserInput } from '@microsoft/vscode-azext-utils'; +import { afterEach, expect, it, vi } from 'vitest'; +import * as vscode from 'vscode'; + +import { AzureSubscriptionProviderWithFilters } from '../plugins/api-shared/azure/AzureSubscriptionProviderWithFilters'; +import { createResourceManagementClient } from './azureClients'; + +import type { HttpClient, PipelineResponse } from '@azure/core-rest-pipeline'; +import type { AzureSubscription, TenantIdAndAccount } from '@microsoft/vscode-azext-azureauth'; +import type { IActionContext } from '@microsoft/vscode-azext-utils'; + +const { getSession, getAccounts } = vi.hoisted(() => { + // Keep the real Azure utilities' extension registration from sending telemetry. + vi.stubEnv('DEBUGTELEMETRY', 'true'); + return { + getSession: + vi.fn< + ( + providerId: string, + scopes: readonly string[] | vscode.AuthenticationWwwAuthenticateRequest, + options?: vscode.AuthenticationGetSessionOptions, + ) => Promise + >(), + getAccounts: vi.fn(async (): Promise => []), + }; +}); + +vi.mock('vscode', async (importOriginal) => { + const actual = await importOriginal }>(); + const authentication = { + getSession, + getAccounts, + onDidChangeSessions: vi.fn(() => ({ dispose: vi.fn() })), + }; + // Share the fixture with both Vite's ESM alias and the setup hook for CommonJS require('vscode'). + actual.default.authentication = authentication; + return { ...actual, authentication }; +}); + +class TestSubscriptionProvider extends AzureSubscriptionProviderWithFilters { + public getSubscriptionAuth(tenant: TenantIdAndAccount): Pick { + return this.getSubscriptionContext(tenant); + } +} + +function idToken(expiry: number): string { + // azureauth reads the numeric exp claim in seconds from the ID token, not the access token. + const payload = Buffer.from(JSON.stringify({ exp: expiry / 1000 })).toString('base64url'); + return `eyJhbGciOiJub25lIn0.${payload}.`; +} + +afterEach((): void => { + vi.restoreAllMocks(); + vi.useRealTimers(); + vi.unstubAllEnvs(); +}); + +it('silently renews the bearer token across ARM operations on the same stored subscription', async (): Promise => { + const now = Date.UTC(2026, 0, 1); + const expiry = now + 60 * 60 * 1000; + vi.useFakeTimers({ now }); + + const showQuickPick = vi.spyOn(vscode.window, 'showQuickPick'); + const createQuickPick = vi.spyOn(vscode.window, 'createQuickPick'); + + registerAzureUtilsExtensionVariables({ + prefix: 'fixture', + context: { + extension: { + packageJSON: { name: 'fixture', version: '0.0.0', publisher: 'fixture', aiKey: 'fixture' }, + }, + } as vscode.ExtensionContext, + outputChannel: new TestOutputChannel(), + }); + const context: IActionContext = { + telemetry: { properties: {}, measurements: {} }, + errorHandling: { issueProperties: {} }, + ui: new TestUserInput(vscode), + valuesToMask: [], + }; + + const provider = new TestSubscriptionProvider(); + try { + const listSubscriptions = vi.spyOn(provider, 'getAvailableSubscriptions'); + const listTenants = vi.spyOn(provider, 'getTenantsForAccount'); + const listTenantSubscriptions = vi.spyOn(provider, 'getSubscriptionsForTenant'); + const environment = getConfiguredAzureEnv(); + const account = { id: 'fixture-account', label: 'Fixture account', environment }; + const tenant = { tenantId: '00000000-0000-4000-8000-000000000001', account }; + const subscription: AzureSubscription = { + ...tenant, + ...provider.getSubscriptionAuth(tenant), + environment, + isCustomCloud: environment.isCustomCloud, + name: 'Fixture subscription', + subscriptionId: '00000000-0000-4000-8000-000000000002', + }; + const acquiredTokens: string[] = []; + getSession.mockImplementation(async (): Promise => { + const expired = Date.now() >= expiry; + const accessToken = expired ? 'fixture-B' : 'fixture-A'; + acquiredTokens.push(accessToken); + return { + id: 'fixture-session', + account, + scopes: [], + accessToken, + idToken: idToken(expired ? expiry + 60 * 60 * 1000 : expiry), + }; + }); + + const authorizations: (string | undefined)[] = []; + const transport: HttpClient = { + async sendRequest(request): Promise { + authorizations.push(request.headers.get('authorization')); + return { + request, + status: 200, + headers: createHttpHeaders({ 'content-type': 'application/json' }), + bodyAsText: JSON.stringify({ name: 'fixture-group', location: 'fixture-region' }), + }; + }, + }; + async function readResourceGroup(): Promise { + const client = await createResourceManagementClient(context, subscription); + // Substitute only the transport; the SDK still runs every pipeline policy. + const sendRequest = client.pipeline.sendRequest.bind(client.pipeline); + vi.spyOn(client.pipeline, 'sendRequest').mockImplementation( + (_transport, request): Promise => sendRequest(transport, request), + ); + await client.resourceGroups.get('fixture-group'); + } + + await readResourceGroup(); + expect(authorizations).toEqual(['Bearer fixture-A']); + expect(getSession).toHaveBeenCalledTimes(1); + + vi.advanceTimersByTime(expiry - now + 1000); + await readResourceGroup(); + + expect(acquiredTokens).toEqual(['fixture-A', 'fixture-B']); + for (const [authProviderId, scopes, options] of getSession.mock.calls) { + expect(authProviderId).toBe('microsoft'); + expect(scopes).toContain(`VSCODE_TENANT:${tenant.tenantId}`); + expect(options).toMatchObject({ account, silent: true }); + expect(options?.createIfNone).toBeFalsy(); + expect(options).not.toHaveProperty('forceNewSession'); + } + expect(getAccounts).not.toHaveBeenCalled(); + expect(listTenants).not.toHaveBeenCalled(); + expect(listTenantSubscriptions).not.toHaveBeenCalled(); + expect(listSubscriptions).not.toHaveBeenCalled(); + expect(showQuickPick).not.toHaveBeenCalled(); + expect(createQuickPick).not.toHaveBeenCalled(); + expect(authorizations).toEqual(['Bearer fixture-A', 'Bearer fixture-B']); + } finally { + provider.dispose(); + } +}); From 490cf43769b2de51d911ca517570b2325da428e1 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 09:41:21 +0000 Subject: [PATCH 069/380] fix: fetch fresh tenants in Manage Azure Accounts (PR2-R4) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../SelectAccountStep.test.ts | 44 +++++++++++++++++++ .../SelectAccountStep.ts | 2 +- 2 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 src/plugins/api-shared/azure/credentialsManagement/SelectAccountStep.test.ts diff --git a/src/plugins/api-shared/azure/credentialsManagement/SelectAccountStep.test.ts b/src/plugins/api-shared/azure/credentialsManagement/SelectAccountStep.test.ts new file mode 100644 index 000000000..b7e261cb0 --- /dev/null +++ b/src/plugins/api-shared/azure/credentialsManagement/SelectAccountStep.test.ts @@ -0,0 +1,44 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { describe, expect, it, vi } from 'vitest'; +import { type CredentialsManagementWizardContext } from './CredentialsManagementWizardContext'; +import { SelectAccountStep } from './SelectAccountStep'; + +vi.mock('../../../../extensionVariables', () => ({ ext: { outputChannel: { info: vi.fn(), error: vi.fn() } } })); + +describe('SelectAccountStep', () => { + it('includes a newly invited tenant when opening Manage Azure Accounts with a warm tenant cache', async () => { + const account = { id: 'fixture-account', label: 'Fixture account' }; + const existing = { tenantId: 'existing-tenant', account }; + const invited = { tenantId: 'new-tenant', account }; + const getTenantsForAccount = vi.fn(async (_account: typeof account, options?: { noCache?: boolean }) => + options?.noCache ? [existing, invited] : [existing], + ); + const signIn = vi.fn().mockResolvedValue(true); + const showQuickPick = vi.fn(async (items: Promise) => + (await items).find((item) => item.account === account), + ); + const context = { + azureSubscriptionProvider: { + getAccounts: vi.fn().mockResolvedValue([account]), + getTenantsForAccount, + signIn, + }, + allAccountsWithTenantInfo: [], + telemetry: { properties: {}, measurements: {} }, + ui: { showQuickPick }, + } as unknown as CredentialsManagementWizardContext; + + await new SelectAccountStep().prompt(context); + + expect(context.selectedAccount).toBe(account); + expect(context.allAccountsWithTenantInfo[0].tenantsWithStatus.map(({ tenant }) => tenant)).toEqual([ + existing, + invited, + ]); + expect(signIn).toHaveBeenCalledWith({ tenantId: invited.tenantId, account }, { promptIfNeeded: false }); + }); +}); diff --git a/src/plugins/api-shared/azure/credentialsManagement/SelectAccountStep.ts b/src/plugins/api-shared/azure/credentialsManagement/SelectAccountStep.ts index 2bb6a85cf..eafe0e382 100644 --- a/src/plugins/api-shared/azure/credentialsManagement/SelectAccountStep.ts +++ b/src/plugins/api-shared/azure/credentialsManagement/SelectAccountStep.ts @@ -151,7 +151,7 @@ export class SelectAccountStep extends AzureWizardPromptStep - getUnfilteredAzureTenants(context.azureSubscriptionProvider), + getUnfilteredAzureTenants(context.azureSubscriptionProvider, true), ); // Check sign-in status for all tenants with bounded parallelism From d4dccaa16c87311fd81435f4ed7c66e48e40148d Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 09:42:06 +0000 Subject: [PATCH 070/380] docs: record PR2 Copilot review follow-up Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iterations/01-pr2-azureauth-review.md | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr2-azureauth-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr2-azureauth-review.md index b2d368818..9783e3d23 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr2-azureauth-review.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr2-azureauth-review.md @@ -57,3 +57,26 @@ reported unresolved types in the fresh worktree; it passed when rerun after the build generated the package declarations. No source changes were needed. Automated VSIX activation remains unavailable on this host; the operator accepted the manual OP-2 result and its coverage gaps above. + +## Copilot review follow-up + +The operator approved all four follow-ups: + +- [R1](https://github.com/microsoft/vscode-documentdb/pull/1111#discussion_r4643940342), `8de2a67da`: + Azure policy and app-registration failures no longer get misclassified as sign-in problems. + Typed additional-verification codes still report `signInRequired`. +- [R2](https://github.com/microsoft/vscode-documentdb/pull/1111#discussion_r4643940422), `df66e0172`: + A deep-link cache miss triggers a fresh listing before the extension offers tenant sign-in. + A successful tenant sign-in still triggers a fresh listing. Native SDK challenges are unchanged. +- [R3](https://github.com/microsoft/vscode-documentdb/pull/1111#discussion_r4643940489), `9805b7e25`: + A regression test uses the same stored subscription for two ARM operations across expiry. + Each operation creates its own management client, as production does. With the real SDK + pipeline and fake transport, the second request uses the fresh token without prompting or + relisting. Reusing one long-lived management client can send the previous token for an + additional request; changing that credential adapter is outside this follow-up. +- [R4](https://github.com/microsoft/vscode-documentdb/pull/1111#discussion_r4643940542), `490cf4376`: + Manage Azure Accounts fetches fresh tenants when loading its inventory. Routine Discovery + listing and wizard back-navigation keep their existing caching. + +Claude Opus 5.5 advised the dispositions (90%, 85%, 80%, and 85% confidence, respectively). +The build and all 109 focused tests passed. The earlier full Case 2 run predates these changes. From dfb6ae10ff7822020eabfcb23d3a27bdfb310dff Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 09:48:12 +0000 Subject: [PATCH 071/380] test: use inline type imports in Azure renewal regression Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/utils/azureClients.test.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/utils/azureClients.test.ts b/src/utils/azureClients.test.ts index 46aba7969..b5566190f 100644 --- a/src/utils/azureClients.test.ts +++ b/src/utils/azureClients.test.ts @@ -13,9 +13,9 @@ import * as vscode from 'vscode'; import { AzureSubscriptionProviderWithFilters } from '../plugins/api-shared/azure/AzureSubscriptionProviderWithFilters'; import { createResourceManagementClient } from './azureClients'; -import type { HttpClient, PipelineResponse } from '@azure/core-rest-pipeline'; -import type { AzureSubscription, TenantIdAndAccount } from '@microsoft/vscode-azext-azureauth'; -import type { IActionContext } from '@microsoft/vscode-azext-utils'; +import { type HttpClient, type PipelineResponse } from '@azure/core-rest-pipeline'; +import { type AzureSubscription, type TenantIdAndAccount } from '@microsoft/vscode-azext-azureauth'; +import { type IActionContext } from '@microsoft/vscode-azext-utils'; const { getSession, getAccounts } = vi.hoisted(() => { // Keep the real Azure utilities' extension registration from sending telemetry. From e751df24b9bfa0102edadc5bec1bf4cb38b2f4a6 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 09:54:04 +0000 Subject: [PATCH 072/380] fix: preserve shared decoded-password startup on cancellation (WI-4) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../DocumentDBClusterItem.test.ts | 37 ++++++++++++++++++- .../connections-view/DocumentDBClusterItem.ts | 6 +++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/src/tree/connections-view/DocumentDBClusterItem.test.ts b/src/tree/connections-view/DocumentDBClusterItem.test.ts index 9d0f8e0f4..98eec549f 100644 --- a/src/tree/connections-view/DocumentDBClusterItem.test.ts +++ b/src/tree/connections-view/DocumentDBClusterItem.test.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import { + UserCancelledError, type AzureWizard, type callWithTelemetryAndErrorHandling, type IActionContext, @@ -74,7 +75,10 @@ vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ }); try { return await callback(context); - } catch { + } catch (error) { + if (error instanceof UserCancelledError) { + context.telemetry.properties.result = 'Canceled'; + } return undefined; } }, @@ -271,6 +275,37 @@ describe('connect request telemetry', () => { expect(connectEvent()).toMatchObject({ connectionResult: 'failed', connectionCorrelationId: 'failed-attempt' }); }); + it('cancels the decoded-password retry without reporting another failure or clearing shared state', async (): Promise => { + const connection = makeConnection('mongodb://localhost:27017/', AuthMethodId.NativeAuth); + connection.secrets.nativeAuthConfig = { connectionUser: 'test-user', connectionPassword: 'test%40password' }; + vi.mocked(ConnectionStorageService.get).mockResolvedValue(connection); + const connectInteractive = vi.mocked(ClustersClient.connectInteractive); + connectInteractive + .mockRejectedValueOnce(new Error('Authentication failed.')) + .mockRejectedValueOnce(new UserCancelledError()); + showErrorMessage.mockResolvedValueOnce('Try with decoded password'); + const item = makeItem(); + + await expect(item.connect()).resolves.toBeNull(); + + expect(connectInteractive).toHaveBeenCalledTimes(2); + expect(showErrorMessage).toHaveBeenCalledExactlyOnceWith( + expect.any(String), + expect.objectContaining({ modal: true }), + 'Try with decoded password', + ); + const deleteClient = vi.mocked(ClustersClient.deleteClient); + expect(deleteClient).toHaveBeenCalledExactlyOnceWith('stable-id'); + expect(deleteClient.mock.invocationCallOrder[0]).toBeLessThan(connectInteractive.mock.invocationCallOrder[1]); + expect(CredentialCache.deleteCredentials).not.toHaveBeenCalled(); + expect(item.lastConnectionOutcome).toBe('canceled'); + expect(connectEvent()).toMatchObject({ + result: 'Canceled', + connectionResult: 'cancelled', + urlDecodePasswordResult: 'cancelled', + }); + }); + it('reports a successful connection with its connection ID', async (): Promise => { vi.mocked(ClustersClient.connectInteractive).mockResolvedValue({ connectionCorrelationId: 'attempt', diff --git a/src/tree/connections-view/DocumentDBClusterItem.ts b/src/tree/connections-view/DocumentDBClusterItem.ts index 2b6497b94..37ee132ca 100644 --- a/src/tree/connections-view/DocumentDBClusterItem.ts +++ b/src/tree/connections-view/DocumentDBClusterItem.ts @@ -308,6 +308,12 @@ export class DocumentDBClusterItem extends ClusterItemBase Date: Mon, 23 Nov 2026 09:54:04 +0000 Subject: [PATCH 073/380] fix: keep passive index counts from starting clients (WI-4) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/tree/documentdb/IndexesItem.test.ts | 6 +++++- src/tree/documentdb/IndexesItem.ts | 13 +++++-------- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/src/tree/documentdb/IndexesItem.test.ts b/src/tree/documentdb/IndexesItem.test.ts index 350f0625a..3d67ef096 100644 --- a/src/tree/documentdb/IndexesItem.test.ts +++ b/src/tree/documentdb/IndexesItem.test.ts @@ -98,7 +98,7 @@ describe('compareIndexNames', () => { describe('IndexesItem - async index loading', () => { const cluster = { - treeId: 'cluster1', + treeId: 'folder/cluster1', clusterId: 'cluster1', dbExperience: { api: 'MongoDB' } as unknown as Experience, } as TreeCluster; @@ -137,6 +137,9 @@ describe('IndexesItem - async index loading', () => { item.loadIndexCount(); await flushAsync(); + expect(ClustersClient.getClient).toHaveBeenCalledWith(cluster.clusterId, undefined, undefined, 'treeChildren', { + background: true, + }); expect(listIndexesMock).toHaveBeenCalledTimes(1); expect(notifyChildrenChangedMock).toHaveBeenCalledWith(item.id); expect(item.getTreeItem().description).toContain('3'); @@ -158,6 +161,7 @@ describe('IndexesItem - async index loading', () => { const children = await item.getChildren(); + expect(ClustersClient.getClient).toHaveBeenCalledWith(cluster.clusterId, undefined, undefined, 'treeChildren'); expect(listIndexesMock).toHaveBeenCalledTimes(1); expect(children).toHaveLength(3); expect(item.getTreeItem().description).toContain('3'); diff --git a/src/tree/documentdb/IndexesItem.ts b/src/tree/documentdb/IndexesItem.ts index 651178323..885ef817e 100644 --- a/src/tree/documentdb/IndexesItem.ts +++ b/src/tree/documentdb/IndexesItem.ts @@ -98,7 +98,7 @@ export class IndexesItem implements TreeElement, TreeElementWithExperience, Tree private async fetchAndUpdateCount(): Promise { try { - const indexes = await this.fetchIndexes(); + const indexes = await this.fetchIndexes({ background: true }); this.indexCount = indexes.length; } catch { meterSilentCatch('IndexesItem_loadIndexCount'); @@ -111,13 +111,10 @@ export class IndexesItem implements TreeElement, TreeElementWithExperience, Tree } } - private async fetchIndexes(): Promise { - const client: ClustersClient = await ClustersClient.getClient( - this.cluster.clusterId, - undefined, - undefined, - 'treeChildren', - ); + private async fetchIndexes(options?: { readonly background?: boolean }): Promise { + 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); // Try to get search indexes, but silently fail if not supported by the platform From 1d51999c6eff38dce14bfc4919dbc48cfb635388 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 09:56:03 +0000 Subject: [PATCH 074/380] docs: record PR3 review and defer stable tunnel fingerprints Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../features/connection-lifecycle/README.md | 2 +- .../connection-lifecycle/decisions.md | 5 +++ .../iterations/01-dev-plan.md | 8 ++++- .../iterations/01-implementation-plan.md | 5 +-- .../01-pr3-client-identity-review.md | 31 +++++++++++++++++++ 5 files changed, 47 insertions(+), 4 deletions(-) create mode 100644 docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr3-client-identity-review.md diff --git a/docs/ai-and-plans/features/connection-lifecycle/README.md b/docs/ai-and-plans/features/connection-lifecycle/README.md index c53663161..87b66ed56 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/README.md +++ b/docs/ai-and-plans/features/connection-lifecycle/README.md @@ -74,7 +74,7 @@ See [decisions.md](./decisions.md): - 0006 delivery through a feature branch with stacked sub-PRs, shipped once; - 0007 the Disconnect choice is a modal, not remembered, with a setting for the default; - 0008 the azext stack is upgraded as high as viable, with Azure Resources as the reference; -- 0009 Kubernetes tunnel recovery, case handling and wider network-resilience testing move to #1105; +- 0009 Kubernetes tunnel recovery, stable tunnel fingerprints, case handling and wider network-resilience testing move to #1105; - 0010 rely on the server to reject expired tokens; same-identity client replacement is transparent; - 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; diff --git a/docs/ai-and-plans/features/connection-lifecycle/decisions.md b/docs/ai-and-plans/features/connection-lifecycle/decisions.md index 42dc1c27a..dcbef7f08 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/decisions.md +++ b/docs/ai-and-plans/features/connection-lifecycle/decisions.md @@ -245,6 +245,11 @@ Moved to [#1105](https://github.com/microsoft/vscode-documentdb/issues/1105), to - Kubernetes API credential expiry (the AKS exec plugin); - a network-resilience test matrix beyond OT-4, including a Kubernetes acceptance test. +**Amended by the operator on 2026-11-23:** Stable fingerprints across Kubernetes forwarded-port +changes also move to #1105. Until then, keep the identity check unchanged: if a closed binding +still exists and the forwarded port changes, automatic replacement can reject it as an identity +change. Do not ignore port changes for ordinary connections or bypass the fingerprint check. + **Stays in iteration 1:** generic idle and network-drop recovery. That means closed-client and transient classification, the cancelled-reuse fix, closed-client replacement and OT-4, which together are #1102's "recover on the next operation without a restart". 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 150197987..74bf7788e 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 @@ -949,7 +949,8 @@ shim (0005). - another user changes it; - an edited connection string changes it; - two managed identity client IDs differ; - - a tunnel's local port change keeps it. + - stable fingerprints across Kubernetes local-port changes are deferred to #1105 + (operator amendment to decision 0009); automatic replacement still rejects a mismatch. 2. **Generation.** - Keep a static `Map` that only ever increases and is never cleared. - Each `ClustersClient` instance records `generation`, `fingerprint`, `createdAt` and its credentials @@ -1118,6 +1119,11 @@ shim (0005). approved. The leader checked the topology event and caller, epoch, and latch checks against the advised WI-4e contract. Build and 116 focused tests passed. The cancellation and stale retry tests now exercise a pending replacement rather than an obsolete cached `connect()` call. +- **PR3 pre-review (2026-11-23):** The operator approved two scoped fixes: preserve the shared + startup when the decoded-password wait is canceled (`e751df24b`), and keep passive index counts + from starting a client (`db01f24a5`). Both used `gpt-6.2-sol`; build and 95 focused tests passed. + The operator also approved deferring stable Kubernetes tunnel fingerprints to #1105. See the + [review record](./01-pr3-client-identity-review.md) for advisor confidence and verification. --- 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 36a2570e0..8b0bb4bd0 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 @@ -278,8 +278,9 @@ In [ClustersClient.ts](../../../../../src/documentdb/ClustersClient.ts): The fingerprint is derived from **what was used to connect**, not from the current `CredentialCache`. The helper alone returned `native:sam` for two hosts and two auth databases. Bind the logical - deployment plus the effective principal (including auth source); for tunnels use the provider's - target, not its temporary local port. Test managed identity using the actual runtime credential + deployment plus the effective principal (including auth source). Using a stable Kubernetes + provider target instead of the forwarded local port is deferred to #1105 (decision 0009). + Test managed identity using the actual runtime credential shape, a password-only change, and the same username on a different deployment or auth source. - **Fix:** cancelling a _cached_ reuse must not close the shared client. diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr3-client-identity-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr3-client-identity-review.md new file mode 100644 index 000000000..04992ddf5 --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr3-client-identity-review.md @@ -0,0 +1,31 @@ +--- +feature: connection-lifecycle +kind: review +status: active +created: 2026-11-23 +--- + +# PR3 pre-review: client identity and lifecycle + +Reviewed [PR #1113](https://github.com/microsoft/vscode-documentdb/pull/1113) at `657c9b2cf`, +against `96085c1dd`. GPT-6.2-Sol performed the initial review and Claude Opus 5.5 validated +the findings. The operator approved the dispositions on 2026-11-23. + +| Finding | Approved disposition | +| --- | --- | +| Canceling the decoded-password retry could invalidate a startup shared by another caller. | Fix in PR3 (90% advisor confidence). Treat the canceled wait like the first attempt: record cancellation without showing another failure modal or evicting the shared client or credentials. | +| The passive index-count badge could start or replace a client. | Fix in PR3 (95%). Apply the existing background restriction to the count, not to explicit Indexes expansion. | +| A changed Kubernetes forwarded port could cause an identity mismatch if the old closed binding is still cached. | Defer stable tunnel fingerprints to [#1105](https://github.com/microsoft/vscode-documentdb/issues/1105) (85% confidence in the finding). Keep the identity check in place, per [decision 0009](../decisions.md#0009-kubernetes-tunnel-recovery-cluster-id-case-handling-and-wider-network-resilience-testing-move-to-1105). | + +## Implementation and verification + +- `e751df24b` (`gpt-6.2-sol`) preserves the shared startup and credentials when the + decoded-password wait is canceled. Its regression checks cancellation reporting, the existing + pre-retry eviction, and the absence of failure UI or cleanup after the canceled wait. +- `db01f24a5` (`gpt-6.2-sol`) marks only the passive index count as background. Tests pin + the background flag and preserve the foreground expansion call. +- The operator approved keeping the fingerprint check unchanged and deferring stable tunnel + fingerprints. The feature decisions and both plans record this limitation. + +Case 1: the build and 95 focused tests passed with both fixes. Full Case 2 verification is +pending. From f2b4641e638ffb10b5588daeb54d8fab88325800 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 10:01:34 +0000 Subject: [PATCH 075/380] fix: verify Azure ARM ESM imports without the legacy alias (WI-3) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- build/verification/README.md | 14 +++--- .../lowered-import/azureauthLowering.cjs | 14 ------ build/verification/lowered-import/check.cjs | 49 ++++++++++--------- .../lowered-import/lowered-import.test.cjs | 14 ++---- build/verification/lowered-import/probe.mjs | 8 +-- build/verification/vite-host-probe.cjs | 14 ++++-- build/vite/README.md | 47 ++++++++---------- vite.config.ext.mjs | 12 +---- 8 files changed, 73 insertions(+), 99 deletions(-) delete mode 100644 build/verification/lowered-import/azureauthLowering.cjs diff --git a/build/verification/README.md b/build/verification/README.md index f4ded0576..df6e6564e 100644 --- a/build/verification/README.md +++ b/build/verification/README.md @@ -157,13 +157,13 @@ node build/verification/bson-identity/check.cjs # identity node build/verification/bson-identity/check.cjs --prove # identity, then the alias-removed control ``` -[`lowered-import/check.cjs`](./lowered-import/check.cjs) builds the same way (shared -[`vite-host-probe.cjs`](./vite-host-probe.cjs)) a CommonJS module containing azureauth's lowered -`Promise.resolve().then(() => require('@azure/arm-resources-subscriptions'))` and requires the -result to expose `SubscriptionClient` (G5-I01, [Vite rationale](../vite/README.md)). Its negative -control removes the package's CommonJS alias; Rolldown 1.0.3 then emits a call to the ESM -initializer, and the result must be `undefined`. Both run in `npm run test:verification`; add -`--prove` to the standalone command for the control. +### Azure ARM ESM (runtime) + +[`lowered-import/check.cjs`](./lowered-import/check.cjs) uses the same production host probe to +bundle the three ARM subscription subpaths azureauth v6 imports. It checks that the bundle +exports `createSubscription` and both list functions, and that the ARM modules in its graph +come from `dist/esm`. This runs in `npm run test:verification` and replaces the historical +G5-I01 alias-removal control, which no longer reproduced after the SDK upgrade. These probes build and run bundles instead of inspecting the packaged artifact, so they are not part of L1, which stays offline and build-free for the ADO release build. diff --git a/build/verification/lowered-import/azureauthLowering.cjs b/build/verification/lowered-import/azureauthLowering.cjs deleted file mode 100644 index 2c0cdb0e1..000000000 --- a/build/verification/lowered-import/azureauthLowering.cjs +++ /dev/null @@ -1,14 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - -'use strict'; -Object.defineProperty(exports, '__esModule', { value: true }); -exports.loadArmSubscriptions = loadArmSubscriptions; - -// TypeScript's CommonJS lowering of `await import(...)`, character for character as in -// @microsoft/vscode-azext-azureauth's VSCodeAzureSubscriptionProvider.getSubscriptionClient. -function loadArmSubscriptions() { - return Promise.resolve().then(() => require('@azure/arm-resources-subscriptions')); -} diff --git a/build/verification/lowered-import/check.cjs b/build/verification/lowered-import/check.cjs index f846b8bf9..0fe760391 100644 --- a/build/verification/lowered-import/check.cjs +++ b/build/verification/lowered-import/check.cjs @@ -3,8 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -// G5-I01: a lowered `import()` of @azure/arm-resources-subscriptions must yield its namespace -// when built with the shipped host config (production), which pins the package to CommonJS. +// Check azureauth's ARM subscription import routes with the shipped production host config. const assert = require('node:assert/strict'); const fs = require('node:fs'); const os = require('node:os'); @@ -14,42 +13,48 @@ const { buildHostProbes } = require('../vite-host-probe.cjs'); const specifier = '@azure/arm-resources-subscriptions'; -async function checkLoweredImport({ withoutAlias = false } = {}) { +async function checkAzureArmEsm() { const outputPath = fs.mkdtempSync(path.join(os.tmpdir(), 'documentdb-lowered-import-')); try { - await buildHostProbes({ + const chunks = await buildHostProbes({ input: { loweredImport: path.join(__dirname, 'probe.mjs') }, outputPath, - pinned: specifier, - withoutAlias, }); - const { loadArmSubscriptions } = await import(pathToFileURL(path.join(outputPath, 'loweredImport.mjs'))); - const namespace = await loadArmSubscriptions(); - assert.equal( - typeof namespace?.SubscriptionClient, - 'function', - `Lowered import() of ${specifier} returned ${namespace === undefined ? 'undefined' : 'an object without SubscriptionClient'}, not its namespace`, + const armModules = chunks + .flatMap((chunk) => chunk.moduleIds) + .flatMap((id) => { + const match = /\/node_modules\/@azure\/arm-resources-subscriptions\/(.+)$/.exec( + id.replaceAll('\\', '/'), + ); + return match ? [match[1]] : []; + }); + assert.ok(armModules.length > 0, `Host probe did not bundle any ${specifier} modules`); + assert.deepEqual( + armModules.filter((id) => !id.startsWith('dist/esm/')), + [], + `Host probe bundled ${specifier} modules outside dist/esm`, ); - return { exports: Object.keys(namespace).length }; + + const runtime = await import(pathToFileURL(path.join(outputPath, 'loweredImport.mjs'))); + for (const name of ['createSubscription', 'listSubscriptions', 'listTenants']) { + assert.equal(typeof runtime[name], 'function', `Bundled ${specifier} export ${name} is not a function`); + } + return armModules; } finally { fs.rmSync(outputPath, { recursive: true, force: true }); } } -async function main(args) { - const result = await checkLoweredImport({ withoutAlias: args.includes('--without-alias') }); - console.log(`PASS: lowered import() of ${specifier} returned its namespace (${result.exports} exports)`); - if (args.includes('--prove')) { - await assert.rejects(checkLoweredImport({ withoutAlias: true }), /returned undefined, not its namespace/); - console.log(`PASS: ${specifier}-alias-removed rejected for the expected reason`); - } +async function main() { + const armModules = await checkAzureArmEsm(); + console.log(`PASS: ${specifier} runtime exports are functions (${armModules.length} dist/esm modules)`); } if (require.main === module) { - main(process.argv.slice(2)).catch((error) => { + main().catch((error) => { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; }); } -module.exports = { checkLoweredImport }; +module.exports = { checkAzureArmEsm }; diff --git a/build/verification/lowered-import/lowered-import.test.cjs b/build/verification/lowered-import/lowered-import.test.cjs index 372f655d9..f61f8461b 100644 --- a/build/verification/lowered-import/lowered-import.test.cjs +++ b/build/verification/lowered-import/lowered-import.test.cjs @@ -3,17 +3,9 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -const assert = require('node:assert/strict'); const test = require('node:test'); -const { checkLoweredImport } = require('./check.cjs'); +const { checkAzureArmEsm } = require('./check.cjs'); -test('azureauth-style lowered import() of @azure/arm-resources-subscriptions yields its namespace', async () => { - await checkLoweredImport(); -}); - -test('negative control: without the CommonJS alias, the lowered import() yields undefined (G5-I01)', async () => { - await assert.rejects( - checkLoweredImport({ withoutAlias: true }), - /Lowered import\(\) of @azure\/arm-resources-subscriptions returned undefined, not its namespace/, - ); +test('azureauth ARM subscription subpaths expose runtime functions and bundle only ESM modules', async () => { + await checkAzureArmEsm(); }); diff --git a/build/verification/lowered-import/probe.mjs b/build/verification/lowered-import/probe.mjs index 321b80039..2992a4c14 100644 --- a/build/verification/lowered-import/probe.mjs +++ b/build/verification/lowered-import/probe.mjs @@ -3,7 +3,9 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -// Built with `vite.config.ext.mjs` as a host entry, as the extension bundles azureauth's CommonJS. -import { loadArmSubscriptions } from './azureauthLowering.cjs'; +// Match the static imports in azureauth's ESM AzureSubscriptionProviderBase. +import { createSubscription } from '@azure/arm-resources-subscriptions/api'; +import { list as listSubscriptions } from '@azure/arm-resources-subscriptions/api/subscriptions'; +import { list as listTenants } from '@azure/arm-resources-subscriptions/api/tenants'; -export { loadArmSubscriptions }; +export { createSubscription, listSubscriptions, listTenants }; diff --git a/build/verification/vite-host-probe.cjs b/build/verification/vite-host-probe.cjs index 925993f9d..f5efb6565 100644 --- a/build/verification/vite-host-probe.cjs +++ b/build/verification/vite-host-probe.cjs @@ -11,15 +11,19 @@ const { pathToFileURL } = require('node:url'); const repository = path.resolve(__dirname, '../..'); /** - * @param {{ input: Record, outputPath: string, pinned: string, withoutAlias: boolean }} options - * `pinned` is a bare specifier that `vite.config.ext.mjs` must alias; `withoutAlias` drops that alias. + * @param {{ input: Record, outputPath: string, pinned?: string, withoutAlias?: boolean }} options + * When supplied, `pinned` must be aliased by `vite.config.ext.mjs`; `withoutAlias` drops that alias. */ async function buildHostProbes({ input, outputPath, pinned, withoutAlias }) { const { createBuilder } = await import('vite'); const { default: createConfig } = await import(pathToFileURL(path.join(repository, 'vite.config.ext.mjs'))); const config = await createConfig({ mode: 'production', command: 'build' }); - const pin = config.resolve.alias.find((alias) => alias.find instanceof RegExp && alias.find.test(pinned)); - assert.ok(pin, `vite.config.ext.mjs no longer pins ${pinned} (resolve.alias)`); + let aliases = config.resolve.alias; + if (pinned !== undefined) { + const pin = aliases.find((alias) => alias.find instanceof RegExp && alias.find.test(pinned)); + assert.ok(pin, `vite.config.ext.mjs no longer pins ${pinned} (resolve.alias)`); + if (withoutAlias) aliases = aliases.filter((alias) => alias !== pin); + } const host = config.environments.host; let chunks; const builder = await createBuilder({ @@ -29,7 +33,7 @@ async function buildHostProbes({ input, outputPath, pinned, withoutAlias }) { logLevel: 'silent', resolve: { ...config.resolve, - alias: config.resolve.alias.filter((alias) => !(withoutAlias && alias === pin)), + alias: aliases, }, environments: { host: { diff --git a/build/vite/README.md b/build/vite/README.md index bfa00393b..91f2c9abf 100644 --- a/build/vite/README.md +++ b/build/vite/README.md @@ -213,18 +213,13 @@ rather than reproducing webpack's CommonJS resolution globally. The `module` con `tslib.es6.mjs`, so no `tslib` alias is needed. Treat resolution changes as runtime changes, not just size optimizations. -One targeted exception is `resolve.alias` for `/^@azure\/arm-resources-subscriptions$/`, pointing -to `require.resolve('@azure/arm-resources-subscriptions')`, its CommonJS `dist/index.js`. -**G5-I01:** azureauth uses `Promise.resolve().then(() => require('x'))`, TypeScript's lowered -dynamic import. When `x` resolved to ESM, Rolldown 1.0.3 emitted a call to its ESM initializer -that returned `undefined`, not the module namespace; reading `SubscriptionClient` then failed. -Pinning this package to CommonJS restores the expected result without rewriting dependencies. -`TODO(#990)` tracks upgrading azureauth to real `import()` and removing the alias in -[#990](https://github.com/microsoft/vscode-documentdb/issues/990). There is no L1 invariant for -this lowering bug, and L3 does not call Azure discovery; the build-time -[lowered-import probe](../verification/README.md#bson-identity-runtime) bundles the same lowered -`require` with this config and fails without the alias. Re-test discovery and -both azureauth subscription-provider paths when removing the workaround. +The older azureauth CommonJS build needed an alias for `@azure/arm-resources-subscriptions` +because Rolldown could return `undefined` instead of its module namespace (G5-I01). +[#990](https://github.com/microsoft/vscode-documentdb/issues/990) removed that workaround: +azureauth v6 uses static ESM subpath imports. The +[Azure ARM ESM probe](../verification/README.md#azure-arm-esm-runtime) checks those exports +and their ESM provenance with the production host config. L3 activation does not exercise +live Azure Discovery. ### Externals: deliberate runtime requests @@ -316,20 +311,20 @@ for a downloaded VSIX; unrelated local reports cannot establish provenance. See [verification commands and limits](../verification/README.md) for complete recipes. -| Setting / boundary | Guard | -| ---------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `views.js`, `preserveEntrySignatures`, relative chunk/asset URLs | L1 named `render`, packaged literal imports / `new URL(..., import.meta.url)` targets, report hashes; L2 network, CSP and preload diagnostics. | -| `cssCodeSplit`, CSS injection, fonts-as-files | L2 computed styles, font requests and marked-CSS removal negative control; L1 literal asset targets. | -| `React.lazy`, group priority, no catch-all vendor | L1 registry-backed lazy chunks and lightweight-view exclusions; L2 fetched chunks and grid interop. | -| Monaco worker format and Blob trampoline | L1 worker targets / nonliteral import budget; L2 actual editor worker responses; installed-VSIX real-origin check. | -| Dev origin, preamble, optimization/warmup, readiness hooks | L2-dev source scenarios; F5/HMR/rapid-save checks. L1 rejects the production dev-server strings; it does not test HMR. | -| Host ESM loader, strict exports, banner/global handling | L1 required entries, extension dynamic boundary and Kubernetes startup exclusion; L3 activation, late commands, clean logs and activation-error proof. | -| Host `keepNames` | L1 `keptClassName` (`UserCancelledError`) and `keepnames-class-name-lost` negative control. | -| BSON aliases | L1 implementation count per graph; runtime `bson-identity` probe with alias-removed control. | -| Azure alias / optional externals / default resolution conditions | L3 normal startup only; targeted discovery, auth, proxy and worker tests for paths it does not exercise. G5-I01 has no dedicated automated invariant. | -| CommonJS plugin and copied assets | L1 required `.cjs`, CommonJS `import.meta` rejection, manifest paths and `runtimeAssets`; TS-server completions/hover check separately. | -| Bundle-report ownership / `append` | L1 report-to-VSIX hashes and host-owned graph closure; proof controls reject missing/unowned chunks. | -| Overall loading cost | Warning-only [size report](../verification/README.md#size-report-warning-only): full host graphs, `mainStartup`, views entry/per-view JavaScript closures, `viewsAssets` for all report-owned non-script view assets, each worker and compressed VSIX, compared with the base branch on PRs. A smaller entry alone is not a smaller view. | +| Setting / boundary | Guard | +| ------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `views.js`, `preserveEntrySignatures`, relative chunk/asset URLs | L1 named `render`, packaged literal imports / `new URL(..., import.meta.url)` targets, report hashes; L2 network, CSP and preload diagnostics. | +| `cssCodeSplit`, CSS injection, fonts-as-files | L2 computed styles, font requests and marked-CSS removal negative control; L1 literal asset targets. | +| `React.lazy`, group priority, no catch-all vendor | L1 registry-backed lazy chunks and lightweight-view exclusions; L2 fetched chunks and grid interop. | +| Monaco worker format and Blob trampoline | L1 worker targets / nonliteral import budget; L2 actual editor worker responses; installed-VSIX real-origin check. | +| Dev origin, preamble, optimization/warmup, readiness hooks | L2-dev source scenarios; F5/HMR/rapid-save checks. L1 rejects the production dev-server strings; it does not test HMR. | +| Host ESM loader, strict exports, banner/global handling | L1 required entries, extension dynamic boundary and Kubernetes startup exclusion; L3 activation, late commands, clean logs and activation-error proof. | +| Host `keepNames` | L1 `keptClassName` (`UserCancelledError`) and `keepnames-class-name-lost` negative control. | +| BSON aliases | L1 implementation count per graph; runtime `bson-identity` probe with alias-removed control. | +| Azure ARM ESM / optional externals / default resolution conditions | Production host probe for ARM exports and ESM provenance; L3 activation; targeted discovery, auth, proxy and worker tests for paths activation does not exercise. | +| CommonJS plugin and copied assets | L1 required `.cjs`, CommonJS `import.meta` rejection, manifest paths and `runtimeAssets`; TS-server completions/hover check separately. | +| Bundle-report ownership / `append` | L1 report-to-VSIX hashes and host-owned graph closure; proof controls reject missing/unowned chunks. | +| Overall loading cost | Warning-only [size report](../verification/README.md#size-report-warning-only): full host graphs, `mainStartup`, views entry/per-view JavaScript closures, `viewsAssets` for all report-owned non-script view assets, each worker and compressed VSIX, compared with the base branch on PRs. A smaller entry alone is not a smaller view. | L2 and L2-dev use fixture backends and ordinary browser origins. L3 is installed-VSIX activation, not discovery, playground execution or a complete editor workflow suite. Do not weaken the CSP diff --git a/vite.config.ext.mjs b/vite.config.ext.mjs index 22e9b3751..b31235d2c 100644 --- a/vite.config.ext.mjs +++ b/vite.config.ext.mjs @@ -147,17 +147,7 @@ export default defineConfig(({ mode }) => { 'process.env.DEVSERVER': JSON.stringify(isDev ? 'true' : ''), }, resolve: { - alias: [ - { find: /^bson$/, replacement: bsonEntry }, - // G5-I01: Rolldown 1.0.3 drops the namespace of azureauth's lowered import() in - // VSCodeAzureSubscriptionProvider and AzureDevOpsSubscriptionProvider. - // Pin CommonJS to restore webpack's behaviour for this package. - // TODO(#990): Remove when @microsoft/vscode-azext-azureauth uses real import(). - { - find: /^@azure\/arm-resources-subscriptions$/, - replacement: require.resolve('@azure/arm-resources-subscriptions'), - }, - ], + alias: [{ find: /^bson$/, replacement: bsonEntry }], }, builder: { async buildApp(builder) { From 0ba6843eba19ed3293d721d0ed4968dea441853a Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 10:06:19 +0000 Subject: [PATCH 076/380] docs: record Azure bundle verification and OP-2 repeat Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iterations/01-pr2-azureauth-review.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr2-azureauth-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr2-azureauth-review.md index 9783e3d23..b1a928d9e 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr2-azureauth-review.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr2-azureauth-review.md @@ -80,3 +80,15 @@ The operator approved all four follow-ups: Claude Opus 5.5 advised the dispositions (90%, 85%, 80%, and 85% confidence, respectively). The build and all 109 focused tests passed. The earlier full Case 2 run predates these changes. + +## Azure ESM bundle verification + +The operator approved removing the obsolete CommonJS alias and replacing its historical +expected-failure test. In `f2b4641e6`, the production host probe verifies that the Azure ARM +subscription and tenant exports are callable and that the bundle uses ESM modules. The probe, +both BSON controls, all 267 verification tests, and inspection of the rebuilt VSIX passed. + +Two builds of the new revision had identical VSIX entry contents. Compared with the build +before alias removal, the host chunks kept the same module membership, but some chunk bytes +and names changed. The earlier live OP-2 result therefore does not verify this package. +**OP-2 repeat pending** on the VSIX built from `f2b4641e6`. From 19740452ad1ea85aa833f8e998d97724266d0ead Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 11:19:36 +0000 Subject: [PATCH 077/380] docs: record operator acceptance of the repeated OP-2 test Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../connection-lifecycle/iterations/01-dev-plan.md | 4 ++++ .../iterations/01-pr2-azureauth-review.md | 7 ++++++- 2 files changed, 10 insertions(+), 1 deletion(-) 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 ca34c2e0d..2c419c883 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 @@ -907,6 +907,10 @@ shim (0005). The build, installed dependency tree, bundle inspection, and operator-accepted OP-2 support this choice. L1 uses the same azureauth and Azure Resources API versions and does not reduce the remaining risks. The untested OP-2 cases above remain unverified. +- **OP-2 repeat accepted (2026-11-23):** After the alias removal changed the packaged payload, + the operator tested the PR2 CI-built VSIX and cleared the gate. The + [PR2 review record](./01-pr2-azureauth-review.md#azure-esm-bundle-verification) lists what + passed and what was not tested. CP-W3 still retains L2. --- diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr2-azureauth-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr2-azureauth-review.md index b1a928d9e..d5e6d098f 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr2-azureauth-review.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr2-azureauth-review.md @@ -91,4 +91,9 @@ both BSON controls, all 267 verification tests, and inspection of the rebuilt VS Two builds of the new revision had identical VSIX entry contents. Compared with the build before alias removal, the host chunks kept the same module membership, but some chunk bytes and names changed. The earlier live OP-2 result therefore does not verify this package. -**OP-2 repeat pending** on the VSIX built from `f2b4641e6`. +**OP-2 repeat accepted (2026-11-23):** On the PR2 CI-built VSIX, the operator confirmed +that the Discovery roots loaded, filters and Refresh/Retry worked, signing out and back +in worked, and New Connection and the Azure Resources nodes worked. Update Credentials, +deep links, and partial-result handling were not tested. No separate account-switch, +sovereign-cloud, or MFA result was reported. The operator accepted these coverage gaps +and cleared the gate. From be211c14cc981dbe91af6909b973d22b7fd8c6d0 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 11:32:28 +0000 Subject: [PATCH 078/380] test: keep connection-string recovery coverage on the interactive path Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../updateConnectionString.test.ts | 22 ++++++++++--------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/src/commands/updateConnectionString/updateConnectionString.test.ts b/src/commands/updateConnectionString/updateConnectionString.test.ts index 5c09c56c8..d28dc9029 100644 --- a/src/commands/updateConnectionString/updateConnectionString.test.ts +++ b/src/commands/updateConnectionString/updateConnectionString.test.ts @@ -85,7 +85,7 @@ vi.mock('../../services/connectionStorageService', async (importOriginal) => ({ ConnectionStorageService: { get: vi.fn(), save: vi.fn() }, })); vi.mock('../../documentdb/ClustersClient', () => ({ - ClustersClient: { getClient: vi.fn(), deleteClient: vi.fn(), exists: vi.fn() }, + ClustersClient: { connectInteractive: vi.fn(), deleteClient: vi.fn(), exists: vi.fn() }, })); vi.mock('../../services/connectionReachabilityService', () => ({ ConnectionReachabilityService: { ensureReachable: vi.fn() }, @@ -166,7 +166,7 @@ describe('updateConnectionString rejected-destination recovery', () => { items.find((entry) => entry.authMethod === AuthMethodId.NoAuth), ); CredentialCache.setAuthCredentials('stable-id', AuthMethodId.ManagedIdentity, originalUri); - vi.mocked(ClustersClient.getClient).mockRejectedValue( + vi.mocked(ClustersClient.connectInteractive).mockRejectedValue( new EntraDestinationRejectedError({ firstHost: 'old.example.com', hostCount: 1 }), ); }); @@ -205,14 +205,16 @@ describe('updateConnectionString rejected-destination recovery', () => { expect(deleteCredentials.mock.invocationCallOrder[0]).toBeLessThan(resetError.mock.invocationCallOrder[0]); expect(resetError.mock.invocationCallOrder[0]).toBeLessThan(refresh.mock.invocationCallOrder[0]); const client = { listDatabases: vi.fn().mockResolvedValue([]), connectionCorrelationId: 'retry' }; - vi.mocked(ClustersClient.getClient).mockImplementation(async (clusterId): Promise => { - expect(clusterId).toBe('stable-id'); - expect(CredentialCache.getCredentials(clusterId)).toMatchObject({ - connectionString: newUri, - authMechanism: expectedMethod, - }); - return client as unknown as ClustersClient; - }); + vi.mocked(ClustersClient.connectInteractive).mockImplementation( + async (clusterId): Promise => { + expect(clusterId).toBe('stable-id'); + expect(CredentialCache.getCredentials(clusterId)).toMatchObject({ + connectionString: newUri, + authMechanism: expectedMethod, + }); + return client as unknown as ClustersClient; + }, + ); const retriedChildren = await provider.getChildren(item); From 57cd2db144b880b9fb24186eda7f6bd971d49c3c Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 11:32:28 +0000 Subject: [PATCH 079/380] chore: regenerate localization and format the WI-4 changes Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- l10n/bundle.l10n.json | 4 +++- src/documentdb/ClustersClient.test.ts | 15 ++++++++++++--- src/documentdb/ClustersClient.ts | 8 ++++++-- src/documentdb/ConnectionUnavailableError.ts | 4 +++- .../auth/MicrosoftEntraIDAuthHandler.test.ts | 5 ++++- src/documentdb/connectionFingerprint.test.ts | 4 +++- src/tree/documentdb/DatabaseItem.ts | 12 +++++++++--- 7 files changed, 40 insertions(+), 12 deletions(-) diff --git a/l10n/bundle.l10n.json b/l10n/bundle.l10n.json index a07aa3619..91360cd83 100644 --- a/l10n/bundle.l10n.json +++ b/l10n/bundle.l10n.json @@ -2016,9 +2016,9 @@ "No copyable indexes are selected.": "No copyable indexes are selected.", "No credentials found for cluster \"{0}\"": "No credentials found for cluster \"{0}\"", "No credentials found for cluster {0}": "No credentials found for cluster {0}", - "No credentials found for id {clusterId}": "No credentials found for id {clusterId}", "No credentials found for the query playground connection.": "No credentials found for the query playground connection.", "No credentials found for the selected cluster.": "No credentials found for the selected cluster.", + "No credentials found.": "No credentials found.", "No databases in this cluster": "No databases in this cluster", "No databases visible": "No databases visible", "No diagnostic timeouts": "No diagnostic timeouts", @@ -2949,6 +2949,7 @@ "The connection already exists in the Connections view. Opening it selects and expands it there.": "The connection already exists in the Connections view. Opening it selects and expands it there.", "The connection appears in the Connections view, ready to open.": "The connection appears in the Connections view, ready to open.", "The connection attempt failed, and the diagnosis could not identify a more specific cause.": "The connection attempt failed, and the diagnosis could not identify a more specific cause.", + "The connection changed while it was opening. Try again.": "The connection changed while it was opening. Try again.", "The connection closed during the secure handshake, before a certificate arrived.": "The connection closed during the secure handshake, before a certificate arrived.", "The connection could not be prepared for diagnosis.": "The connection could not be prepared for diagnosis.", "The connection details could not be read because Azure Resource Manager could not be reached from the host running these checks.": "The connection details could not be read because Azure Resource Manager could not be reached from the host running these checks.", @@ -2957,6 +2958,7 @@ "The connection details could not be read from MongoDB Atlas.": "The connection details could not be read from MongoDB Atlas.", "The connection details could not be read.": "The connection details could not be read.", "The connection did not finish in time. You can increase the timeout in Settings:": "The connection did not finish in time. You can increase the timeout in Settings:", + "The connection is unavailable.": "The connection is unavailable.", "The connection on this computer was accepted, then closed during the secure handshake, before a certificate arrived.": "The connection on this computer was accepted, then closed during the secure handshake, before a certificate arrived.", "The connection option {0} is deprecated. This does not establish that the driver ignores it.": "The connection option {0} is deprecated. This does not establish that the driver ignores it.", "The connection requests {0}, but the extension cannot use it.": "The connection requests {0}, but the extension cannot use it.", diff --git a/src/documentdb/ClustersClient.test.ts b/src/documentdb/ClustersClient.test.ts index 944962490..1c5f97c3f 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -235,7 +235,9 @@ describe('regular connection startup diagnostics', () => { it('never hydrates unpinned Entra silently, even after a native connection', async () => { const expectNoSession = async (): Promise => { - await expect(ClustersClient.getClient(clusterId, undefined, undefined, 'treeConnect')).rejects.toMatchObject({ + await expect( + ClustersClient.getClient(clusterId, undefined, undefined, 'treeConnect'), + ).rejects.toMatchObject({ name: 'EntraSignInRequiredError', reason: 'noSession', }); @@ -302,7 +304,11 @@ describe('regular connection startup diagnostics', () => { it('rechecks silent authorization using the credentials cloned during initialization', async () => { CredentialCache.setAuthCredentials(clusterId, AuthMethodId.NativeAuth, 'mongodb://private-host:27017'); const waiter = ClustersClient.getClient(clusterId, undefined, () => { - CredentialCache.setAuthCredentials(clusterId, AuthMethodId.MicrosoftEntraID, 'mongodb://private-host:27017'); + CredentialCache.setAuthCredentials( + clusterId, + AuthMethodId.MicrosoftEntraID, + 'mongodb://private-host:27017', + ); }); await expect(waiter).rejects.toMatchObject({ name: 'EntraSignInRequiredError', reason: 'noSession' }); expect(authHandlerFactory.createAuthHandler).not.toHaveBeenCalled(); @@ -539,7 +545,10 @@ describe('regular connection startup diagnostics', () => { const first = pauseNextConnect(); const retried = deferred(); - const onStartup = vi.fn().mockImplementationOnce(() => undefined).mockImplementationOnce(retried.resolve); + const onStartup = vi + .fn() + .mockImplementationOnce(() => undefined) + .mockImplementationOnce(retried.resolve); const waiter = ClustersClient.getClient(clusterId, undefined, onStartup); await first.started; await ClustersClient.deleteClient(clusterId); diff --git a/src/documentdb/ClustersClient.ts b/src/documentdb/ClustersClient.ts index ef62fe0f7..51bbb8d32 100644 --- a/src/documentdb/ClustersClient.ts +++ b/src/documentdb/ClustersClient.ts @@ -204,7 +204,9 @@ async function waitForClient( try { return await new Promise((resolve, reject) => { onAbort = (): void => { - ext.outputChannel.debug(`[ClustersClient] startup=${startupId} wait canceled by user surface=extension`); + ext.outputChannel.debug( + `[ClustersClient] startup=${startupId} wait canceled by user surface=extension`, + ); reject(new UserCancelledError('abortConnection')); }; // Observe settlement even if this caller has already left. @@ -866,7 +868,9 @@ export class ClustersClient { if (epoch !== ClustersClient.getEpoch(clusterId)) { client._closed = true; void client._mongoClient.close().catch(() => { - ext.outputChannel.debug(`[ClustersClient] startup=${id} superseded client cleanup failed surface=extension`); + ext.outputChannel.debug( + `[ClustersClient] startup=${id} superseded client cleanup failed surface=extension`, + ); }); } else { const generation = (ClustersClient._generations.get(clusterId) ?? 0) + 1; diff --git a/src/documentdb/ConnectionUnavailableError.ts b/src/documentdb/ConnectionUnavailableError.ts index ac6765a7a..1db3cfff2 100644 --- a/src/documentdb/ConnectionUnavailableError.ts +++ b/src/documentdb/ConnectionUnavailableError.ts @@ -21,7 +21,9 @@ export class ConnectionUnavailableError extends Error { options?: ErrorOptions, ) { super( - reason === 'credentialsMissing' ? l10n.t('No credentials found.') : l10n.t('The connection is unavailable.'), + reason === 'credentialsMissing' + ? l10n.t('No credentials found.') + : l10n.t('The connection is unavailable.'), options, ); this.name = 'ConnectionUnavailableError'; diff --git a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts index 0e187df01..b223c2417 100644 --- a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts +++ b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts @@ -140,7 +140,10 @@ describe('MicrosoftEntraIDAuthHandler', () => { } else if (failure === 'noSession') { getSessionFromVSCode.mockResolvedValue(undefined); } else { - getSessionFromVSCode.mockResolvedValue({ ...session, account: { ...account, id: 'different-account' } }); + getSessionFromVSCode.mockResolvedValue({ + ...session, + account: { ...account, id: 'different-account' }, + }); } const configuring = new MicrosoftEntraIDAuthHandler(credentials, { diff --git a/src/documentdb/connectionFingerprint.test.ts b/src/documentdb/connectionFingerprint.test.ts index ba58d6873..0baa94b78 100644 --- a/src/documentdb/connectionFingerprint.test.ts +++ b/src/documentdb/connectionFingerprint.test.ts @@ -68,7 +68,9 @@ describe('computeConnectionFingerprint', () => { { kind: 'managedIdentity' }, { kind: 'none' }, ]; - const fingerprints = principals.map((principal) => computeConnectionFingerprint({ connectionString, principal })); + const fingerprints = principals.map((principal) => + computeConnectionFingerprint({ connectionString, principal }), + ); expect(new Set(fingerprints).size).toBe(principals.length); }); diff --git a/src/tree/documentdb/DatabaseItem.ts b/src/tree/documentdb/DatabaseItem.ts index 8d05b7e37..b9cef919f 100644 --- a/src/tree/documentdb/DatabaseItem.ts +++ b/src/tree/documentdb/DatabaseItem.ts @@ -136,9 +136,15 @@ export class DatabaseItem implements TreeElement, TreeElementWithExperience, Tre private async fetchAndUpdateCount(): Promise { try { - const client = await ClustersClient.getClient(this.cluster.clusterId, undefined, undefined, 'treeChildren', { - background: true, - }); + const client = await ClustersClient.getClient( + this.cluster.clusterId, + undefined, + undefined, + 'treeChildren', + { + background: true, + }, + ); const { count, hasMore } = await client.countCollections(this.databaseInfo.name, COLLECTION_COUNT_LIMIT); // `getChildren()` may have run while this request was in flight and // established the exact count. Never replace an exact count with From a301f65610405bffe258578bf43771d7606278ba Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 11:32:40 +0000 Subject: [PATCH 080/380] docs: record PR3 verification and review handoff Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iterations/01-dev-plan.md | 32 +++++++++++-------- .../01-pr3-client-identity-review.md | 25 +++++++++++---- 2 files changed, 38 insertions(+), 19 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index 455f125fe..9db2e2406 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 @@ -1066,19 +1066,19 @@ shim (0005). ranking had 60–65% confidence. Test counts differ because candidates authored their own tests. Fusion ran alone via the Copilot CLI; its AI credits are reported separately from AIU. - | Variant | Candidate | Score | Elapsed | Input / output tokens | Tool calls | Usage | - | --- | --- | ---: | ---: | ---: | ---: | ---: | - | `gpt-6.2-astra`, High, large context | `89d642e66` | 92 | 4m03s | 737k / 12k | 27 | 254.7 AIU | - | `gpt-6.1-sol`, High | `18e933d13` | 89 | 8m16s | 1.1M / 24k | 33 | 55.8 AIU | - | `gpt-6.1-sol`, Extra High | `7a1845af5` | 88 | 6m56s | 918k / 21k | 31 | 51.2 AIU | - | `gpt-6.2-sol`, default | `eb388ef45` | 88 | 5m04s | 1.0M / 13k | 28 | 78.5 AIU | - | Copilot Fusion Standard (`gpt-6.1-terra`) | `4ac6c4765` | 86 | 3m07s | 911.6k / 12.5k | Not reported | 13.55 AI credits | - | Copilot Fusion High | No complete candidate | Not scored | 9m55s reported | 2.0M / 77.1k | 40 | 184.43 AI credits | - | `gpt-6.2-sol`, High | `f80f3a325` | 84 | 4m41s | 1.1M / 15k | 28 | 79.6 AIU | - | `gpt-6.2-sol`, Extra High | `aeabaabd2` | 84 | 7m01s | 1.1M / 18k | 33 | 87.6 AIU | - | `mai-code-2`, default | `1978a3c80` | 74 | 8m06s | 1.6M / 21k | 41 | 17.0 AIU | - | `gpt-6.1-sol`, Medium | `2cb904a18` | 73, fix required | 5m46s | 982k / 14k | 28 | 41.3 AIU | - | `claude-opus-5.5`, default, large context | `a0b581b07` | Disqualified | 7m53s | 2.5M / 44k | 29 | 201.1 AIU | + | Variant | Candidate | Score | Elapsed | Input / output tokens | Tool calls | Usage | + | ----------------------------------------- | --------------------- | ---------------: | -------------: | --------------------: | -----------: | ----------------: | + | `gpt-6.2-astra`, High, large context | `89d642e66` | 92 | 4m03s | 737k / 12k | 27 | 254.7 AIU | + | `gpt-6.1-sol`, High | `18e933d13` | 89 | 8m16s | 1.1M / 24k | 33 | 55.8 AIU | + | `gpt-6.1-sol`, Extra High | `7a1845af5` | 88 | 6m56s | 918k / 21k | 31 | 51.2 AIU | + | `gpt-6.2-sol`, default | `eb388ef45` | 88 | 5m04s | 1.0M / 13k | 28 | 78.5 AIU | + | Copilot Fusion Standard (`gpt-6.1-terra`) | `4ac6c4765` | 86 | 3m07s | 911.6k / 12.5k | Not reported | 13.55 AI credits | + | Copilot Fusion High | No complete candidate | Not scored | 9m55s reported | 2.0M / 77.1k | 40 | 184.43 AI credits | + | `gpt-6.2-sol`, High | `f80f3a325` | 84 | 4m41s | 1.1M / 15k | 28 | 79.6 AIU | + | `gpt-6.2-sol`, Extra High | `aeabaabd2` | 84 | 7m01s | 1.1M / 18k | 33 | 87.6 AIU | + | `mai-code-2`, default | `1978a3c80` | 74 | 8m06s | 1.6M / 21k | 41 | 17.0 AIU | + | `gpt-6.1-sol`, Medium | `2cb904a18` | 73, fix required | 5m46s | 982k / 14k | 28 | 41.3 AIU | + | `claude-opus-5.5`, default, large context | `a0b581b07` | Disqualified | 7m53s | 2.5M / 44k | 29 | 201.1 AIU | The medium-effort candidate could replace a cached client without closing it. The Opus candidate did not honor the retry or latch on an obsolete startup failure. Astra led on @@ -1105,6 +1105,7 @@ shim (0005). only after an explicit credentials change. The initial request went unanswered, so implementation did not start at that checkpoint. + - **WI-4d/e approved (2026-11-20), operator decision:** The operator accepted all five rules above. For rule 1, the operator preferred requiring an explicit first connect to silently picking an account. For rule 3, the operator accepted the reload limitation as an edge case. Finish @@ -1128,6 +1129,11 @@ shim (0005). from starting a client (`db01f24a5`). Both used `gpt-6.2-sol`; build and 95 focused tests passed. The operator also approved deferring stable Kubernetes tunnel fingerprints to #1105. See the [review record](./01-pr3-client-identity-review.md) for advisor confidence and verification. +- **PR3 handoff:** Case 2 passed after syncing PR2 and updating the connection-string edit + fixture to mock the interactive entry point without changing behavior assertions. The full + rerun passed 9,735 tests with one skipped. See the + [verification record](./01-pr3-client-identity-review.md#case-2-handoff). PR3 stays stacked + on PR2; WI-5 starts with the classifier and stops at CP-2 before recovery wiring. --- diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr3-client-identity-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr3-client-identity-review.md index 04992ddf5..f7201b1e3 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr3-client-identity-review.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr3-client-identity-review.md @@ -11,10 +11,10 @@ Reviewed [PR #1113](https://github.com/microsoft/vscode-documentdb/pull/1113) at against `96085c1dd`. GPT-6.2-Sol performed the initial review and Claude Opus 5.5 validated the findings. The operator approved the dispositions on 2026-11-23. -| Finding | Approved disposition | -| --- | --- | -| Canceling the decoded-password retry could invalidate a startup shared by another caller. | Fix in PR3 (90% advisor confidence). Treat the canceled wait like the first attempt: record cancellation without showing another failure modal or evicting the shared client or credentials. | -| The passive index-count badge could start or replace a client. | Fix in PR3 (95%). Apply the existing background restriction to the count, not to explicit Indexes expansion. | +| Finding | Approved disposition | +| --------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Canceling the decoded-password retry could invalidate a startup shared by another caller. | Fix in PR3 (90% advisor confidence). Treat the canceled wait like the first attempt: record cancellation without showing another failure modal or evicting the shared client or credentials. | +| The passive index-count badge could start or replace a client. | Fix in PR3 (95%). Apply the existing background restriction to the count, not to explicit Indexes expansion. | | A changed Kubernetes forwarded port could cause an identity mismatch if the old closed binding is still cached. | Defer stable tunnel fingerprints to [#1105](https://github.com/microsoft/vscode-documentdb/issues/1105) (85% confidence in the finding). Keep the identity check in place, per [decision 0009](../decisions.md#0009-kubernetes-tunnel-recovery-cluster-id-case-handling-and-wider-network-resilience-testing-move-to-1105). | ## Implementation and verification @@ -27,5 +27,18 @@ the findings. The operator approved the dispositions on 2026-11-23. - The operator approved keeping the fingerprint check unchanged and deferring stable tunnel fingerprints. The feature decisions and both plans record this limitation. -Case 1: the build and 95 focused tests passed with both fixes. Full Case 2 verification is -pending. +Case 1: the build and 95 focused tests passed with both fixes. + +## Case 2 handoff + +After merging the verified PR2 head in `3119db4ed`, localization generation and validation, +formatting, lint, build, strict workspace test type-check, and VSIX packaging passed. The +first full test run found six failures in the connection-string edit suite: its mock still +targeted `getClient` after the tree moved to `connectInteractive`. `be211c14c` updates the +fixture without changing its assertions or production code. The repaired suite passed all +seven tests and targeted lint; the full rerun passed **429 files, 9,735 tests, one skipped**. +`57cd2db14` records the generated localization and formatting used in verification. + +PR3 remains stacked on PR2 (#1111). Repeat OP-2 was accepted on the PR2 CI-built VSIX +with the gaps recorded in the [PR2 review](./01-pr2-azureauth-review.md). That was not a +live test of PR3; the next planned operator test is OP-3 after WI-5. From 247bc68d31b4d79a6b7868228ab7cc1206c7fe52 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 13:48:28 +0000 Subject: [PATCH 081/380] feat: classify connection failures before deciding how to recover (WI-5) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../auth/driverOidcContract.test.ts | 25 ++ .../auth/entraErrors/entraCallbackErrors.ts | 9 +- src/documentdb/connectionFailures.test.ts | 219 ++++++++++++++++++ src/documentdb/connectionFailures.ts | 159 +++++++++++++ 4 files changed, 409 insertions(+), 3 deletions(-) create mode 100644 src/documentdb/connectionFailures.test.ts create mode 100644 src/documentdb/connectionFailures.ts diff --git a/src/documentdb/auth/driverOidcContract.test.ts b/src/documentdb/auth/driverOidcContract.test.ts index 8048bce08..0f864bcee 100644 --- a/src/documentdb/auth/driverOidcContract.test.ts +++ b/src/documentdb/auth/driverOidcContract.test.ts @@ -18,6 +18,8 @@ import { AutomatedCallbackWorkflow as DriverWorkflow } from 'mongodb/lib/cmap/au // eslint-disable-next-line import/no-internal-modules -- The workflow needs the driver's real token cache. import { TokenCache as DriverTokenCache } from 'mongodb/lib/cmap/auth/mongodb_oidc/token_cache.js'; import { describe, expect, it, vi } from 'vitest'; +import { classifyConnectionFailure } from '../connectionFailures'; +import { AuthMethodId } from './AuthMethod'; // The driver's public declarations omit these internals. Type only the surface the suite uses. interface SaslStart { @@ -121,6 +123,29 @@ describe('driver contract: mongodb OIDC workflow (7.2.0)', () => { ]); }); + it('propagates the final code 18 unchanged when the callback-supplied token is also rejected', async (): Promise => { + const cache = new TokenCache(); + cache.put({ accessToken: 'dummy-cached-token' }); + const callback = vi.fn().mockResolvedValue({ accessToken: 'dummy-callback-token' }); + const workflow = new AutomatedCallbackWorkflow(cache, callback); + const finalError = new MongoServerError({ code: 18, errmsg: 'dummy authentication failure' }); + const command = vi + .fn() + .mockRejectedValueOnce(new MongoServerError({ code: 18, errmsg: 'dummy authentication failure' })) + .mockRejectedValueOnce(finalError); + + await expect(workflow.execute({ command }, credentials)).rejects.toBe(finalError); + expect(classifyConnectionFailure(finalError, AuthMethodId.MicrosoftEntraID)).toEqual({ + kind: 'credentialsRejected', + generation: 'evict', + }); + expect(callback).toHaveBeenCalledTimes(1); + expect(command.mock.calls.map(([, request]) => BSON.deserialize(request.payload.value()))).toEqual([ + { jwt: 'dummy-cached-token' }, + { jwt: 'dummy-callback-token' }, + ]); + }); + it('propagates a network error without calling the callback again or retrying the command', async () => { const callback = vi.fn().mockResolvedValue({ accessToken: 'dummy-cached-token' }); const workflow = new AutomatedCallbackWorkflow(new TokenCache(), callback); diff --git a/src/documentdb/auth/entraErrors/entraCallbackErrors.ts b/src/documentdb/auth/entraErrors/entraCallbackErrors.ts index ab2167fbe..016651b1b 100644 --- a/src/documentdb/auth/entraErrors/entraCallbackErrors.ts +++ b/src/documentdb/auth/entraErrors/entraCallbackErrors.ts @@ -20,10 +20,13 @@ export class EntraIdentityMismatchError extends Error { } } -export class TokenCallbackError extends Error { - public readonly authMethod = AuthMethodId.MicrosoftEntraID; +type TokenCallbackAuthMethod = AuthMethodId.MicrosoftEntraID | AuthMethodId.ManagedIdentity; - constructor(cause: unknown) { +export class TokenCallbackError extends Error { + constructor( + cause: unknown, + public readonly authMethod: TokenCallbackAuthMethod = AuthMethodId.MicrosoftEntraID, + ) { super(l10n.t('Failed to obtain a Microsoft Entra ID token.'), { cause }); this.name = 'TokenCallbackError'; } diff --git a/src/documentdb/connectionFailures.test.ts b/src/documentdb/connectionFailures.test.ts new file mode 100644 index 000000000..6fd96898c --- /dev/null +++ b/src/documentdb/connectionFailures.test.ts @@ -0,0 +1,219 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { UserCancelledError } from '@microsoft/vscode-azext-utils'; +import { + MongoNetworkError, + MongoNetworkTimeoutError, + MongoNotConnectedError, + MongoOperationTimeoutError, + MongoServerError, + MongoServerSelectionError, + MongoTopologyClosedError, + TopologyType, + type ServerDescription, + type TopologyDescription, +} from 'mongodb'; +// eslint-disable-next-line import/no-internal-modules -- These constructors are not public runtime exports. +import { ServerDescription as DriverServerDescription } from 'mongodb/lib/sdam/server_description.js'; +// eslint-disable-next-line import/no-internal-modules -- Use the real .error getter, which aliases the first failed server. +import { TopologyDescription as DriverTopologyDescription } from 'mongodb/lib/sdam/topology_description.js'; +import { describe, expect, it } from 'vitest'; +import { AuthMethodId } from './auth/AuthMethod'; +import { + EntraIdentityMismatchError, + EntraSignInRequiredError, + TokenCallbackError, +} from './auth/entraErrors/entraCallbackErrors'; +import { EntraDestinationRejectedError } from './auth/oidcAllowedHosts'; +import { classifyConnectionFailure } from './connectionFailures'; +import { ConnectionUnavailableError } from './ConnectionUnavailableError'; + +const makeServer = DriverServerDescription as new ( + address: string, + hello: undefined, + options: { error: Error | null }, +) => ServerDescription; +const makeTopology = DriverTopologyDescription as typeof TopologyDescription; + +function selectionError(...errors: (Error | null)[]): MongoServerSelectionError { + const servers = new Map( + errors.map((error, index): [string, ServerDescription] => { + const server = new makeServer(`example-${index}.test:27017`, undefined, { error }); + return [server.address, server]; + }), + ); + return new MongoServerSelectionError('Server selection timed out', new makeTopology(TopologyType.Unknown, servers)); +} + +const entra = AuthMethodId.MicrosoftEntraID; +const native = AuthMethodId.NativeAuth; +const rejected = new MongoServerError({ code: 18, errmsg: 'Authentication failed' }); +const network = new MongoNetworkError('connection closed'); +const refused = Object.assign(new Error('connect ECONNREFUSED 127.0.0.1:27017'), { code: 'ECONNREFUSED' }); + +describe('classifyConnectionFailure', (): void => { + it.each(['noSession', 'providerChanged'] as const)('recognizes typed Entra sign-in: %s', (reason): void => { + const error = new Error('Wrapper', { cause: new EntraSignInRequiredError(reason) }); + expect(classifyConnectionFailure(error, entra)).toEqual({ + kind: 'signInRequired', + generation: 'replaceOnRecovery', + }); + expect(classifyConnectionFailure(error, native)).toEqual({ kind: 'other', generation: 'keep' }); + }); + + it.each([new EntraIdentityMismatchError(), new ConnectionUnavailableError('identityChanged')])( + 'requires a rebind for %s', + (error): void => { + expect(classifyConnectionFailure(new Error('Wrapper', { cause: error }))).toEqual({ + kind: 'identityChanged', + generation: 'evict', + }); + }, + ); + + it('reports missing credentials without inventing a generation to evict', (): void => { + expect(classifyConnectionFailure(new ConnectionUnavailableError('credentialsMissing'))).toEqual({ + kind: 'credentialsMissing', + generation: 'none', + }); + }); + + it.each([AuthMethodId.MicrosoftEntraID, AuthMethodId.ManagedIdentity] as const)( + 'distinguishes a broken %s callback from its underlying network cause', + (authMethod): void => { + const error = new TokenCallbackError(network, authMethod); + expect(classifyConnectionFailure(error, authMethod)).toEqual({ + kind: 'transient', + generation: 'replaceOnNextForeground', + }); + }, + ); + + it('classifies code 18 for native or RU key auth, including through real selection errors', (): void => { + const error = selectionError(rejected, null, new MongoServerError({ code: 18 })); + expect(error.cause).toBe(rejected); + expect(error.code).toBe(18); + expect(classifyConnectionFailure(error, native)).toEqual({ kind: 'credentialsRejected', generation: 'evict' }); + }); + + it('evicts a rejected Entra client without classifying the failure as a missing session', (): void => { + expect(classifyConnectionFailure(selectionError(rejected), entra)).toEqual({ + kind: 'credentialsRejected', + generation: 'evict', + }); + expect(classifyConnectionFailure(rejected, AuthMethodId.ManagedIdentity)).toEqual({ + kind: 'other', + generation: 'keep', + }); + }); + + it.each([ + new MongoTopologyClosedError(), + new MongoNotConnectedError('Client must be connected before running operations'), + ])('recognizes a typed closed client or topology: %s', (error): void => { + expect(classifyConnectionFailure(new Error('Wrapper', { cause: error }))).toEqual({ + kind: 'clientClosed', + generation: 'replaceOnNextForeground', + }); + }); + + it.each([ + network, + new MongoNetworkError('Sign in again (AADSTS50058)'), + new MongoNetworkTimeoutError('timed out'), + new MongoOperationTimeoutError('Timed out during server selection', { cause: selectionError(null) }), + selectionError(new Error('unrecognized server error')), + ])('keeps an Entra client on plain network, timeout, or selection failures: %s', (error): void => { + expect(classifyConnectionFailure(error, entra)).toEqual({ kind: 'transient', generation: 'keep' }); + }); + + it('keeps the generation when a Kubernetes port-forward refuses the connection', (): void => { + const socketError = new MongoNetworkError(refused.message, { cause: refused }); + expect(classifyConnectionFailure(selectionError(socketError), native)).toEqual({ + kind: 'transient', + generation: 'keep', + }); + expect(classifyConnectionFailure(refused, native)).toEqual({ kind: 'transient', generation: 'keep' }); + }); + + it('does not treat the first server’s code 18 as authoritative when peers failed differently', (): void => { + const firstAuth = selectionError(rejected, network); + const firstNetwork = selectionError(network, rejected); + expect(firstAuth.cause).toBe(rejected); + expect(firstNetwork.cause).toBe(network); + for (const error of [firstAuth, firstNetwork]) { + expect(classifyConnectionFailure(error, native)).toEqual({ + kind: 'transient', + generation: 'keep', + note: 'mixedServerErrors', + }); + } + }); + + it('distinguishes consistent and mixed typed causes in constructed driver descriptions', (): void => { + // A MongoError can be retained by SDAM. The installed OIDC path does not create this wrapper. + const wrappedMiss = new MongoNetworkError('wrapped failure', { + cause: new EntraSignInRequiredError('noSession'), + }); + expect(classifyConnectionFailure(selectionError(null, wrappedMiss), entra)).toEqual({ + kind: 'signInRequired', + generation: 'replaceOnRecovery', + }); + for (const error of [selectionError(wrappedMiss, network), selectionError(network, wrappedMiss)]) { + expect(classifyConnectionFailure(error, entra)).toEqual({ + kind: 'transient', + generation: 'keep', + note: 'mixedServerErrors', + }); + } + }); + + it('leaves cancellation and destination rejection to their existing handlers', (): void => { + const cancellation = new TokenCallbackError(new UserCancelledError()); + const rejectedHost = new EntraDestinationRejectedError({ firstHost: 'not-allowed.test', hostCount: 1 }); + const tlsError = new MongoNetworkError('TLS failed', { cause: rejectedHost }); + + expect(classifyConnectionFailure(cancellation, entra)).toEqual({ + kind: 'other', + generation: 'keep', + note: 'cancelled', + }); + expect(classifyConnectionFailure(selectionError(network, tlsError), entra)).toEqual({ + kind: 'other', + generation: 'keep', + note: 'destinationRejected', + }); + const disconnected = new ConnectionUnavailableError('userDisconnected', { cause: rejected }); + expect(classifyConnectionFailure(disconnected)).toEqual({ + kind: 'other', + generation: 'keep', + note: 'alreadyUnavailable', + }); + }); + + it('does not classify messages or an arbitrary code as typed failures', (): void => { + for (const error of [ + 'EntraSignInRequiredError', + new Error('Client must be connected before running operations'), + Object.assign(new Error('Sign in again (AADSTS50058)'), { code: 18 }), + ]) { + expect(classifyConnectionFailure(error, entra)).toEqual({ kind: 'other', generation: 'keep' }); + } + }); + + it('keeps the generation on cyclic or uninspected server evidence', (): void => { + const cyclic = new Error('cycle'); + cyclic.cause = cyclic; + const tooManyServers = Array(64).fill(null); + for (const error of [cyclic, selectionError(rejected, ...tooManyServers, network)]) { + expect(classifyConnectionFailure(error, native)).toEqual({ + kind: 'other', + generation: 'keep', + note: 'incompleteEvidence', + }); + } + }); +}); diff --git a/src/documentdb/connectionFailures.ts b/src/documentdb/connectionFailures.ts new file mode 100644 index 000000000..2966504a4 --- /dev/null +++ b/src/documentdb/connectionFailures.ts @@ -0,0 +1,159 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { UserCancelledError } from '@microsoft/vscode-azext-utils'; +import { + MongoNetworkError, + MongoNotConnectedError, + MongoOperationTimeoutError, + MongoServerError, + MongoServerSelectionError, + MongoTopologyClosedError, + type TopologyDescription, +} from 'mongodb'; +import { networkCode } from '../utils/connectionErrorClassification'; +import { AuthMethodId } from './auth/AuthMethod'; +import { isEntraDestinationRejectedError } from './auth/oidcAllowedHosts'; +import { ConnectionUnavailableError } from './ConnectionUnavailableError'; + +export interface ConnectionFailure { + readonly kind: + | 'signInRequired' + | 'identityChanged' + | 'credentialsMissing' + | 'credentialsRejected' + | 'clientClosed' + | 'transient' + | 'other'; + readonly generation: 'keep' | 'evict' | 'replaceOnRecovery' | 'replaceOnNextForeground' | 'none'; + readonly note?: + | 'cancelled' + | 'destinationRejected' + | 'alreadyUnavailable' + | 'mixedServerErrors' + | 'incompleteEvidence'; +} + +const OTHER: ConnectionFailure = { kind: 'other', generation: 'keep' }; +const TRANSIENT: ConnectionFailure = { kind: 'transient', generation: 'keep' }; +const INCOMPLETE: ConnectionFailure = { ...OTHER, note: 'incompleteEvidence' }; +const MAX_DEPTH = 8; +const MAX_NODES = 64; + +/** Classifies failures using the auth method actually used (RU key connections use NativeAuth). */ +export function classifyConnectionFailure(error: unknown, authMethod?: AuthMethodId): ConnectionFailure { + let remaining = MAX_NODES; + const path = new Set(); + + function inspect(candidate: unknown, depth: number): ConnectionFailure | undefined { + if (!(candidate instanceof Error)) { + return undefined; + } + if (depth >= MAX_DEPTH || remaining-- <= 0 || path.has(candidate)) { + return INCOMPLETE; + } + path.add(candidate); + try { + return classify(candidate, depth); + } finally { + path.delete(candidate); + } + } + + function classify(candidate: Error, depth: number): ConnectionFailure { + if (candidate instanceof UserCancelledError) { + return { ...OTHER, note: 'cancelled' }; + } + if (isEntraDestinationRejectedError(candidate)) { + return { ...OTHER, note: 'destinationRejected' }; + } + if (candidate instanceof ConnectionUnavailableError) { + switch (candidate.reason) { + case 'identityChanged': + return { kind: 'identityChanged', generation: 'evict' }; + case 'credentialsMissing': + return { kind: 'credentialsMissing', generation: 'none' }; + default: + return { ...OTHER, note: 'alreadyUnavailable' }; + } + } + if (candidate instanceof MongoServerSelectionError && candidate.reason?.servers instanceof Map) { + return classifyServers(candidate.reason.servers, depth + 1); + } + + const cause = inspect(candidate.cause, depth + 1); + if (cause?.note !== undefined) { + return cause; + } + switch (candidate.name) { + case 'EntraSignInRequiredError': + return authMethod === undefined || authMethod === AuthMethodId.MicrosoftEntraID + ? { kind: 'signInRequired', generation: 'replaceOnRecovery' } + : OTHER; + case 'EntraIdentityMismatchError': + return { kind: 'identityChanged', generation: 'evict' }; + case 'TokenCallbackError': + return { kind: 'transient', generation: 'replaceOnNextForeground' }; + } + if (candidate instanceof MongoServerError && candidate.code === 18) { + // The OIDC workflow already tries its callback after a cached token is rejected. + return authMethod === AuthMethodId.NativeAuth || authMethod === AuthMethodId.MicrosoftEntraID + ? { kind: 'credentialsRejected', generation: 'evict' } + : OTHER; + } + if (candidate instanceof MongoNotConnectedError || candidate instanceof MongoTopologyClosedError) { + return { kind: 'clientClosed', generation: 'replaceOnNextForeground' }; + } + if (cause && cause.kind !== 'other') { + return cause; + } + if ( + candidate instanceof MongoNetworkError || + candidate instanceof MongoOperationTimeoutError || + candidate instanceof MongoServerSelectionError || + networkCode(candidate) + ) { + return TRANSIENT; + } + return OTHER; + } + + function classifyServers(servers: TopologyDescription['servers'], depth: number): ConnectionFailure { + // In 7.2.0, selection.cause and .code summarize the *first* server error, not the topology. + // Consider the per-server errors instead, so reversing the map cannot change the verdict. + let agreed: ConnectionFailure | undefined; + let mixed = false; + let constraint: ConnectionFailure | undefined; + for (const server of servers.values()) { + if (remaining <= 0) { + return constraint ?? INCOMPLETE; + } + remaining--; // Bound map iteration even when descriptions have no error. + const result = inspect(server?.error, depth); + if (!result) { + continue; + } + if (result.note === 'cancelled' || result.note === 'destinationRejected') { + // Preserve both constraints without enlarging either policy. + constraint = result.note === 'cancelled' ? result : (constraint ?? result); + } + if (agreed) { + mixed ||= + result.kind !== agreed.kind || result.generation !== agreed.generation || result.note !== agreed.note; + } else { + agreed = result; + } + } + if (constraint) { + return constraint; + } + if (mixed) { + return { ...TRANSIENT, note: 'mixedServerErrors' }; + } + return agreed && (agreed.kind !== 'other' || agreed.note) ? agreed : TRANSIENT; + } + + return inspect(error, 0) ?? OTHER; +} From afe4bc2e193690b14ef83aeef1e1bf0e744c82d3 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 13:48:28 +0000 Subject: [PATCH 082/380] docs: record CP-2 and retain verified Entra settings for explicit sign-in Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../features/connection-lifecycle/README.md | 4 +++ .../connection-lifecycle/decisions.md | 13 +++++++++ .../iterations/01-dev-plan.md | 28 +++++++++++++++++-- .../iterations/01-implementation-plan.md | 2 ++ 4 files changed, 44 insertions(+), 3 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/README.md b/docs/ai-and-plans/features/connection-lifecycle/README.md index 87b66ed56..8d5207066 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/README.md +++ b/docs/ai-and-plans/features/connection-lifecycle/README.md @@ -49,6 +49,9 @@ Evidence, telemetry and source pointers: [research-findings.md](./research-findi fingerprint and generation. - **Never change identity under an open surface.** It becomes disconnected, keeps its state, says why and offers one action. +- After a database rejects a verified Entra identity, discard the client but keep its in-memory + connection settings for explicit **Sign in again**. Do not retain the rejected token or retry + silently. - **One teardown** serves Disconnect, Remove Connection and identity-changing credential updates. - Disconnect uses the existing task-conflict guard: if a copy or export is using the cluster, leave the task and connection running. The user can retry after the task finishes or is stopped. @@ -79,6 +82,7 @@ See [decisions.md](./decisions.md): - 0011 Disconnect keeps the cached credentials and the verified identity; only Remove drops them; - 0012 a minimal lifecycle design: no state machine, one epoch, no prompts in `getClient`, one-step teardown; - 0013 corrections to 0012: latch before a credential save, epoch checks on replies, bindings carried through handoffs, an operation wrapper, folder deletion runs teardown. +- 0014 retain in-memory settings for explicit sign-in recovery after verified Entra rejection. ## Timeline diff --git a/docs/ai-and-plans/features/connection-lifecycle/decisions.md b/docs/ai-and-plans/features/connection-lifecycle/decisions.md index dcbef7f08..e83c02dc9 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/decisions.md +++ b/docs/ai-and-plans/features/connection-lifecycle/decisions.md @@ -25,6 +25,7 @@ created: 2026-11-19 | 0011 | Disconnect keeps the cached credentials and the verified identity; only Remove drops them | Accepted | Operator: reverses the #1059 proposal (plan Q3) | 2026-11-19 | — | | 0012 | Keep the lifecycle design minimal: no state machine, one epoch, no prompts in getClient, one-step teardown | Accepted | Operator: approved every proposed simplification | 2026-11-19 | — | | 0013 | Correct the minimal design where it lost edits, identity or recovery: latch before save, epoch checks | Accepted (modifies 0012) | Operator: "update the plan" after the omissions review | 2026-11-19 | — | +| 0014 | Keep in-memory connection settings after a rejection for a verified Entra identity | Accepted | Operator selected A to make sign-in recovery smoother | 2026-11-23 | Yes; WI-5 previously said to delete the entry | > Entries below are **semantically** immutable: append new entries rather than rewriting old ones, > and record reversals as a new entry plus a status change above. Heading text is frozen once @@ -399,3 +400,15 @@ The findings, each confirmed in the code, and the corrections now in the dev pla submission, no replay, no stale UI update and no claim that an unacknowledged write was not applied. None of the corrections adds a state machine or a service; 0012's other rules stand. + +## 0014. Keep in-memory connection settings after a rejection for a verified Entra identity + +A final Entra database authentication rejection still evicts the client. If the connection has a +verified Entra identity, keep its existing in-memory connection settings so **Sign in again** can +start from that identity, including when invoked with only `clusterId`. The operator chose this +over deleting the settings and losing that recovery action, to keep recovery smooth. + +This does not retain the rejected token, write anything to persistent storage, change destination +checks, or start a silent retry. Native authentication and RU key handling are unchanged. The +explicit sign-in path still checks the epoch after prompting and never moves an open surface to a +different identity. diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index 9db2e2406..ed50ecd3f 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md @@ -1171,8 +1171,8 @@ shim (0005). | `TokenCallbackError` (step 2) | Entra, MI | `transient`, workflow broken | replace on the next **foreground** operation | Retry | | `ConnectionUnavailableError('credentialsMissing')` (F-20) | any | `credentialsMissing` | none to keep | Update credentials | | code 18 | Native, RU | `credentialsRejected` | evict; no automatic retry | Update credentials (RU: Retry re-reads the key) | - | code 18 after a fresh callback | Entra | per T-5 | evict | per T-5 | - | `MongoNotConnectedError`, `topologyClosed`, "Client must be connected" | any | `clientClosed` | new generation on the next foreground call | none | + | final code 18 | Entra | `credentialsRejected` | evict; no automatic retry | Sign in again with a verified Entra identity | + | `MongoNotConnectedError`, `MongoTopologyClosedError` | any | `clientClosed` | new generation on the next foreground call | none | | network errors, timeouts, server selection with no auth cause | any | `transient` | keep | Retry | | anything else | any | `other` | keep | existing behavior | @@ -1213,7 +1213,9 @@ shim (0005). - Call `addEstablishedConnectionContext` on the failure events of `connect`, `getchildren` and the tree. - **Keep credentials on recoverable failures (F-20).** In every provider item's `authenticateAndConnect` failure path, still call `deleteClient`, but call `CredentialCache.deleteCredentials` only when the - kind is `credentialsRejected`, or `other` as today. For `transient`, `clientClosed` and + kind is `credentialsRejected`, or `other` as today. For `credentialsRejected` with a verified + Entra identity, retain the in-memory settings for explicit **Sign in again** (decision 0014). + For `transient`, `clientClosed` and `signInRequired`, keep the entry: a network outage during a tree expand must not leave open surfaces with nothing to reconnect from, nor make the user retype a discovery password. Put the decision in one shared helper, not in ten copies. @@ -1272,6 +1274,26 @@ shim (0005). **Progress:** +- **CP-2, advisor verdict: revise before wiring.** The classifier draft builds and 32 focused + tests pass. The pinned 7.2.0 workflow test shows that if a cached OIDC token receives code 18, + the driver calls the callback and propagates the final rejection unchanged if that token is + also refused. This does not prove that the callback returned newly issued token bytes. + Treat the final Entra authentication rejection as `credentialsRejected` and evict the client, + rather than adding callback-freshness fields with no reliable producer (85% advisor confidence). + Keep typed `noSession` distinct. Plain network failures (including the OP-1a shape and tunnel + refusal) and mixed per-server failures keep the client. Closed-client checks are typed only. + Plain callback errors do not reach the per-server descriptions through the pinned OIDC path, + so R5 does not require changing the Entra explainer now. Cancellation and destination handling + stay in place. +- **CP-2 / OC-1, accepted (2026-11-23):** The operator chose A for smoother recovery and asked + to record it in [decision 0014](../decisions.md#0014-keep-in-memory-connection-settings-after-a-rejection-for-a-verified-entra-identity). + Evict the rejected client, but keep the in-memory settings for a verified Entra identity. + Explicit **Sign in again** then works when invoked with just `clusterId`. No rejected token is + retained, no automatic retry is started, and Native/RU rejection and persistent storage are unchanged. +- **CP-2 revision verified:** Removed the unproducible freshness inputs. The contract test now + sends the exact final code 18 from the driver workflow through the classifier. Case 1 passed: + build and 31 focused tests across classification, the driver contract, and the Entra explainer. + --- ## WI-6: Bind surfaces and add the unavailable state (PR 5) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-implementation-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-implementation-plan.md index 8b0bb4bd0..c83e4ecc2 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-implementation-plan.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-implementation-plan.md @@ -314,6 +314,8 @@ In [ClustersClient.ts](../../../../../src/documentdb/ClustersClient.ts): - `signInRequired` (Entra): offer **Sign in again**. - `credentialsRejected` (Native code 18 after a reconnect): offer **Update credentials**, and **no automatic retry loop**. + - `credentialsRejected` (final Entra code 18): evict the client. With a verified Entra identity, + keep its in-memory connection settings and offer explicit **Sign in again** (decision 0014). - `clientClosed`: create a new generation with the same identity. - `transient` (network or timeout): no eviction, because the driver recovers. Offer Retry. From 6565f5f3d1f88cfe941597a9d209bc00e6525953 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 13:57:27 +0000 Subject: [PATCH 083/380] feat: fence authentication recovery to the failed client generation (WI-5) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/documentdb/ClustersClient.test.ts | 132 +++++++++++++++++- src/documentdb/ClustersClient.ts | 79 ++++++++++- .../auth/ManagedIdentityAuthHandler.test.ts | 32 ++--- .../auth/ManagedIdentityAuthHandler.ts | 2 + .../auth/MicrosoftEntraIDAuthHandler.ts | 6 +- src/documentdb/auth/oidcClientOptions.ts | 28 +++- src/documentdb/runWithClient.ts | 65 +++++++++ 7 files changed, 315 insertions(+), 29 deletions(-) create mode 100644 src/documentdb/runWithClient.ts diff --git a/src/documentdb/ClustersClient.test.ts b/src/documentdb/ClustersClient.test.ts index 1c5f97c3f..09436fc69 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -20,6 +20,11 @@ import { traceAuthFlow, type AuthTraceContext } from '../utils/authTrace'; import { type VerifiedEntraIdentity } from './auth/AuthHandler'; import { AuthMethodId } from './auth/AuthMethod'; import * as authHandlerFactory from './auth/createAuthHandler'; +import { + EntraIdentityMismatchError, + EntraSignInRequiredError, + TokenCallbackError, +} from './auth/entraErrors/entraCallbackErrors'; import { ManagedIdentityAuthHandler } from './auth/ManagedIdentityAuthHandler'; import { MicrosoftEntraIDAuthHandler } from './auth/MicrosoftEntraIDAuthHandler'; import { NativeAuthHandler } from './auth/NativeAuthHandler'; @@ -33,6 +38,7 @@ import { import { computeConnectionFingerprint } from './connectionFingerprint'; import { ConnectionUnavailableError } from './ConnectionUnavailableError'; import { CredentialCache } from './CredentialCache'; +import { runWithClient } from './runWithClient'; import { prepareDriverConnectionString } from './srv/prepareDriverConnectionString'; import { type SrvResolutionSummary } from './srv/srvResolutionSummary'; import { getClusterMetadata, getDomainMetadata } from './utils/getClusterMetadata'; @@ -320,7 +326,7 @@ describe('regular connection startup diagnostics', () => { const background = (): Promise => ClustersClient.getClient(clusterId, undefined, onStartup, 'clusterDashboardPoll', { background: true }); - await expect(background()).rejects.toBeInstanceOf(MongoNotConnectedError); + await expect(background()).rejects.toMatchObject({ name: 'ConnectionUnavailableError', reason: 'unreachable' }); CredentialCache.deleteCredentials(clusterId); await expect(background()).rejects.toMatchObject({ name: 'ConnectionUnavailableError', @@ -388,7 +394,7 @@ describe('regular connection startup diagnostics', () => { const background = (): Promise => ClustersClient.getClient(clusterId, undefined, onBackground, 'clusterDashboardPoll', { background: true }); - await expect(background()).rejects.toBeInstanceOf(MongoNotConnectedError); + await expect(background()).rejects.toMatchObject({ name: 'ConnectionUnavailableError', reason: 'unreachable' }); expect(onBackground).not.toHaveBeenCalled(); expect(mockConnect).toHaveBeenCalledOnce(); expect(MongoClient).toHaveBeenCalledOnce(); @@ -439,6 +445,128 @@ describe('regular connection startup diagnostics', () => { expect(mockConnect).toHaveBeenCalledOnce(); }); + it.each([ + ['transient', new TokenCallbackError(new Error('IMDS unavailable'), AuthMethodId.ManagedIdentity)], + ['clientClosed', new MongoNotConnectedError('driver closed')], + ] as const)('reports %s and replaces once on foreground, fencing late failures and close', async (kind, error) => { + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.ManagedIdentity, 'mongodb://private-host:27017'); + const old = await ClustersClient.getClient(clusterId); + const background = (): Promise => + ClustersClient.getClient(clusterId, undefined, undefined, 'clusterDashboardPoll', { background: true }); + + expect(ClustersClient.reportFailure(old.binding, error)).toBe(kind); + await expect(background()).rejects.toMatchObject({ reason: 'unreachable' }); + expect(mockConnect).toHaveBeenCalledOnce(); + expect(mockClose).not.toHaveBeenCalled(); + + const closing = deferred(); + mockClose.mockReturnValueOnce(closing.promise); + const foreground = ClustersClient.getClient(clusterId); + const [replacement, joined] = await Promise.all([foreground, background()]); + expect(joined).toBe(replacement); + expect(replacement.binding).toEqual({ ...old.binding, generation: old.generation + 1 }); + expect(mockConnect).toHaveBeenCalledTimes(2); + expect(mockClose).toHaveBeenCalledExactlyOnceWith(true); + expect(mockClose.mock.contexts[0]).toBe(old.getMongoClient()); + + expect(ClustersClient.reportFailure(old.binding, new EntraIdentityMismatchError())).toBeUndefined(); + expect( + ClustersClient.reportFailure({ ...replacement.binding, fingerprint: 'unmatched' }, error), + ).toBeUndefined(); + expect(ClustersClient.reportFailure(replacement.binding, new ConnectionUnavailableError('unreachable'))).toBe( + 'other', + ); + closing.reject(new Error('old close failed')); + await expect(background()).resolves.toBe(replacement); + }); + + it('holds a sign-in miss for explicit recovery and does not let a pending replacement bypass it', async () => { + const client = await ClustersClient.connectInteractive(clusterId); + const pin = ClustersClient.getLastVerifiedIdentity(clusterId); + const credentials = CredentialCache.getCredentials(clusterId); + ClustersClient.reportFailure(client.binding, new MongoNotConnectedError('driver closed')); + const handshake = pauseNextConnect(); + const pending = ClustersClient.getClient(clusterId); + await handshake.started; + + expect(ClustersClient.reportFailure(client.binding, new EntraSignInRequiredError('noSession'))).toBe( + 'signInRequired', + ); + handshake.resolve(); + await expect(pending).rejects.toMatchObject({ reason: 'signInRequired' }); + await expect(ClustersClient.getClient(clusterId)).rejects.toMatchObject({ reason: 'signInRequired' }); + expect(ClustersClient.getBinding(clusterId)).toBe(client.binding); + expect(ClustersClient.getLastVerifiedIdentity(clusterId)).toBe(pin); + expect(CredentialCache.getCredentials(clusterId)).toBe(credentials); + expect(mockConnect).toHaveBeenCalledTimes(2); + + await ClustersClient.deleteClient(clusterId); + const recovered = await ClustersClient.getClient(clusterId); + expect(recovered.binding).toEqual({ ...client.binding, generation: client.generation + 1 }); + }); + + it('evicts rejected clients without silently retrying or losing the verified Entra settings', async () => { + const client = await ClustersClient.connectInteractive(clusterId); + const settings = CredentialCache.getCredentials(clusterId); + const identity = ClustersClient.getLastVerifiedIdentity(clusterId); + const error = new MongoServerError({ code: 18 }); + + expect(ClustersClient.reportFailure(client.binding, error)).toBe('credentialsRejected'); + expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); + expect(mockClose).toHaveBeenCalledExactlyOnceWith(true); + expect(CredentialCache.getCredentials(clusterId)).toBe(settings); + expect(ClustersClient.getLastVerifiedIdentity(clusterId)).toBe(identity); + await expect(ClustersClient.getClient(clusterId)).rejects.toMatchObject({ reason: 'credentialsRejected' }); + await expect(ClustersClient.getClient(clusterId, undefined, undefined, 'treeChildren', { + background: true, + })).rejects.toMatchObject({ reason: 'credentialsRejected' }); + expect(MongoClient).toHaveBeenCalledOnce(); + + expect(ClustersClient.clearCredentialRejection(clusterId, ClustersClient.getEpoch(clusterId))).toBe(true); + const recovered = await ClustersClient.getClient(clusterId); + expect(recovered.binding).toEqual({ ...client.binding, generation: client.generation + 1 }); + expect(ClustersClient.reportFailure(client.binding, error)).toBeUndefined(); + expect(ClustersClient.getBinding(clusterId)).toBe(recovered.binding); + }); + + it('does not let recovery from a credential rejection clear a newer Disconnect', async () => { + const client = await ClustersClient.connectInteractive(clusterId); + ClustersClient.reportFailure(client.binding, new MongoServerError({ code: 18 })); + const epoch = ClustersClient.getEpoch(clusterId); + ClustersClient.latch(clusterId, 'userDisconnected'); + + expect(ClustersClient.clearCredentialRejection(clusterId, epoch)).toBe(false); + expect(ClustersClient.clearCredentialRejection(clusterId, ClustersClient.getEpoch(clusterId))).toBe(false); + await expect(ClustersClient.getClient(clusterId)).rejects.toMatchObject({ reason: 'userDisconnected' }); + expect(MongoClient).toHaveBeenCalledOnce(); + }); + + it('uses the resolved binding, preserves nonterminal errors and returns terminal unavailability without replay', async () => { + const old = await ClustersClient.connectInteractive(clusterId); + poolEvents.emit('topologyClosed'); + const client = await ClustersClient.getClient(clusterId); + const resolveClient = vi.fn(async (): Promise => client); + const network = Object.freeze(new MongoNetworkError('tunnel refused')); + const op = vi.fn<() => Promise>().mockRejectedValueOnce(network); + resolveClient.mockRejectedValueOnce(new ConnectionUnavailableError('unreachable')); + await expect(runWithClient(old.binding, op, { resolveClient, background: true })).resolves.toEqual({ + unavailable: { reason: 'unreachable' }, + }); + expect(op).not.toHaveBeenCalled(); + + await expect(runWithClient(old.binding, op, { resolveClient, background: true })).rejects.toBe(network); + expect(resolveClient).toHaveBeenLastCalledWith(old.binding, { background: true }); + expect(op).toHaveBeenCalledExactlyOnceWith(client); + expect(await ClustersClient.getClient(clusterId)).toBe(client); + + op.mockRejectedValueOnce(new EntraIdentityMismatchError()); + await expect(runWithClient(old.binding, op, { resolveClient })).resolves.toEqual({ + unavailable: { reason: 'identityChanged' }, + }); + expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); + expect(op).toHaveBeenCalledTimes(2); + }); + it('binds Entra to the original cached URI and the verified identity, even if credentials change during startup', async () => { const originalUri = 'mongodb+srv://original.example.com/database?authSource=admin'; const driverUri = 'mongodb://localhost:27018/database'; diff --git a/src/documentdb/ClustersClient.ts b/src/documentdb/ClustersClient.ts index 51bbb8d32..f64979c97 100644 --- a/src/documentdb/ClustersClient.ts +++ b/src/documentdb/ClustersClient.ts @@ -50,6 +50,7 @@ import { createAuthHandler } from './auth/createAuthHandler'; import { EntraSignInRequiredError } from './auth/entraErrors/entraCallbackErrors'; import { getAzureHostSuffix } from './auth/oidcAllowedHosts'; import { QueryInsightsApis, type ExplainVerbosity } from './client/QueryInsightsApis'; +import { classifyConnectionFailure, type ConnectionFailure } from './connectionFailures'; import { computeConnectionFingerprint, type ConnectionPrincipal } from './connectionFingerprint'; import { ConnectionUnavailableError, type ConnectionUnavailableReason } from './ConnectionUnavailableError'; import { CredentialCache, type CachedClusterCredentials } from './CredentialCache'; @@ -307,6 +308,17 @@ export class ClustersClient { return ClustersClient._latches.get(clusterId); } + public static clearCredentialRejection(clusterId: string, epoch: number): boolean { + if ( + ClustersClient.getEpoch(clusterId) !== epoch || + ClustersClient.getLatchReason(clusterId) !== 'credentialsRejected' + ) { + return false; + } + ClustersClient.unlatch(clusterId); + return true; + } + #startupCredentials: Readonly; #verifiedIdentity: VerifiedIdentity; private _fingerprint: string; @@ -314,6 +326,7 @@ export class ClustersClient { private _createdAt: number; private _mongoClient: MongoClient; private _closed = false; + private _replacement?: 'replaceOnNextForeground' | 'replaceOnRecovery'; private _interactiveEntraStartupId?: string; private _llmEnhancedFeatureApis: llmEnhancedFeatureApis | null = null; private _queryInsightsApis: QueryInsightsApis | null = null; @@ -758,7 +771,10 @@ export class ClustersClient { const epoch = ClustersClient.getEpoch(clusterId); const cached = ClustersClient._clients.get(clusterId); - if (cached && !cached._closed) { + if (cached?._replacement === 'replaceOnRecovery') { + throw new ConnectionUnavailableError('signInRequired'); + } + if (cached?.canReuse()) { const id = cached.connectionCorrelationId; if (id) { onStartup?.(id); @@ -770,12 +786,12 @@ export class ClustersClient { ext.outputChannel.debug(`[ClustersClient] startup=${id} wait canceled by user surface=extension`); throw new UserCancelledError('abortConnection'); } - if (!cached._closed) { + if (cached.canReuse()) { return cached; } } - // Until a replacement succeeds, the closed entry still pins the connection identity. + // Until a replacement succeeds, the old entry still pins the connection identity. const { id, promise } = ClustersClient.getOrStartClient( clusterId, epoch, @@ -787,7 +803,7 @@ export class ClustersClient { onStartup?.(id); try { const client = await waitForClient(promise, abortSignal, id); - if (epoch === ClustersClient.getEpoch(clusterId)) { + if (epoch === ClustersClient.getEpoch(clusterId) && client.canReuse()) { return client; } } catch (error) { @@ -817,7 +833,8 @@ export class ClustersClient { if (!credentials) { throw new ConnectionUnavailableError('credentialsMissing'); } - throw new MongoNotConnectedError(l10n.t('The connection is unavailable.')); + // This caller didn't run anything on a client. Don't treat this as a driver close. + throw new ConnectionUnavailableError('unreachable'); } if ( !allowInteractive && @@ -854,6 +871,9 @@ export class ClustersClient { const client = new ClustersClient(clusterId); try { await client.initClient(id, trigger, epoch, allowInteractive, expectedFingerprint); + if (client._closed) { + throw new MongoNotConnectedError(l10n.t('The connection is unavailable.')); + } } catch (error) { if (!(error instanceof UserCancelledError) && epoch === ClustersClient.getEpoch(clusterId)) { ClustersClient._lastFailedStartups.set(clusterId, id); @@ -873,6 +893,7 @@ export class ClustersClient { ); }); } else { + const previous = ClustersClient._clients.get(clusterId); const generation = (ClustersClient._generations.get(clusterId) ?? 0) + 1; client._binding = Object.freeze({ clusterId, fingerprint: client._fingerprint, generation }); client._createdAt = Date.now(); @@ -880,10 +901,58 @@ export class ClustersClient { ClustersClient._lastVerifiedIdentities.set(clusterId, Object.freeze({ ...client.#verifiedIdentity })); ClustersClient._clients.set(clusterId, client); ClustersClient._lastFailedStartups.delete(clusterId); + if (previous && !previous._closed) { + previous._closed = true; + void previous._mongoClient.close(true).catch(() => { + // Closing a retired driver must not affect its replacement. + }); + } } return client; } + private canReuse(): boolean { + return !this._closed && this._replacement === undefined; + } + + /** Reports an operation's failure against the generation that actually ran it. */ + public static reportFailure(binding: ConnectionBinding, error: unknown): ConnectionFailure['kind'] | undefined { + const { clusterId, fingerprint, generation } = binding; + const client = ClustersClient._clients.get(clusterId); + if ( + !client || + client.generation !== generation || + client.fingerprint !== fingerprint || + ClustersClient.getLatchReason(clusterId) + ) { + return undefined; + } + + const failure = classifyConnectionFailure(error, client.authMethod); + if (client._replacement === 'replaceOnRecovery') { + return failure.kind; + } + switch (failure.generation) { + case 'replaceOnNextForeground': + client._replacement = failure.generation; + break; + case 'replaceOnRecovery': + client._replacement = failure.generation; + // An already-started replacement must not bypass explicit recovery. + ClustersClient.invalidate(clusterId); + break; + case 'evict': + if (failure.kind === 'credentialsRejected') { + ClustersClient.latch(clusterId, 'credentialsRejected'); + } + void ClustersClient.deleteClient(clusterId).catch(() => { + ext.outputChannel.debug('[ClustersClient] failed to close an evicted client'); + }); + break; + } + return failure.kind; + } + /** * Retrieves cluster metadata for this client instance. * diff --git a/src/documentdb/auth/ManagedIdentityAuthHandler.test.ts b/src/documentdb/auth/ManagedIdentityAuthHandler.test.ts index e5a8bb7c4..503004071 100644 --- a/src/documentdb/auth/ManagedIdentityAuthHandler.test.ts +++ b/src/documentdb/auth/ManagedIdentityAuthHandler.test.ts @@ -15,6 +15,7 @@ import { type AuthPhaseObserver } from './authCallerPolicy'; import { buildAuthConnectionTarget } from './authConnectionTarget'; import { AuthMethodId } from './AuthMethod'; import * as tokenResources from './documentdbTokenResource'; +import { TokenCallbackError } from './entraErrors/entraCallbackErrors'; import { EntraErrorExplainer } from './entraErrors/EntraErrorExplainer'; import { getRecentEntraTokenFailure, @@ -341,16 +342,7 @@ describe('ManagedIdentityAuthHandler', () => { expect(getManagedIdentityAccessToken.mock.calls[0][3]).toBe(getManagedIdentityAccessToken.mock.calls[1][3]); }); - it('propagates the provider readable failure', async () => { - getManagedIdentityAccessToken.mockRejectedValue(new Error('More than one managed identity is available.')); - const handler = new ManagedIdentityAuthHandler(buildCredentials()); - - const { options } = await handler.configureAuth(); - - await expect(invokeOidcCallback(options)).rejects.toThrow(/more than one managed identity/i); - }); - - it('records failures only inside the deferred token callback and rethrows the same error', async (): Promise => { + it('wraps and records failures only inside the deferred token callback', async (): Promise => { const connectionString = 'mongodb://cluster.mongocluster.cosmos.azure.us/'; const handler = new ManagedIdentityAuthHandler( buildCredentials({ connectionString, connectionStringWithPassword: connectionString }), @@ -367,7 +359,10 @@ describe('ManagedIdentityAuthHandler', () => { expect(getRecentEntraTokenFailure('cluster-1')).toBeUndefined(); expect(getManagedIdentityAccessToken).not.toHaveBeenCalled(); - await expect(invokeOidcCallback(options)).rejects.toBe(error); + const callback = invokeOidcCallback(options); + await expect(callback).rejects.toBeInstanceOf(TokenCallbackError); + await expect(callback).rejects.toMatchObject({ authMethod: AuthMethodId.ManagedIdentity, cause: error }); + await expect(callback).rejects.not.toThrow(/AADSTS500011/); expect(startupProperties.entraFailureKind).toBe('tokenAcquisitionFailed'); expect(JSON.stringify(startupProperties)).not.toMatch(/cluster-1|AADSTS|https/); expect(getRecentEntraTokenFailure('cluster-1')).toEqual({ @@ -416,11 +411,12 @@ describe('ManagedIdentityAuthHandler', () => { surface: 'extension', startupProperties: failedProperties, }); - await expect(invokeOidcCallback(failed.options)).rejects.toBe(error); + const callbackError: unknown = await invokeOidcCallback(failed.options).catch((failure: unknown) => failure); + expect(callbackError).toMatchObject({ cause: error }); const failure = getRecentEntraTokenFailure('cluster-1'); expect(failure).toMatchObject({ cloudCategory: 'usgov', authMethod: 'managedIdentity' }); const diagnostics = new EntraErrorExplainer(); - expect(await diagnostics.explain({ clusterId: 'cluster-1', error })).toContain( + expect(await diagnostics.explain({ clusterId: 'cluster-1', error: callbackError })).toContain( 'Sign-in failed in Azure US Government', ); @@ -600,14 +596,18 @@ describe('ManagedIdentityAuthHandler', () => { const error = new Error('AADSTS700016: identity not found'); getManagedIdentityAccessToken.mockRejectedValueOnce(error); const events: string[] = []; + const onTokenFailed = vi.fn(() => { + events.push('tokenFailed'); + }); const handler = new ManagedIdentityAuthHandler(buildCredentials(), { interactive: false, - observer: recordingObserver(events), + observer: { ...recordingObserver(events), onTokenFailed }, }); const { options } = await handler.configureAuth(); expect(events).toEqual(['resolved:public:host:*.mongocluster.cosmos.azure.com']); - await expect(invokeOidcCallback(options)).rejects.toBe(error); + await expect(invokeOidcCallback(options)).rejects.toMatchObject({ cause: error }); + expect(onTokenFailed).toHaveBeenCalledExactlyOnceWith(error); expect(events).toEqual([ 'resolved:public:host:*.mongocluster.cosmos.azure.com', 'tokenStarted', @@ -655,7 +655,7 @@ describe('ManagedIdentityAuthHandler', () => { await expect(invokeOidcCallback(options)).resolves.toMatchObject({ accessToken: 'a-token' }); const error = new Error('token failure'); getManagedIdentityAccessToken.mockRejectedValueOnce(error); - await expect(invokeOidcCallback(options)).rejects.toBe(error); + await expect(invokeOidcCallback(options)).rejects.toMatchObject({ cause: error }); }); }); }); diff --git a/src/documentdb/auth/ManagedIdentityAuthHandler.ts b/src/documentdb/auth/ManagedIdentityAuthHandler.ts index aaad4b268..265d7f6d9 100644 --- a/src/documentdb/auth/ManagedIdentityAuthHandler.ts +++ b/src/documentdb/auth/ManagedIdentityAuthHandler.ts @@ -12,6 +12,7 @@ import { type CachedClusterCredentials } from '../CredentialCache'; import { withTokenAcquisitionTiming, type ConnectionStartupTimings } from '../utils/ConnectionStartupTimings'; import { notifyAuthPhaseObserver, type AuthCallerPolicy, type AuthPhaseObserver } from './authCallerPolicy'; import { type AuthHandler, type AuthHandlerResponse } from './AuthHandler'; +import { AuthMethodId } from './AuthMethod'; import { resolveManagedIdentityTokenResource, TokenResourceResolutionError } from './documentdbTokenResource'; import { evaluateEntraDestinationFromSettings, getEntraCustomHostnameSuffix } from './entraDestinationSettings'; import { classifyEntraError } from './entraErrors/classifyEntraError'; @@ -100,6 +101,7 @@ export class ManagedIdentityAuthHandler implements AuthHandler { const configuration = buildOidcClientConfiguration({ connectionString, policy, + callbackAuthMethod: AuthMethodId.ManagedIdentity, oidcCallback: async (): Promise => { const currentDecision = evaluateEntraDestinationFromSettings(connectionString); traceEntraDestination(currentDecision, this.tokenCorrelationId, traceContext); diff --git a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts index cda5b17d7..b767942c3 100644 --- a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts +++ b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts @@ -18,6 +18,7 @@ import { type AuthPhaseObserver, } from './authCallerPolicy'; import { type AuthHandler, type AuthHandlerResponse, type VerifiedEntraIdentity } from './AuthHandler'; +import { AuthMethodId } from './AuthMethod'; import { resolveInteractiveTokenResource, TokenResourceResolutionError } from './documentdbTokenResource'; import { evaluateEntraDestinationFromSettings, getEntraCustomHostnameSuffix } from './entraDestinationSettings'; import { classifyEntraError } from './entraErrors/classifyEntraError'; @@ -227,6 +228,7 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { const configuration = buildOidcClientConfiguration({ connectionString, policy, + callbackAuthMethod: AuthMethodId.MicrosoftEntraID, oidcCallback: async (_params: OIDCCallbackParams): Promise => { const currentInvocation = ++invocation; let observation: EntraTokenLookupObservation = { outcome: 'failed' }; @@ -263,7 +265,7 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { observation = { outcome: 'noSession' }; throw error; } - if (observation.outcome === 'identityMismatch') { + if (error instanceof EntraIdentityMismatchError || error instanceof EntraDestinationRejectedError) { throw error; } recordEntraTokenFailure(clusterId, { @@ -271,7 +273,7 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { authMethod: 'interactive', ruleId: classifyEntraError(error instanceof Error ? error.message : String(error))?.ruleId, }); - throw new TokenCallbackError(error); + throw error; } finally { traceAuthFlow( 'interactiveEntra.oidcCallback', diff --git a/src/documentdb/auth/oidcClientOptions.ts b/src/documentdb/auth/oidcClientOptions.ts index 9cc953536..aa1a89d4e 100644 --- a/src/documentdb/auth/oidcClientOptions.ts +++ b/src/documentdb/auth/oidcClientOptions.ts @@ -6,10 +6,16 @@ import { type MongoClientOptions, type OIDCCallbackFunction, type OIDCResponse } from 'mongodb'; import { checkServerIdentity, type PeerCertificate } from 'tls'; import { DocumentDBConnectionString } from '../utils/DocumentDBConnectionString'; +import { + EntraIdentityMismatchError, + EntraSignInRequiredError, + TokenCallbackError, +} from './entraErrors/entraCallbackErrors'; import { EntraDestinationRejectedError, evaluateEntraDestination, isEntraDestinationHostAllowed, + isEntraDestinationRejectedError, } from './oidcAllowedHosts'; const TLS_BYPASS_KEYS = new Set([ @@ -97,6 +103,7 @@ export function buildOidcClientConfiguration(input: { connectionString: string; policy: OidcDestinationPolicy; oidcCallback: OIDCCallbackFunction; + callbackAuthMethod?: TokenCallbackError['authMethod']; baseOptions?: MongoClientOptions; }): { connectionString: string; @@ -149,10 +156,23 @@ export function buildOidcClientConfiguration(input: { authMechanismProperties: { ALLOWED_HOSTS: [...input.policy.allowedHostPatterns], OIDC_CALLBACK: async (params): Promise => { - input.policy.assertAllowed(); - const response = await input.oidcCallback(params); - input.policy.assertAllowed(); - return response; + try { + input.policy.assertAllowed(); + const response = await input.oidcCallback(params); + input.policy.assertAllowed(); + return response; + } catch (error) { + if ( + input.callbackAuthMethod === undefined || + error instanceof EntraSignInRequiredError || + error instanceof EntraIdentityMismatchError || + error instanceof TokenCallbackError || + isEntraDestinationRejectedError(error) + ) { + throw error; + } + throw new TokenCallbackError(error, input.callbackAuthMethod); + } }, }, tls: true, diff --git a/src/documentdb/runWithClient.ts b/src/documentdb/runWithClient.ts new file mode 100644 index 000000000..5bcf53a7b --- /dev/null +++ b/src/documentdb/runWithClient.ts @@ -0,0 +1,65 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { ClustersClient, type ConnectionBinding } from './ClustersClient'; +import { classifyConnectionFailure, type ConnectionFailure } from './connectionFailures'; +import { ConnectionUnavailableError, type ConnectionUnavailableReason } from './ConnectionUnavailableError'; + +interface ResolveOptions { + readonly background?: boolean; +} + +interface RunOptions extends ResolveOptions { + resolveClient(binding: ConnectionBinding, options: ResolveOptions): Promise; +} + +interface Unavailable { + readonly unavailable: { readonly reason: ConnectionUnavailableReason }; +} + +function unavailableFor(kind: ConnectionFailure['kind'] | undefined): Unavailable | undefined { + switch (kind) { + case 'signInRequired': + case 'credentialsRejected': + case 'credentialsMissing': + case 'identityChanged': + return { unavailable: { reason: kind } }; + default: + return undefined; + } +} + +/** @internal The bound resolver and conversion to a surface response are supplied by WI-6. */ +export async function runWithClient( + binding: ConnectionBinding, + op: (client: ClustersClient) => Promise, + { resolveClient, background }: RunOptions, +): Promise { + let client: ClustersClient; + try { + client = await resolveClient(binding, { background }); + } catch (error) { + // No operation ran, so there is no client generation to report against. + const unavailable = + error instanceof ConnectionUnavailableError + ? { unavailable: { reason: error.reason } } + : unavailableFor(classifyConnectionFailure(error).kind); + if (unavailable) { + return unavailable; + } + throw error; + } + + try { + return await op(client); + } catch (error) { + // Resolution can advance the generation without changing the surface's identity. + const unavailable = unavailableFor(ClustersClient.reportFailure(client.binding, error)); + if (unavailable) { + return unavailable; + } + throw error; + } +} From 7c515413095eecc9ee6c147d983b1f011b23efa2 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 13:57:27 +0000 Subject: [PATCH 084/380] docs: reuse the existing latch for explicit rejection recovery Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../features/connection-lifecycle/README.md | 1 + .../features/connection-lifecycle/decisions.md | 12 ++++++++++++ .../connection-lifecycle/iterations/01-dev-plan.md | 7 +++++++ 3 files changed, 20 insertions(+) diff --git a/docs/ai-and-plans/features/connection-lifecycle/README.md b/docs/ai-and-plans/features/connection-lifecycle/README.md index 8d5207066..f32fb1728 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/README.md +++ b/docs/ai-and-plans/features/connection-lifecycle/README.md @@ -83,6 +83,7 @@ See [decisions.md](./decisions.md): - 0012 a minimal lifecycle design: no state machine, one epoch, no prompts in `getClient`, one-step teardown; - 0013 corrections to 0012: latch before a credential save, epoch checks on replies, bindings carried through handoffs, an operation wrapper, folder deletion runs teardown. - 0014 retain in-memory settings for explicit sign-in recovery after verified Entra rejection. +- 0015 use the existing latch to block startup after authentication rejection until explicit recovery. ## Timeline diff --git a/docs/ai-and-plans/features/connection-lifecycle/decisions.md b/docs/ai-and-plans/features/connection-lifecycle/decisions.md index e83c02dc9..2f6b7a190 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/decisions.md +++ b/docs/ai-and-plans/features/connection-lifecycle/decisions.md @@ -26,6 +26,7 @@ created: 2026-11-19 | 0012 | Keep the lifecycle design minimal: no state machine, one epoch, no prompts in getClient, one-step teardown | Accepted | Operator: approved every proposed simplification | 2026-11-19 | — | | 0013 | Correct the minimal design where it lost edits, identity or recovery: latch before save, epoch checks | Accepted (modifies 0012) | Operator: "update the plan" after the omissions review | 2026-11-19 | — | | 0014 | Keep in-memory connection settings after a rejection for a verified Entra identity | Accepted | Operator selected A to make sign-in recovery smoother | 2026-11-23 | Yes; WI-5 previously said to delete the entry | +| 0015 | Use the existing latch to block startup after authentication rejection | Accepted | Operator selected A; keep the approach simple and pragmatic | 2026-11-23 | Yes; expands the existing latch rather than adding a second hold | > Entries below are **semantically** immutable: append new entries rather than rewriting old ones, > and record reversals as a new entry plus a status change above. Heading text is frozen once @@ -412,3 +413,14 @@ This does not retain the rejected token, write anything to persistent storage, c checks, or start a silent retry. Native authentication and RU key handling are unchanged. The explicit sign-in path still checks the epoch after prompting and never moves an open surface to a different identity. + +## 0015. Use the existing latch to block startup after authentication rejection + +Evicting a rejected client is not enough: a subsequent operation could immediately start a new +one with the same settings. Set the existing in-memory latch to `credentialsRejected` before +evicting the rejected generation. The matching explicit recovery can clear that reason only if +the epoch still matches. It cannot clear a latch set by Disconnect, Remove or a credential change. + +The operator chose to reuse the existing latch rather than introduce a separate authentication +hold, keeping one place to check for an unavailable connection. The rejection latch uses the +existing epoch and does not add a subscription, new persistence, or a retry loop. diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index ed50ecd3f..a8dbe8a1e 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md @@ -414,6 +414,8 @@ a checkpoint changes them. Only the explicit Connect and Reconnect actions clear the latch, plus one internal case: an identity-changing credential update whose save reached nothing clears the latch it set (WI-7 step 5). New tasks and resource leases are refused while the latch is set. + A `credentialsRejected` latch blocks startup until the matching explicit recovery clears it + with an unchanged epoch (decision 0015). That recovery cannot clear a teardown latch. - **One epoch:** a per-cluster counter that `invalidate` increases **synchronously** on every latch, unlatch, eviction and teardown. A startup publishes only if the epoch is unchanged. Every recovery command (Retry, Sign in again, Reconnect) captures the epoch **before** its first `await`, and applies @@ -1293,6 +1295,11 @@ shim (0005). - **CP-2 revision verified:** Removed the unproducible freshness inputs. The contract test now sends the exact final code 18 from the driver workflow through the classifier. Case 1 passed: build and 31 focused tests across classification, the driver contract, and the Entra explainer. +- **CP-2 / OC-2, accepted:** Reuse the existing latch for `credentialsRejected` rather than + adding a separate hold. Eviction must not let an ordinary operation open another client with + rejected settings. Only the matching explicit recovery can clear the rejection, and only if + its epoch is current. The operator preferred the simpler option and asked to record + [decision 0015](../decisions.md#0015-use-the-existing-latch-to-block-startup-after-authentication-rejection). --- From d4412690bdbc8778fd2622982232670cf3495015 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 14:14:16 +0000 Subject: [PATCH 085/380] feat: recover tree connections through explicit retry and sign-in (WI-5) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../retryAuthentication.test.ts | 126 +++++++- .../retryAuthentication.ts | 93 +++++- src/commands/signInAgain/signInAgain.test.ts | 104 +++++++ src/commands/signInAgain/signInAgain.ts | 114 +++++++ .../updateConnectionString/ExecuteStep.ts | 9 + .../UpdateCSWizardContext.ts | 1 + .../updateConnectionString.test.ts | 6 +- .../updateConnectionString.ts | 28 +- src/commands/updateCredentials/ExecuteStep.ts | 10 + .../UpdateCredentialsWizardContext.ts | 2 + .../updateCredentials.test.ts | 2 + .../updateCredentials/updateCredentials.ts | 31 +- src/documentdb/ClustersClient.test.ts | 21 ++ src/documentdb/ClustersClient.ts | 71 ++++- src/documentdb/ClustersExtension.ts | 5 + .../auth/MicrosoftEntraIDAuthHandler.ts | 7 +- src/documentdb/connectionFailures.ts | 3 + .../discovery-tree/AtlasClusterItem.test.ts | 3 + .../discovery-tree/AtlasClusterItem.ts | 4 +- .../documentdb/MongoRUResourceItem.ts | 8 +- .../documentdb/DocumentDBResourceItem.ts | 4 +- .../discovery-tree/vm/AzureVMResourceItem.ts | 4 +- .../documentdb/KubernetesResourceItem.test.ts | 3 + .../documentdb/KubernetesResourceItem.ts | 6 +- src/tree/BaseExtendedTreeDataProvider.ts | 7 + .../documentdb/VCoreResourceItem.ts | 4 +- .../mongo-ru/RUCoreResourceItem.ts | 8 +- .../DocumentDBClusterItem.test.ts | 15 +- .../connections-view/DocumentDBClusterItem.ts | 25 +- .../LocalQuickStart/LocalQuickStartItem.ts | 7 +- src/tree/documentdb/ClusterItemBase.test.ts | 41 ++- src/tree/documentdb/ClusterItemBase.ts | 284 ++++++++++-------- 32 files changed, 884 insertions(+), 172 deletions(-) create mode 100644 src/commands/signInAgain/signInAgain.test.ts create mode 100644 src/commands/signInAgain/signInAgain.ts diff --git a/src/commands/retryAuthentication/retryAuthentication.test.ts b/src/commands/retryAuthentication/retryAuthentication.test.ts index e0c080d82..60c81da13 100644 --- a/src/commands/retryAuthentication/retryAuthentication.test.ts +++ b/src/commands/retryAuthentication/retryAuthentication.test.ts @@ -5,6 +5,12 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { UserCancelledError } from '@microsoft/vscode-azext-utils'; +import { window } from 'vscode'; +import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; +import { ClustersClient } from '../../documentdb/ClustersClient'; +import { CredentialCache } from '../../documentdb/CredentialCache'; +import { type ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; import { ext } from '../../extensionVariables'; import { retryAuthentication } from './retryAuthentication'; @@ -30,17 +36,28 @@ vi.mock('../../extensionVariables', () => ({ })); vi.mock('../../documentdb/ClustersClient', () => ({ + addEstablishedConnectionContext: vi.fn(), ClustersClient: { + getEpoch: vi.fn(() => 0), + getLatchReason: vi.fn(), + clearCredentialRejection: vi.fn(), + deleteClient: vi.fn(), getLastFailedStartupCorrelationId: vi.fn((clusterId: string) => clusterId === 'failed-cluster' ? 'failed-attempt' : undefined, ), }, })); -vi.mock('vscode', () => ({ +vi.mock('../../documentdb/CredentialCache', () => ({ + CredentialCache: { getCredentials: vi.fn(), deleteCredentials: vi.fn(), setAuthCredentials: vi.fn() }, +})); + +vi.mock('vscode', async (importOriginal) => ({ + ...(await importOriginal()), l10n: { t: vi.fn((value: string) => value), }, + window: { showErrorMessage: vi.fn() }, })); describe('retryAuthentication', () => { @@ -124,4 +141,111 @@ describe('retryAuthentication', () => { }), ).rejects.toThrow('Unsupported view for an authentication retry.'); }); + + function ruNode(): Parameters[1] & { + readReplacementKey: ReturnType>>; + } { + return { + id: 'discoveryView/azure/ru', + cluster: { clusterId: 'ru' }, + getTreeItem, + readReplacementKey: vi.fn>(), + }; + } + + it('discards the old RU key and installs the single replacement read', async (): Promise => { + const node = ruNode(); + const nativeAuthConfig = { connectionUser: 'test', connectionPassword: 'new-key' }; + node.readReplacementKey.mockResolvedValue({ + connectionString: 'mongodb://test', availableAuthMethods: [AuthMethodId.NativeAuth], nativeAuthConfig, + }); + vi.mocked(ClustersClient.getLatchReason).mockReturnValueOnce('credentialsRejected'); + vi.mocked(ClustersClient.clearCredentialRejection).mockReturnValueOnce(true); + + await retryAuthentication(actionContext as never, node); + + expect(CredentialCache.deleteCredentials).toHaveBeenCalledExactlyOnceWith('ru'); + expect(node.readReplacementKey).toHaveBeenCalledTimes(1); + expect(CredentialCache.setAuthCredentials).toHaveBeenCalledExactlyOnceWith( + 'ru', AuthMethodId.NativeAuth, 'mongodb://test', nativeAuthConfig, + ); + expect(ext.discoveryBranchDataProvider.refresh).toHaveBeenCalledExactlyOnceWith(node); + }); + + it.each([ + ['discoveryView', AuthMethodId.NativeAuth, true], + ['discoveryView', AuthMethodId.MicrosoftEntraID, false], + ['connectionsView', AuthMethodId.NativeAuth, false], + ] as const)( + 'allows the existing discovery credential setup only for Native auth (%s, %s)', + async (view, authMechanism, shouldRefresh): Promise => { + const node = { id: `${view}/test`, cluster: { clusterId: 'test' }, getTreeItem }; + vi.mocked(CredentialCache.getCredentials).mockReturnValueOnce({ + clusterId: 'test', + connectionString: 'mongodb://test', + authMechanism, + }); + vi.mocked(ClustersClient.getLatchReason).mockReturnValueOnce('credentialsRejected'); + if (shouldRefresh) { + vi.mocked(ClustersClient.clearCredentialRejection).mockReturnValueOnce(true); + } + + await retryAuthentication(actionContext as never, node); + + if (shouldRefresh) { + expect(CredentialCache.deleteCredentials).toHaveBeenCalledExactlyOnceWith('test'); + expect(CredentialCache.deleteCredentials).toHaveBeenCalledBefore( + vi.mocked(ext.discoveryBranchDataProvider.refresh), + ); + expect(ext.discoveryBranchDataProvider.refresh).toHaveBeenCalledExactlyOnceWith(node); + } else { + expect(ClustersClient.clearCredentialRejection).not.toHaveBeenCalled(); + expect(CredentialCache.deleteCredentials).not.toHaveBeenCalled(); + expect(ext.discoveryBranchDataProvider.refresh).not.toHaveBeenCalled(); + expect(ext.connectionsBranchDataProvider.refresh).not.toHaveBeenCalled(); + } + }, + ); + + it('abandons a successful key read if the epoch changed', async (): Promise => { + const node = ruNode(); + node.readReplacementKey.mockResolvedValue({ connectionString: 'mongodb://test', availableAuthMethods: [] }); + vi.mocked(ClustersClient.getLatchReason).mockReturnValueOnce('credentialsRejected'); + vi.mocked(ClustersClient.getEpoch).mockReturnValueOnce(1).mockReturnValueOnce(2); + await retryAuthentication(actionContext as never, node); + expect(ClustersClient.clearCredentialRejection).not.toHaveBeenCalled(); + expect(CredentialCache.setAuthCredentials).not.toHaveBeenCalled(); + expect(ext.discoveryBranchDataProvider.refresh).not.toHaveBeenCalled(); + }); + + it('does not refresh an old Retry after the client was replaced while its close was pending', async (): Promise => { + const node = { + id: 'connectionsView/stale', cluster: { clusterId: 'stale' }, getTreeItem, + lastConnectionFailureKind: 'clientClosed' as const, + }; + vi.mocked(ClustersClient.getEpoch).mockReturnValueOnce(0).mockReturnValueOnce(1).mockReturnValueOnce(2); + vi.mocked(ClustersClient.deleteClient).mockResolvedValueOnce(undefined); + + await retryAuthentication(actionContext as never, node); + + expect(ClustersClient.deleteClient).toHaveBeenCalledExactlyOnceWith('stale'); + expect(ext.connectionsBranchDataProvider.refresh).not.toHaveBeenCalled(); + }); + + it.each([new UserCancelledError(), Object.assign(new Error('ARM rejected access'), { statusCode: 401 })])( + 'distinguishes ARM sign-in failure from dismissal and keeps the rejection latch', + async (error): Promise => { + const node = ruNode(); + node.readReplacementKey.mockRejectedValue(error); + vi.mocked(ClustersClient.getLatchReason).mockReturnValueOnce('credentialsRejected'); + await expect(retryAuthentication(actionContext as never, node)).rejects.toBe(error); + if (error instanceof UserCancelledError) { + expect(window.showErrorMessage).not.toHaveBeenCalled(); + } else { + expect(window.showErrorMessage).toHaveBeenCalledWith('Azure sign-in needed', expect.anything()); + } + expect(ClustersClient.clearCredentialRejection).not.toHaveBeenCalled(); + expect(ext.discoveryBranchDataProvider.refresh).not.toHaveBeenCalled(); + }, + ); }); diff --git a/src/commands/retryAuthentication/retryAuthentication.ts b/src/commands/retryAuthentication/retryAuthentication.ts index 9389931b0..48a917026 100644 --- a/src/commands/retryAuthentication/retryAuthentication.ts +++ b/src/commands/retryAuthentication/retryAuthentication.ts @@ -3,14 +3,19 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { type IActionContext } from '@microsoft/vscode-azext-utils'; -import { l10n } from 'vscode'; -import { ClustersClient } from '../../documentdb/ClustersClient'; +import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext-utils'; +import { l10n, window } from 'vscode'; +import { classifyResolutionFailure } from '../../connectionDiagnostics/checks/resolveTarget'; +import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; +import { addEstablishedConnectionContext, ClustersClient } from '../../documentdb/ClustersClient'; +import { CredentialCache } from '../../documentdb/CredentialCache'; import { inferViewIdFromTreeId, Views } from '../../documentdb/Views'; import { ext } from '../../extensionVariables'; import { type TreeElement } from '../../tree/TreeElement'; import { type TreeElementWithContextValue } from '../../tree/TreeElementWithContextValue'; import { isTreeElementWithExplicitReload } from '../../tree/TreeElementWithExplicitReload'; +import { type ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; +import { ConnectionSourceUnavailableError } from '../../tree/documentdb/diagnosticCredentialRead'; const containsDelimited = (fullContext: string | undefined, value: string): boolean => { if (!fullContext) { @@ -19,7 +24,10 @@ const containsDelimited = (fullContext: string | undefined, value: string): bool return new RegExp(`\\b${value}\\b`, 'i').test(fullContext); }; -type RetryableTreeNode = TreeElement & Partial; +type RetryableTreeNode = TreeElement & + Partial> & { + readonly cluster?: { readonly clusterId: string }; + }; function getViewId(node: RetryableTreeNode): Views | undefined { if (containsDelimited(node.contextValue, Views.ConnectionsView)) { @@ -66,6 +74,83 @@ export async function retryAuthentication(context: IActionContext, node: Retryab context.telemetry.properties.failedStartupCorrelationId = failedStartupCorrelationId; } + const clusterId = node.cluster?.clusterId; + if (clusterId) { + let epoch = ClustersClient.getEpoch(clusterId); + const latch = ClustersClient.getLatchReason(clusterId); + const kind = latch === 'credentialsRejected' ? latch : node.lastConnectionFailureKind; + if (latch && latch !== 'credentialsRejected') { + return; + } + addEstablishedConnectionContext(context.telemetry, clusterId); + if (kind) { + context.telemetry.properties.connectionFailureKind = kind; + } + if (latch === 'credentialsRejected') { + if (!node.readReplacementKey) { + const view = getViewId(node); + const credentials = CredentialCache.getCredentials(clusterId); + // Native discovery nodes have no saved-credential editor. Retry through the + // existing provider flow, but never with the rejected cached credentials. + if ( + (view !== Views.DiscoveryView && view !== Views.AzureResourcesView) || + !credentials || + (credentials.authMechanism ?? AuthMethodId.NativeAuth) !== AuthMethodId.NativeAuth || + !ClustersClient.clearCredentialRejection(clusterId, epoch) + ) { + return; + } + CredentialCache.deleteCredentials(clusterId); + refreshAuthenticationNode(node); + return; + } + context.telemetry.maskEntireErrorMessage = true; + CredentialCache.deleteCredentials(clusterId); + let credentials: Awaited>>; + try { + credentials = await node.readReplacementKey(context); + } catch (error) { + if (ClustersClient.getEpoch(clusterId) !== epoch) { + return; + } + if (error instanceof UserCancelledError) { + throw error; + } + const finding = classifyResolutionFailure(new ConnectionSourceUnavailableError('azure', error)); + const signInNeeded = finding.code === 'target.sourceInaccessible' && finding.data?.reason === 'signInRequired'; + context.telemetry.properties.azureKeyReadFailure = signInNeeded ? 'signInRequired' : 'other'; + context.errorHandling.suppressDisplay = true; + void window.showErrorMessage( + signInNeeded ? l10n.t('Azure sign-in needed') : l10n.t('Could not read the database key from Azure.'), + { modal: true, detail: signInNeeded ? l10n.t('Sign in to Azure and try Retry again.') : l10n.t('Check access to the Azure resource and try again.') }, + ); + throw error; + } + if (ClustersClient.getEpoch(clusterId) !== epoch) { + return; + } + // One fresh ARM read per explicit click. A subsequent database rejection re-latches in + // the tree; it cannot start another ARM read. + if (credentials.nativeAuthConfig?.connectionPassword && + ClustersClient.clearCredentialRejection(clusterId, epoch)) { + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.NativeAuth, credentials.connectionString, credentials.nativeAuthConfig); + } else { + return; + } + } else if (kind === 'signInRequired' || kind === 'credentialsRejected' || kind === 'clientClosed') { + const closing = ClustersClient.deleteClient(clusterId); + epoch = ClustersClient.getEpoch(clusterId); + await closing; + if (ClustersClient.getEpoch(clusterId) !== epoch) { + return; + } + } + } + + refreshAuthenticationNode(node); +} + +export function refreshAuthenticationNode(node: RetryableTreeNode): void { const contextValue = node.contextValue; const viewId = getViewId(node); diff --git a/src/commands/signInAgain/signInAgain.test.ts b/src/commands/signInAgain/signInAgain.test.ts new file mode 100644 index 000000000..e4a419f6c --- /dev/null +++ b/src/commands/signInAgain/signInAgain.test.ts @@ -0,0 +1,104 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext-utils'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import * as vscode from 'vscode'; +import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; +import { getEntraSession } from '../../documentdb/auth/entraSession'; +import { ClustersClient } from '../../documentdb/ClustersClient'; +import { CredentialCache } from '../../documentdb/CredentialCache'; +import { signInAgain } from './signInAgain'; + +const pin = { kind: 'entra', providerId: 'microsoft', accountId: 'pinned', accountLabel: 'Pinned', tenantId: 'tenant' } as const; +const clusterId = 'cluster'; + +vi.mock('../../documentdb/ClustersClient', () => ({ + addEstablishedConnectionContext: vi.fn(), + ClustersClient: { + getEpoch: vi.fn(() => 1), + getLatchReason: vi.fn(() => 'credentialsRejected'), + getLastVerifiedIdentity: vi.fn(() => pin), + startAfterSignIn: vi.fn(), + getExistingClient: vi.fn(), + }, +})); +vi.mock('../../documentdb/auth/entraSession', () => ({ getEntraSession: vi.fn() })); +vi.mock('../../documentdb/auth/MicrosoftEntraIDAuthHandler', () => ({ + MicrosoftEntraIDAuthHandler: class { + public async configureAuth( + _timings: undefined, + _trace: undefined, + acquire: typeof getEntraSession, + ): Promise { + const session = await acquire({ + mode: 'forceNew', providerId: pin.providerId, resource: 'scope', tenantId: pin.tenantId, + account: { id: pin.accountId, label: pin.accountLabel }, + }); + return { verifiedIdentity: { ...pin, accountId: session?.account.id } }; + } + }, +})); +vi.mock('../retryAuthentication/retryAuthentication', () => ({ refreshAuthenticationNode: vi.fn() })); +vi.mock('../../documentdb/showClusterConnectFailure', () => ({ showClusterConnectFailure: vi.fn() })); + +function actionContext(): IActionContext { + return { telemetry: { properties: {}, measurements: {} }, errorHandling: {} } as IActionContext; +} + +describe('signInAgain', () => { + beforeEach(() => { + vi.clearAllMocks(); + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.MicrosoftEntraID, 'mongodb://test', undefined, + undefined, { tenantId: pin.tenantId }); + }); + + it.each([ + { id: pin.accountId, label: pin.accountLabel }, + { id: 'different-account', label: 'Explicitly selected in VS Code' }, + ])('requests one pinned forced session and forwards the accepted account', async (account): Promise => { + vi.mocked(getEntraSession).mockResolvedValueOnce({ account } as vscode.AuthenticationSession); + vi.mocked(ClustersClient.startAfterSignIn).mockResolvedValueOnce({} as ClustersClient); + + await signInAgain(actionContext(), { clusterId }); + + expect(getEntraSession).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ + mode: 'forceNew', tenantId: pin.tenantId, providerId: pin.providerId, + account: { id: pin.accountId, label: pin.accountLabel }, + })); + expect(ClustersClient.startAfterSignIn).toHaveBeenCalledExactlyOnceWith( + clusterId, 1, CredentialCache.getCredentials(clusterId), + { verifiedIdentity: expect.objectContaining({ accountId: account.id }) }, + ); + }); + + it.each([undefined, new Error('User did not consent to login.')])( + 'dismisses without reconnecting or retrying session acquisition', + async (error): Promise => { + if (error) { + vi.mocked(getEntraSession).mockRejectedValueOnce(error); + } else { + vi.mocked(getEntraSession).mockResolvedValueOnce(undefined); + } + await expect(signInAgain(actionContext(), { clusterId })).rejects.toBeInstanceOf(UserCancelledError); + expect(getEntraSession).toHaveBeenCalledTimes(1); + expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + }, + ); + + it('does not reconnect when the epoch changes during sign-in', async (): Promise => { + vi.mocked(getEntraSession).mockImplementationOnce(async () => { + vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); + return { account: { id: pin.accountId, label: pin.accountLabel } } as vscode.AuthenticationSession; + }); + await signInAgain(actionContext(), { clusterId }); + expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( + 'The connection was closed while you were signing in.', { modal: true }, + ); + vi.mocked(ClustersClient.getEpoch).mockReturnValue(1); + }); +}); diff --git a/src/commands/signInAgain/signInAgain.ts b/src/commands/signInAgain/signInAgain.ts new file mode 100644 index 000000000..3890cbb57 --- /dev/null +++ b/src/commands/signInAgain/signInAgain.ts @@ -0,0 +1,114 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext-utils'; +import * as vscode from 'vscode'; +import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; +import { EntraIdentityMismatchError } from '../../documentdb/auth/entraErrors/entraCallbackErrors'; +import { getEntraSession } from '../../documentdb/auth/entraSession'; +import { MicrosoftEntraIDAuthHandler } from '../../documentdb/auth/MicrosoftEntraIDAuthHandler'; +import { classifyConnectionFailure } from '../../documentdb/connectionFailures'; +import { addEstablishedConnectionContext, ClustersClient } from '../../documentdb/ClustersClient'; +import { CredentialCache } from '../../documentdb/CredentialCache'; +import { showClusterConnectFailure } from '../../documentdb/showClusterConnectFailure'; +import { type ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; +import { refreshAuthenticationNode } from '../retryAuthentication/retryAuthentication'; + +function isSignInDismissal(error: unknown): boolean { + return error instanceof UserCancelledError || + (error instanceof Error && + (error.name === 'Canceled' || + error.message === 'User did not consent to login.' || + ('errorCode' in error && error.errorCode === 'user_cancelled'))); +} + +export async function signInAgain( + context: IActionContext, + target: ClusterItemBase | { readonly clusterId: string }, +): Promise { + const node = target && 'cluster' in target ? target : undefined; + const clusterId = target && ('cluster' in target ? target.cluster.clusterId : target.clusterId); + if (!clusterId) { + throw new Error(vscode.l10n.t('No node selected.')); + } + const epoch = ClustersClient.getEpoch(clusterId); + const reason = ClustersClient.getLatchReason(clusterId); + if (reason && reason !== 'credentialsRejected') { + return; + } + const identity = ClustersClient.getLastVerifiedIdentity(clusterId); + const credentials = CredentialCache.getCredentials(clusterId); + if (identity?.kind !== 'entra' || + credentials?.authMechanism !== AuthMethodId.MicrosoftEntraID || + identity.tenantId !== credentials.entraIdConfig?.tenantId) { + throw new Error(vscode.l10n.t('No verified Microsoft Entra ID connection is available to sign in again.')); + } + + context.telemetry.maskEntireErrorMessage = true; + context.errorHandling.suppressDisplay = true; + addEstablishedConnectionContext(context.telemetry, clusterId); + const isCurrent = (): boolean => + ClustersClient.getEpoch(clusterId) === epoch && CredentialCache.getCredentials(clusterId) === credentials; + const reportClosed = (): void => { + void vscode.window.showErrorMessage(vscode.l10n.t('The connection was closed while you were signing in.'), { + modal: true, + }); + }; + + let starting = false; + try { + const handler = new MicrosoftEntraIDAuthHandler(credentials, { interactive: false, pinnedEntraIdentity: identity }); + const auth = await handler.configureAuth(undefined, undefined, async (request) => { + if (!isCurrent()) { + throw new UserCancelledError('signInAgain'); + } + const session = await getEntraSession(request); + if (!session || !isCurrent()) { + throw new UserCancelledError('signInAgain'); + } + if (session.account.id !== identity.accountId) { + // VS Code only confirms account changes when the account *label* is different. + // A same-label/different-ID session is not an explicit user choice. + if (session.account.label === identity.accountLabel || + (identity.providerId !== 'microsoft' && identity.providerId !== 'microsoft-sovereign-cloud')) { + throw new EntraIdentityMismatchError(); + } + } + return session; + }); + if (!isCurrent()) { + reportClosed(); + return; + } + starting = true; + const startup = ClustersClient.startAfterSignIn(clusterId, epoch, credentials, auth); + const startupEpoch = ClustersClient.getEpoch(clusterId); + const client = await startup; + if (!client || ClustersClient.getEpoch(clusterId) !== startupEpoch) { + reportClosed(); + return; + } + if (ClustersClient.getExistingClient(clusterId) === client && !ClustersClient.getLatchReason(clusterId) && node) { + refreshAuthenticationNode(node); + } + } catch (error) { + if (!starting && !isCurrent()) { + reportClosed(); + return; + } + if (isSignInDismissal(error)) { + throw new UserCancelledError('signInAgain'); + } + context.telemetry.properties.connectionFailureKind = classifyConnectionFailure(error, AuthMethodId.MicrosoftEntraID).kind; + await showClusterConnectFailure({ + clusterId, + clusterName: node?.cluster.name ?? vscode.l10n.t('connection'), + fallbackHeading: vscode.l10n.t('Could not sign in again.'), + error, + context, + }); + throw error; + } +} diff --git a/src/commands/updateConnectionString/ExecuteStep.ts b/src/commands/updateConnectionString/ExecuteStep.ts index 72f517229..948097962 100644 --- a/src/commands/updateConnectionString/ExecuteStep.ts +++ b/src/commands/updateConnectionString/ExecuteStep.ts @@ -18,9 +18,15 @@ export class ExecuteStep extends AzureWizardExecuteStep { public priority: number = 100; public async execute(context: UpdateCSWizardContext): Promise { + if (context.isRecoveryCurrent?.() === false) { + return; + } const resourceType = context.storageZone ?? (context.isEmulator ? ConnectionType.Emulators : ConnectionType.Clusters); const connection = await ConnectionStorageService.get(context.storageId, resourceType); + if (context.isRecoveryCurrent?.() === false) { + return; + } if (!connection || !connection.secrets?.connectionString) { ext.outputChannel.error( @@ -86,6 +92,9 @@ export class ExecuteStep extends AzureWizardExecuteStep { } await ConnectionStorageService.save(resourceType, connection, true); + if (context.isRecoveryCurrent?.() === false) { + return; + } context.connectionStringSaved = true; if (clearedEntraMethod) { diff --git a/src/commands/updateConnectionString/UpdateCSWizardContext.ts b/src/commands/updateConnectionString/UpdateCSWizardContext.ts index 81fe2af6e..ba54a2dac 100644 --- a/src/commands/updateConnectionString/UpdateCSWizardContext.ts +++ b/src/commands/updateConnectionString/UpdateCSWizardContext.ts @@ -16,4 +16,5 @@ export interface UpdateCSWizardContext extends IActionContext { originalConnectionString: string; newConnectionString?: string; connectionStringSaved?: boolean; + isRecoveryCurrent?: () => boolean; } diff --git a/src/commands/updateConnectionString/updateConnectionString.test.ts b/src/commands/updateConnectionString/updateConnectionString.test.ts index d28dc9029..8cf9fdd1c 100644 --- a/src/commands/updateConnectionString/updateConnectionString.test.ts +++ b/src/commands/updateConnectionString/updateConnectionString.test.ts @@ -85,7 +85,11 @@ vi.mock('../../services/connectionStorageService', async (importOriginal) => ({ ConnectionStorageService: { get: vi.fn(), save: vi.fn() }, })); vi.mock('../../documentdb/ClustersClient', () => ({ - ClustersClient: { connectInteractive: vi.fn(), deleteClient: vi.fn(), exists: vi.fn() }, + addEstablishedConnectionContext: vi.fn(), + ClustersClient: { + connectInteractive: vi.fn(), deleteClient: vi.fn(), exists: vi.fn(), + getEpoch: vi.fn(() => 0), getLatchReason: vi.fn(), getExistingClient: vi.fn(), + }, })); vi.mock('../../services/connectionReachabilityService', () => ({ ConnectionReachabilityService: { ensureReachable: vi.fn() }, diff --git a/src/commands/updateConnectionString/updateConnectionString.ts b/src/commands/updateConnectionString/updateConnectionString.ts index cfb7f9d25..de04cfedf 100644 --- a/src/commands/updateConnectionString/updateConnectionString.ts +++ b/src/commands/updateConnectionString/updateConnectionString.ts @@ -37,6 +37,10 @@ export async function updateConnectionString(context: IActionContext, node: Docu throw new Error(l10n.t('No node selected.')); } const recoveringRejectedDestination = node.lastConnectionFailureReason === 'entraDestinationRejected'; + const clusterId = node.cluster.clusterId; + let epoch = ClustersClient.getEpoch(clusterId); + const recoveringRejectedCredentials = ClustersClient.getLatchReason(clusterId) === 'credentialsRejected'; + const isCurrent = (): boolean => ClustersClient.getEpoch(clusterId) === epoch; // Extract the connection string but hide the username and password @@ -46,6 +50,9 @@ export async function updateConnectionString(context: IActionContext, node: Docu const resourceType = resolveStorageZone(node.cluster); const connection = await ConnectionStorageService.get(node.storageId, resourceType); + if (!isCurrent()) { + return; + } const connectionString = connection?.secrets?.connectionString || ''; context.valuesToMask.push(connectionString); @@ -63,6 +70,7 @@ export async function updateConnectionString(context: IActionContext, node: Docu storageZone: resolveStorageZone(node.cluster), storageId: node.storageId, connectionStringSaved: false, + isRecoveryCurrent: isCurrent, }; const wizard = new AzureWizard(wizardContext, { @@ -72,11 +80,25 @@ export async function updateConnectionString(context: IActionContext, node: Docu }); await wizard.prompt(); + if (!isCurrent()) { + return; + } await wizard.execute(); + if (!isCurrent()) { + return; + } - if (recoveringRejectedDestination && wizardContext.connectionStringSaved) { - await ClustersClient.deleteClient(node.cluster.clusterId); - CredentialCache.deleteCredentials(node.cluster.clusterId); + if ((recoveringRejectedDestination || recoveringRejectedCredentials) && wizardContext.connectionStringSaved) { + const closing = ClustersClient.deleteClient(clusterId); + epoch = ClustersClient.getEpoch(clusterId); + await closing; + if (!isCurrent()) { + return; + } + CredentialCache.deleteCredentials(clusterId); + if (recoveringRejectedCredentials) { + ClustersClient.clearCredentialRejection(clusterId, epoch); + } ext.connectionsBranchDataProvider.resetNodeErrorState(node.id); node.lastConnectionFailureReason = undefined; node.lastConnectionOutcome = undefined; diff --git a/src/commands/updateCredentials/ExecuteStep.ts b/src/commands/updateCredentials/ExecuteStep.ts index 4e2d78552..4e185a558 100644 --- a/src/commands/updateCredentials/ExecuteStep.ts +++ b/src/commands/updateCredentials/ExecuteStep.ts @@ -27,9 +27,15 @@ export class ExecuteStep extends AzureWizardExecuteStep { + if (context.isRecoveryCurrent?.() === false) { + return; + } const resourceType = context.storageZone ?? (context.isEmulator ? ConnectionType.Emulators : ConnectionType.Clusters); const connectionCredentials = await ConnectionStorageService.get(context.storageId, resourceType); + if (context.isRecoveryCurrent?.() === false) { + return; + } if (!connectionCredentials) { ext.outputChannel.error(l10n.t('Failed to save credentials: connection not found in storage.')); @@ -101,6 +107,10 @@ export class ExecuteStep extends AzureWizardExecuteStep boolean; + credentialsSaved?: boolean; } diff --git a/src/commands/updateCredentials/updateCredentials.test.ts b/src/commands/updateCredentials/updateCredentials.test.ts index 03545615a..bb97c28df 100644 --- a/src/commands/updateCredentials/updateCredentials.test.ts +++ b/src/commands/updateCredentials/updateCredentials.test.ts @@ -46,6 +46,8 @@ vi.mock('../../documentdb/ClustersClient', () => ({ ClustersClient: { deleteClient: (...args: unknown[]): unknown => mockDeleteClient(...args), getLastFailedStartupCorrelationId: (): undefined => undefined, + getEpoch: (): number => 0, + getLatchReason: (): undefined => undefined, }, })); vi.mock('../playground/executePlaygroundCode', () => ({ diff --git a/src/commands/updateCredentials/updateCredentials.ts b/src/commands/updateCredentials/updateCredentials.ts index 301e09c7d..07ede843c 100644 --- a/src/commands/updateCredentials/updateCredentials.ts +++ b/src/commands/updateCredentials/updateCredentials.ts @@ -57,6 +57,10 @@ export async function updateCredentials(context: IActionContext, node: DocumentD if (!node) { throw new Error(l10n.t('No node selected.')); } + const clusterId = node.cluster.clusterId; + let epoch = ClustersClient.getEpoch(clusterId); + const recoveringRejection = ClustersClient.getLatchReason(clusterId) === 'credentialsRejected'; + const isCurrent = (): boolean => ClustersClient.getEpoch(clusterId) === epoch; // The failed attempt these credentials replace; the reconnect's `connect.startup` names it in // `previousFailedStartupCorrelationId`, so it shows whether the new credentials worked. const failedStartupCorrelationId = ClustersClient.getLastFailedStartupCorrelationId(node.cluster.clusterId); @@ -72,6 +76,9 @@ export async function updateCredentials(context: IActionContext, node: DocumentD const resourceType = resolveStorageZone(node.cluster); const storedItem = await ConnectionStorageService.get(node.storageId, resourceType); + if (!isCurrent()) { + return; + } // Type guard ensures we have connection properties (not a folder) const connectionCredentials = storedItem && isConnection(storedItem) ? storedItem : undefined; const connectionString = connectionCredentials?.secrets?.connectionString || ''; @@ -115,6 +122,7 @@ export async function updateCredentials(context: IActionContext, node: DocumentD storageId: node.storageId, isErrorState, reconnectAfterError: false, + isRecoveryCurrent: isCurrent, }; const wizard = new AzureWizard(wizardContext, { @@ -137,15 +145,31 @@ export async function updateCredentials(context: IActionContext, node: DocumentD }); await wizard.prompt(); + if (!isCurrent()) { + return; + } await wizard.execute(); - - await ClustersClient.deleteClient(node.cluster.clusterId); + if (!isCurrent() || (recoveringRejection && !wizardContext.credentialsSaved)) { + return; + } const updatedStoredItem = await ConnectionStorageService.get(node.storageId, resourceType); + if (!isCurrent()) { + return; + } const updatedConnection = updatedStoredItem && isConnection(updatedStoredItem) ? updatedStoredItem : undefined; + const closing = ClustersClient.deleteClient(clusterId); + epoch = ClustersClient.getEpoch(clusterId); + await closing; + if (!isCurrent()) { + return; + } const authMethod = authMethodFromString(updatedConnection?.properties.selectedAuthMethod); const username = updatedConnection?.secrets.nativeAuthConfig?.connectionUser; const password = updatedConnection?.secrets.nativeAuthConfig?.connectionPassword; + if (recoveringRejection && authMethod === AuthMethodId.MicrosoftEntraID) { + ClustersClient.discardEntraPinForDifferentTenant(clusterId, updatedConnection?.secrets.entraIdAuthConfig?.tenantId); + } if (updatedConnection && authMethod && !(authMethod === AuthMethodId.NativeAuth && (!username || !password))) { const connectionString = new DocumentDBConnectionString(updatedConnection.secrets.connectionString); @@ -162,6 +186,9 @@ export async function updateCredentials(context: IActionContext, node: DocumentD // Clear stale credentials so the tree can prompt from storage. CredentialCache.deleteCredentials(node.cluster.clusterId); } + if (recoveringRejection && updatedConnection) { + ClustersClient.clearCredentialRejection(clusterId, epoch); + } shutdownEvaluator(node.cluster.clusterId); diff --git a/src/documentdb/ClustersClient.test.ts b/src/documentdb/ClustersClient.test.ts index 09436fc69..09908c6c3 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -541,6 +541,27 @@ describe('regular connection startup diagnostics', () => { expect(MongoClient).toHaveBeenCalledOnce(); }); + it('does not publish an explicitly selected account when Disconnect wins the startup race', async (): Promise => { + const client = await ClustersClient.connectInteractive(clusterId); + ClustersClient.reportFailure(client.binding, new MongoServerError({ code: 18 })); + const connection = pauseNextConnect(); + const startup = ClustersClient.startAfterSignIn( + clusterId, + ClustersClient.getEpoch(clusterId), + CredentialCache.getCredentials(clusterId)!, + { connectionString: 'mongodb://private-host:27017', options: {}, + verifiedIdentity: { ...verifiedIdentity, accountId: 'other-account' } }, + ); + await connection.started; + ClustersClient.latch(clusterId, 'userDisconnected'); + connection.resolve(); + + await expect(startup).resolves.toBeUndefined(); + expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); + expect(ClustersClient.getLastVerifiedIdentity(clusterId)).toEqual(verifiedIdentity); + await expect(ClustersClient.getClient(clusterId)).rejects.toMatchObject({ reason: 'userDisconnected' }); + }); + it('uses the resolved binding, preserves nonterminal errors and returns terminal unavailability without replay', async () => { const old = await ClustersClient.connectInteractive(clusterId); poolEvents.emit('topologyClosed'); diff --git a/src/documentdb/ClustersClient.ts b/src/documentdb/ClustersClient.ts index f64979c97..290bbd936 100644 --- a/src/documentdb/ClustersClient.ts +++ b/src/documentdb/ClustersClient.ts @@ -44,7 +44,7 @@ import { ext } from '../extensionVariables'; import { meterSilentCatch } from '../utils/accumulatingTelemetry'; import { type EmulatorConfiguration } from '../utils/emulatorConfiguration'; import { nonNullValue } from '../utils/nonNull'; -import { type VerifiedEntraIdentity } from './auth/AuthHandler'; +import { type AuthHandlerResponse, type VerifiedEntraIdentity } from './auth/AuthHandler'; import { AuthMethodId } from './auth/AuthMethod'; import { createAuthHandler } from './auth/createAuthHandler'; import { EntraSignInRequiredError } from './auth/entraErrors/entraCallbackErrors'; @@ -279,6 +279,14 @@ export class ClustersClient { return ClustersClient._lastVerifiedIdentities.get(clusterId); } + /** A saved, explicit tenant change must not silently use the previous tenant's pin. */ + public static discardEntraPinForDifferentTenant(clusterId: string, tenantId: string | undefined): void { + const identity = ClustersClient.getEntraPin(clusterId); + if (identity && identity.tenantId !== tenantId) { + ClustersClient._lastVerifiedIdentities.delete(clusterId); + } + } + private static getEntraPin(clusterId: string): VerifiedEntraIdentity | undefined { const identity = ClustersClient.getLastVerifiedIdentity(clusterId); return identity?.kind === 'entra' ? identity : undefined; @@ -424,6 +432,7 @@ export class ClustersClient { epoch: number, allowInteractive: boolean, expectedFingerprint?: string, + recoveredAuth?: AuthHandlerResponse, ): Promise { this.connectionCorrelationId = startupId; let originalFailure: { error: unknown } | undefined; @@ -457,7 +466,7 @@ export class ClustersClient { }; try { - await this.initializeClient(startup, epoch, allowInteractive); + await this.initializeClient(startup, epoch, allowInteractive, recoveredAuth); this.finishClientStartup(startup, 'succeeded'); } catch (error) { const canceled = error instanceof UserCancelledError; @@ -512,7 +521,12 @@ export class ClustersClient { ); } - private async initializeClient(startup: ClientStartup, epoch: number, allowInteractive: boolean): Promise { + private async initializeClient( + startup: ClientStartup, + epoch: number, + allowInteractive: boolean, + recoveredAuth?: AuthHandlerResponse, + ): Promise { const cachedCredentials = CredentialCache.getCredentials(this.clusterId); if (!cachedCredentials) { startup.credentialsMissing = true; @@ -545,7 +559,7 @@ export class ClustersClient { // Configure auth and get connection options this.advanceClientStartup(startup, 'stage02ConfiguringAuth'); - const { connectionString, options, verifiedIdentity } = await authHandler.configureAuth(startup.costTimings, { + const { connectionString, options, verifiedIdentity } = recoveredAuth ?? await authHandler.configureAuth(startup.costTimings, { startupCorrelationId: startup.id, surface: 'extension', startupProperties: startup.telemetry.properties, @@ -592,6 +606,9 @@ export class ClustersClient { }, startupTelemetry: startup.telemetry, }); + if (recoveredAuth && epoch !== ClustersClient.getEpoch(this.clusterId)) { + throw new UserCancelledError('signInAgain'); + } this._srvResolution = prepared.summary; await this.connect( startup, @@ -601,6 +618,9 @@ export class ClustersClient { credentials.emulatorConfiguration, connectionString, ); + if (recoveredAuth && epoch !== ClustersClient.getEpoch(this.clusterId)) { + throw new UserCancelledError('signInAgain'); + } // Start metadata collection and store the promise this._clusterMetadataPromise = getClusterMetadata(this._mongoClient, hosts); @@ -749,6 +769,43 @@ export class ClustersClient { return ClustersClient.acquireClient(clusterId, abortSignal, onStartup, trigger, true, false); } + /** Publish only after explicit sign-in and database startup succeed. The prior pin stays intact until then. */ + public static async startAfterSignIn( + clusterId: string, + epoch: number, + credentials: CachedClusterCredentials, + auth: AuthHandlerResponse, + ): Promise { + const reason = ClustersClient.getLatchReason(clusterId); + if (epoch !== ClustersClient.getEpoch(clusterId) || + CredentialCache.getCredentials(clusterId) !== credentials || + credentials.authMechanism !== AuthMethodId.MicrosoftEntraID || + (reason && reason !== 'credentialsRejected')) { + return undefined; + } + if (reason && !ClustersClient.clearCredentialRejection(clusterId, epoch)) { + return undefined; + } + void ClustersClient.deleteClient(clusterId).catch(() => { + ext.outputChannel.debug('[ClustersClient] failed to close a client during sign-in recovery'); + }); + const startupEpoch = ClustersClient.getEpoch(clusterId); + try { + const { promise } = ClustersClient.getOrStartClient(clusterId, startupEpoch, 'treeConnect', false, false, undefined, auth); + const client = await promise; + return startupEpoch === ClustersClient.getEpoch(clusterId) ? client : undefined; + } catch (error) { + if (startupEpoch !== ClustersClient.getEpoch(clusterId)) { + return undefined; + } + if (reason === 'credentialsRejected' || + classifyConnectionFailure(error, AuthMethodId.MicrosoftEntraID).kind === 'credentialsRejected') { + ClustersClient.latch(clusterId, 'credentialsRejected'); + } + throw error; + } + } + private static async acquireClient( clusterId: string, abortSignal: AbortSignal | undefined, @@ -822,6 +879,7 @@ export class ClustersClient { allowInteractive: boolean, background: boolean, expectedFingerprint?: string, + recoveredAuth?: AuthHandlerResponse, ): PendingStartup { const existing = ClustersClient._pendingStartups.get(clusterId); if (existing?.epoch === epoch) { @@ -847,7 +905,7 @@ export class ClustersClient { const id = randomUUID(); // Register before initialization or a caller's onStartup callback can re-enter getClient. const promise = Promise.resolve().then(() => - ClustersClient.establishClient(clusterId, epoch, id, trigger, allowInteractive, expectedFingerprint), + ClustersClient.establishClient(clusterId, epoch, id, trigger, allowInteractive, expectedFingerprint, recoveredAuth), ); const pending = { id, epoch, promise }; ClustersClient._pendingStartups.set(clusterId, pending); @@ -867,10 +925,11 @@ export class ClustersClient { trigger: ClientStartupTrigger, allowInteractive: boolean, expectedFingerprint?: string, + recoveredAuth?: AuthHandlerResponse, ): Promise { const client = new ClustersClient(clusterId); try { - await client.initClient(id, trigger, epoch, allowInteractive, expectedFingerprint); + await client.initClient(id, trigger, epoch, allowInteractive, expectedFingerprint, recoveredAuth); if (client._closed) { throw new MongoNotConnectedError(l10n.t('The connection is unavailable.')); } diff --git a/src/documentdb/ClustersExtension.ts b/src/documentdb/ClustersExtension.ts index 5141727e1..cd3b99150 100644 --- a/src/documentdb/ClustersExtension.ts +++ b/src/documentdb/ClustersExtension.ts @@ -83,6 +83,7 @@ import { refreshView } from '../commands/refreshView/refreshView'; import { removeConnection } from '../commands/removeConnection/removeConnection'; import { removeDiscoveryRegistry } from '../commands/removeDiscoveryRegistry/removeDiscoveryRegistry'; import { retryAuthentication } from '../commands/retryAuthentication/retryAuthentication'; +import { signInAgain } from '../commands/signInAgain/signInAgain'; import { revealView } from '../commands/revealView/revealView'; import { clearSchemaCache } from '../commands/schemaStore/clearSchemaCache'; import { showSchemaStoreStats } from '../commands/schemaStore/showSchemaStoreStats'; @@ -1008,6 +1009,10 @@ export class ClustersExtension implements vscode.Disposable { 'vscode-documentdb.command.internal.retry', withTreeNodeCommandCorrelation(retryAuthentication), ); + registerCommandWithTreeNodeUnwrapping( + 'vscode-documentdb.command.signInAgain', + withTreeNodeCommandCorrelation(signInAgain), + ); registerCommandWithTreeNodeUnwrapping( 'vscode-documentdb.command.internal.revealView', withTreeNodeCommandCorrelation(revealView), diff --git a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts index b767942c3..671f5a530 100644 --- a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts +++ b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts @@ -79,6 +79,7 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { public async configureAuth( timings?: ConnectionStartupTimings, traceContext?: AuthTraceContext, + acquireRecoverySession?: (request: Parameters[0]) => ReturnType, ): Promise { const authCorrelationId = randomUUID(); const { connectionString, clusterId } = this.clusterCredentials; @@ -140,12 +141,12 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { throw new EntraSignInRequiredError('providerChanged'); } try { - const session = await getEntraSession({ + const session = await (acquireRecoverySession ?? getEntraSession)({ providerId: pin?.providerId ?? signInEnvironment.providerId, resource, tenantId, account: pin ? { id: pin.accountId, label: pin.accountLabel } : undefined, - mode: interactive ? 'interactive' : 'silent', + mode: acquireRecoverySession ? 'forceNew' : interactive ? 'interactive' : 'silent', }); return { session, signInEnvironment }; } finally { @@ -177,7 +178,7 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { } throw new Error(l10n.t('Failed to obtain Entra ID token.')); } - if (pin && session.account.id !== pin.accountId) { + if (pin && !acquireRecoverySession && session.account.id !== pin.accountId) { throw new EntraIdentityMismatchError(); } } catch (error) { diff --git a/src/documentdb/connectionFailures.ts b/src/documentdb/connectionFailures.ts index 2966504a4..740711801 100644 --- a/src/documentdb/connectionFailures.ts +++ b/src/documentdb/connectionFailures.ts @@ -75,6 +75,9 @@ export function classifyConnectionFailure(error: unknown, authMethod?: AuthMetho return { kind: 'identityChanged', generation: 'evict' }; case 'credentialsMissing': return { kind: 'credentialsMissing', generation: 'none' }; + case 'credentialsRejected': + case 'signInRequired': + return { kind: candidate.reason, generation: 'none', note: 'alreadyUnavailable' }; default: return { ...OTHER, note: 'alreadyUnavailable' }; } diff --git a/src/plugins/service-atlas-mongodb/discovery-tree/AtlasClusterItem.test.ts b/src/plugins/service-atlas-mongodb/discovery-tree/AtlasClusterItem.test.ts index a8340f9dc..36abd6522 100644 --- a/src/plugins/service-atlas-mongodb/discovery-tree/AtlasClusterItem.test.ts +++ b/src/plugins/service-atlas-mongodb/discovery-tree/AtlasClusterItem.test.ts @@ -108,9 +108,12 @@ vi.mock('../../../documentdb/CredentialCache', () => ({ })); vi.mock('../../../documentdb/ClustersClient', () => ({ + addEstablishedConnectionContext: vi.fn(), ClustersClient: { connectInteractive: vi.fn(), deleteClient: vi.fn(), + getEpoch: vi.fn(() => 0), + getLatchReason: vi.fn(), }, })); diff --git a/src/plugins/service-atlas-mongodb/discovery-tree/AtlasClusterItem.ts b/src/plugins/service-atlas-mongodb/discovery-tree/AtlasClusterItem.ts index b315dd7c2..8b6ee7b5d 100644 --- a/src/plugins/service-atlas-mongodb/discovery-tree/AtlasClusterItem.ts +++ b/src/plugins/service-atlas-mongodb/discovery-tree/AtlasClusterItem.ts @@ -183,6 +183,7 @@ export class AtlasClusterItem extends ClusterItemBase { */ protected async authenticateAndConnect(): Promise { const result = await callWithTelemetryAndErrorHandling('connect', async (context: IActionContext) => { + const epoch = ClustersClient.getEpoch(this.cluster.clusterId); const connectionStartTime = monotonicNow(); context.telemetry.properties.view = Views.DiscoveryView; context.telemetry.properties.discoveryProviderId = DISCOVERY_PROVIDER_ID; @@ -277,8 +278,7 @@ export class AtlasClusterItem extends ClusterItemBase { await this.showConnectionFailure(context, error); // Clean up failed connection - await ClustersClient.deleteClient(this.cluster.clusterId); - CredentialCache.deleteCredentials(this.cluster.clusterId); + await this.finishFailedStartup(context, error, epoch); return null; } diff --git a/src/plugins/service-azure-mongo-ru/discovery-tree/documentdb/MongoRUResourceItem.ts b/src/plugins/service-azure-mongo-ru/discovery-tree/documentdb/MongoRUResourceItem.ts index c3087cc89..1244b4b17 100644 --- a/src/plugins/service-azure-mongo-ru/discovery-tree/documentdb/MongoRUResourceItem.ts +++ b/src/plugins/service-azure-mongo-ru/discovery-tree/documentdb/MongoRUResourceItem.ts @@ -82,12 +82,17 @@ export class MongoRUResourceItem extends ClusterItemBase { return credentials; } + public override readReplacementKey(context: IActionContext): Promise { + return this.readCredentials(context); + } + /** * Authenticates and connects to the MongoDB cluster. * @returns An instance of ClustersClient if successful; otherwise, null. */ protected async authenticateAndConnect(): Promise { const result = await callWithTelemetryAndErrorHandling('connect', async (context: IActionContext) => { + const epoch = ClustersClient.getEpoch(this.cluster.clusterId); const connectionStartTime = Date.now(); context.telemetry.properties.view = Views.DiscoveryView; context.telemetry.properties.discoveryProviderId = DISCOVERY_PROVIDER_ID; @@ -161,8 +166,7 @@ export class MongoRUResourceItem extends ClusterItemBase { }); // Clean up failed connection - await ClustersClient.deleteClient(this.cluster.clusterId); - CredentialCache.deleteCredentials(this.cluster.clusterId); + await this.finishFailedStartup(context, error, epoch); return null; } diff --git a/src/plugins/service-azure-mongo-vcore/discovery-tree/documentdb/DocumentDBResourceItem.ts b/src/plugins/service-azure-mongo-vcore/discovery-tree/documentdb/DocumentDBResourceItem.ts index a50d347c6..8c68af0f6 100644 --- a/src/plugins/service-azure-mongo-vcore/discovery-tree/documentdb/DocumentDBResourceItem.ts +++ b/src/plugins/service-azure-mongo-vcore/discovery-tree/documentdb/DocumentDBResourceItem.ts @@ -102,6 +102,7 @@ export class DocumentDBResourceItem extends ClusterItemBase { */ protected async authenticateAndConnect(): Promise { const result = await callWithTelemetryAndErrorHandling('connect', async (context: IActionContext) => { + const epoch = ClustersClient.getEpoch(this.cluster.clusterId); const connectionStartTime = Date.now(); context.telemetry.properties.view = Views.DiscoveryView; context.telemetry.properties.discoveryProviderId = DISCOVERY_PROVIDER_ID; @@ -220,8 +221,7 @@ export class DocumentDBResourceItem extends ClusterItemBase { }); // Clean up failed connection - await ClustersClient.deleteClient(this.cluster.clusterId); - CredentialCache.deleteCredentials(this.cluster.clusterId); + await this.finishFailedStartup(context, error, epoch); return null; } diff --git a/src/plugins/service-azure-vm/discovery-tree/vm/AzureVMResourceItem.ts b/src/plugins/service-azure-vm/discovery-tree/vm/AzureVMResourceItem.ts index d38c83d0b..9b266cb45 100644 --- a/src/plugins/service-azure-vm/discovery-tree/vm/AzureVMResourceItem.ts +++ b/src/plugins/service-azure-vm/discovery-tree/vm/AzureVMResourceItem.ts @@ -254,6 +254,7 @@ export class AzureVMResourceItem extends ClusterItemBase { */ protected async authenticateAndConnect(): Promise { const result = await callWithTelemetryAndErrorHandling('connect', async (context: IActionContext) => { + const epoch = ClustersClient.getEpoch(this.cluster.clusterId); context.telemetry.properties.discoveryProviderId = DISCOVERY_PROVIDER_ID; context.telemetry.properties.view = Views.DiscoveryView; if (this.journeyCorrelationId) { @@ -330,8 +331,7 @@ export class AzureVMResourceItem extends ClusterItemBase { error, context, }); - await ClustersClient.deleteClient(this.cluster.clusterId); - CredentialCache.deleteCredentials(this.cluster.clusterId); + await this.finishFailedStartup(context, error, epoch); return null; } diff --git a/src/plugins/service-kubernetes/discovery-tree/documentdb/KubernetesResourceItem.test.ts b/src/plugins/service-kubernetes/discovery-tree/documentdb/KubernetesResourceItem.test.ts index 4e6c066a9..36dc654f5 100644 --- a/src/plugins/service-kubernetes/discovery-tree/documentdb/KubernetesResourceItem.test.ts +++ b/src/plugins/service-kubernetes/discovery-tree/documentdb/KubernetesResourceItem.test.ts @@ -126,10 +126,13 @@ vi.mock('../../../../documentdb/CredentialCache', () => ({ })); vi.mock('../../../../documentdb/ClustersClient', () => ({ + addEstablishedConnectionContext: vi.fn(), ClustersClient: { exists: vi.fn().mockReturnValue(false), connectInteractive: (...args: unknown[]) => mockGetClient(...args), deleteClient: vi.fn(), + getEpoch: vi.fn(() => 0), + getLatchReason: vi.fn(), }, })); diff --git a/src/plugins/service-kubernetes/discovery-tree/documentdb/KubernetesResourceItem.ts b/src/plugins/service-kubernetes/discovery-tree/documentdb/KubernetesResourceItem.ts index e117c9270..1ddf1100d 100644 --- a/src/plugins/service-kubernetes/discovery-tree/documentdb/KubernetesResourceItem.ts +++ b/src/plugins/service-kubernetes/discovery-tree/documentdb/KubernetesResourceItem.ts @@ -257,6 +257,8 @@ export class KubernetesResourceItem extends ClusterItemBase { const result = await callWithTelemetryAndErrorHandling('connect', async (context: IActionContext) => { + const { ClustersClient } = await import('../../../../documentdb/ClustersClient'); + const epoch = ClustersClient.getEpoch(this.cluster.clusterId); this.populateTelemetry(context); context.telemetry.properties.connectionInitiatedFrom = 'discoveryView'; @@ -367,9 +369,7 @@ export class KubernetesResourceItem extends ClusterItemBase return this.failedChildrenCache.get(element.id); } + // Capture the established generation before expansion. A classified failure can evict it + // before the getChildren event is reported. + const clusterId = (element as { cluster?: { clusterId?: string } }).cluster?.clusterId; + if (clusterId) { + addEstablishedConnectionContext(context.telemetry, clusterId); + } // 2. Fetch the children of the current element const children = await this.fetchChildrenWithDiagnostics(element, context, childrenFetchFunc); context.telemetry.measurements.childrenCount = children?.length ?? 0; diff --git a/src/tree/azure-resources-view/documentdb/VCoreResourceItem.ts b/src/tree/azure-resources-view/documentdb/VCoreResourceItem.ts index ee2a224aa..a14655e1f 100644 --- a/src/tree/azure-resources-view/documentdb/VCoreResourceItem.ts +++ b/src/tree/azure-resources-view/documentdb/VCoreResourceItem.ts @@ -94,6 +94,7 @@ export class VCoreResourceItem extends ClusterItemBase { */ protected async authenticateAndConnect(): Promise { const result = await callWithTelemetryAndErrorHandling('connect', async (context: IActionContext) => { + const epoch = ClustersClient.getEpoch(this.cluster.clusterId); context.telemetry.properties.view = Views.AzureResourcesView; context.telemetry.properties.branch = 'documentdb'; context.telemetry.properties.connectionInitiatedFrom = Views.AzureResourcesView; @@ -203,8 +204,7 @@ export class VCoreResourceItem extends ClusterItemBase { }); // Clean up failed connection - await ClustersClient.deleteClient(this.cluster.clusterId); - CredentialCache.deleteCredentials(this.cluster.clusterId); + await this.finishFailedStartup(context, error, epoch); return null; } diff --git a/src/tree/azure-resources-view/mongo-ru/RUCoreResourceItem.ts b/src/tree/azure-resources-view/mongo-ru/RUCoreResourceItem.ts index 5f62ee492..6eca8c5d7 100644 --- a/src/tree/azure-resources-view/mongo-ru/RUCoreResourceItem.ts +++ b/src/tree/azure-resources-view/mongo-ru/RUCoreResourceItem.ts @@ -78,6 +78,10 @@ export class RUResourceItem extends ClusterItemBase { return credentials; } + public override readReplacementKey(context: IActionContext): Promise { + return this.readCredentials(context); + } + /** * Authenticates and connects to the Azure Cosmos DB for MongoDB (RU) cluster. * No authentication prompt as we're accessing the cluster with the default credentials. @@ -118,6 +122,7 @@ export class RUResourceItem extends ClusterItemBase { }), ); + const epoch = ClustersClient.getEpoch(this.cluster.clusterId); try { const clustersClient = await this.getClientWithProgress(this.cluster.clusterId); @@ -150,8 +155,7 @@ export class RUResourceItem extends ClusterItemBase { }); // Clean up failed connection - await ClustersClient.deleteClient(this.cluster.clusterId); - CredentialCache.deleteCredentials(this.cluster.clusterId); + await this.finishFailedStartup(context, error, epoch); return null; } diff --git a/src/tree/connections-view/DocumentDBClusterItem.test.ts b/src/tree/connections-view/DocumentDBClusterItem.test.ts index 98eec549f..35aed1f64 100644 --- a/src/tree/connections-view/DocumentDBClusterItem.test.ts +++ b/src/tree/connections-view/DocumentDBClusterItem.test.ts @@ -88,10 +88,11 @@ vi.mock('../../services/connectionStorageService', async (importOriginal) => ({ ConnectionStorageService: { get: vi.fn(), save: vi.fn() }, })); vi.mock('../../documentdb/ClustersClient', () => ({ - ClustersClient: { connectInteractive: vi.fn(), deleteClient: vi.fn(), exists: vi.fn() }, + addEstablishedConnectionContext: vi.fn(), + ClustersClient: { connectInteractive: vi.fn(), deleteClient: vi.fn(), exists: vi.fn(), getEpoch: vi.fn(() => 0), getLatchReason: vi.fn() }, })); vi.mock('../../documentdb/CredentialCache', () => ({ - CredentialCache: { hasCredentials: vi.fn(), setAuthCredentials: vi.fn(), deleteCredentials: vi.fn() }, + CredentialCache: { hasCredentials: vi.fn(), setAuthCredentials: vi.fn(), deleteCredentials: vi.fn(), getCredentials: vi.fn() }, })); vi.mock('../../services/connectionReachabilityService', () => ({ ConnectionReachabilityService: { ensureReachable: vi.fn() }, @@ -315,6 +316,16 @@ describe('connect request telemetry', () => { expect(connectEvent()).toMatchObject({ connectionResult: 'success', connectionCorrelationId: 'attempt' }); }); + + it('does not drop startup settings for a transient connection error', async (): Promise => { + vi.mocked(ClustersClient.connectInteractive).mockRejectedValue( + Object.assign(new Error('connection refused'), { code: 'ECONNREFUSED' }), + ); + await expect(makeItem().connect()).resolves.toBeNull(); + expect(ClustersClient.deleteClient).toHaveBeenCalledExactlyOnceWith('stable-id'); + expect(CredentialCache.deleteCredentials).not.toHaveBeenCalled(); + expect(connectEvent()).toMatchObject({ connectionFailureKind: 'transient' }); + }); }); describe('DocumentDBClusterItem credential reachability', (): void => { diff --git a/src/tree/connections-view/DocumentDBClusterItem.ts b/src/tree/connections-view/DocumentDBClusterItem.ts index 37ee132ca..639b853f0 100644 --- a/src/tree/connections-view/DocumentDBClusterItem.ts +++ b/src/tree/connections-view/DocumentDBClusterItem.ts @@ -262,6 +262,8 @@ export class DocumentDBClusterItem extends ClusterItemBase { return result ?? null; } - protected override async getClientWithProgress(clusterId: string): Promise { + protected override async getClientWithProgress( + clusterId: string, + onReuse?: (client: ClustersClient | undefined) => void, + ): Promise { const result = await callWithTelemetryAndErrorHandling('connect', async (context: IActionContext) => { context.errorHandling.rethrow = true; context.errorHandling.suppressDisplay = true; @@ -391,7 +394,7 @@ class QuickStartClusterItem extends ClusterItemBase { if (connectionString) { maskSensitiveValuesInTelemetry(context, new DocumentDBConnectionString(connectionString)); } - return super.getClientWithProgress(clusterId); + return super.getClientWithProgress(clusterId, onReuse); }); return nonNullValue(result, 'connected client', 'QuickStartClusterItem.getClientWithProgress'); } diff --git a/src/tree/documentdb/ClusterItemBase.test.ts b/src/tree/documentdb/ClusterItemBase.test.ts index 01e8663a4..e9b29b340 100644 --- a/src/tree/documentdb/ClusterItemBase.test.ts +++ b/src/tree/documentdb/ClusterItemBase.test.ts @@ -12,7 +12,10 @@ import { } from '@microsoft/vscode-azext-utils'; import * as vscode from 'vscode'; import { EntraDestinationRejectedError } from '../../documentdb/auth/oidcAllowedHosts'; +import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; import { ClustersClient, type DatabaseItemModel } from '../../documentdb/ClustersClient'; +import { ConnectionUnavailableError } from '../../documentdb/ConnectionUnavailableError'; +import { CredentialCache } from '../../documentdb/CredentialCache'; import { ShellCommandIds } from '../../documentdb/shell/constants'; import { type Experience } from '../../DocumentDBExperiences'; import { containsRetryNode, RETRY_NODE_ID_SUFFIX } from '../api/retryNode'; @@ -67,11 +70,17 @@ const mockGetSetting = vi.fn().mockReturnValue(false); vi.mock('../../documentdb/CredentialCache', () => ({ CredentialCache: { hasCredentials: (...args: unknown[]) => mockHasCredentials(...args), + getCredentials: vi.fn(), + deleteCredentials: vi.fn(), }, })); vi.mock('../../documentdb/ClustersClient', () => ({ - ClustersClient: { connectInteractive: vi.fn(), exists: vi.fn().mockReturnValue(false), getExistingClient: vi.fn() }, + addEstablishedConnectionContext: vi.fn(), + ClustersClient: { + connectInteractive: vi.fn(), exists: vi.fn().mockReturnValue(false), getExistingClient: vi.fn(), + getLatchReason: vi.fn(), getEpoch: vi.fn(() => 0), getLastVerifiedIdentity: vi.fn(), reportFailure: vi.fn(), + }, })); vi.mock('../../extensionVariables', () => ({ @@ -436,6 +445,36 @@ describe('ClusterItemBase.getChildren — cached client connection failure handl ); }); + it('renders the Entra action for an already-latched rejection without reporting a new failure', async (): Promise => { + ClustersClientMock.getLatchReason.mockReturnValueOnce('credentialsRejected'); + ClustersClientMock.connectInteractive.mockRejectedValueOnce(new ConnectionUnavailableError('credentialsRejected')); + const credentials = { authMechanism: AuthMethodId.MicrosoftEntraID } as ReturnType; + vi.mocked(CredentialCache.getCredentials).mockReturnValue(credentials); + ClustersClientMock.getLastVerifiedIdentity.mockReturnValueOnce({ + kind: 'entra', providerId: 'microsoft', accountLabel: 'test', accountId: 'id', + }); + const item = new TestClusterItem(makeCluster(), null); + + expect((await item.getChildren()).map(({ id }) => id)).toEqual([ + 'cluster-1/sign-in-again', 'cluster-1/diagnose', 'cluster-1/open-shell', 'cluster-1/retry', + ]); + expect(ClustersClientMock.reportFailure).not.toHaveBeenCalled(); + expect(CredentialCache.deleteCredentials).not.toHaveBeenCalled(); + vi.mocked(CredentialCache.getCredentials).mockReset(); + }); + + it('reports the binding that executed listDatabases, not the current cache entry', async (): Promise => { + const error = new Error('deprecated generation'); + const binding = { clusterId: 'cluster-1', fingerprint: 'old', generation: 1 }; + const client = { ...makeClient(vi.fn().mockRejectedValue(error)), binding } as ClustersClient; + ClustersClientMock.connectInteractive.mockResolvedValueOnce(client); + ClustersClientMock.reportFailure.mockReturnValueOnce(undefined); + + expect(await new TestClusterItem(makeCluster(), null).getChildren()).toEqual([]); + expect(ClustersClientMock.reportFailure).toHaveBeenCalledExactlyOnceWith(binding, error); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + }); + it('returns a retry node when reusing the cached client fails (without listing databases)', async () => { (ClustersClientMock.connectInteractive as Mock).mockRejectedValue(new Error('server down')); diff --git a/src/tree/documentdb/ClusterItemBase.ts b/src/tree/documentdb/ClusterItemBase.ts index 7aeab3a49..525488e94 100644 --- a/src/tree/documentdb/ClusterItemBase.ts +++ b/src/tree/documentdb/ClusterItemBase.ts @@ -14,15 +14,20 @@ import * as l10n from '@vscode/l10n'; import * as vscode from 'vscode'; import { type IconPath } from 'vscode'; import { type Experience } from '../../DocumentDBExperiences'; -import { ClustersClient, type DatabaseItemModel } from '../../documentdb/ClustersClient'; +import { + addEstablishedConnectionContext, + ClustersClient, + type DatabaseItemModel, +} from '../../documentdb/ClustersClient'; import { CredentialCache } from '../../documentdb/CredentialCache'; import { type EntraIdAuthConfig, type ManagedIdentityAuthConfig, type NativeAuthConfig, } from '../../documentdb/auth/AuthConfig'; -import { type AuthMethodId } from '../../documentdb/auth/AuthMethod'; +import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; import { isEntraDestinationRejectedError } from '../../documentdb/auth/oidcAllowedHosts'; +import { classifyConnectionFailure, type ConnectionFailure } from '../../documentdb/connectionFailures'; import { ShellCommandIds } from '../../documentdb/shell/constants'; import { showClusterConnectFailure } from '../../documentdb/showClusterConnectFailure'; import { ext } from '../../extensionVariables'; @@ -103,6 +108,7 @@ export abstract class ClusterItemBase { context.errorHandling.suppressDisplay = true; + context.telemetry.maskEntireErrorMessage = true; + addEstablishedConnectionContext(context.telemetry, this.cluster.clusterId); context.telemetry.properties.connectionResult = 'failed'; context.telemetry.properties.experience = this.experience.api; context.telemetry.properties.failurePhase = 'cachedClientConnect'; @@ -248,13 +258,20 @@ export abstract class ClusterItemBase { + protected async getClientWithProgress( + clusterId: string, + onReuse?: (client: ClustersClient | undefined) => void, + ): Promise { const abortController = new AbortController(); const clientPromise = ClustersClient.connectInteractive( clusterId, abortController.signal, (id) => { this.lastConnectionCorrelationId = id; + if (onReuse) { + const client = ClustersClient.getExistingClient(clusterId); + onReuse(client?.connectionCorrelationId === id ? client : undefined); + } }, 'treeConnect', ); @@ -285,6 +302,45 @@ export abstract class ClusterItemBase { + const { clusterId } = this.cluster; + const failure = this.classifyTreeFailure(error); + context.telemetry.properties.connectionFailureKind = failure.kind; + addEstablishedConnectionContext(context.telemetry, clusterId); + if (ClustersClient.getEpoch(clusterId) !== epoch || failure.note === 'cancelled') { + return; + } + this.lastConnectionFailureKind = failure.kind; + if (ClustersClient.getLatchReason(clusterId)) { + return; + } + const retainedEntraSettings = failure.kind === 'credentialsRejected' && this.canSignInAgain(); + if (failure.kind === 'other' || (failure.kind === 'credentialsRejected' && !retainedEntraSettings)) { + CredentialCache.deleteCredentials(clusterId); + } + if (retainedEntraSettings || (failure.kind === 'credentialsRejected' && this.readReplacementKey)) { + ClustersClient.latch(clusterId, 'credentialsRejected'); + } + await ClustersClient.deleteClient(clusterId); + } + + /** Only the two Azure RU item types can replace a rejected database key from ARM. */ + public readReplacementKey?(context: IActionContext): Promise; + + private classifyTreeFailure(error: unknown): ConnectionFailure { + const method = CredentialCache.getCredentials(this.cluster.clusterId)?.authMechanism ?? AuthMethodId.NativeAuth; + return classifyConnectionFailure(error, method); + } + + private canSignInAgain(): boolean { + const { clusterId } = this.cluster; + const credentials = CredentialCache.getCredentials(clusterId); + const identity = ClustersClient.getLastVerifiedIdentity(clusterId); + return credentials?.authMechanism === AuthMethodId.MicrosoftEntraID && identity?.kind === 'entra' && + identity.tenantId === credentials.entraIdConfig?.tenantId; + } + /** * Builds the FAILURE-TYPE error-recovery nodes owned by the element layer. * @@ -303,6 +359,17 @@ export abstract class ClusterItemBase { + const { clusterId, name } = this.cluster; + const failure = failedClient + ? classifyConnectionFailure(error, failedClient.authMethod) + : this.classifyTreeFailure(error); + const destinationRejected = isEntraDestinationRejectedError(error); + let children: TreeElement[] = []; + const telemetry = callWithTelemetryAndErrorHandling('connect', async (context) => { + context.errorHandling.suppressDisplay = true; + context.telemetry.maskEntireErrorMessage = true; + context.telemetry.properties.connectionResult = failure.note === 'cancelled' ? 'cancelled' : 'failed'; + context.telemetry.properties.source = 'treeExpansion'; + context.telemetry.properties.experience = this.experience.api; + context.telemetry.properties.failurePhase = phase; + if (failedClient?.binding) { + addEstablishedConnectionContext(context.telemetry, failedClient); + const kind = ClustersClient.reportFailure(failedClient.binding, error); + if (!kind && failure.note !== 'cancelled') { + return; + } + this.lastConnectionFailureKind = kind; + } else { + if (acquisitionEpoch !== undefined && ClustersClient.getEpoch(clusterId) !== acquisitionEpoch && + failure.note !== 'cancelled' && failure.note !== 'alreadyUnavailable') { + return; + } + addEstablishedConnectionContext(context.telemetry, clusterId); + this.lastConnectionFailureKind = failure.kind; + if (this.lastConnectionCorrelationId) { + context.telemetry.properties.connectionCorrelationId = this.lastConnectionCorrelationId; + } + // A failed replacement startup has no published generation of its own. + if (failure.kind === 'credentialsRejected' && !failure.note && + (this.canSignInAgain() || this.readReplacementKey) && !ClustersClient.getLatchReason(clusterId)) { + ClustersClient.latch(clusterId, 'credentialsRejected'); + } + } + context.telemetry.properties.connectionFailureKind = failure.kind; + if (failure.note === 'cancelled') { + this.lastConnectionOutcome = 'canceled'; + throw error; + } + this.lastConnectionOutcome = 'failed'; + this.lastConnectionFailureReason = destinationRejected ? 'entraDestinationRejected' : undefined; + children = this.createErrorRecoveryChildren(); + if (destinationRejected) { + await showClusterConnectFailure({ clusterId, clusterName: name, error, context }); + } else { + const renderingEpoch = ClustersClient.getEpoch(clusterId); + const explanation = await ErrorExplanationService.explain({ clusterId, error }); + if (ClustersClient.getEpoch(clusterId) !== renderingEpoch) { + children = []; + return; + } + context.telemetry.properties.explanationProviderId = explanation?.providerId ?? 'none'; + const heading = explanation?.message ?? (phase === 'listDatabases' + ? vscode.l10n.t('Failed to load databases for "{0}"', name) + : vscode.l10n.t('Failed to connect to "{0}"', name)); + const detail = failure.note === 'alreadyUnavailable' && this.lastConnectionFailureKind === 'signInRequired' + ? vscode.l10n.t('Sign in again to continue using this connection.') + : error instanceof Error ? error.message : String(error); + void vscode.window.showErrorMessage(heading, { modal: true, detail }); + } + throw error; + }); + await telemetry; + return children; + } + /** * Authenticates and connects to the cluster to list all available databases. * Here, the MongoDB client is created and cached for future use. @@ -342,100 +483,29 @@ export abstract class ClusterItemBase { - context.telemetry.properties.connectionResult = 'cancelled'; - context.telemetry.properties.source = 'treeExpansion'; - context.telemetry.properties.experience = this.experience.api; - throw error; - }); - - return []; - } - - // Reusing a cached client can still fail (server down, stale credentials, dropped - // tunnel, TLS/auth renegotiation, …). If we let the rejection propagate out of - // getChildren(), the tree expansion would end with no children and — crucially — - // no retry affordance, leaving the user stuck. Mirror the `!clustersClient` and - // listDatabases branches: record telemetry, surface a modal, and return a retry - // node. We intentionally keep the cached credentials so the retry can re-attempt - // the connection without forcing the user to re-enter credentials (the failure may - // be transient). - const errorMessage = error instanceof Error ? error.message : String(error); - const entraRejected = isEntraDestinationRejectedError(error); - const explanation = entraRejected - ? undefined - : await ErrorExplanationService.explain({ - clusterId: this.cluster.clusterId, - error, - }); - - const telemetryPromise = callWithTelemetryAndErrorHandling('connect', async (telemetryContext) => { - telemetryContext.errorHandling.suppressDisplay = true; - telemetryContext.telemetry.properties.connectionResult = 'failed'; - telemetryContext.telemetry.properties.source = 'treeExpansion'; - telemetryContext.telemetry.properties.experience = this.experience.api; - telemetryContext.telemetry.properties.failurePhase = 'cachedClientConnect'; - telemetryContext.telemetry.properties.explanationProviderId = explanation?.providerId ?? 'none'; - // The connection being reused, so the failure joins its destination. - const reusedConnectionId = ClustersClient.getExistingClient( - this.cluster.clusterId, - )?.connectionCorrelationId; - if (reusedConnectionId) { - telemetryContext.telemetry.properties.connectionCorrelationId = reusedConnectionId; - } - if (entraRejected) { - await showClusterConnectFailure({ - clusterId: this.cluster.clusterId, - clusterName: this.cluster.name, - error, - context: telemetryContext, - }); - } - throw error; - }); - if (entraRejected) { - await telemetryPromise; + if (!ClustersClient.getLatchReason(clusterId)) { + await this.beforeCachedClientConnect(); } - - ext.outputChannel.appendLine( - l10n.t('Failed to reuse the active connection for "{cluster}": {error}', { - cluster: this.cluster.name, - error: errorMessage, - }), - ); - - if (!entraRejected) { - void vscode.window.showErrorMessage( - explanation?.message ?? vscode.l10n.t('Failed to connect to "{0}"', this.cluster.name), - { - modal: true, - detail: errorMessage, - }, - ); - } - - return this.createErrorRecoveryChildren(); + acquisitionEpoch = ClustersClient.getEpoch(clusterId); + clustersClient = await this.getClientWithProgress(clusterId, (client) => { reusedClient = client; }); + } catch (error) { + return this.renderExpansionFailure(error, 'cachedClientConnect', reusedClient, acquisitionEpoch); } } else { // Call to the abstract method to authenticate and connect to the cluster @@ -463,45 +533,7 @@ export abstract class ClusterItemBase { - telemetryContext.errorHandling.suppressDisplay = true; - telemetryContext.telemetry.properties.connectionResult = 'failed'; - telemetryContext.telemetry.properties.source = 'treeExpansion'; - telemetryContext.telemetry.properties.experience = this.experience.api; - telemetryContext.telemetry.properties.failurePhase = 'listDatabases'; - telemetryContext.telemetry.properties.explanationProviderId = explanation?.providerId ?? 'none'; - // The connection that worked but was refused the listing, so the failure joins its destination. - if (connectedClient.connectionCorrelationId) { - telemetryContext.telemetry.properties.connectionCorrelationId = - connectedClient.connectionCorrelationId; - } - throw error; - }); - - ext.outputChannel.appendLine( - l10n.t('Failed to list databases for "{cluster}": {error}', { - cluster: this.cluster.name, - error: errorMessage, - }), - ); - - void vscode.window.showErrorMessage( - explanation?.message ?? vscode.l10n.t('Failed to load databases for "{0}"', this.cluster.name), - { modal: true, detail: errorMessage }, - ); - - return this.createErrorRecoveryChildren(); + return this.renderExpansionFailure(error, 'listDatabases', connectedClient); } // A deep link that opens the dashboard itself suppresses the automatic open; that is not a skip. From 814debb3dc07739eba33cb51e68b14bfe33d0e8a Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 14:14:16 +0000 Subject: [PATCH 086/380] docs: record WI-5 verification and the OP-3 candidate Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../features/connection-lifecycle/iterations/01-dev-plan.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index a8dbe8a1e..e4b5fb2b9 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md @@ -1300,6 +1300,12 @@ shim (0005). rejected settings. Only the matching explicit recovery can clear the rejection, and only if its epoch is current. The operator preferred the simpler option and asked to record [decision 0015](../decisions.md#0015-use-the-existing-latch-to-block-startup-after-authentication-rejection). +- **OP-3 candidate:** Host and tree recovery, Retry and **Sign in again** are implemented + for [draft PR4 (#1117)](https://github.com/microsoft/vscode-documentdb/pull/1117). Case 1 passed: + the host batch passed 222 tests, the tree batch passed 367, and a final 127-test run covered + the Native discovery Retry correction and the core recovery paths. These counts overlap. + OP-3 requires a real Entra sign-out on the dev host and a fresh-socket callback. PR4 pre-review + and handoff checks remain; WI-6 does not start before OP-3 is cleared. --- From cac13fb701378a88270545607be64102fc397f2e Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 15:57:27 +0000 Subject: [PATCH 087/380] fix: show one primary action for Entra tree recovery (WI-5) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../features/connection-lifecycle/README.md | 2 +- .../iterations/01-dev-plan.md | 10 ++-- src/tree/documentdb/ClusterItemBase.test.ts | 50 ++++++++++++------- src/tree/documentdb/ClusterItemBase.ts | 22 ++++---- 4 files changed, 52 insertions(+), 32 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/README.md b/docs/ai-and-plans/features/connection-lifecycle/README.md index f32fb1728..b35c648cf 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/README.md +++ b/docs/ai-and-plans/features/connection-lifecycle/README.md @@ -51,7 +51,7 @@ Evidence, telemetry and source pointers: [research-findings.md](./research-findi and offers one action. - After a database rejects a verified Entra identity, discard the client but keep its in-memory connection settings for explicit **Sign in again**. Do not retain the rejected token or retry - silently. + silently. When the tree offers **Sign in again**, it does not also offer **Retry**. - **One teardown** serves Disconnect, Remove Connection and identity-changing credential updates. - Disconnect uses the existing task-conflict guard: if a copy or export is using the cluster, leave the task and connection running. The user can retry after the task finishes or is stopped. diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index e4b5fb2b9..5e55abc92 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md @@ -1206,11 +1206,12 @@ shim (0005). - Route both catch paths in `getChildren` (cached-client reuse and `listDatabases`) through `reportFailure`. Keep the modal-plus-actions presentation. - Change `createErrorRecoveryChildren` to: - - **Sign in again** (when the kind is `signInRequired`), or **Update credentials** (the - provider-owned action that exists today); + - **Sign in again** when the kind is `signInRequired` or `credentialsRejected` and the + Entra identity and settings are available, or **Update credentials** (the provider-owned + action that exists today); - then Diagnose; - then Open shell; - - then **Retry last**. + - then **Retry last**, except when **Sign in again** is offered in its place. - Check that order against the skill text, and update the skill in WI-10 if it differs. - Call `addEstablishedConnectionContext` on the failure events of `connect`, `getchildren` and the tree. - **Keep credentials on recoverable failures (F-20).** In every provider item's `authenticateAndConnect` @@ -1306,6 +1307,9 @@ shim (0005). the Native discovery Retry correction and the core recovery paths. These counts overlap. OP-3 requires a real Entra sign-out on the dev host and a fresh-socket callback. PR4 pre-review and handoff checks remain; WI-6 does not start before OP-3 is cleared. +- **OP-3 UI clarification:** The operator accepted showing **Sign in again** instead of **Retry** + when Entra sign-in is the next useful step. Diagnose and Open shell remain. This follows decision + 0001's single sign-in action and preserves the original Retry behavior for transient failures. --- diff --git a/src/tree/documentdb/ClusterItemBase.test.ts b/src/tree/documentdb/ClusterItemBase.test.ts index e9b29b340..63c506d27 100644 --- a/src/tree/documentdb/ClusterItemBase.test.ts +++ b/src/tree/documentdb/ClusterItemBase.test.ts @@ -445,23 +445,39 @@ describe('ClusterItemBase.getChildren — cached client connection failure handl ); }); - it('renders the Entra action for an already-latched rejection without reporting a new failure', async (): Promise => { - ClustersClientMock.getLatchReason.mockReturnValueOnce('credentialsRejected'); - ClustersClientMock.connectInteractive.mockRejectedValueOnce(new ConnectionUnavailableError('credentialsRejected')); - const credentials = { authMechanism: AuthMethodId.MicrosoftEntraID } as ReturnType; - vi.mocked(CredentialCache.getCredentials).mockReturnValue(credentials); - ClustersClientMock.getLastVerifiedIdentity.mockReturnValueOnce({ - kind: 'entra', providerId: 'microsoft', accountLabel: 'test', accountId: 'id', - }); - const item = new TestClusterItem(makeCluster(), null); - - expect((await item.getChildren()).map(({ id }) => id)).toEqual([ - 'cluster-1/sign-in-again', 'cluster-1/diagnose', 'cluster-1/open-shell', 'cluster-1/retry', - ]); - expect(ClustersClientMock.reportFailure).not.toHaveBeenCalled(); - expect(CredentialCache.deleteCredentials).not.toHaveBeenCalled(); - vi.mocked(CredentialCache.getCredentials).mockReset(); - }); + it.each(['signInRequired', 'credentialsRejected'] as const)( + 'offers Sign in again instead of Retry for %s and keeps the failed-expansion marker', + async (reason): Promise => { + if (reason === 'credentialsRejected') { + ClustersClientMock.getLatchReason.mockReturnValueOnce(reason); + } + ClustersClientMock.connectInteractive.mockRejectedValueOnce(new ConnectionUnavailableError(reason)); + vi.mocked(CredentialCache.getCredentials).mockReturnValue({ + clusterId: 'cluster-1', + connectionString: 'mongodb://example.test', + authMechanism: AuthMethodId.MicrosoftEntraID, + }); + ClustersClientMock.getLastVerifiedIdentity.mockReturnValueOnce({ + kind: 'entra', + providerId: 'microsoft', + accountLabel: 'test', + accountId: 'id', + }); + const item = new TestClusterItem(makeCluster(), null); + + const children = await item.getChildren(); + + expect(children.map(({ id }) => id)).toEqual([ + 'cluster-1/sign-in-again', + 'cluster-1/diagnose', + 'cluster-1/open-shell', + ]); + expect(item.hasRetryNode(children)).toBe(true); + expect(ClustersClientMock.reportFailure).not.toHaveBeenCalled(); + expect(CredentialCache.deleteCredentials).not.toHaveBeenCalled(); + vi.mocked(CredentialCache.getCredentials).mockReset(); + }, + ); it('reports the binding that executed listDatabases, not the current cache entry', async (): Promise => { const error = new Error('deprecated generation'); diff --git a/src/tree/documentdb/ClusterItemBase.ts b/src/tree/documentdb/ClusterItemBase.ts index 525488e94..ae0c8be40 100644 --- a/src/tree/documentdb/ClusterItemBase.ts +++ b/src/tree/documentdb/ClusterItemBase.ts @@ -344,23 +344,25 @@ export abstract class ClusterItemBase child.id === `${this.id}/sign-in-again`) === true; } /** From 40a8d54d76615554fa188e37f679062379af9d31 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 16:22:37 +0000 Subject: [PATCH 088/380] fix: restore draft CI checks for connection recovery (WI-5) Repair the lifecycle test fixtures and type-only import, then update the generated localization and formatting reported by CI. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../connection-lifecycle/decisions.md | 32 ++++---- .../iterations/01-dev-plan.md | 7 +- l10n/bundle.l10n.json | 12 ++- .../diagnoseConnection.test.ts | 3 + .../retryAuthentication.test.ts | 18 +++-- .../retryAuthentication.ts | 31 ++++++-- src/commands/signInAgain/signInAgain.test.ts | 42 ++++++++--- src/commands/signInAgain/signInAgain.ts | 36 ++++++--- .../updateConnectionString.test.ts | 8 +- .../updateCredentials/updateCredentials.ts | 5 +- src/documentdb/ClustersClient.test.ts | 15 ++-- src/documentdb/ClustersClient.ts | 44 ++++++++--- src/documentdb/ClustersExtension.ts | 2 +- src/documentdb/connectionFailures.ts | 4 +- .../azureResourceAuthentication.test.ts | 15 +++- .../DocumentDBClusterItem.test.ts | 15 +++- .../LocalQuickStartItem.credentials.test.ts | 3 + src/tree/documentdb/ClusterItemBase.test.ts | 11 ++- src/tree/documentdb/ClusterItemBase.ts | 73 +++++++++++++------ 19 files changed, 271 insertions(+), 105 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/decisions.md b/docs/ai-and-plans/features/connection-lifecycle/decisions.md index 2f6b7a190..9e5712c39 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/decisions.md +++ b/docs/ai-and-plans/features/connection-lifecycle/decisions.md @@ -10,22 +10,22 @@ created: 2026-11-19 > Why connections stay usable across token expiry and idle drops, and how open surfaces behave > when credentials or the identity change. Evidence: [research-findings.md](./research-findings.md). -| # | Decision | Status | Changed from the proposal? | Date | PR | -| ---- | ---------------------------------------------------------------------------------------------------------- | --------------------------- | ------------------------------------------------------ | ---------- | --- | -| 0001 | Entra tokens are renewed silently in every OIDC callback; the callback never prompts | Accepted | Operator accepted the explanation (2026-11-19) | 2026-11-19 | — | -| 0002 | Keep one cached client per cluster; surfaces resolve it per operation with identity + generation | Accepted (modified by 0010) | Operator position: per-operation clients cost too much | 2026-11-19 | — | -| 0003 | An open surface never moves to a different identity; it becomes disconnected, keeps its state and says why | Accepted | Operator requirement | 2026-11-19 | — | -| 0004 | Disconnect lets the user choose: close all affected tabs, or keep them open and disabled | Accepted | Operator position; the default is still open (Q2) | 2026-11-19 | — | -| 0005 | Fix stale ARM credentials by upgrading azureauth to v6 (#990), not with a local shim | Accepted | Operator: open to updating dependencies | 2026-11-19 | — | -| 0006 | Deliver through `feature/connection-lifecycle` with stacked sub-PRs, ship once | Accepted (amended) | Operator removed the intermediate merge wait | 2026-11-19 | — | -| 0007 | The Disconnect choice is a VS Code modal with nothing remembered; a setting can set the default | Accepted | Operator: modal cannot pre-select; no remembering | 2026-11-19 | — | -| 0008 | Upgrade the azext stack as high as viable without breaking workflows, using Azure Resources as reference | Accepted | Operator: replaces the "minimal versions" proposal | 2026-11-19 | — | -| 0009 | Kubernetes tunnel recovery, cluster ID case handling and wider network-resilience testing move to #1105 | Accepted | Operator: keep 1.2.0 focused; schedule after release | 2026-11-19 | — | -| 0010 | Rely on the server to reject expired tokens; replacing a client for the same identity is transparent | Accepted | Operator: no rotation, no out-of-date notices | 2026-11-19 | — | -| 0011 | Disconnect keeps the cached credentials and the verified identity; only Remove drops them | Accepted | Operator: reverses the #1059 proposal (plan Q3) | 2026-11-19 | — | -| 0012 | Keep the lifecycle design minimal: no state machine, one epoch, no prompts in getClient, one-step teardown | Accepted | Operator: approved every proposed simplification | 2026-11-19 | — | -| 0013 | Correct the minimal design where it lost edits, identity or recovery: latch before save, epoch checks | Accepted (modifies 0012) | Operator: "update the plan" after the omissions review | 2026-11-19 | — | -| 0014 | Keep in-memory connection settings after a rejection for a verified Entra identity | Accepted | Operator selected A to make sign-in recovery smoother | 2026-11-23 | Yes; WI-5 previously said to delete the entry | +| # | Decision | Status | Changed from the proposal? | Date | PR | +| ---- | ---------------------------------------------------------------------------------------------------------- | --------------------------- | ----------------------------------------------------------- | ---------- | ---------------------------------------------------------------- | +| 0001 | Entra tokens are renewed silently in every OIDC callback; the callback never prompts | Accepted | Operator accepted the explanation (2026-11-19) | 2026-11-19 | — | +| 0002 | Keep one cached client per cluster; surfaces resolve it per operation with identity + generation | Accepted (modified by 0010) | Operator position: per-operation clients cost too much | 2026-11-19 | — | +| 0003 | An open surface never moves to a different identity; it becomes disconnected, keeps its state and says why | Accepted | Operator requirement | 2026-11-19 | — | +| 0004 | Disconnect lets the user choose: close all affected tabs, or keep them open and disabled | Accepted | Operator position; the default is still open (Q2) | 2026-11-19 | — | +| 0005 | Fix stale ARM credentials by upgrading azureauth to v6 (#990), not with a local shim | Accepted | Operator: open to updating dependencies | 2026-11-19 | — | +| 0006 | Deliver through `feature/connection-lifecycle` with stacked sub-PRs, ship once | Accepted (amended) | Operator removed the intermediate merge wait | 2026-11-19 | — | +| 0007 | The Disconnect choice is a VS Code modal with nothing remembered; a setting can set the default | Accepted | Operator: modal cannot pre-select; no remembering | 2026-11-19 | — | +| 0008 | Upgrade the azext stack as high as viable without breaking workflows, using Azure Resources as reference | Accepted | Operator: replaces the "minimal versions" proposal | 2026-11-19 | — | +| 0009 | Kubernetes tunnel recovery, cluster ID case handling and wider network-resilience testing move to #1105 | Accepted | Operator: keep 1.2.0 focused; schedule after release | 2026-11-19 | — | +| 0010 | Rely on the server to reject expired tokens; replacing a client for the same identity is transparent | Accepted | Operator: no rotation, no out-of-date notices | 2026-11-19 | — | +| 0011 | Disconnect keeps the cached credentials and the verified identity; only Remove drops them | Accepted | Operator: reverses the #1059 proposal (plan Q3) | 2026-11-19 | — | +| 0012 | Keep the lifecycle design minimal: no state machine, one epoch, no prompts in getClient, one-step teardown | Accepted | Operator: approved every proposed simplification | 2026-11-19 | — | +| 0013 | Correct the minimal design where it lost edits, identity or recovery: latch before save, epoch checks | Accepted (modifies 0012) | Operator: "update the plan" after the omissions review | 2026-11-19 | — | +| 0014 | Keep in-memory connection settings after a rejection for a verified Entra identity | Accepted | Operator selected A to make sign-in recovery smoother | 2026-11-23 | Yes; WI-5 previously said to delete the entry | | 0015 | Use the existing latch to block startup after authentication rejection | Accepted | Operator selected A; keep the approach simple and pragmatic | 2026-11-23 | Yes; expands the existing latch rather than adding a second hold | > Entries below are **semantically** immutable: append new entries rather than rewriting old ones, diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index 5e55abc92..6784455de 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md @@ -1174,7 +1174,7 @@ shim (0005). | `ConnectionUnavailableError('credentialsMissing')` (F-20) | any | `credentialsMissing` | none to keep | Update credentials | | code 18 | Native, RU | `credentialsRejected` | evict; no automatic retry | Update credentials (RU: Retry re-reads the key) | | final code 18 | Entra | `credentialsRejected` | evict; no automatic retry | Sign in again with a verified Entra identity | - | `MongoNotConnectedError`, `MongoTopologyClosedError` | any | `clientClosed` | new generation on the next foreground call | none | + | `MongoNotConnectedError`, `MongoTopologyClosedError` | any | `clientClosed` | new generation on the next foreground call | none | | network errors, timeouts, server selection with no auth cause | any | `transient` | keep | Retry | | anything else | any | `other` | keep | existing behavior | @@ -1310,6 +1310,11 @@ shim (0005). - **OP-3 UI clarification:** The operator accepted showing **Sign in again** instead of **Retry** when Entra sign-in is the next useful step. Diagnose and Open shell remain. This follows decision 0001's single sign-in action and preserves the original Retry behavior for transient failures. +- **Draft PR4 CI follow-up:** The VSIX built, passed inspection, and activated in VS Code. Static + checks exposed stale localization, formatting changes, and a type-only import lint error. The + full test run found 32 failures in three suites whose mocks did not expose the new lifecycle + methods. Update those fixtures without changing their assertions or runtime recovery behavior. + OP-3 remains the live Entra sign-out and dismissal gate. --- diff --git a/l10n/bundle.l10n.json b/l10n/bundle.l10n.json index 91360cd83..79c6e5f2e 100644 --- a/l10n/bundle.l10n.json +++ b/l10n/bundle.l10n.json @@ -604,6 +604,7 @@ "Changelog": "Changelog", "Check": "Check", "Check a connection step by step and review the results.": "Check a connection step by step and review the results.", + "Check access to the Azure resource and try again.": "Check access to the Azure resource and try again.", "Check Docker again": "Check Docker again", "Check documentDB.customEnvironment.ossrdbmsEndpoint with your cloud administrator. If no override is set, report this on GitHub.": "Check documentDB.customEnvironment.ossrdbmsEndpoint with your cloud administrator. If no override is set, report this on GitHub.", "Check how database traffic should reach this cluster from the host running these checks.": "Check how database traffic should reach this cluster from the host running these checks.", @@ -823,6 +824,7 @@ "Connecting to the cluster using a managed identity…": "Connecting to the cluster using a managed identity…", "Connecting to the cluster using a Microsoft Entra account…": "Connecting to the cluster using a Microsoft Entra account…", "Connecting…": "Connecting…", + "connection": "connection", "Connection": "Connection", "connection \"{0}\"": "connection \"{0}\"", "Connection attempt failed": "Connection attempt failed", @@ -859,7 +861,6 @@ "Connection successful, but 1 check failed": "Connection successful, but 1 check failed", "Connection successful, but 1 check needs attention": "Connection successful, but 1 check needs attention", "Connection timed out": "Connection timed out", - "Connection to \"{cluster}\" was cancelled.": "Connection to \"{cluster}\" was cancelled.", "Connection updated successfully.": "Connection updated successfully.", "Connection updated. Microsoft Entra ID isn't available for the new server, so choose another method when you connect.": "Connection updated. Microsoft Entra ID isn't available for the new server, so choose another method when you connect.", "Connection works, but sign-in is required": "Connection works, but sign-in is required", @@ -950,8 +951,10 @@ "Could not reach a server": "Could not reach a server", "Could not read collections": "Could not read collections", "Could not read databases": "Could not read databases", + "Could not read the database key from Azure.": "Could not read the database key from Azure.", "Could not save the report: {0}": "Could not save the report: {0}", "Could not show the report: {0}": "Could not show the report: {0}", + "Could not sign in again.": "Could not sign in again.", "Counting documents in the source collection...": "Counting documents in the source collection...", "Counting source indexes…": "Counting source indexes…", "Coverage and limits": "Coverage and limits", @@ -1405,7 +1408,6 @@ "Failed to initialize task": "Failed to initialize task", "Failed to initialize the DocumentDB survey: {0}": "Failed to initialize the DocumentDB survey: {0}", "Failed to initialize the Kubernetes client: {0}. Try reloading the window; if the problem persists, reinstall the extension.": "Failed to initialize the Kubernetes client: {0}. Try reloading the window; if the problem persists, reinstall the extension.", - "Failed to list databases for \"{cluster}\": {error}": "Failed to list databases for \"{cluster}\": {error}", "Failed to list DKO resources in namespace \"{0}\": {1}. Check that the DocumentDB Kubernetes Operator CRD is installed and that your Kubernetes credentials can list documentdb.io dbs resources.": "Failed to list DKO resources in namespace \"{0}\": {1}. Check that the DocumentDB Kubernetes Operator CRD is installed and that your Kubernetes credentials can list documentdb.io dbs resources.", "Failed to list namespaces: {0}. Check that your credentials are valid and you have the required RBAC permissions.": "Failed to list namespaces: {0}. Check that your credentials are valid and you have the required RBAC permissions.", "Failed to list services": "Failed to list services", @@ -1453,7 +1455,6 @@ "Failed to rename connection: connection not found in storage.": "Failed to rename connection: connection not found in storage.", "Failed to rename the connection.": "Failed to rename the connection.", "Failed to retrieve Azure accounts: {0}": "Failed to retrieve Azure accounts: {0}", - "Failed to reuse the active connection for \"{cluster}\": {error}": "Failed to reuse the active connection for \"{cluster}\": {error}", "Failed to save credentials for \"{cluster}\".": "Failed to save credentials for \"{cluster}\".", "Failed to save credentials: {0}": "Failed to save credentials: {0}", "Failed to save credentials: connection not found in storage.": "Failed to save credentials: connection not found in storage.", @@ -2087,6 +2088,7 @@ "No tenants selected. Tenant filtering disabled (all tenants will be shown).": "No tenants selected. Tenant filtering disabled (all tenants will be shown).", "No tenants were returned for the available Azure accounts.": "No tenants were returned for the available Azure accounts.", "no token was returned": "no token was returned", + "No verified Microsoft Entra ID connection is available to sign in again.": "No verified Microsoft Entra ID connection is available to sign in again.", "No, only copy documents": "No, only copy documents", "node-routed": "node-routed", "Node.js: {0}": "Node.js: {0}", @@ -2718,11 +2720,14 @@ "Showing the first {shown} collections; {omitted} more are not listed.": "Showing the first {shown} collections; {omitted} more are not listed.", "Showing the first {shown} databases; {omitted} more are not listed.": "Showing the first {shown} databases; {omitted} more are not listed.", "Sign in": "Sign in", + "Sign in again": "Sign in again", "Sign in again to continue using Microsoft Entra ID.": "Sign in again to continue using Microsoft Entra ID.", + "Sign in again to continue using this connection.": "Sign in again to continue using this connection.", "Sign in to": "Sign in to", "Sign in to additional accounts or authenticate with other tenants to see more options.": "Sign in to additional accounts or authenticate with other tenants to see more options.", "Sign in to additional accounts or authenticate with other tenants to see more subscriptions.": "Sign in to additional accounts or authenticate with other tenants to see more subscriptions.", "Sign in to Azure": "Sign in to Azure", + "Sign in to Azure and try Retry again.": "Sign in to Azure and try Retry again.", "Sign in to Azure in VS Code, then run the diagnosis again.": "Sign in to Azure in VS Code, then run the diagnosis again.", "Sign in to Azure to continue…": "Sign in to Azure to continue…", "Sign in to Azure to open {0}.": "Sign in to Azure to open {0}.", @@ -2971,6 +2976,7 @@ "The connection string will not include the password": "The connection string will not include the password", "The connection succeeded, but the database-list request returned no databases visible to this user.": "The connection succeeded, but the database-list request returned no databases visible to this user.", "The connection succeeded, but the server denied the database-list request used by the extension.": "The connection succeeded, but the server denied the database-list request used by the extension.", + "The connection was closed while you were signing in.": "The connection was closed while you were signing in.", "The connection works, but these checks need attention:": "The connection works, but these checks need attention:", "The container and its data volume will be permanently removed. All data, logs, and the auto-generated credentials will be lost. This cannot be undone. You can recreate a fresh instance any time with \"Set up DocumentDB Local\".": "The container and its data volume will be permanently removed. All data, logs, and the auto-generated credentials will be lost. This cannot be undone. You can recreate a fresh instance any time with \"Set up DocumentDB Local\".", "The container engine": "The container engine", diff --git a/src/commands/diagnoseConnection/diagnoseConnection.test.ts b/src/commands/diagnoseConnection/diagnoseConnection.test.ts index 024a5d509..6adbb78c4 100644 --- a/src/commands/diagnoseConnection/diagnoseConnection.test.ts +++ b/src/commands/diagnoseConnection/diagnoseConnection.test.ts @@ -49,7 +49,10 @@ vi.mock('../../documentdb/CredentialCache', () => ({ CredentialCache: { hasCredentials: vi.fn(), setCredentials: vi.fn(), setAuthCredentials: vi.fn() }, })); vi.mock('../../documentdb/ClustersClient', () => ({ + addEstablishedConnectionContext: vi.fn(), ClustersClient: { + getEpoch: vi.fn(() => 0), + getLatchReason: vi.fn(), getClient: vi.fn(), exists: vi.fn().mockReturnValue(false), getExistingClient: vi.fn(), diff --git a/src/commands/retryAuthentication/retryAuthentication.test.ts b/src/commands/retryAuthentication/retryAuthentication.test.ts index 60c81da13..7fa94f715 100644 --- a/src/commands/retryAuthentication/retryAuthentication.test.ts +++ b/src/commands/retryAuthentication/retryAuthentication.test.ts @@ -6,12 +6,13 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { UserCancelledError } from '@microsoft/vscode-azext-utils'; +import type * as vscode from 'vscode'; import { window } from 'vscode'; import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; import { ClustersClient } from '../../documentdb/ClustersClient'; import { CredentialCache } from '../../documentdb/CredentialCache'; -import { type ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; import { ext } from '../../extensionVariables'; +import { type ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; import { retryAuthentication } from './retryAuthentication'; vi.mock('../../extensionVariables', () => ({ @@ -53,7 +54,7 @@ vi.mock('../../documentdb/CredentialCache', () => ({ })); vi.mock('vscode', async (importOriginal) => ({ - ...(await importOriginal()), + ...(await importOriginal()), l10n: { t: vi.fn((value: string) => value), }, @@ -157,7 +158,9 @@ describe('retryAuthentication', () => { const node = ruNode(); const nativeAuthConfig = { connectionUser: 'test', connectionPassword: 'new-key' }; node.readReplacementKey.mockResolvedValue({ - connectionString: 'mongodb://test', availableAuthMethods: [AuthMethodId.NativeAuth], nativeAuthConfig, + connectionString: 'mongodb://test', + availableAuthMethods: [AuthMethodId.NativeAuth], + nativeAuthConfig, }); vi.mocked(ClustersClient.getLatchReason).mockReturnValueOnce('credentialsRejected'); vi.mocked(ClustersClient.clearCredentialRejection).mockReturnValueOnce(true); @@ -167,7 +170,10 @@ describe('retryAuthentication', () => { expect(CredentialCache.deleteCredentials).toHaveBeenCalledExactlyOnceWith('ru'); expect(node.readReplacementKey).toHaveBeenCalledTimes(1); expect(CredentialCache.setAuthCredentials).toHaveBeenCalledExactlyOnceWith( - 'ru', AuthMethodId.NativeAuth, 'mongodb://test', nativeAuthConfig, + 'ru', + AuthMethodId.NativeAuth, + 'mongodb://test', + nativeAuthConfig, ); expect(ext.discoveryBranchDataProvider.refresh).toHaveBeenCalledExactlyOnceWith(node); }); @@ -220,7 +226,9 @@ describe('retryAuthentication', () => { it('does not refresh an old Retry after the client was replaced while its close was pending', async (): Promise => { const node = { - id: 'connectionsView/stale', cluster: { clusterId: 'stale' }, getTreeItem, + id: 'connectionsView/stale', + cluster: { clusterId: 'stale' }, + getTreeItem, lastConnectionFailureKind: 'clientClosed' as const, }; vi.mocked(ClustersClient.getEpoch).mockReturnValueOnce(0).mockReturnValueOnce(1).mockReturnValueOnce(2); diff --git a/src/commands/retryAuthentication/retryAuthentication.ts b/src/commands/retryAuthentication/retryAuthentication.ts index 48a917026..ef9606445 100644 --- a/src/commands/retryAuthentication/retryAuthentication.ts +++ b/src/commands/retryAuthentication/retryAuthentication.ts @@ -11,11 +11,11 @@ import { addEstablishedConnectionContext, ClustersClient } from '../../documentd import { CredentialCache } from '../../documentdb/CredentialCache'; import { inferViewIdFromTreeId, Views } from '../../documentdb/Views'; import { ext } from '../../extensionVariables'; +import { type ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; +import { ConnectionSourceUnavailableError } from '../../tree/documentdb/diagnosticCredentialRead'; import { type TreeElement } from '../../tree/TreeElement'; import { type TreeElementWithContextValue } from '../../tree/TreeElementWithContextValue'; import { isTreeElementWithExplicitReload } from '../../tree/TreeElementWithExplicitReload'; -import { type ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; -import { ConnectionSourceUnavailableError } from '../../tree/documentdb/diagnosticCredentialRead'; const containsDelimited = (fullContext: string | undefined, value: string): boolean => { if (!fullContext) { @@ -117,12 +117,20 @@ export async function retryAuthentication(context: IActionContext, node: Retryab throw error; } const finding = classifyResolutionFailure(new ConnectionSourceUnavailableError('azure', error)); - const signInNeeded = finding.code === 'target.sourceInaccessible' && finding.data?.reason === 'signInRequired'; + const signInNeeded = + finding.code === 'target.sourceInaccessible' && finding.data?.reason === 'signInRequired'; context.telemetry.properties.azureKeyReadFailure = signInNeeded ? 'signInRequired' : 'other'; context.errorHandling.suppressDisplay = true; void window.showErrorMessage( - signInNeeded ? l10n.t('Azure sign-in needed') : l10n.t('Could not read the database key from Azure.'), - { modal: true, detail: signInNeeded ? l10n.t('Sign in to Azure and try Retry again.') : l10n.t('Check access to the Azure resource and try again.') }, + signInNeeded + ? l10n.t('Azure sign-in needed') + : l10n.t('Could not read the database key from Azure.'), + { + modal: true, + detail: signInNeeded + ? l10n.t('Sign in to Azure and try Retry again.') + : l10n.t('Check access to the Azure resource and try again.'), + }, ); throw error; } @@ -131,9 +139,16 @@ export async function retryAuthentication(context: IActionContext, node: Retryab } // One fresh ARM read per explicit click. A subsequent database rejection re-latches in // the tree; it cannot start another ARM read. - if (credentials.nativeAuthConfig?.connectionPassword && - ClustersClient.clearCredentialRejection(clusterId, epoch)) { - CredentialCache.setAuthCredentials(clusterId, AuthMethodId.NativeAuth, credentials.connectionString, credentials.nativeAuthConfig); + if ( + credentials.nativeAuthConfig?.connectionPassword && + ClustersClient.clearCredentialRejection(clusterId, epoch) + ) { + CredentialCache.setAuthCredentials( + clusterId, + AuthMethodId.NativeAuth, + credentials.connectionString, + credentials.nativeAuthConfig, + ); } else { return; } diff --git a/src/commands/signInAgain/signInAgain.test.ts b/src/commands/signInAgain/signInAgain.test.ts index e4a419f6c..90c25099a 100644 --- a/src/commands/signInAgain/signInAgain.test.ts +++ b/src/commands/signInAgain/signInAgain.test.ts @@ -12,7 +12,13 @@ import { ClustersClient } from '../../documentdb/ClustersClient'; import { CredentialCache } from '../../documentdb/CredentialCache'; import { signInAgain } from './signInAgain'; -const pin = { kind: 'entra', providerId: 'microsoft', accountId: 'pinned', accountLabel: 'Pinned', tenantId: 'tenant' } as const; +const pin = { + kind: 'entra', + providerId: 'microsoft', + accountId: 'pinned', + accountLabel: 'Pinned', + tenantId: 'tenant', +} as const; const clusterId = 'cluster'; vi.mock('../../documentdb/ClustersClient', () => ({ @@ -34,7 +40,10 @@ vi.mock('../../documentdb/auth/MicrosoftEntraIDAuthHandler', () => ({ acquire: typeof getEntraSession, ): Promise { const session = await acquire({ - mode: 'forceNew', providerId: pin.providerId, resource: 'scope', tenantId: pin.tenantId, + mode: 'forceNew', + providerId: pin.providerId, + resource: 'scope', + tenantId: pin.tenantId, account: { id: pin.accountId, label: pin.accountLabel }, }); return { verifiedIdentity: { ...pin, accountId: session?.account.id } }; @@ -51,8 +60,14 @@ function actionContext(): IActionContext { describe('signInAgain', () => { beforeEach(() => { vi.clearAllMocks(); - CredentialCache.setAuthCredentials(clusterId, AuthMethodId.MicrosoftEntraID, 'mongodb://test', undefined, - undefined, { tenantId: pin.tenantId }); + CredentialCache.setAuthCredentials( + clusterId, + AuthMethodId.MicrosoftEntraID, + 'mongodb://test', + undefined, + undefined, + { tenantId: pin.tenantId }, + ); }); it.each([ @@ -64,12 +79,18 @@ describe('signInAgain', () => { await signInAgain(actionContext(), { clusterId }); - expect(getEntraSession).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ - mode: 'forceNew', tenantId: pin.tenantId, providerId: pin.providerId, - account: { id: pin.accountId, label: pin.accountLabel }, - })); + expect(getEntraSession).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + mode: 'forceNew', + tenantId: pin.tenantId, + providerId: pin.providerId, + account: { id: pin.accountId, label: pin.accountLabel }, + }), + ); expect(ClustersClient.startAfterSignIn).toHaveBeenCalledExactlyOnceWith( - clusterId, 1, CredentialCache.getCredentials(clusterId), + clusterId, + 1, + CredentialCache.getCredentials(clusterId), { verifiedIdentity: expect.objectContaining({ accountId: account.id }) }, ); }); @@ -97,7 +118,8 @@ describe('signInAgain', () => { await signInAgain(actionContext(), { clusterId }); expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( - 'The connection was closed while you were signing in.', { modal: true }, + 'The connection was closed while you were signing in.', + { modal: true }, ); vi.mocked(ClustersClient.getEpoch).mockReturnValue(1); }); diff --git a/src/commands/signInAgain/signInAgain.ts b/src/commands/signInAgain/signInAgain.ts index 3890cbb57..caebaeedf 100644 --- a/src/commands/signInAgain/signInAgain.ts +++ b/src/commands/signInAgain/signInAgain.ts @@ -9,19 +9,21 @@ import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; import { EntraIdentityMismatchError } from '../../documentdb/auth/entraErrors/entraCallbackErrors'; import { getEntraSession } from '../../documentdb/auth/entraSession'; import { MicrosoftEntraIDAuthHandler } from '../../documentdb/auth/MicrosoftEntraIDAuthHandler'; -import { classifyConnectionFailure } from '../../documentdb/connectionFailures'; import { addEstablishedConnectionContext, ClustersClient } from '../../documentdb/ClustersClient'; +import { classifyConnectionFailure } from '../../documentdb/connectionFailures'; import { CredentialCache } from '../../documentdb/CredentialCache'; import { showClusterConnectFailure } from '../../documentdb/showClusterConnectFailure'; import { type ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; import { refreshAuthenticationNode } from '../retryAuthentication/retryAuthentication'; function isSignInDismissal(error: unknown): boolean { - return error instanceof UserCancelledError || + return ( + error instanceof UserCancelledError || (error instanceof Error && (error.name === 'Canceled' || error.message === 'User did not consent to login.' || - ('errorCode' in error && error.errorCode === 'user_cancelled'))); + ('errorCode' in error && error.errorCode === 'user_cancelled'))) + ); } export async function signInAgain( @@ -40,9 +42,11 @@ export async function signInAgain( } const identity = ClustersClient.getLastVerifiedIdentity(clusterId); const credentials = CredentialCache.getCredentials(clusterId); - if (identity?.kind !== 'entra' || + if ( + identity?.kind !== 'entra' || credentials?.authMechanism !== AuthMethodId.MicrosoftEntraID || - identity.tenantId !== credentials.entraIdConfig?.tenantId) { + identity.tenantId !== credentials.entraIdConfig?.tenantId + ) { throw new Error(vscode.l10n.t('No verified Microsoft Entra ID connection is available to sign in again.')); } @@ -59,7 +63,10 @@ export async function signInAgain( let starting = false; try { - const handler = new MicrosoftEntraIDAuthHandler(credentials, { interactive: false, pinnedEntraIdentity: identity }); + const handler = new MicrosoftEntraIDAuthHandler(credentials, { + interactive: false, + pinnedEntraIdentity: identity, + }); const auth = await handler.configureAuth(undefined, undefined, async (request) => { if (!isCurrent()) { throw new UserCancelledError('signInAgain'); @@ -71,8 +78,10 @@ export async function signInAgain( if (session.account.id !== identity.accountId) { // VS Code only confirms account changes when the account *label* is different. // A same-label/different-ID session is not an explicit user choice. - if (session.account.label === identity.accountLabel || - (identity.providerId !== 'microsoft' && identity.providerId !== 'microsoft-sovereign-cloud')) { + if ( + session.account.label === identity.accountLabel || + (identity.providerId !== 'microsoft' && identity.providerId !== 'microsoft-sovereign-cloud') + ) { throw new EntraIdentityMismatchError(); } } @@ -90,7 +99,11 @@ export async function signInAgain( reportClosed(); return; } - if (ClustersClient.getExistingClient(clusterId) === client && !ClustersClient.getLatchReason(clusterId) && node) { + if ( + ClustersClient.getExistingClient(clusterId) === client && + !ClustersClient.getLatchReason(clusterId) && + node + ) { refreshAuthenticationNode(node); } } catch (error) { @@ -101,7 +114,10 @@ export async function signInAgain( if (isSignInDismissal(error)) { throw new UserCancelledError('signInAgain'); } - context.telemetry.properties.connectionFailureKind = classifyConnectionFailure(error, AuthMethodId.MicrosoftEntraID).kind; + context.telemetry.properties.connectionFailureKind = classifyConnectionFailure( + error, + AuthMethodId.MicrosoftEntraID, + ).kind; await showClusterConnectFailure({ clusterId, clusterName: node?.cluster.name ?? vscode.l10n.t('connection'), diff --git a/src/commands/updateConnectionString/updateConnectionString.test.ts b/src/commands/updateConnectionString/updateConnectionString.test.ts index 8cf9fdd1c..e92706332 100644 --- a/src/commands/updateConnectionString/updateConnectionString.test.ts +++ b/src/commands/updateConnectionString/updateConnectionString.test.ts @@ -87,8 +87,12 @@ vi.mock('../../services/connectionStorageService', async (importOriginal) => ({ vi.mock('../../documentdb/ClustersClient', () => ({ addEstablishedConnectionContext: vi.fn(), ClustersClient: { - connectInteractive: vi.fn(), deleteClient: vi.fn(), exists: vi.fn(), - getEpoch: vi.fn(() => 0), getLatchReason: vi.fn(), getExistingClient: vi.fn(), + connectInteractive: vi.fn(), + deleteClient: vi.fn(), + exists: vi.fn(), + getEpoch: vi.fn(() => 0), + getLatchReason: vi.fn(), + getExistingClient: vi.fn(), }, })); vi.mock('../../services/connectionReachabilityService', () => ({ diff --git a/src/commands/updateCredentials/updateCredentials.ts b/src/commands/updateCredentials/updateCredentials.ts index 07ede843c..8ebc1c3fe 100644 --- a/src/commands/updateCredentials/updateCredentials.ts +++ b/src/commands/updateCredentials/updateCredentials.ts @@ -168,7 +168,10 @@ export async function updateCredentials(context: IActionContext, node: DocumentD const username = updatedConnection?.secrets.nativeAuthConfig?.connectionUser; const password = updatedConnection?.secrets.nativeAuthConfig?.connectionPassword; if (recoveringRejection && authMethod === AuthMethodId.MicrosoftEntraID) { - ClustersClient.discardEntraPinForDifferentTenant(clusterId, updatedConnection?.secrets.entraIdAuthConfig?.tenantId); + ClustersClient.discardEntraPinForDifferentTenant( + clusterId, + updatedConnection?.secrets.entraIdAuthConfig?.tenantId, + ); } if (updatedConnection && authMethod && !(authMethod === AuthMethodId.NativeAuth && (!username || !password))) { const connectionString = new DocumentDBConnectionString(updatedConnection.secrets.connectionString); diff --git a/src/documentdb/ClustersClient.test.ts b/src/documentdb/ClustersClient.test.ts index 09908c6c3..b7b2c69bd 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -517,9 +517,11 @@ describe('regular connection startup diagnostics', () => { expect(CredentialCache.getCredentials(clusterId)).toBe(settings); expect(ClustersClient.getLastVerifiedIdentity(clusterId)).toBe(identity); await expect(ClustersClient.getClient(clusterId)).rejects.toMatchObject({ reason: 'credentialsRejected' }); - await expect(ClustersClient.getClient(clusterId, undefined, undefined, 'treeChildren', { - background: true, - })).rejects.toMatchObject({ reason: 'credentialsRejected' }); + await expect( + ClustersClient.getClient(clusterId, undefined, undefined, 'treeChildren', { + background: true, + }), + ).rejects.toMatchObject({ reason: 'credentialsRejected' }); expect(MongoClient).toHaveBeenCalledOnce(); expect(ClustersClient.clearCredentialRejection(clusterId, ClustersClient.getEpoch(clusterId))).toBe(true); @@ -549,8 +551,11 @@ describe('regular connection startup diagnostics', () => { clusterId, ClustersClient.getEpoch(clusterId), CredentialCache.getCredentials(clusterId)!, - { connectionString: 'mongodb://private-host:27017', options: {}, - verifiedIdentity: { ...verifiedIdentity, accountId: 'other-account' } }, + { + connectionString: 'mongodb://private-host:27017', + options: {}, + verifiedIdentity: { ...verifiedIdentity, accountId: 'other-account' }, + }, ); await connection.started; ClustersClient.latch(clusterId, 'userDisconnected'); diff --git a/src/documentdb/ClustersClient.ts b/src/documentdb/ClustersClient.ts index 290bbd936..d0a0a534a 100644 --- a/src/documentdb/ClustersClient.ts +++ b/src/documentdb/ClustersClient.ts @@ -559,11 +559,13 @@ export class ClustersClient { // Configure auth and get connection options this.advanceClientStartup(startup, 'stage02ConfiguringAuth'); - const { connectionString, options, verifiedIdentity } = recoveredAuth ?? await authHandler.configureAuth(startup.costTimings, { - startupCorrelationId: startup.id, - surface: 'extension', - startupProperties: startup.telemetry.properties, - }); + const { connectionString, options, verifiedIdentity } = + recoveredAuth ?? + (await authHandler.configureAuth(startup.costTimings, { + startupCorrelationId: startup.id, + surface: 'extension', + startupProperties: startup.telemetry.properties, + })); this.advanceClientStartup(startup, 'stage03PreparingClient'); this.#verifiedIdentity = getVerifiedIdentity(authMethod, credentials, connectionString, verifiedIdentity); @@ -777,10 +779,12 @@ export class ClustersClient { auth: AuthHandlerResponse, ): Promise { const reason = ClustersClient.getLatchReason(clusterId); - if (epoch !== ClustersClient.getEpoch(clusterId) || + if ( + epoch !== ClustersClient.getEpoch(clusterId) || CredentialCache.getCredentials(clusterId) !== credentials || credentials.authMechanism !== AuthMethodId.MicrosoftEntraID || - (reason && reason !== 'credentialsRejected')) { + (reason && reason !== 'credentialsRejected') + ) { return undefined; } if (reason && !ClustersClient.clearCredentialRejection(clusterId, epoch)) { @@ -791,15 +795,25 @@ export class ClustersClient { }); const startupEpoch = ClustersClient.getEpoch(clusterId); try { - const { promise } = ClustersClient.getOrStartClient(clusterId, startupEpoch, 'treeConnect', false, false, undefined, auth); + const { promise } = ClustersClient.getOrStartClient( + clusterId, + startupEpoch, + 'treeConnect', + false, + false, + undefined, + auth, + ); const client = await promise; return startupEpoch === ClustersClient.getEpoch(clusterId) ? client : undefined; } catch (error) { if (startupEpoch !== ClustersClient.getEpoch(clusterId)) { return undefined; } - if (reason === 'credentialsRejected' || - classifyConnectionFailure(error, AuthMethodId.MicrosoftEntraID).kind === 'credentialsRejected') { + if ( + reason === 'credentialsRejected' || + classifyConnectionFailure(error, AuthMethodId.MicrosoftEntraID).kind === 'credentialsRejected' + ) { ClustersClient.latch(clusterId, 'credentialsRejected'); } throw error; @@ -905,7 +919,15 @@ export class ClustersClient { const id = randomUUID(); // Register before initialization or a caller's onStartup callback can re-enter getClient. const promise = Promise.resolve().then(() => - ClustersClient.establishClient(clusterId, epoch, id, trigger, allowInteractive, expectedFingerprint, recoveredAuth), + ClustersClient.establishClient( + clusterId, + epoch, + id, + trigger, + allowInteractive, + expectedFingerprint, + recoveredAuth, + ), ); const pending = { id, epoch, promise }; ClustersClient._pendingStartups.set(clusterId, pending); diff --git a/src/documentdb/ClustersExtension.ts b/src/documentdb/ClustersExtension.ts index cd3b99150..91e5f41b3 100644 --- a/src/documentdb/ClustersExtension.ts +++ b/src/documentdb/ClustersExtension.ts @@ -83,11 +83,11 @@ import { refreshView } from '../commands/refreshView/refreshView'; import { removeConnection } from '../commands/removeConnection/removeConnection'; import { removeDiscoveryRegistry } from '../commands/removeDiscoveryRegistry/removeDiscoveryRegistry'; import { retryAuthentication } from '../commands/retryAuthentication/retryAuthentication'; -import { signInAgain } from '../commands/signInAgain/signInAgain'; import { revealView } from '../commands/revealView/revealView'; import { clearSchemaCache } from '../commands/schemaStore/clearSchemaCache'; import { showSchemaStoreStats } from '../commands/schemaStore/showSchemaStoreStats'; import { showWorkerStats } from '../commands/showWorkerStats/showWorkerStats'; +import { signInAgain } from '../commands/signInAgain/signInAgain'; import { updateConnectionString } from '../commands/updateConnectionString/updateConnectionString'; import { updateCredentials } from '../commands/updateCredentials/updateCredentials'; import { isVCoreAndRURolloutEnabled } from '../extension'; diff --git a/src/documentdb/connectionFailures.ts b/src/documentdb/connectionFailures.ts index 740711801..c51df8b30 100644 --- a/src/documentdb/connectionFailures.ts +++ b/src/documentdb/connectionFailures.ts @@ -144,7 +144,9 @@ export function classifyConnectionFailure(error: unknown, authMethod?: AuthMetho } if (agreed) { mixed ||= - result.kind !== agreed.kind || result.generation !== agreed.generation || result.note !== agreed.note; + result.kind !== agreed.kind || + result.generation !== agreed.generation || + result.note !== agreed.note; } else { agreed = result; } diff --git a/src/tree/azure-resources-view/documentdb/azureResourceAuthentication.test.ts b/src/tree/azure-resources-view/documentdb/azureResourceAuthentication.test.ts index 93db00959..312715fbf 100644 --- a/src/tree/azure-resources-view/documentdb/azureResourceAuthentication.test.ts +++ b/src/tree/azure-resources-view/documentdb/azureResourceAuthentication.test.ts @@ -71,10 +71,21 @@ vi.mock('../../../utils/azureClients', () => ({ createMongoClustersManagementClient: vi.fn(() => ({ mongoClusters: { get: getCluster } })), })); vi.mock('../../../documentdb/ClustersClient', () => ({ - ClustersClient: { connectInteractive: vi.fn(), deleteClient: vi.fn() }, + addEstablishedConnectionContext: vi.fn(), + ClustersClient: { + getEpoch: vi.fn(() => 0), + getLatchReason: vi.fn(), + connectInteractive: vi.fn(), + deleteClient: vi.fn(), + }, })); vi.mock('../../../documentdb/CredentialCache', () => ({ - CredentialCache: { hasCredentials: vi.fn(), setAuthCredentials: vi.fn(), deleteCredentials: vi.fn() }, + CredentialCache: { + getCredentials: vi.fn(), + hasCredentials: vi.fn(), + setAuthCredentials: vi.fn(), + deleteCredentials: vi.fn(), + }, })); vi.mock('../../../extensionVariables', () => ({ ext: { diff --git a/src/tree/connections-view/DocumentDBClusterItem.test.ts b/src/tree/connections-view/DocumentDBClusterItem.test.ts index 35aed1f64..74027545f 100644 --- a/src/tree/connections-view/DocumentDBClusterItem.test.ts +++ b/src/tree/connections-view/DocumentDBClusterItem.test.ts @@ -89,10 +89,21 @@ vi.mock('../../services/connectionStorageService', async (importOriginal) => ({ })); vi.mock('../../documentdb/ClustersClient', () => ({ addEstablishedConnectionContext: vi.fn(), - ClustersClient: { connectInteractive: vi.fn(), deleteClient: vi.fn(), exists: vi.fn(), getEpoch: vi.fn(() => 0), getLatchReason: vi.fn() }, + ClustersClient: { + connectInteractive: vi.fn(), + deleteClient: vi.fn(), + exists: vi.fn(), + getEpoch: vi.fn(() => 0), + getLatchReason: vi.fn(), + }, })); vi.mock('../../documentdb/CredentialCache', () => ({ - CredentialCache: { hasCredentials: vi.fn(), setAuthCredentials: vi.fn(), deleteCredentials: vi.fn(), getCredentials: vi.fn() }, + CredentialCache: { + hasCredentials: vi.fn(), + setAuthCredentials: vi.fn(), + deleteCredentials: vi.fn(), + getCredentials: vi.fn(), + }, })); vi.mock('../../services/connectionReachabilityService', () => ({ ConnectionReachabilityService: { ensureReachable: vi.fn() }, diff --git a/src/tree/connections-view/LocalQuickStart/LocalQuickStartItem.credentials.test.ts b/src/tree/connections-view/LocalQuickStart/LocalQuickStartItem.credentials.test.ts index f45687f83..55745158a 100644 --- a/src/tree/connections-view/LocalQuickStart/LocalQuickStartItem.credentials.test.ts +++ b/src/tree/connections-view/LocalQuickStart/LocalQuickStartItem.credentials.test.ts @@ -77,7 +77,10 @@ vi.mock('../../../services/SettingsService', () => ({ const mockGetClient = vi.fn(); vi.mock('../../../documentdb/ClustersClient', () => ({ + addEstablishedConnectionContext: vi.fn(), ClustersClient: { + getEpoch: vi.fn(() => 0), + getLatchReason: vi.fn(), exists: vi.fn().mockReturnValue(false), connectInteractive: (...args: unknown[]) => mockGetClient(...args), }, diff --git a/src/tree/documentdb/ClusterItemBase.test.ts b/src/tree/documentdb/ClusterItemBase.test.ts index 63c506d27..7de34e605 100644 --- a/src/tree/documentdb/ClusterItemBase.test.ts +++ b/src/tree/documentdb/ClusterItemBase.test.ts @@ -11,8 +11,8 @@ import { type IActionContext, } from '@microsoft/vscode-azext-utils'; import * as vscode from 'vscode'; -import { EntraDestinationRejectedError } from '../../documentdb/auth/oidcAllowedHosts'; import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; +import { EntraDestinationRejectedError } from '../../documentdb/auth/oidcAllowedHosts'; import { ClustersClient, type DatabaseItemModel } from '../../documentdb/ClustersClient'; import { ConnectionUnavailableError } from '../../documentdb/ConnectionUnavailableError'; import { CredentialCache } from '../../documentdb/CredentialCache'; @@ -78,8 +78,13 @@ vi.mock('../../documentdb/CredentialCache', () => ({ vi.mock('../../documentdb/ClustersClient', () => ({ addEstablishedConnectionContext: vi.fn(), ClustersClient: { - connectInteractive: vi.fn(), exists: vi.fn().mockReturnValue(false), getExistingClient: vi.fn(), - getLatchReason: vi.fn(), getEpoch: vi.fn(() => 0), getLastVerifiedIdentity: vi.fn(), reportFailure: vi.fn(), + connectInteractive: vi.fn(), + exists: vi.fn().mockReturnValue(false), + getExistingClient: vi.fn(), + getLatchReason: vi.fn(), + getEpoch: vi.fn(() => 0), + getLastVerifiedIdentity: vi.fn(), + reportFailure: vi.fn(), }, })); diff --git a/src/tree/documentdb/ClusterItemBase.ts b/src/tree/documentdb/ClusterItemBase.ts index ae0c8be40..cad28218c 100644 --- a/src/tree/documentdb/ClusterItemBase.ts +++ b/src/tree/documentdb/ClusterItemBase.ts @@ -4,10 +4,10 @@ *--------------------------------------------------------------------------------------------*/ import { - UserCancelledError, callWithTelemetryAndErrorHandling, createContextValue, createGenericElement, + UserCancelledError, type IActionContext, } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; @@ -158,7 +158,10 @@ export abstract class ClusterItemBase { reusedClient = client; }); + clustersClient = await this.getClientWithProgress(clusterId, (client) => { + reusedClient = client; + }); } catch (error) { return this.renderExpansionFailure(error, 'cachedClientConnect', reusedClient, acquisitionEpoch); } @@ -585,7 +608,9 @@ export abstract class ClusterItemBase child.id === `${this.id}/sign-in-again`) === true; + return ( + containsRetryNode(children) || children?.some((child) => child.id === `${this.id}/sign-in-again`) === true + ); } /** From 20dcde1be4b835b6d9b40971de37f64e3dca4162 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 17:06:52 +0000 Subject: [PATCH 089/380] docs: defer prompt Microsoft sign-out handling until after 1.2.0 Record the partial OP-3 evidence and track prompt sign-out handling in #1119 without changing the existing gate. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../features/connection-lifecycle/README.md | 6 +++-- .../iterations/01-dev-plan.md | 24 ++++++++++++++++++- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/README.md b/docs/ai-and-plans/features/connection-lifecycle/README.md index b35c648cf..e6598d6f6 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/README.md +++ b/docs/ai-and-plans/features/connection-lifecycle/README.md @@ -18,8 +18,10 @@ code: - [#1059](https://github.com/microsoft/vscode-documentdb/issues/1059) - [#566](https://github.com/microsoft/vscode-documentdb/issues/566) - [#990](https://github.com/microsoft/vscode-documentdb/issues/990) -- follow-up after 1.2.0: [#1105](https://github.com/microsoft/vscode-documentdb/issues/1105) (Kubernetes tunnels, network resilience) and - [#1106](https://github.com/microsoft/vscode-documentdb/issues/1106) (out-of-date results) +- follow-ups after 1.2.0: [#1105](https://github.com/microsoft/vscode-documentdb/issues/1105) + (Kubernetes tunnels, network resilience), [#1106](https://github.com/microsoft/vscode-documentdb/issues/1106) + (out-of-date results), and [#1119](https://github.com/microsoft/vscode-documentdb/issues/1119) + (prompt handling of Microsoft account sign-out) **Branch:** `feature/connection-lifecycle`, with stacked sub-PRs from `dev/tnaum/*`. Implementation does not wait for intermediate merges; the operator handles approvals and merges (decision 0006). diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index 6784455de..5a816c517 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md @@ -135,7 +135,7 @@ Every PR names the issues it may resolve, using the table below, and says for ea Keep it factual and short. Never include tokens, account names, cluster names or connection strings. Record the comment's link in the WI's Progress block. -- **Work moved to a follow-up issue** (#1105, #1106): when a PR hands work over, comment on the +- **Work moved to a follow-up issue** (#1105, #1106, #1119): when a PR hands work over, comment on the follow-up in the same way, so it can be planned from that comment alone. | Issue | Title (short) | PRs | Expected | @@ -148,6 +148,7 @@ Every PR names the issues it may resolve, using the table below, and says for ea | #1091 | Dashboard health check: pause, back off, stop | 6 (WI-8) | Partial unless WI-8 also does the visibility pause and backoff | | #1105 | Follow-up: Kubernetes tunnels, network resilience | — | Not resolved; comment when a PR moves work there | | #1106 | Follow-up: indicate possibly out-of-date results | — | Not resolved; comment when a PR moves work there | +| #1119 | Follow-up: handle Microsoft sign-out promptly | — | Not in 1.2.0 | ### Skills to load per work item @@ -339,6 +340,12 @@ Moved to [#1106](https://github.com/microsoft/vscode-documentdb/issues/1106) (de "results may be out of date" indication. That covers the return from the disconnected state, long idle, and writes made from another view or another client. +Prompt handling of Microsoft account sign-out is deferred to +[#1119](https://github.com/microsoft/vscode-documentdb/issues/1119), after 1.2.0. Under decisions +0001 and 0012, signing out of VS Code does not close an established database client. The client +can keep authenticating with a cached token while the server accepts it. When the driver requests +a new token and the pinned session is gone, recovery remains explicit through **Sign in again**. + Generic idle and network-drop recovery **stays in scope**: closed-client and transient classification, the cancelled-reuse fix, closed-client replacement and OT-4. It is #1102's "recover on the next operation without a restart". The no-regression rules in WI-5 and WI-6 keep tunneled connections @@ -1315,6 +1322,21 @@ shim (0005). full test run found 32 failures in three suites whose mocks did not expose the new lifecycle methods. Update those fixtures without changing their assertions or runtime recovery behavior. OP-3 remains the live Entra sign-out and dismissal gate. +- **OP-3 partial live run (2026-11-23):** A CI-built PR4 VSIX loaded databases and the dashboard. + After sign-out, idle sockets closed and fresh sockets became ready under the same client startup. + No post-sign-out OIDC callback appears in the supplied excerpt, and sign-in recovery and dismissal + were not reached. The run is inconclusive; OP-3 remains open. On resume, close the dashboard, + wait until the cached token is no longer accepted, and explicitly refresh the cluster node + without restarting the extension host. Collapse and re-expand can show cached children. +- **Sign-out scope review (2026-11-23):** Claude Opus 5.5 recommended keeping the approved + 1.2.0 scope (80% confidence). Prompt sign-out handling would need account-specific session + checks, coordination with active tasks, and separate handling for Shell and Playground + clients. Track it in [#1119](https://github.com/microsoft/vscode-documentdb/issues/1119). + OP-3 and its required evidence are unchanged. +- **Future operator VSIX builds:** Give each new test candidate a distinct extension version in + the root `package.json` and corresponding root lockfile entries. Verify the version in the + packaged manifest, and give the operator that version, the commit, and the CI artifact link. + Do not rebuild an unchanged candidate just to label the partial run. --- From a557fb642ed18c1629eed8980a5ef5e6da56578c Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 17:14:24 +0000 Subject: [PATCH 090/380] fix: keep VS Code UI imports out of the database worker Separate the shared auth IDs from host-only UI metadata so workers can load OIDC options in Node. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/documentdb/auth/AuthMethod.ts | 21 ++----------------- src/documentdb/auth/AuthMethodId.ts | 21 +++++++++++++++++++ .../auth/entraErrors/entraCallbackErrors.ts | 2 +- src/documentdb/auth/oidcClientOptions.test.ts | 4 ++++ 4 files changed, 28 insertions(+), 20 deletions(-) create mode 100644 src/documentdb/auth/AuthMethodId.ts diff --git a/src/documentdb/auth/AuthMethod.ts b/src/documentdb/auth/AuthMethod.ts index e0c92b178..d32b7bc9d 100644 --- a/src/documentdb/auth/AuthMethod.ts +++ b/src/documentdb/auth/AuthMethod.ts @@ -5,26 +5,9 @@ import * as vscode from 'vscode'; import { getIconPath } from '../../utils/icons'; +import { AuthMethodId } from './AuthMethodId'; -/** - * Authentication method identifiers - */ -export enum AuthMethodId { - /** The regular, typical username+password and connection string authentication. */ - NativeAuth = 'NativeAuth', - /** Microsoft Entra ID (Azure AD) authentication. */ - MicrosoftEntraID = 'MicrosoftEntraID', - /** - * Microsoft Entra ID using the managed identity of the Azure resource hosting VS Code. - * - * Note: unlike the other values, this one has no counterpart in the ARM `authConfig.allowedModes` - * vocabulary, so it is never produced by pass-through of service metadata. It is synthesized by - * an explicit rule in `clusterHelpers.ts`. - */ - ManagedIdentity = 'ManagedIdentity', - /** Anonymous connection without a username, password, or Entra ID. */ - NoAuth = 'NoAuth', -} +export { AuthMethodId }; /** * Authentication method metadata diff --git a/src/documentdb/auth/AuthMethodId.ts b/src/documentdb/auth/AuthMethodId.ts new file mode 100644 index 000000000..d43a37ec5 --- /dev/null +++ b/src/documentdb/auth/AuthMethodId.ts @@ -0,0 +1,21 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +export enum AuthMethodId { + /** The regular, typical username+password and connection string authentication. */ + NativeAuth = 'NativeAuth', + /** Microsoft Entra ID (Azure AD) authentication. */ + MicrosoftEntraID = 'MicrosoftEntraID', + /** + * Microsoft Entra ID using the managed identity of the Azure resource hosting VS Code. + * + * Note: unlike the other values, this one has no counterpart in the ARM `authConfig.allowedModes` + * vocabulary, so it is never produced by pass-through of service metadata. It is synthesized by + * an explicit rule in `clusterHelpers.ts`. + */ + ManagedIdentity = 'ManagedIdentity', + /** Anonymous connection without a username, password, or Entra ID. */ + NoAuth = 'NoAuth', +} diff --git a/src/documentdb/auth/entraErrors/entraCallbackErrors.ts b/src/documentdb/auth/entraErrors/entraCallbackErrors.ts index 016651b1b..ef0df558b 100644 --- a/src/documentdb/auth/entraErrors/entraCallbackErrors.ts +++ b/src/documentdb/auth/entraErrors/entraCallbackErrors.ts @@ -4,7 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import * as l10n from '@vscode/l10n'; -import { AuthMethodId } from '../AuthMethod'; +import { AuthMethodId } from '../AuthMethodId'; export class EntraSignInRequiredError extends Error { constructor(public readonly reason: 'noSession' | 'providerChanged') { diff --git a/src/documentdb/auth/oidcClientOptions.test.ts b/src/documentdb/auth/oidcClientOptions.test.ts index 552f02746..da5736391 100644 --- a/src/documentdb/auth/oidcClientOptions.test.ts +++ b/src/documentdb/auth/oidcClientOptions.test.ts @@ -14,6 +14,10 @@ import { createOidcDestinationPolicy, } from './oidcClientOptions'; +vi.mock('vscode', () => { + throw new Error('Node workers must be able to load OIDC options without the VS Code host module.'); +}); + const host = 'cluster.mongocluster.cosmos.azure.com'; const connectionString = `mongodb://${host}/`; const patterns = ['*.mongocluster.cosmos.azure.com']; From 34929b54038f24e073bed646d78658cb35e438e0 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 17:14:24 +0000 Subject: [PATCH 091/380] feat: show sanitized extension-host connection stats (WI-5) Expose a read-only snapshot for operators without changing the existing OP-3 candidate. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iterations/01-dev-plan.md | 8 +++ package.json | 6 +++ package.nls.json | 1 + .../showConnectionStats.ts | 36 +++++++++++++ src/documentdb/ClustersClient.test.ts | 53 +++++++++++++++++++ src/documentdb/ClustersClient.ts | 49 ++++++++++++++++- src/documentdb/ClustersExtension.ts | 5 ++ 7 files changed, 156 insertions(+), 2 deletions(-) create mode 100644 src/commands/showConnectionStats/showConnectionStats.ts diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index 5a816c517..09687d174 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md @@ -1337,6 +1337,14 @@ shim (0005). the root `package.json` and corresponding root lockfile entries. Verify the version in the packaged manifest, and give the operator that version, the commit, and the CI artifact link. Do not rebuild an unchanged candidate just to label the partial run. +- **Connection stats add-on:** Add a read-only **Show Connection Stats** command alongside + **Show Worker Stats**, as a separate WI-5 commit. The extension-host snapshot shows client + generation, age, auth method, startup correlation, pending or held state, and whether socket + events are traced. It contains no cluster or account identifiers and makes no service calls. + Leave socket counts out rather than guessing. Keep the published OP-3 candidate unchanged. +- **Worker startup regression:** PR4's shared OIDC code imported the VS Code UI auth-method + module into the Node worker path. Keep the shared auth IDs independent of VS Code. Verify + the next packaged candidate starts both Shell and Playground; the tree OP-3 gate is unchanged. --- diff --git a/package.json b/package.json index 452852242..5a096fdb1 100644 --- a/package.json +++ b/package.json @@ -935,6 +935,12 @@ "command": "vscode-documentdb.command.showSchemaStoreStats", "title": "Show Schema Store Stats" }, + { + "//": "[Diagnostics] Show Connection Stats", + "category": "DocumentDB", + "command": "vscode-documentdb.command.showConnectionStats", + "title": "%diagnostics.showConnectionStats%" + }, { "//": "[Diagnostics] Show Worker Stats", "category": "DocumentDB", diff --git a/package.nls.json b/package.nls.json index 88f95c3c7..b30f91418 100644 --- a/package.nls.json +++ b/package.nls.json @@ -1,4 +1,5 @@ { + "diagnostics.showConnectionStats": "Show Connection Stats", "survey.containerTitle": "DocumentDB Feedback", "survey.viewTitle": "Share Your Experience", "survey.giveFeedbackTitle": "Give Feedback", diff --git a/src/commands/showConnectionStats/showConnectionStats.ts b/src/commands/showConnectionStats/showConnectionStats.ts new file mode 100644 index 000000000..8e7f08364 --- /dev/null +++ b/src/commands/showConnectionStats/showConnectionStats.ts @@ -0,0 +1,36 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { type IActionContext } from '@microsoft/vscode-azext-utils'; +import { ClustersClient } from '../../documentdb/ClustersClient'; +import { ext } from '../../extensionVariables'; + +export function showConnectionStats(_context: IActionContext): void { + const snapshot = ClustersClient.getDiagnosticsSnapshot(); + ext.outputChannel.appendLog(`[Connection Stats] Extension-host cache entries: ${String(snapshot.length)}`); + ext.outputChannel.appendLog( + 'Each cached client can own multiple sockets. Socket counts are not tracked here. For Shell and Playground, use Show Worker Stats.', + ); + for (const [index, { client, pending, held, lastFailedStartupId }] of snapshot.entries()) { + ext.outputChannel.appendLog(` Connection ${String(index + 1)}:`); + ext.outputChannel.appendLog( + client + ? ` Client: ${client.state} generation=${String(client.generation)} ageMs=${String(client.ageMs)} auth=${client.authMethod ?? 'unknown'} startup=${client.startupId ?? 'none'} socketTrace=${String(client.socketTrace)}` + : ' Client: none', + ); + if (pending) { + ext.outputChannel.appendLog( + ` Pending: ${pending.superseded ? 'superseded' : 'current'} startup=${pending.startupId}`, + ); + } + if (held) { + ext.outputChannel.appendLog(` Held: ${held}`); + } + if (lastFailedStartupId) { + ext.outputChannel.appendLog(` Last failed startup: ${lastFailedStartupId}`); + } + } + ext.outputChannel.show(); +} diff --git a/src/documentdb/ClustersClient.test.ts b/src/documentdb/ClustersClient.test.ts index b7b2c69bd..2965fc986 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -239,6 +239,59 @@ describe('regular connection startup diagnostics', () => { expect(second.createdAt).toBeGreaterThan(first.createdAt); }); + it('reports read-only client diagnostics without connection or identity details', async (): Promise => { + const client = await ClustersClient.connectInteractive(clusterId); + vi.advanceTimersByTime(2_000); + + const snapshot = ClustersClient.getDiagnosticsSnapshot(); + const entry = snapshot.find(({ client: row }) => row?.startupId === client.connectionCorrelationId); + + expect(entry?.client).toEqual({ + generation: client.generation, + ageMs: 2_000, + authMethod: AuthMethodId.MicrosoftEntraID, + startupId: client.connectionCorrelationId, + state: 'cached', + socketTrace: true, + }); + const output = JSON.stringify(snapshot); + for (const value of [ + clusterId, + client.fingerprint, + verifiedIdentity.accountId, + verifiedIdentity.accountLabel, + verifiedIdentity.tenantId, + 'private-host', + ]) { + expect(output).not.toContain(value); + } + expect(await ClustersClient.getClient(clusterId)).toBe(client); + expect(mockConnect).toHaveBeenCalledOnce(); + expect(mockClose).not.toHaveBeenCalled(); + }); + + it('shows a superseded startup and a hold even without a cached client', async (): Promise => { + const handshake = pauseNextConnect(); + const onStartup = vi.fn<(id: string) => void>(); + const opening = ClustersClient.connectInteractive(clusterId, undefined, onStartup); + await handshake.started; + const startupId = onStartup.mock.calls[0][0]; + const findPending = () => + ClustersClient.getDiagnosticsSnapshot().find(({ pending }) => pending?.startupId === startupId); + expect(findPending()).toMatchObject({ client: undefined, pending: { superseded: false } }); + + ClustersClient.latch(clusterId, 'userDisconnected'); + expect(findPending()).toMatchObject({ + client: undefined, + pending: { superseded: true }, + held: 'userDisconnected', + }); + + handshake.resolve(); + await expect(opening).rejects.toMatchObject({ reason: 'userDisconnected' }); + ClustersClient.unlatch(clusterId); + }); + it('never hydrates unpinned Entra silently, even after a native connection', async () => { const expectNoSession = async (): Promise => { await expect( diff --git a/src/documentdb/ClustersClient.ts b/src/documentdb/ClustersClient.ts index d0a0a534a..a578629e3 100644 --- a/src/documentdb/ClustersClient.ts +++ b/src/documentdb/ClustersClient.ts @@ -45,7 +45,7 @@ import { meterSilentCatch } from '../utils/accumulatingTelemetry'; import { type EmulatorConfiguration } from '../utils/emulatorConfiguration'; import { nonNullValue } from '../utils/nonNull'; import { type AuthHandlerResponse, type VerifiedEntraIdentity } from './auth/AuthHandler'; -import { AuthMethodId } from './auth/AuthMethod'; +import { AuthMethodId, isSupportedAuthMethod } from './auth/AuthMethod'; import { createAuthHandler } from './auth/createAuthHandler'; import { EntraSignInRequiredError } from './auth/entraErrors/entraCallbackErrors'; import { getAzureHostSuffix } from './auth/oidcAllowedHosts'; @@ -89,6 +89,20 @@ export interface ConnectionBinding { readonly generation: number; } +interface ConnectionStatsEntry { + readonly client?: { + readonly generation: number; + readonly ageMs: number; + readonly authMethod?: AuthMethodId; + readonly startupId?: string; + readonly state: 'cached' | 'closed' | 'replaceOnNextForeground' | 'replaceOnRecovery'; + readonly socketTrace: boolean; + }; + readonly pending?: { readonly startupId: string; readonly superseded: boolean }; + readonly held?: ConnectionUnavailableReason; + readonly lastFailedStartupId?: string; +} + export type VerifiedIdentity = VerifiedEntraIdentity | Exclude; export interface CollectionItemModel { @@ -363,6 +377,37 @@ export class ClustersClient { return ClustersClient._lastFailedStartups.get(clusterId); } + public static getDiagnosticsSnapshot(): readonly ConnectionStatsEntry[] { + const now = Date.now(); + const clusterIds = new Set([ + ...ClustersClient._clients.keys(), + ...ClustersClient._pendingStartups.keys(), + ...ClustersClient._latches.keys(), + ...ClustersClient._lastFailedStartups.keys(), + ]); + return Array.from(clusterIds, (clusterId): ConnectionStatsEntry => { + const client = ClustersClient._clients.get(clusterId); + const pending = ClustersClient._pendingStartups.get(clusterId); + const authMethod = client?.authMethod; + return { + client: client && { + generation: client.generation, + ageMs: Math.max(0, now - client.createdAt), + authMethod: isSupportedAuthMethod(authMethod) ? authMethod : undefined, + startupId: client.connectionCorrelationId, + state: client._replacement ?? (client._closed ? 'closed' : 'cached'), + socketTrace: client._interactiveEntraStartupId !== undefined, + }, + pending: pending && { + startupId: pending.id, + superseded: pending.epoch !== ClustersClient.getEpoch(clusterId), + }, + held: ClustersClient.getLatchReason(clusterId), + lastFailedStartupId: ClustersClient.getLastFailedStartupCorrelationId(clusterId), + }; + }); + } + /** * Private constructor - use getClient() instead. * Connections/Clients are being cached and reused. @@ -1057,7 +1102,7 @@ export class ClustersClient { } /** - * Returns an existing client synchronously if it is already in the connection pool. + * Returns an existing client synchronously if it is already in the client cache. * Returns `undefined` if the client is not yet connected. This is useful for * accessing cached data (e.g., cached collection/database listings) without * triggering a connection or blocking on async operations. diff --git a/src/documentdb/ClustersExtension.ts b/src/documentdb/ClustersExtension.ts index 91e5f41b3..23a91d37a 100644 --- a/src/documentdb/ClustersExtension.ts +++ b/src/documentdb/ClustersExtension.ts @@ -86,6 +86,7 @@ import { retryAuthentication } from '../commands/retryAuthentication/retryAuthen import { revealView } from '../commands/revealView/revealView'; import { clearSchemaCache } from '../commands/schemaStore/clearSchemaCache'; import { showSchemaStoreStats } from '../commands/schemaStore/showSchemaStoreStats'; +import { showConnectionStats } from '../commands/showConnectionStats/showConnectionStats'; import { showWorkerStats } from '../commands/showWorkerStats/showWorkerStats'; import { signInAgain } from '../commands/signInAgain/signInAgain'; import { updateConnectionString } from '../commands/updateConnectionString/updateConnectionString'; @@ -624,6 +625,10 @@ export class ClustersExtension implements vscode.Disposable { withCommandCorrelation(showSchemaStoreStats), ); + registerCommand( + 'vscode-documentdb.command.showConnectionStats', + withCommandCorrelation(showConnectionStats), + ); registerCommand('vscode-documentdb.command.showWorkerStats', withCommandCorrelation(showWorkerStats)); //// General Commands: From 886490748b52f0f494c967aa0a307bd1d3bb5735 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 18:02:21 +0000 Subject: [PATCH 092/380] feat: show Entra token expiry in connection stats (WI-5) Show the declared expiry of the last token supplied to the driver without retaining the token or changing renewal. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iterations/01-dev-plan.md | 3 ++ .../showConnectionStats.ts | 4 ++ src/documentdb/ClustersClient.test.ts | 40 +++++++++++++++++++ src/documentdb/ClustersClient.ts | 22 ++++++++++ 4 files changed, 69 insertions(+) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index 09687d174..4faf363ab 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md @@ -1341,6 +1341,9 @@ shim (0005). **Show Worker Stats**, as a separate WI-5 commit. The extension-host snapshot shows client generation, age, auth method, startup correlation, pending or held state, and whether socket events are traced. It contains no cluster or account identifiers and makes no service calls. + For Entra it can show the UTC expiry declared by the last token supplied to the driver, or + `unknown`. This local diagnostic retains no token and does not predict server acceptance or + force renewal. Leave socket counts out rather than guessing. Keep the published OP-3 candidate unchanged. - **Worker startup regression:** PR4's shared OIDC code imported the VS Code UI auth-method module into the Node worker path. Keep the shared auth IDs independent of VS Code. Verify diff --git a/src/commands/showConnectionStats/showConnectionStats.ts b/src/commands/showConnectionStats/showConnectionStats.ts index 8e7f08364..3a7907d75 100644 --- a/src/commands/showConnectionStats/showConnectionStats.ts +++ b/src/commands/showConnectionStats/showConnectionStats.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import { type IActionContext } from '@microsoft/vscode-azext-utils'; +import { AuthMethodId } from '../../documentdb/auth/AuthMethodId'; import { ClustersClient } from '../../documentdb/ClustersClient'; import { ext } from '../../extensionVariables'; @@ -20,6 +21,9 @@ export function showConnectionStats(_context: IActionContext): void { ? ` Client: ${client.state} generation=${String(client.generation)} ageMs=${String(client.ageMs)} auth=${client.authMethod ?? 'unknown'} startup=${client.startupId ?? 'none'} socketTrace=${String(client.socketTrace)}` : ' Client: none', ); + if (client?.authMethod === AuthMethodId.MicrosoftEntraID) { + ext.outputChannel.appendLog(` lastEntraTokenExpiresAt=${client.lastEntraTokenExpiresAt ?? 'unknown'}`); + } if (pending) { ext.outputChannel.appendLog( ` Pending: ${pending.superseded ? 'superseded' : 'current'} startup=${pending.startupId}`, diff --git a/src/documentdb/ClustersClient.test.ts b/src/documentdb/ClustersClient.test.ts index 2965fc986..84fb391cf 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -253,6 +253,7 @@ describe('regular connection startup diagnostics', () => { startupId: client.connectionCorrelationId, state: 'cached', socketTrace: true, + lastEntraTokenExpiresAt: undefined, }); const output = JSON.stringify(snapshot); for (const value of [ @@ -270,6 +271,45 @@ describe('regular connection startup diagnostics', () => { expect(mockClose).not.toHaveBeenCalled(); }); + it('reports only the expiry of the last Entra token supplied to the driver', async (): Promise => { + const firstExpiry = 1_800_000_000; + const renewedExpiry = firstExpiry + 3600; + const tokenAt = (exp: number): string => + `test.${Buffer.from(JSON.stringify({ exp })).toString('base64url')}.signature`; + const first = { accessToken: tokenAt(firstExpiry) }; + const renewed = { accessToken: tokenAt(renewedExpiry) }; + const missingSession = new EntraSignInRequiredError('noSession'); + const callback = vi + .fn() + .mockResolvedValueOnce(first) + .mockRejectedValueOnce(missingSession) + .mockResolvedValueOnce(renewed) + .mockResolvedValueOnce({ accessToken: 'opaque-test-token' }); + vi.mocked(MicrosoftEntraIDAuthHandler.prototype.configureAuth).mockResolvedValueOnce({ + connectionString: 'mongodb://private-host:27017', + options: { authMechanismProperties: { OIDC_CALLBACK: callback } }, + verifiedIdentity, + }); + const client = await ClustersClient.connectInteractive(clusterId); + const driverCallback = vi.mocked(MongoClient).mock.calls[0][1]?.authMechanismProperties?.OIDC_CALLBACK; + const params: Mongodb.OIDCCallbackParams = { version: 1, timeoutContext: new AbortController().signal }; + const expiry = (): string | undefined => + ClustersClient.getDiagnosticsSnapshot() + .find(({ client: row }) => row?.startupId === client.connectionCorrelationId) + ?.client?.lastEntraTokenExpiresAt; + + expect(expiry()).toBeUndefined(); + await expect(driverCallback!(params)).resolves.toBe(first); + expect(expiry()).toBe(new Date(firstExpiry * 1000).toISOString()); + expect(JSON.stringify(ClustersClient.getDiagnosticsSnapshot())).not.toContain(first.accessToken); + await expect(driverCallback!(params)).rejects.toBe(missingSession); + expect(expiry()).toBe(new Date(firstExpiry * 1000).toISOString()); + await expect(driverCallback!(params)).resolves.toBe(renewed); + expect(expiry()).toBe(new Date(renewedExpiry * 1000).toISOString()); + await driverCallback!(params); + expect(expiry()).toBeUndefined(); + }); + it('shows a superseded startup and a hold even without a cached client', async (): Promise => { const handshake = pauseNextConnect(); const onStartup = vi.fn<(id: string) => void>(); diff --git a/src/documentdb/ClustersClient.ts b/src/documentdb/ClustersClient.ts index a578629e3..c11d1d7c5 100644 --- a/src/documentdb/ClustersClient.ts +++ b/src/documentdb/ClustersClient.ts @@ -36,6 +36,7 @@ import { type InsertManyResult, type ListDatabasesResult, type MongoClientOptions, + type OIDCResponse, type WithId, type WithoutId, } from 'mongodb'; @@ -49,6 +50,7 @@ import { AuthMethodId, isSupportedAuthMethod } from './auth/AuthMethod'; import { createAuthHandler } from './auth/createAuthHandler'; import { EntraSignInRequiredError } from './auth/entraErrors/entraCallbackErrors'; import { getAzureHostSuffix } from './auth/oidcAllowedHosts'; +import { readJwtTimes } from './auth/tokenExpiry'; import { QueryInsightsApis, type ExplainVerbosity } from './client/QueryInsightsApis'; import { classifyConnectionFailure, type ConnectionFailure } from './connectionFailures'; import { computeConnectionFingerprint, type ConnectionPrincipal } from './connectionFingerprint'; @@ -97,6 +99,7 @@ interface ConnectionStatsEntry { readonly startupId?: string; readonly state: 'cached' | 'closed' | 'replaceOnNextForeground' | 'replaceOnRecovery'; readonly socketTrace: boolean; + readonly lastEntraTokenExpiresAt?: string; }; readonly pending?: { readonly startupId: string; readonly superseded: boolean }; readonly held?: ConnectionUnavailableReason; @@ -350,6 +353,7 @@ export class ClustersClient { private _closed = false; private _replacement?: 'replaceOnNextForeground' | 'replaceOnRecovery'; private _interactiveEntraStartupId?: string; + private _lastEntraTokenExpiresAt?: string; private _llmEnhancedFeatureApis: llmEnhancedFeatureApis | null = null; private _queryInsightsApis: QueryInsightsApis | null = null; private _clusterMetadataPromise: Promise | null = null; @@ -397,6 +401,7 @@ export class ClustersClient { startupId: client.connectionCorrelationId, state: client._replacement ?? (client._closed ? 'closed' : 'cached'), socketTrace: client._interactiveEntraStartupId !== undefined, + lastEntraTokenExpiresAt: client._lastEntraTokenExpiresAt, }, pending: pending && { startupId: pending.id, @@ -718,6 +723,23 @@ export class ClustersClient { emulatorConfiguration?: EmulatorConfiguration, originalConnectionString: string = connectionString, ): Promise { + const authProperties = options.authMechanismProperties; + const callback = authProperties?.OIDC_CALLBACK; + if (interactiveEntra && callback) { + options = { + ...options, + authMechanismProperties: { + ...authProperties, + OIDC_CALLBACK: async (params): Promise => { + const response = await callback(params); + const { expSec } = readJwtTimes(response.accessToken); + this._lastEntraTokenExpiresAt = + expSec === undefined ? undefined : (new Date(expSec * 1000).toJSON() ?? undefined); + return response; + }, + }, + }; + } this._mongoClient = new MongoClient(connectionString, options); this._mongoClient.once('topologyClosed', (): void => { this._closed = true; From 917e2e1cf8d07b949b6bc60ef3839909185adf74 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 18:05:49 +0000 Subject: [PATCH 093/380] feat: show time remaining on the Entra token (WI-5) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../showConnectionStats.test.ts | 48 +++++++++++++++++++ .../showConnectionStats.ts | 22 ++++++++- 2 files changed, 69 insertions(+), 1 deletion(-) create mode 100644 src/commands/showConnectionStats/showConnectionStats.test.ts diff --git a/src/commands/showConnectionStats/showConnectionStats.test.ts b/src/commands/showConnectionStats/showConnectionStats.test.ts new file mode 100644 index 000000000..fe1a2161f --- /dev/null +++ b/src/commands/showConnectionStats/showConnectionStats.test.ts @@ -0,0 +1,48 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { type IActionContext } from '@microsoft/vscode-azext-utils'; +import { afterEach, expect, it, vi } from 'vitest'; +import { AuthMethodId } from '../../documentdb/auth/AuthMethodId'; +import { ClustersClient } from '../../documentdb/ClustersClient'; +import { ext } from '../../extensionVariables'; +import { showConnectionStats } from './showConnectionStats'; + +vi.mock('../../documentdb/ClustersClient', () => ({ + ClustersClient: { getDiagnosticsSnapshot: vi.fn() }, +})); + +vi.mock('../../extensionVariables', () => ({ + ext: { outputChannel: { appendLog: vi.fn(), show: vi.fn() } }, +})); + +afterEach(() => { + vi.useRealTimers(); +}); + +it.each([ + ['2026-11-24T19:02:03.000Z', '2026-11-24T19:02:03.000Z (in 25:02:03)'], + ['2026-11-23T18:00:00.001Z', '2026-11-23T18:00:00.001Z (in 00:00:01)'], + ['2026-11-23T18:00:00.000Z', '2026-11-23T18:00:00.000Z (expired)'], + [undefined, 'unknown'], +])('prints the UTC expiry with remaining time or status for %s', (expiry, expected): void => { + vi.useFakeTimers({ now: new Date('2026-11-23T18:00:00.000Z') }); + vi.mocked(ClustersClient.getDiagnosticsSnapshot).mockReturnValueOnce([ + { + client: { + generation: 1, + ageMs: 1000, + authMethod: AuthMethodId.MicrosoftEntraID, + state: 'cached', + socketTrace: true, + lastEntraTokenExpiresAt: expiry, + }, + }, + ]); + + showConnectionStats({} as IActionContext); + + expect(ext.outputChannel.appendLog).toHaveBeenCalledWith(` lastEntraTokenExpiresAt=${expected}`); +}); diff --git a/src/commands/showConnectionStats/showConnectionStats.ts b/src/commands/showConnectionStats/showConnectionStats.ts index 3a7907d75..2685115f3 100644 --- a/src/commands/showConnectionStats/showConnectionStats.ts +++ b/src/commands/showConnectionStats/showConnectionStats.ts @@ -8,8 +8,26 @@ import { AuthMethodId } from '../../documentdb/auth/AuthMethodId'; import { ClustersClient } from '../../documentdb/ClustersClient'; import { ext } from '../../extensionVariables'; +function formatEntraExpiry(expiresAt: string | undefined, now: number): string { + if (expiresAt === undefined) { + return 'unknown'; + } + + const remainingMs = Date.parse(expiresAt) - now; + if (remainingMs <= 0) { + return `${expiresAt} (expired)`; + } + + const seconds = Math.ceil(remainingMs / 1000); + const remaining = [Math.floor(seconds / 3600), Math.floor(seconds / 60) % 60, seconds % 60] + .map((part) => String(part).padStart(2, '0')) + .join(':'); + return `${expiresAt} (in ${remaining})`; +} + export function showConnectionStats(_context: IActionContext): void { const snapshot = ClustersClient.getDiagnosticsSnapshot(); + const now = Date.now(); ext.outputChannel.appendLog(`[Connection Stats] Extension-host cache entries: ${String(snapshot.length)}`); ext.outputChannel.appendLog( 'Each cached client can own multiple sockets. Socket counts are not tracked here. For Shell and Playground, use Show Worker Stats.', @@ -22,7 +40,9 @@ export function showConnectionStats(_context: IActionContext): void { : ' Client: none', ); if (client?.authMethod === AuthMethodId.MicrosoftEntraID) { - ext.outputChannel.appendLog(` lastEntraTokenExpiresAt=${client.lastEntraTokenExpiresAt ?? 'unknown'}`); + ext.outputChannel.appendLog( + ` lastEntraTokenExpiresAt=${formatEntraExpiry(client.lastEntraTokenExpiresAt, now)}`, + ); } if (pending) { ext.outputChannel.appendLog( From 98d72dd4817f7da36f722edebc1c158a3f70c32d Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 18:05:49 +0000 Subject: [PATCH 094/380] chore: identify the next OP-3 test build as 1.1.1-alpha.1 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../connection-lifecycle/iterations/01-dev-plan.md | 9 +++++---- package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index 4faf363ab..c167d80ab 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md @@ -1341,10 +1341,11 @@ shim (0005). **Show Worker Stats**, as a separate WI-5 commit. The extension-host snapshot shows client generation, age, auth method, startup correlation, pending or held state, and whether socket events are traced. It contains no cluster or account identifiers and makes no service calls. - For Entra it can show the UTC expiry declared by the last token supplied to the driver, or - `unknown`. This local diagnostic retains no token and does not predict server acceptance or - force renewal. - Leave socket counts out rather than guessing. Keep the published OP-3 candidate unchanged. + For Entra it shows the UTC expiry declared by the last token supplied to the driver, with + the remaining time at capture (`hh:mm:ss`), `expired`, or `unknown`. This local diagnostic + retains no token and does not predict server acceptance or force renewal. + Leave socket counts out rather than guessing. The operator requested restarting OP-3 on + the next CI-built candidate, `1.1.1-alpha.1`, which includes the diagnostics and worker fix. - **Worker startup regression:** PR4's shared OIDC code imported the VS Code UI auth-method module into the Node worker path. Keep the shared auth IDs independent of VS Code. Verify the next packaged candidate starts both Shell and Playground; the tree OP-3 gate is unchanged. diff --git a/package-lock.json b/package-lock.json index 919b04803..a2ea6de7a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "vscode-documentdb", - "version": "1.1.1-alpha.0", + "version": "1.1.1-alpha.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "vscode-documentdb", - "version": "1.1.1-alpha.0", + "version": "1.1.1-alpha.1", "license": "SEE LICENSE IN LICENSE.md", "workspaces": [ "packages/*" diff --git a/package.json b/package.json index 5a096fdb1..eec16dff8 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "vscode-documentdb", - "version": "1.1.1-alpha.0", + "version": "1.1.1-alpha.1", "releaseNotesUrl": "https://github.com/microsoft/vscode-documentdb/discussions/1089", "aiKey": "0c6ae279ed8443289764825290e4f9e2-1a736e7c-1324-4338-be46-fc2a58ae4d14-7255", "publisher": "ms-azuretools", From ee19ba44e65d5582b9f0f4c0f3fe535e8e4fd7b6 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 19:09:28 +0000 Subject: [PATCH 095/380] fix: clarify the tree sign-in recovery action (WI-5) Record the OP-3 pass and use Retry sign-in as the primary Entra recovery action without changing its command or position. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../features/connection-lifecycle/README.md | 4 ++-- .../connection-lifecycle/iterations/01-dev-plan.md | 12 ++++++++++-- l10n/bundle.l10n.json | 2 +- src/tree/documentdb/ClusterItemBase.test.ts | 3 ++- src/tree/documentdb/ClusterItemBase.ts | 2 +- 5 files changed, 16 insertions(+), 7 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/README.md b/docs/ai-and-plans/features/connection-lifecycle/README.md index e6598d6f6..25a97a0d5 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/README.md +++ b/docs/ai-and-plans/features/connection-lifecycle/README.md @@ -52,8 +52,8 @@ Evidence, telemetry and source pointers: [research-findings.md](./research-findi - **Never change identity under an open surface.** It becomes disconnected, keeps its state, says why and offers one action. - After a database rejects a verified Entra identity, discard the client but keep its in-memory - connection settings for explicit **Sign in again**. Do not retain the rejected token or retry - silently. When the tree offers **Sign in again**, it does not also offer **Retry**. + connection settings for explicit sign-in. Do not retain the rejected token or retry silently. + When the tree offers **Retry sign-in**, it does not also offer **Retry**. - **One teardown** serves Disconnect, Remove Connection and identity-changing credential updates. - Disconnect uses the existing task-conflict guard: if a copy or export is using the cluster, leave the task and connection running. The user can retry after the task finishes or is stopped. diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index c167d80ab..02e3cca12 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md @@ -1213,12 +1213,12 @@ shim (0005). - Route both catch paths in `getChildren` (cached-client reuse and `listDatabases`) through `reportFailure`. Keep the modal-plus-actions presentation. - Change `createErrorRecoveryChildren` to: - - **Sign in again** when the kind is `signInRequired` or `credentialsRejected` and the + - **Retry sign-in** when the kind is `signInRequired` or `credentialsRejected` and the Entra identity and settings are available, or **Update credentials** (the provider-owned action that exists today); - then Diagnose; - then Open shell; - - then **Retry last**, except when **Sign in again** is offered in its place. + - then **Retry last**, except when **Retry sign-in** is offered in its place. - Check that order against the skill text, and update the skill in WI-10 if it differs. - Call `addEstablishedConnectionContext` on the failure events of `connect`, `getchildren` and the tree. - **Keep credentials on recoverable failures (F-20).** In every provider item's `authenticateAndConnect` @@ -1328,6 +1328,14 @@ shim (0005). were not reached. The run is inconclusive; OP-3 remains open. On resume, close the dashboard, wait until the cached token is no longer accepted, and explicitly refresh the cluster node without restarting the extension host. Collapse and re-expand can show cached children. +- **OP-3 resumed on the older VSIX (2026-11-23):** A refresh opened a new socket on the + same client. OIDC callback invocation 2 threw, and the database listing failed. + The operator confirmed that the initial failure showed an error modal, not a sign-in + prompt. Closing the modal revealed the recovery action. They confirmed dismissing the + actual Microsoft sign-in prompt as requested and that the recovery actions remained. + A later explicit sign-in restored the database list. **OP-3 passed** on the older CI VSIX. + The operator approved renaming the tree action to **Retry sign-in**, first before Diagnose + and Open shell, without a separate Retry row. Command ID and recovery behavior are unchanged. - **Sign-out scope review (2026-11-23):** Claude Opus 5.5 recommended keeping the approved 1.2.0 scope (80% confidence). Prompt sign-out handling would need account-specific session checks, coordination with active tasks, and separate handling for Shell and Playground diff --git a/l10n/bundle.l10n.json b/l10n/bundle.l10n.json index 79c6e5f2e..de81ca768 100644 --- a/l10n/bundle.l10n.json +++ b/l10n/bundle.l10n.json @@ -2510,6 +2510,7 @@ "Retry loading tenants": "Retry loading tenants", "Retry setup": "Retry setup", "Retry setup…": "Retry setup…", + "Retry sign-in": "Retry sign-in", "Retry TS Plugin Setup": "Retry TS Plugin Setup", "Retry with longer timeouts": "Retry with longer timeouts", "Retry without diagnostic timeouts": "Retry without diagnostic timeouts", @@ -2720,7 +2721,6 @@ "Showing the first {shown} collections; {omitted} more are not listed.": "Showing the first {shown} collections; {omitted} more are not listed.", "Showing the first {shown} databases; {omitted} more are not listed.": "Showing the first {shown} databases; {omitted} more are not listed.", "Sign in": "Sign in", - "Sign in again": "Sign in again", "Sign in again to continue using Microsoft Entra ID.": "Sign in again to continue using Microsoft Entra ID.", "Sign in again to continue using this connection.": "Sign in again to continue using this connection.", "Sign in to": "Sign in to", diff --git a/src/tree/documentdb/ClusterItemBase.test.ts b/src/tree/documentdb/ClusterItemBase.test.ts index 7de34e605..5b9b649b0 100644 --- a/src/tree/documentdb/ClusterItemBase.test.ts +++ b/src/tree/documentdb/ClusterItemBase.test.ts @@ -451,7 +451,7 @@ describe('ClusterItemBase.getChildren — cached client connection failure handl }); it.each(['signInRequired', 'credentialsRejected'] as const)( - 'offers Sign in again instead of Retry for %s and keeps the failed-expansion marker', + 'offers Retry sign-in instead of Retry for %s and keeps the failed-expansion marker', async (reason): Promise => { if (reason === 'credentialsRejected') { ClustersClientMock.getLatchReason.mockReturnValueOnce(reason); @@ -477,6 +477,7 @@ describe('ClusterItemBase.getChildren — cached client connection failure handl 'cluster-1/diagnose', 'cluster-1/open-shell', ]); + expect(children[0]).toMatchObject({ label: 'Retry sign-in' }); expect(item.hasRetryNode(children)).toBe(true); expect(ClustersClientMock.reportFailure).not.toHaveBeenCalled(); expect(CredentialCache.deleteCredentials).not.toHaveBeenCalled(); diff --git a/src/tree/documentdb/ClusterItemBase.ts b/src/tree/documentdb/ClusterItemBase.ts index cad28218c..086d9f8a7 100644 --- a/src/tree/documentdb/ClusterItemBase.ts +++ b/src/tree/documentdb/ClusterItemBase.ts @@ -373,7 +373,7 @@ export abstract class ClusterItemBase Date: Mon, 23 Nov 2026 19:09:28 +0000 Subject: [PATCH 096/380] style: format connection diagnostics tests for CI Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/documentdb/ClustersClient.test.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/documentdb/ClustersClient.test.ts b/src/documentdb/ClustersClient.test.ts index 84fb391cf..0106bbb11 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -294,9 +294,9 @@ describe('regular connection startup diagnostics', () => { const driverCallback = vi.mocked(MongoClient).mock.calls[0][1]?.authMechanismProperties?.OIDC_CALLBACK; const params: Mongodb.OIDCCallbackParams = { version: 1, timeoutContext: new AbortController().signal }; const expiry = (): string | undefined => - ClustersClient.getDiagnosticsSnapshot() - .find(({ client: row }) => row?.startupId === client.connectionCorrelationId) - ?.client?.lastEntraTokenExpiresAt; + ClustersClient.getDiagnosticsSnapshot().find( + ({ client: row }) => row?.startupId === client.connectionCorrelationId, + )?.client?.lastEntraTokenExpiresAt; expect(expiry()).toBeUndefined(); await expect(driverCallback!(params)).resolves.toBe(first); From 87ab0ed1f2959e4874f73a6f08afa97c84761df7 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 19:38:17 +0000 Subject: [PATCH 097/380] fix: respect client recovery when reconnecting and retrying (WI-5) Hold current verified Entra replacement rejections and leave a healthy replacement alone when an old Retry action is clicked. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../retryAuthentication.test.ts | 16 ++++++++++++++++ .../retryAuthentication/retryAuthentication.ts | 5 ++++- src/documentdb/ClustersClient.test.ts | 13 +++++++++++++ src/documentdb/ClustersClient.ts | 14 ++++++++++++++ 4 files changed, 47 insertions(+), 1 deletion(-) diff --git a/src/commands/retryAuthentication/retryAuthentication.test.ts b/src/commands/retryAuthentication/retryAuthentication.test.ts index 7fa94f715..9b6b96455 100644 --- a/src/commands/retryAuthentication/retryAuthentication.test.ts +++ b/src/commands/retryAuthentication/retryAuthentication.test.ts @@ -41,6 +41,7 @@ vi.mock('../../documentdb/ClustersClient', () => ({ ClustersClient: { getEpoch: vi.fn(() => 0), getLatchReason: vi.fn(), + hasReusableClient: vi.fn(), clearCredentialRejection: vi.fn(), deleteClient: vi.fn(), getLastFailedStartupCorrelationId: vi.fn((clusterId: string) => @@ -224,6 +225,21 @@ describe('retryAuthentication', () => { expect(ext.discoveryBranchDataProvider.refresh).not.toHaveBeenCalled(); }); + it('refreshes without closing a healthy client that replaced the one that failed', async (): Promise => { + const node = { + id: 'connectionsView/stale', + cluster: { clusterId: 'stale' }, + getTreeItem, + lastConnectionFailureKind: 'clientClosed' as const, + }; + vi.mocked(ClustersClient.hasReusableClient).mockReturnValueOnce(true); + + await retryAuthentication(actionContext as never, node); + + expect(ClustersClient.deleteClient).not.toHaveBeenCalled(); + expect(ext.connectionsBranchDataProvider.refresh).toHaveBeenCalledExactlyOnceWith(node); + }); + it('does not refresh an old Retry after the client was replaced while its close was pending', async (): Promise => { const node = { id: 'connectionsView/stale', diff --git a/src/commands/retryAuthentication/retryAuthentication.ts b/src/commands/retryAuthentication/retryAuthentication.ts index ef9606445..56f7a92ca 100644 --- a/src/commands/retryAuthentication/retryAuthentication.ts +++ b/src/commands/retryAuthentication/retryAuthentication.ts @@ -152,7 +152,10 @@ export async function retryAuthentication(context: IActionContext, node: Retryab } else { return; } - } else if (kind === 'signInRequired' || kind === 'credentialsRejected' || kind === 'clientClosed') { + } else if ( + (kind === 'signInRequired' || kind === 'credentialsRejected' || kind === 'clientClosed') && + !ClustersClient.hasReusableClient(clusterId) + ) { const closing = ClustersClient.deleteClient(clusterId); epoch = ClustersClient.getEpoch(clusterId); await closing; diff --git a/src/documentdb/ClustersClient.test.ts b/src/documentdb/ClustersClient.test.ts index 0106bbb11..3fe3353a3 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -573,6 +573,19 @@ describe('regular connection startup diagnostics', () => { await expect(background()).resolves.toBe(replacement); }); + it('holds a rejected Entra replacement without retrying its cached settings', async (): Promise => { + await ClustersClient.connectInteractive(clusterId); + const credentials = CredentialCache.getCredentials(clusterId); + poolEvents.emit('topologyClosed'); + mockConnect.mockRejectedValueOnce(new MongoServerError({ code: 18 })); + + await expect(ClustersClient.getClient(clusterId)).rejects.toMatchObject({ reason: 'credentialsRejected' }); + await expect(ClustersClient.getClient(clusterId)).rejects.toMatchObject({ reason: 'credentialsRejected' }); + expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); + expect(CredentialCache.getCredentials(clusterId)).toBe(credentials); + expect(MongoClient).toHaveBeenCalledTimes(2); + }); + it('holds a sign-in miss for explicit recovery and does not let a pending replacement bypass it', async () => { const client = await ClustersClient.connectInteractive(clusterId); const pin = ClustersClient.getLastVerifiedIdentity(clusterId); diff --git a/src/documentdb/ClustersClient.ts b/src/documentdb/ClustersClient.ts index c11d1d7c5..bba86d893 100644 --- a/src/documentdb/ClustersClient.ts +++ b/src/documentdb/ClustersClient.ts @@ -1025,6 +1025,16 @@ export class ClustersClient { } catch (error) { if (!(error instanceof UserCancelledError) && epoch === ClustersClient.getEpoch(clusterId)) { ClustersClient._lastFailedStartups.set(clusterId, id); + const previous = ClustersClient._clients.get(clusterId); + if ( + previous?.authMethod === AuthMethodId.MicrosoftEntraID && + previous.fingerprint === expectedFingerprint + ) { + const failure = classifyConnectionFailure(error, previous.authMethod); + if (failure.kind === 'credentialsRejected' && failure.generation === 'evict') { + ClustersClient.reportFailure(previous.binding, error); + } + } } client._closed = true; void client._mongoClient?.close().catch(() => { @@ -1063,6 +1073,10 @@ export class ClustersClient { return !this._closed && this._replacement === undefined; } + public static hasReusableClient(clusterId: string): boolean { + return ClustersClient._clients.get(clusterId)?.canReuse() ?? false; + } + /** Reports an operation's failure against the generation that actually ran it. */ public static reportFailure(binding: ConnectionBinding, error: unknown): ConnectionFailure['kind'] | undefined { const { clusterId, fingerprint, generation } = binding; From 1500634d11d947c29583b993dbe9d54d2ffea615 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 19:38:17 +0000 Subject: [PATCH 098/380] fix: keep stale and inert recovery rows out of the cluster tree (WI-5) Drop listings from a different identity, keep actionable repairs, and detect failures without mistaking a database name for a recovery row. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/tree/documentdb/ClusterItemBase.test.ts | 40 +++++++++++++++++++++ src/tree/documentdb/ClusterItemBase.ts | 32 +++++++++++++---- 2 files changed, 66 insertions(+), 6 deletions(-) diff --git a/src/tree/documentdb/ClusterItemBase.test.ts b/src/tree/documentdb/ClusterItemBase.test.ts index 5b9b649b0..eea7db86e 100644 --- a/src/tree/documentdb/ClusterItemBase.test.ts +++ b/src/tree/documentdb/ClusterItemBase.test.ts @@ -17,6 +17,7 @@ import { ClustersClient, type DatabaseItemModel } from '../../documentdb/Cluster import { ConnectionUnavailableError } from '../../documentdb/ConnectionUnavailableError'; import { CredentialCache } from '../../documentdb/CredentialCache'; import { ShellCommandIds } from '../../documentdb/shell/constants'; +import { Views } from '../../documentdb/Views'; import { type Experience } from '../../DocumentDBExperiences'; import { containsRetryNode, RETRY_NODE_ID_SUFFIX } from '../api/retryNode'; import { BaseExtendedTreeDataProvider } from '../BaseExtendedTreeDataProvider'; @@ -485,6 +486,45 @@ describe('ClusterItemBase.getChildren — cached client connection failure handl }, ); + it('does not publish a database listing from a different identity', async (): Promise => { + const binding = { clusterId: 'cluster-1', fingerprint: 'old', generation: 1 }; + const client = { + ...makeClient(vi.fn().mockResolvedValue([{ name: 'old-database' }])), + binding, + } as ClustersClient; + const replacement = { ...client, fingerprint: 'new' } as ClustersClient; + ClustersClientMock.connectInteractive.mockResolvedValueOnce(client); + ClustersClientMock.getExistingClient.mockReturnValueOnce(replacement); + + expect(await new TestClusterItem(makeCluster(), null).getChildren()).toEqual([]); + expect(vscode.commands.executeCommand).not.toHaveBeenCalled(); + }); + + it.each(['diagnose', 'sign-in-again'])('does not mistake a database named %s for a recovery action', (name): void => { + const item = new TestClusterItem(makeCluster(), null); + const child = { + id: `cluster-1/${name}`, + contextValue: 'treeItem_documentdbdatabase', + getTreeItem: (): vscode.TreeItem => ({ label: name }), + }; + + expect(item.hasRetryNode([child])).toBe(false); + }); + + it('keeps actionable recovery children without an inert Retry for stored credentials', async (): Promise => { + ClustersClientMock.getLatchReason.mockReturnValue('credentialsRejected'); + ClustersClientMock.connectInteractive.mockRejectedValueOnce(new ConnectionUnavailableError('credentialsRejected')); + const item = new TestClusterItem({ ...makeCluster(), viewId: Views.ConnectionsView }, null); + try { + const children = await item.getChildren(); + + expect(children.map(({ id }) => id)).toEqual(['cluster-1/diagnose', 'cluster-1/open-shell']); + expect(item.hasRetryNode(children)).toBe(true); + } finally { + ClustersClientMock.getLatchReason.mockReset(); + } + }); + it('reports the binding that executed listDatabases, not the current cache entry', async (): Promise => { const error = new Error('deprecated generation'); const binding = { clusterId: 'cluster-1', fingerprint: 'old', generation: 1 }; diff --git a/src/tree/documentdb/ClusterItemBase.ts b/src/tree/documentdb/ClusterItemBase.ts index 086d9f8a7..f9c7e5bde 100644 --- a/src/tree/documentdb/ClusterItemBase.ts +++ b/src/tree/documentdb/ClusterItemBase.ts @@ -30,6 +30,7 @@ import { isEntraDestinationRejectedError } from '../../documentdb/auth/oidcAllow import { classifyConnectionFailure, type ConnectionFailure } from '../../documentdb/connectionFailures'; import { ShellCommandIds } from '../../documentdb/shell/constants'; import { showClusterConnectFailure } from '../../documentdb/showClusterConnectFailure'; +import { Views } from '../../documentdb/Views'; import { ext } from '../../extensionVariables'; import { SettingsService } from '../../services/SettingsService'; import { ErrorExplanationService } from '../../services/errorExplanationService'; @@ -37,7 +38,7 @@ import { settingsKeys } from '../../settingsKeys'; import { regionToDisplayName } from '../../utils/regionToDisplayName'; import { withDelayedProgress } from '../../utils/withProgress'; import { type TreeElement } from '../TreeElement'; -import { type TreeElementWithContextValue } from '../TreeElementWithContextValue'; +import { isTreeElementWithContextValue, type TreeElementWithContextValue } from '../TreeElementWithContextValue'; import { type TreeElementWithExperience } from '../TreeElementWithExperience'; import { type TreeElementWithRetryChildren } from '../TreeElementWithRetryChildren'; import { createGenericElementWithContext } from '../api/createGenericElementWithContext'; @@ -350,8 +351,8 @@ export abstract class ClusterItemBase + !ClustersClient.getLatchReason(clusterId) && + (!binding || ClustersClient.getExistingClient(clusterId)?.fingerprint === binding.fingerprint); + if (!isCurrentIdentity()) { + return []; + } // A deep link that opens the dashboard itself suppresses the automatic open; that is not a skip. if (!wasConnected && !isAutoOpenDashboardSuppressed(this.cluster.clusterId)) { @@ -567,6 +578,9 @@ export abstract class ClusterItemBase child.id === `${this.id}/sign-in-again`) === true + containsRetryNode(children) || + children?.some( + (child) => + child.id === `${this.id}/diagnose` && + isTreeElementWithContextValue(child) && + child.contextValue === 'error', + ) === true ); } From 64d6f3ffdc87ddc8ef41ed767dbcd7ccadd6a2a7 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 19:39:26 +0000 Subject: [PATCH 099/380] fix: preserve ordinary edits across recovery state changes (WI-5) Scope the wizard epoch fence to rejected-connection recovery and report storage saves accurately without clearing a newer latch. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../updateConnectionString/ExecuteStep.ts | 2 +- .../updateConnectionString.test.ts | 17 ++++++++ .../updateConnectionString.ts | 15 +++---- src/commands/updateCredentials/ExecuteStep.ts | 2 +- .../updateCredentials.test.ts | 41 +++++++++++++++++-- .../updateCredentials/updateCredentials.ts | 15 +++---- 6 files changed, 72 insertions(+), 20 deletions(-) diff --git a/src/commands/updateConnectionString/ExecuteStep.ts b/src/commands/updateConnectionString/ExecuteStep.ts index 948097962..e195ddb64 100644 --- a/src/commands/updateConnectionString/ExecuteStep.ts +++ b/src/commands/updateConnectionString/ExecuteStep.ts @@ -92,10 +92,10 @@ export class ExecuteStep extends AzureWizardExecuteStep { } await ConnectionStorageService.save(resourceType, connection, true); + context.connectionStringSaved = true; if (context.isRecoveryCurrent?.() === false) { return; } - context.connectionStringSaved = true; if (clearedEntraMethod) { void window.showInformationMessage( diff --git a/src/commands/updateConnectionString/updateConnectionString.test.ts b/src/commands/updateConnectionString/updateConnectionString.test.ts index e92706332..db65fdedc 100644 --- a/src/commands/updateConnectionString/updateConnectionString.test.ts +++ b/src/commands/updateConnectionString/updateConnectionString.test.ts @@ -290,4 +290,21 @@ describe('updateConnectionString rejected-destination recovery', () => { expect(item.lastConnectionOutcome).toBe('connected'); expect(refresh).toHaveBeenCalledOnce(); }); + + it('saves an ordinary edit when the epoch changes while the input is open', async (): Promise => { + const refresh = vi.spyOn(provider, 'refresh'); + item.lastConnectionOutcome = 'connected'; + showInputBox.mockImplementationOnce(async (): Promise => { + vi.mocked(ClustersClient.getEpoch).mockReturnValue(1); + return approvedUri; + }); + + await updateConnectionString(makeContext(), item); + + expect(storedConnection.secrets.connectionString).toBe(approvedUri); + expect(capturedContexts[0].connectionStringSaved).toBe(true); + expect(ClustersClient.deleteClient).not.toHaveBeenCalled(); + expect(deleteCredentials).not.toHaveBeenCalled(); + expect(refresh).toHaveBeenCalledOnce(); + }); }); diff --git a/src/commands/updateConnectionString/updateConnectionString.ts b/src/commands/updateConnectionString/updateConnectionString.ts index de04cfedf..39e22d8c5 100644 --- a/src/commands/updateConnectionString/updateConnectionString.ts +++ b/src/commands/updateConnectionString/updateConnectionString.ts @@ -40,7 +40,8 @@ export async function updateConnectionString(context: IActionContext, node: Docu const clusterId = node.cluster.clusterId; let epoch = ClustersClient.getEpoch(clusterId); const recoveringRejectedCredentials = ClustersClient.getLatchReason(clusterId) === 'credentialsRejected'; - const isCurrent = (): boolean => ClustersClient.getEpoch(clusterId) === epoch; + const recovering = recoveringRejectedDestination || recoveringRejectedCredentials; + const isRecoveryCurrent = recovering ? (): boolean => ClustersClient.getEpoch(clusterId) === epoch : undefined; // Extract the connection string but hide the username and password @@ -50,7 +51,7 @@ export async function updateConnectionString(context: IActionContext, node: Docu const resourceType = resolveStorageZone(node.cluster); const connection = await ConnectionStorageService.get(node.storageId, resourceType); - if (!isCurrent()) { + if (isRecoveryCurrent?.() === false) { return; } const connectionString = connection?.secrets?.connectionString || ''; @@ -70,7 +71,7 @@ export async function updateConnectionString(context: IActionContext, node: Docu storageZone: resolveStorageZone(node.cluster), storageId: node.storageId, connectionStringSaved: false, - isRecoveryCurrent: isCurrent, + isRecoveryCurrent, }; const wizard = new AzureWizard(wizardContext, { @@ -80,19 +81,19 @@ export async function updateConnectionString(context: IActionContext, node: Docu }); await wizard.prompt(); - if (!isCurrent()) { + if (isRecoveryCurrent?.() === false) { return; } await wizard.execute(); - if (!isCurrent()) { + if (isRecoveryCurrent?.() === false) { return; } - if ((recoveringRejectedDestination || recoveringRejectedCredentials) && wizardContext.connectionStringSaved) { + if (recovering && wizardContext.connectionStringSaved) { const closing = ClustersClient.deleteClient(clusterId); epoch = ClustersClient.getEpoch(clusterId); await closing; - if (!isCurrent()) { + if (isRecoveryCurrent?.() === false) { return; } CredentialCache.deleteCredentials(clusterId); diff --git a/src/commands/updateCredentials/ExecuteStep.ts b/src/commands/updateCredentials/ExecuteStep.ts index 4e185a558..d37c7ac03 100644 --- a/src/commands/updateCredentials/ExecuteStep.ts +++ b/src/commands/updateCredentials/ExecuteStep.ts @@ -107,10 +107,10 @@ export class ExecuteStep extends AzureWizardExecuteStep Promise>().mockResolvedValue(undefined); const mockGet = vi.fn(); +const mockSave = vi.fn(); +const mockGetEpoch = vi.fn(() => 0); const mockDeleteClient = vi.fn(); const mockDeleteCredentials = vi.spyOn(CredentialCache, 'deleteCredentials'); const mockShutdownEvaluator = vi.fn(); @@ -26,27 +30,30 @@ const mockGetRegisteredShellTerminals = vi.fn(); vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ ...(await importOriginal<{ AzureWizard: typeof AzureWizard }>()), AzureWizard: class { - constructor(context: UpdateCredentialsWizardContext) { + constructor(private readonly context: UpdateCredentialsWizardContext) { capturedContexts.push(context); } public prompt(): Promise { return Promise.resolve(); } public execute(): Promise { - return Promise.resolve(); + return mockExecute(this.context); } }, })); vi.mock('../../services/connectionStorageService', async (importOriginal) => ({ ...(await importOriginal()), - ConnectionStorageService: { get: (...args: unknown[]): unknown => mockGet(...args) }, + ConnectionStorageService: { + get: (...args: unknown[]): unknown => mockGet(...args), + save: (...args: unknown[]): unknown => mockSave(...args), + }, })); vi.mock('../../documentdb/ClustersClient', () => ({ ClustersClient: { deleteClient: (...args: unknown[]): unknown => mockDeleteClient(...args), getLastFailedStartupCorrelationId: (): undefined => undefined, - getEpoch: (): number => 0, + getEpoch: (): number => mockGetEpoch(), getLatchReason: (): undefined => undefined, }, })); @@ -57,6 +64,7 @@ vi.mock('../../documentdb/shell/ShellTerminalLinkProvider', () => ({ getRegisteredShellTerminals: (): unknown => mockGetRegisteredShellTerminals(), })); vi.mock('../refreshView/refreshView', () => ({ refreshView: vi.fn() })); +vi.mock('../../utils/dialogs/showConfirmation', () => ({ showConfirmationAsInSettings: vi.fn() })); vi.mock('../../extensionVariables', () => ({ ext: { connectionsBranchDataProvider: { hasNodeErrorState: vi.fn(() => false) } }, })); @@ -64,6 +72,7 @@ vi.mock('../../extensionVariables', () => ({ beforeEach(() => { CredentialCache.deleteCredentials('stable-cluster-id'); vi.clearAllMocks(); + mockGetEpoch.mockReturnValue(0); mockGetRegisteredShellTerminals.mockReturnValue([]); capturedContexts.length = 0; }); @@ -210,6 +219,30 @@ describe('updateCredentials post-wizard updates', () => { ); }); + it('updates runtime credentials when the epoch changes during an ordinary save', async (): Promise => { + let storedConnection = originalConnection; + const newCredentials = { connectionUser: 'old-user', connectionPassword: 'new-password' }; + mockGet.mockImplementation(async () => structuredClone(storedConnection)); + mockExecute.mockImplementationOnce(async (wizardContext): Promise => { + wizardContext.nativeAuthConfig = newCredentials; + await new ExecuteStep().execute(wizardContext); + }); + mockSave.mockImplementationOnce( + async (_zone: storageModule.StorageZone, item: storageModule.ConnectionItem): Promise => { + storedConnection = structuredClone(item); + mockGetEpoch.mockReturnValue(1); + }, + ); + + await updateCredentials(context, node); + + expect(storedConnection.secrets.nativeAuthConfig).toEqual(newCredentials); + expect(CredentialCache.getCredentials(node.cluster.clusterId)?.nativeAuthConfig).toEqual(newCredentials); + expect(capturedContexts[0].credentialsSaved).toBe(true); + expect(mockDeleteClient).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId); + expect(mockShutdownEvaluator).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId); + }); + it.each<{ authMethod: AuthMethodId; secrets: Partial }>([ { authMethod: AuthMethodId.NativeAuth, diff --git a/src/commands/updateCredentials/updateCredentials.ts b/src/commands/updateCredentials/updateCredentials.ts index 8ebc1c3fe..e132a6f0e 100644 --- a/src/commands/updateCredentials/updateCredentials.ts +++ b/src/commands/updateCredentials/updateCredentials.ts @@ -60,7 +60,7 @@ export async function updateCredentials(context: IActionContext, node: DocumentD const clusterId = node.cluster.clusterId; let epoch = ClustersClient.getEpoch(clusterId); const recoveringRejection = ClustersClient.getLatchReason(clusterId) === 'credentialsRejected'; - const isCurrent = (): boolean => ClustersClient.getEpoch(clusterId) === epoch; + const isRecoveryCurrent = recoveringRejection ? (): boolean => ClustersClient.getEpoch(clusterId) === epoch : undefined; // The failed attempt these credentials replace; the reconnect's `connect.startup` names it in // `previousFailedStartupCorrelationId`, so it shows whether the new credentials worked. const failedStartupCorrelationId = ClustersClient.getLastFailedStartupCorrelationId(node.cluster.clusterId); @@ -76,7 +76,7 @@ export async function updateCredentials(context: IActionContext, node: DocumentD const resourceType = resolveStorageZone(node.cluster); const storedItem = await ConnectionStorageService.get(node.storageId, resourceType); - if (!isCurrent()) { + if (isRecoveryCurrent?.() === false) { return; } // Type guard ensures we have connection properties (not a folder) @@ -122,7 +122,7 @@ export async function updateCredentials(context: IActionContext, node: DocumentD storageId: node.storageId, isErrorState, reconnectAfterError: false, - isRecoveryCurrent: isCurrent, + isRecoveryCurrent, }; const wizard = new AzureWizard(wizardContext, { @@ -145,23 +145,24 @@ export async function updateCredentials(context: IActionContext, node: DocumentD }); await wizard.prompt(); - if (!isCurrent()) { + if (isRecoveryCurrent?.() === false) { return; } await wizard.execute(); - if (!isCurrent() || (recoveringRejection && !wizardContext.credentialsSaved)) { + if (isRecoveryCurrent?.() === false || (recoveringRejection && !wizardContext.credentialsSaved)) { return; } const updatedStoredItem = await ConnectionStorageService.get(node.storageId, resourceType); - if (!isCurrent()) { + if (isRecoveryCurrent?.() === false) { return; } const updatedConnection = updatedStoredItem && isConnection(updatedStoredItem) ? updatedStoredItem : undefined; const closing = ClustersClient.deleteClient(clusterId); epoch = ClustersClient.getEpoch(clusterId); await closing; - if (!isCurrent()) { + // Do not publish cached credentials over a lifecycle change during close. + if (ClustersClient.getEpoch(clusterId) !== epoch) { return; } const authMethod = authMethodFromString(updatedConnection?.properties.selectedAuthMethod); From dcee13654af77d420d0ca7977107f9cf1726a817 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 19:50:39 +0000 Subject: [PATCH 100/380] fix: close lint and type-check gaps in PR4 review fixes Use the existing view ID string comparison convention and the storage read-back type in the credential regression fixture. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../updateCredentials.test.ts | 2 +- .../updateCredentials/updateCredentials.ts | 4 ++- src/tree/documentdb/ClusterItemBase.test.ts | 25 +++++++++++-------- src/tree/documentdb/ClusterItemBase.ts | 4 +-- 4 files changed, 21 insertions(+), 14 deletions(-) diff --git a/src/commands/updateCredentials/updateCredentials.test.ts b/src/commands/updateCredentials/updateCredentials.test.ts index d7e63022e..b82ec629c 100644 --- a/src/commands/updateCredentials/updateCredentials.test.ts +++ b/src/commands/updateCredentials/updateCredentials.test.ts @@ -220,7 +220,7 @@ describe('updateCredentials post-wizard updates', () => { }); it('updates runtime credentials when the epoch changes during an ordinary save', async (): Promise => { - let storedConnection = originalConnection; + let storedConnection: storageModule.ConnectionItem = originalConnection; const newCredentials = { connectionUser: 'old-user', connectionPassword: 'new-password' }; mockGet.mockImplementation(async () => structuredClone(storedConnection)); mockExecute.mockImplementationOnce(async (wizardContext): Promise => { diff --git a/src/commands/updateCredentials/updateCredentials.ts b/src/commands/updateCredentials/updateCredentials.ts index e132a6f0e..8e5e6fcfa 100644 --- a/src/commands/updateCredentials/updateCredentials.ts +++ b/src/commands/updateCredentials/updateCredentials.ts @@ -60,7 +60,9 @@ export async function updateCredentials(context: IActionContext, node: DocumentD const clusterId = node.cluster.clusterId; let epoch = ClustersClient.getEpoch(clusterId); const recoveringRejection = ClustersClient.getLatchReason(clusterId) === 'credentialsRejected'; - const isRecoveryCurrent = recoveringRejection ? (): boolean => ClustersClient.getEpoch(clusterId) === epoch : undefined; + const isRecoveryCurrent = recoveringRejection + ? (): boolean => ClustersClient.getEpoch(clusterId) === epoch + : undefined; // The failed attempt these credentials replace; the reconnect's `connect.startup` names it in // `previousFailedStartupCorrelationId`, so it shows whether the new credentials worked. const failedStartupCorrelationId = ClustersClient.getLastFailedStartupCorrelationId(node.cluster.clusterId); diff --git a/src/tree/documentdb/ClusterItemBase.test.ts b/src/tree/documentdb/ClusterItemBase.test.ts index eea7db86e..da35ebb9a 100644 --- a/src/tree/documentdb/ClusterItemBase.test.ts +++ b/src/tree/documentdb/ClusterItemBase.test.ts @@ -500,20 +500,25 @@ describe('ClusterItemBase.getChildren — cached client connection failure handl expect(vscode.commands.executeCommand).not.toHaveBeenCalled(); }); - it.each(['diagnose', 'sign-in-again'])('does not mistake a database named %s for a recovery action', (name): void => { - const item = new TestClusterItem(makeCluster(), null); - const child = { - id: `cluster-1/${name}`, - contextValue: 'treeItem_documentdbdatabase', - getTreeItem: (): vscode.TreeItem => ({ label: name }), - }; + it.each(['diagnose', 'sign-in-again'])( + 'does not mistake a database named %s for a recovery action', + (name): void => { + const item = new TestClusterItem(makeCluster(), null); + const child = { + id: `cluster-1/${name}`, + contextValue: 'treeItem_documentdbdatabase', + getTreeItem: (): vscode.TreeItem => ({ label: name }), + }; - expect(item.hasRetryNode([child])).toBe(false); - }); + expect(item.hasRetryNode([child])).toBe(false); + }, + ); it('keeps actionable recovery children without an inert Retry for stored credentials', async (): Promise => { ClustersClientMock.getLatchReason.mockReturnValue('credentialsRejected'); - ClustersClientMock.connectInteractive.mockRejectedValueOnce(new ConnectionUnavailableError('credentialsRejected')); + ClustersClientMock.connectInteractive.mockRejectedValueOnce( + new ConnectionUnavailableError('credentialsRejected'), + ); const item = new TestClusterItem({ ...makeCluster(), viewId: Views.ConnectionsView }, null); try { const children = await item.getChildren(); diff --git a/src/tree/documentdb/ClusterItemBase.ts b/src/tree/documentdb/ClusterItemBase.ts index f9c7e5bde..bdd2a8950 100644 --- a/src/tree/documentdb/ClusterItemBase.ts +++ b/src/tree/documentdb/ClusterItemBase.ts @@ -20,6 +20,7 @@ import { type DatabaseItemModel, } from '../../documentdb/ClustersClient'; import { CredentialCache } from '../../documentdb/CredentialCache'; +import { Views } from '../../documentdb/Views'; import { type EntraIdAuthConfig, type ManagedIdentityAuthConfig, @@ -30,7 +31,6 @@ import { isEntraDestinationRejectedError } from '../../documentdb/auth/oidcAllow import { classifyConnectionFailure, type ConnectionFailure } from '../../documentdb/connectionFailures'; import { ShellCommandIds } from '../../documentdb/shell/constants'; import { showClusterConnectFailure } from '../../documentdb/showClusterConnectFailure'; -import { Views } from '../../documentdb/Views'; import { ext } from '../../extensionVariables'; import { SettingsService } from '../../services/SettingsService'; import { ErrorExplanationService } from '../../services/errorExplanationService'; @@ -369,7 +369,7 @@ export abstract class ClusterItemBase Date: Mon, 23 Nov 2026 19:50:39 +0000 Subject: [PATCH 101/380] docs: record PR4 review dispositions and verified handoff checks Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iterations/01-dev-plan.md | 4 ++ .../01-pr4-connection-recovery-review.md | 58 +++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr4-connection-recovery-review.md diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index 02e3cca12..93f7d4c37 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md @@ -1357,6 +1357,10 @@ shim (0005). - **Worker startup regression:** PR4's shared OIDC code imported the VS Code UI auth-method module into the Node worker path. Keep the shared auth IDs independent of VS Code. Verify the next packaged candidate starts both Shell and Playground; the tree OP-3 gate is unchanged. +- **PR4 handoff verification:** OP-3 passed, author-approved pre-review fixes are in + [the review record](./01-pr4-connection-recovery-review.md), and local Case 2 passed + (9,796 runtime tests passed, one skipped). Keep PR4 in draft until the separate live + packaged Shell and Playground smoke passes. WI-6 host work may proceed on this base. --- diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr4-connection-recovery-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr4-connection-recovery-review.md new file mode 100644 index 000000000..79b0160a5 --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr4-connection-recovery-review.md @@ -0,0 +1,58 @@ +--- +feature: connection-lifecycle +kind: review +status: active +created: 2026-11-23 +--- + +# PR4 pre-review: connection failure recovery + +[PR #1117](https://github.com/microsoft/vscode-documentdb/pull/1117), reviewed locally at +`69112da71` against PR3's `a301f6561`. GPT-6.2-Sol performed the initial review; Claude +Opus 5.5 validated the findings and performed an independent sweep. No published GitHub +reviews were present. The review findings below reflect the reviewed revision; the +operator's dispositions and verification are recorded separately. + +| ID | Severity | Validation | Finding and recommended disposition | +| --- | -------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| F1 | Medium | Partial, 75% | A rejected replacement outside the tree can try the same Entra settings again; the tree already covers its own path. Reproduce first, then latch only a current, verified Entra replacement with a terminal rejection. Leave first-startup and Native/RU behavior alone. [Startup](../../../../../src/documentdb/ClustersClient.ts#L1010) | +| F2 | Medium | Valid, 85%; predates PR4 | An explicit tenant edit can leave the old tenant pin after a sign-in failure. Keep the existing WI-7 requirement to replace or clear the pin on a saved tenant change; do not pull the broader credential-update transaction into PR4. [Update credentials](../../../../../src/commands/updateCredentials/updateCredentials.ts#L171) | +| F3 | Medium | Valid, 80% | An old Retry row can close a healthy replacement already published before the click. Fence the destructive step to the failed client; refresh without closing a newer client. [Retry](../../../../../src/commands/retryAuthentication/retryAuthentication.ts#L155) | +| F4 | Medium | Plausible race, 65% | A late successful database listing could render old rows after another account becomes current. Reproduce first. Discard a result when the identity differs or a latch is set, using the existing stale-result path; a same-identity replacement alone should not discard it. [Expansion](../../../../../src/tree/documentdb/ClusterItemBase.ts#L559) | +| F5 | Medium | Valid, 85% | For a latched stored Native connection, Retry does nothing; Update credentials is the repair. Hide only a Retry row with no action, while retaining Diagnose and Open shell and preserving error detection. Keep working RU and Native Discovery Retry paths. [Recovery rows](../../../../../src/tree/documentdb/ClusterItemBase.ts#L360) | +| N1 | Medium | Valid, 90%; WI-6 integration | The operation wrapper lacks auth context for startup rejection. Cover it when WI-6 first wires the wrapper to routers; the host must return the typed unavailable reason instead of a generic error. [Operation wrapper](../../../../../src/documentdb/runWithClient.ts#L48) | +| N2 | Medium | Potential regression, 70% | The new recovery fence applies to ordinary edits, and a return after storage has saved can leave storage and cached settings out of sync. Reproduce first; keep any PR4 repair scoped to the new regression. Leave the broader save, latch, and teardown transaction in WI-7. [Credentials save](../../../../../src/commands/updateCredentials/ExecuteStep.ts#L110) and [connection string save](../../../../../src/commands/updateConnectionString/ExecuteStep.ts#L95). | +| N3 | Medium | Valid, 90% | A real database named `sign-in-again` can match the recovery row's ID. Require the reserved error context as well as the ID, and test that the real database remains visible as healthy. [Error detection](../../../../../src/tree/documentdb/ClusterItemBase.ts#L610) | + +## Author decisions + +The operator approved scoped PR4 fixes for F1, F3–F5 and N2–N3, with reproduction +before changing F1, F4 or N2. They asked to avoid nonessential edge cases and keep the +implementation simple. F2 stays in WI-7; N1 stays in WI-6. + +The focused regressions reproduced F1, F3, F4, F5 and N3. All 132 tests in the three +affected suites passed after `87ab0ed1f` (F1, F3) and `1500634d1` (F4, F5, N3). +The stale-tree guard checks identity, not generation, so a same-identity replacement does +not by itself discard a result. + +N2 was reproduced in both edit commands: a connection-string edit was skipped, and a +credential write succeeded without updating the runtime cache. `64d6f3ffd` limits the +wizard epoch check to recovery edits and records a completed storage save accurately. +An obsolete recovery still cannot evict newer state or clear its latch. All 62 focused +tests passed across six suites. Reconciling an already in-flight recovery save that lands +after teardown stays in WI-7, with F2. + +## Handoff verification + +OP-3 passed on the older CI VSIX. The current review proposals do not change the tested +sign-out, dismissal, or explicit sign-in sequence. The local `1.1.1-alpha.1` VSIX packaged +successfully; its shared Shell/Playground worker booted in plain Node and acknowledged +shutdown. A live Shell and Playground smoke test is separate. + +Final local Case 2 passed: localization generation and check, formatting, lint, build, +strict workspace test type-check, the full runtime suite (**432 files; 9,796 passed, one +skipped**), and VSIX packaging. The initial label test was corrected to assert the +label on the existing plain-object tree fixture. The review-fix run also caught an +enum-to-string lint error and a storage fixture type mismatch; both were fixed +without changing recovery behavior or weakening any assertions. PR4 remains a draft +until the live packaged Shell and Playground smoke test is recorded. From f139b1e89d82462c7a07061e7e7ac371c3e43717 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 19:53:04 +0000 Subject: [PATCH 102/380] feat: register open surfaces by connection identity (WI-6) Give planned teardown a cluster-scoped list without introducing shared surface state or changing panel behavior yet. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iterations/01-dev-plan.md | 5 +++ src/documentdb/connectionSurfaces.test.ts | 36 +++++++++++++++++ src/documentdb/connectionSurfaces.ts | 39 +++++++++++++++++++ 3 files changed, 80 insertions(+) create mode 100644 src/documentdb/connectionSurfaces.test.ts create mode 100644 src/documentdb/connectionSurfaces.ts diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index 93f7d4c37..eb718df2f 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 @@ -1515,6 +1515,11 @@ behave as today. **Progress:** +- **Host foundation:** Started PR5 from verified PR4 `d422d065b` while the independent + packaged-worker smoke test is pending. Added the disposable, cluster-scoped registry. + Build and its focused test passed. Panels are not yet wired to it; next is binding + resolution and the startup-rejection carry-forward from the PR4 review. + --- ## WI-7: Teardown, Disconnect, Remove and Update Credentials (PR 6) diff --git a/src/documentdb/connectionSurfaces.test.ts b/src/documentdb/connectionSurfaces.test.ts new file mode 100644 index 000000000..23957e479 --- /dev/null +++ b/src/documentdb/connectionSurfaces.test.ts @@ -0,0 +1,36 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { expect, it, vi } from 'vitest'; +import { getConnectionSurfaces, registerConnectionSurface, type ConnectionSurface } from './connectionSurfaces'; + +it('keeps teardown scoped to the current registered surfaces for one cluster', (): void => { + const makeSurface = (clusterId: string, kind: ConnectionSurface['kind']): ConnectionSurface => ({ + clusterId, + kind, + disable: vi.fn(), + dispose: vi.fn(), + }); + const document = makeSurface('cluster-a', 'documentView'); + const dashboard = makeSurface('cluster-a', 'clusterDashboard'); + const otherCluster = makeSurface('cluster-b', 'collectionView'); + const registrations = [document, dashboard, otherCluster].map(registerConnectionSurface); + + try { + expect(getConnectionSurfaces('cluster-a')).toEqual([document, dashboard]); + registrations[0].dispose(); + expect(getConnectionSurfaces('cluster-a')).toEqual([dashboard]); + expect(getConnectionSurfaces('cluster-b')).toEqual([otherCluster]); + expect(document.dispose).not.toHaveBeenCalled(); + expect(document.disable).not.toHaveBeenCalled(); + } finally { + for (const registration of registrations) { + registration.dispose(); + } + } + + expect(getConnectionSurfaces('cluster-a')).toEqual([]); + expect(getConnectionSurfaces('cluster-b')).toEqual([]); +}); diff --git a/src/documentdb/connectionSurfaces.ts b/src/documentdb/connectionSurfaces.ts new file mode 100644 index 000000000..f48f199fd --- /dev/null +++ b/src/documentdb/connectionSurfaces.ts @@ -0,0 +1,39 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { type Disposable } from 'vscode'; +import { type ConnectionUnavailableReason } from './ConnectionUnavailableError'; + +export interface ConnectionSurface { + readonly clusterId: string; + readonly kind: 'collectionView' | 'documentView' | 'clusterDashboard'; + disable(reason: ConnectionUnavailableReason): void; + dispose(): void; + isDirty?(): boolean; +} + +const surfacesByCluster = new Map>(); + +export function registerConnectionSurface(surface: ConnectionSurface): Disposable { + const { clusterId } = surface; + let surfaces = surfacesByCluster.get(clusterId); + if (!surfaces) { + surfaces = new Set(); + surfacesByCluster.set(clusterId, surfaces); + } + + surfaces.add(surface); + return { + dispose(): void { + if (surfaces.delete(surface) && surfaces.size === 0) { + surfacesByCluster.delete(clusterId); + } + }, + }; +} + +export function getConnectionSurfaces(clusterId: string): readonly ConnectionSurface[] { + return [...(surfacesByCluster.get(clusterId) ?? [])]; +} From b45e5798043a7be2331b55e58b599a51b7079a9e Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 19:56:15 +0000 Subject: [PATCH 103/380] feat: resolve surface clients without changing identity (WI-6) Use the existing startup fingerprint guard and return typed startup rejections before sending operations. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iterations/01-dev-plan.md | 7 ++- src/documentdb/ClustersClient.test.ts | 62 ++++++++++++++++--- src/documentdb/ClustersClient.ts | 25 +++++++- src/documentdb/runWithClient.ts | 19 +++--- 4 files changed, 94 insertions(+), 19 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index eb718df2f..f861ec592 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 @@ -1517,8 +1517,11 @@ behave as today. - **Host foundation:** Started PR5 from verified PR4 `d422d065b` while the independent packaged-worker smoke test is pending. Added the disposable, cluster-scoped registry. - Build and its focused test passed. Panels are not yet wired to it; next is binding - resolution and the startup-rejection carry-forward from the PR4 review. + The bound resolver permits a new generation of the same identity and refuses to start + or use a client for a changed identity. `runWithClient` uses that resolver and reports + startup credential rejection without submitting the operation (PR4 review N1). Build and + 86 focused tests passed. Panels are not yet wired; next migrate `ClusterSession` and its + host callers. --- diff --git a/src/documentdb/ClustersClient.test.ts b/src/documentdb/ClustersClient.test.ts index 3fe3353a3..3b352cec4 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -271,6 +271,42 @@ describe('regular connection startup diagnostics', () => { expect(mockClose).not.toHaveBeenCalled(); }); + it('lets a surface follow a same-identity generation but does not redial while latched', async (): Promise => { + const client = await ClustersClient.connectInteractive(clusterId); + await ClustersClient.deleteClient(clusterId); + const replacement = await ClustersClient.resolveBoundClient(client.binding); + expect(replacement.binding).toEqual({ ...client.binding, generation: client.generation + 1 }); + expect(mockConnect).toHaveBeenCalledTimes(2); + + ClustersClient.latch(clusterId, 'userDisconnected'); + try { + await expect(ClustersClient.resolveBoundClient(client.binding)).rejects.toMatchObject({ + reason: 'userDisconnected', + }); + expect(mockConnect).toHaveBeenCalledTimes(2); + } finally { + ClustersClient.unlatch(clusterId); + } + }); + + it('does not open a changed connection for an old surface, even with no cached client', async (): Promise => { + const client = await ClustersClient.connectInteractive(clusterId); + await ClustersClient.deleteClient(clusterId); + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.MicrosoftEntraID, 'mongodb://different.test/'); + + await expect(ClustersClient.resolveBoundClient(client.binding)).rejects.toMatchObject({ + reason: 'identityChanged', + }); + expect(MongoClient).toHaveBeenCalledOnce(); + expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); + + const current = await ClustersClient.getClient(clusterId); + await expect(ClustersClient.resolveBoundClient(client.binding)).rejects.toMatchObject({ + reason: 'identityChanged', + }); + expect(ClustersClient.getBinding(clusterId)).toBe(current.binding); + }); + 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; @@ -676,29 +712,41 @@ describe('regular connection startup diagnostics', () => { 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({ + await expect(runWithClient(old.binding, op, { background: true })).resolves.toEqual({ unavailable: { reason: 'unreachable' }, }); + expect(mockConnect).toHaveBeenCalledOnce(); expect(op).not.toHaveBeenCalled(); - await expect(runWithClient(old.binding, op, { resolveClient, background: true })).rejects.toBe(network); - expect(resolveClient).toHaveBeenLastCalledWith(old.binding, { background: true }); + const client = await ClustersClient.getClient(clusterId); + await expect(runWithClient(old.binding, op, { background: true })).rejects.toBe(network); expect(op).toHaveBeenCalledExactlyOnceWith(client); expect(await ClustersClient.getClient(clusterId)).toBe(client); op.mockRejectedValueOnce(new EntraIdentityMismatchError()); - await expect(runWithClient(old.binding, op, { resolveClient })).resolves.toEqual({ + await expect(runWithClient(old.binding, op)).resolves.toEqual({ unavailable: { reason: 'identityChanged' }, }); expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); expect(op).toHaveBeenCalledTimes(2); }); + it('reports a startup credential rejection without submitting the bound operation', async (): Promise => { + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.NativeAuth, 'mongodb://private-host:27017'); + const client = await ClustersClient.getClient(clusterId); + await ClustersClient.deleteClient(clusterId); + mockConnect.mockRejectedValueOnce(new MongoServerError({ code: 18 })); + const op = vi.fn<() => Promise>(); + + await expect(runWithClient(client.binding, op)).resolves.toEqual({ + unavailable: { reason: 'credentialsRejected' }, + }); + expect(mockConnect).toHaveBeenCalledTimes(2); + expect(op).not.toHaveBeenCalled(); + }); + 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 bba86d893..dd72e7759 100644 --- a/src/documentdb/ClustersClient.ts +++ b/src/documentdb/ClustersClient.ts @@ -838,6 +838,22 @@ export class ClustersClient { return ClustersClient.acquireClient(clusterId, abortSignal, onStartup, trigger, true, false); } + /** A surface can follow new generations, but never start or use a client for a different identity. */ + public static resolveBoundClient( + binding: ConnectionBinding, + options?: { readonly background?: boolean; readonly trigger?: ClientStartupTrigger }, + ): Promise { + return ClustersClient.acquireClient( + binding.clusterId, + undefined, + undefined, + options?.trigger ?? 'other', + false, + options?.background === true, + binding.fingerprint, + ); + } + /** Publish only after explicit sign-in and database startup succeed. The prior pin stays intact until then. */ public static async startAfterSignIn( clusterId: string, @@ -894,6 +910,7 @@ export class ClustersClient { trigger: ClientStartupTrigger, allowInteractive: boolean, background: boolean, + boundFingerprint?: string, ): Promise { for (let attempt = 0; ; attempt++) { const reason = ClustersClient.getLatchReason(clusterId); @@ -909,6 +926,9 @@ export class ClustersClient { const epoch = ClustersClient.getEpoch(clusterId); const cached = ClustersClient._clients.get(clusterId); + if (cached && boundFingerprint !== undefined && cached.fingerprint !== boundFingerprint) { + throw new ConnectionUnavailableError('identityChanged'); + } if (cached?._replacement === 'replaceOnRecovery') { throw new ConnectionUnavailableError('signInRequired'); } @@ -936,12 +956,15 @@ export class ClustersClient { trigger, allowInteractive, background, - cached?.fingerprint, + boundFingerprint ?? cached?.fingerprint, ); onStartup?.(id); try { const client = await waitForClient(promise, abortSignal, id); if (epoch === ClustersClient.getEpoch(clusterId) && client.canReuse()) { + if (boundFingerprint !== undefined && client.fingerprint !== boundFingerprint) { + throw new ConnectionUnavailableError('identityChanged'); + } return client; } } catch (error) { diff --git a/src/documentdb/runWithClient.ts b/src/documentdb/runWithClient.ts index 5bcf53a7b..30c370542 100644 --- a/src/documentdb/runWithClient.ts +++ b/src/documentdb/runWithClient.ts @@ -3,16 +3,16 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import { AuthMethodId } from './auth/AuthMethodId'; import { ClustersClient, type ConnectionBinding } from './ClustersClient'; import { classifyConnectionFailure, type ConnectionFailure } from './connectionFailures'; import { ConnectionUnavailableError, type ConnectionUnavailableReason } from './ConnectionUnavailableError'; +import { CredentialCache } from './CredentialCache'; +import { type ClientStartupTrigger } from './utils/startupFailureTelemetry'; -interface ResolveOptions { +interface RunOptions { readonly background?: boolean; -} - -interface RunOptions extends ResolveOptions { - resolveClient(binding: ConnectionBinding, options: ResolveOptions): Promise; + readonly trigger?: ClientStartupTrigger; } interface Unavailable { @@ -31,21 +31,22 @@ function unavailableFor(kind: ConnectionFailure['kind'] | undefined): Unavailabl } } -/** @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, + options?: RunOptions, ): Promise { + const credentials = CredentialCache.getCredentials(binding.clusterId); + const authMethod = credentials ? (credentials.authMechanism ?? AuthMethodId.NativeAuth) : undefined; let client: ClustersClient; try { - client = await resolveClient(binding, { background }); + client = await ClustersClient.resolveBoundClient(binding, options); } 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); + : unavailableFor(classifyConnectionFailure(error, authMethod).kind); if (unavailable) { return unavailable; } From 95dd27be4f3a6fc5a05922f8d75d9c5bfca72055 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 20:04:24 +0000 Subject: [PATCH 104/380] feat: bind Collection View sessions to connection identity (WI-6) Resolve clients per operation and fence cache writes without changing procedure responses yet. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iterations/01-dev-plan.md | 8 +- .../indexAdvisorCommands.ts | 29 ++- src/documentdb/ClusterSession.ts | 154 +++++++++---- src/documentdb/ClustersClient.test.ts | 125 ++++++++++- src/services/ai/QueryInsightsAIService.ts | 44 ++-- .../collectionView/collectionViewRouter.ts | 8 +- .../queryInsightsEventsRouter.ts | 11 +- .../queryInsights/queryInsightsRouter.ts | 212 ++++++++---------- 8 files changed, 390 insertions(+), 201 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index f861ec592..b29f8f488 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 @@ -1520,8 +1520,12 @@ behave as today. The bound resolver permits a new generation of the same identity and refuses to start or use a client for a changed identity. `runWithClient` uses that resolver and reports startup credential rejection without submitting the operation (PR4 review N1). Build and - 86 focused tests passed. Panels are not yet wired; next migrate `ClusterSession` and its - host callers. + 86 focused tests passed. +- **Collection View host slice:** `ClusterSession` holds a binding instead of a client. + Collection View, Query Insights, and the index advisor resolve the client per operation. + Check the epoch, latch, and identity before applying results to session caches. Build + and 193 focused tests passed. Procedure response shapes are unchanged for now; structured + unavailable results and the remaining panels are subsequent WI-6 slices. --- diff --git a/src/commands/llmEnhancedCommands/indexAdvisorCommands.ts b/src/commands/llmEnhancedCommands/indexAdvisorCommands.ts index cdaf10e8c..297d7ceca 100644 --- a/src/commands/llmEnhancedCommands/indexAdvisorCommands.ts +++ b/src/commands/llmEnhancedCommands/indexAdvisorCommands.ts @@ -7,7 +7,7 @@ import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext import * as l10n from '@vscode/l10n'; import { type Document, type Filter } from 'mongodb'; import * as vscode from 'vscode'; -import { type IndexItemModel } from '../../documentdb/ClustersClient'; +import { ClustersClient, type IndexItemModel } from '../../documentdb/ClustersClient'; import { ClusterSession } from '../../documentdb/ClusterSession'; import { type CollectionStats, type IndexStats } from '../../documentdb/LlmEnhancedFeatureApis'; import { type ClusterMetadata } from '../../documentdb/utils/getClusterMetadata'; @@ -469,6 +469,13 @@ async function prepareOptimizationRequest( throw new UserCancelledError('AbortSignal'); } + // TODO: allow null sessionId for testing framework + if (!queryContext.sessionId) { + throw new Error(l10n.t('sessionId is required for query optimization')); + } + const session = ClusterSession.getSession(queryContext.sessionId); + const epoch = session.getEpoch(); + // Check if Copilot is available const copilotAvailable = await CopilotService.isAvailable(); if (!copilotAvailable) { @@ -479,16 +486,22 @@ async function prepareOptimizationRequest( ); } + return session.runWithClient(async (client) => { + const prepared = await prepareBoundOptimizationRequest(context, queryContext, client); + session.assertCurrent(epoch, queryContext.signal); + return prepared; + }, epoch); +} + +async function prepareBoundOptimizationRequest( + context: IActionContext, + queryContext: QueryOptimizationContext, + client: ClustersClient, +): Promise { let explainResult: unknown; let collectionStats: CollectionStats | undefined; let indexes: IndexStats[] | undefined; - // TODO: allow null sessionId for testing framework - if (!queryContext.sessionId) { - throw new Error(l10n.t('sessionId is required for query optimization')); - } - const session = ClusterSession.getSession(queryContext.sessionId); - const client = session.getClient(); const clusterInfo = await client.getClusterMetadata(); // Track cluster information in telemetry @@ -589,6 +602,7 @@ async function prepareOptimizationRequest( l10n.t('Failed to gather query optimization data: {message}', { message: error instanceof Error ? error.message : String(error), }), + { cause: error }, ); } } @@ -674,6 +688,7 @@ async function prepareOptimizationRequest( if (error instanceof UserCancelledError) { throw error; } + ClustersClient.reportFailure(client.binding, error); // They are not critical errors, we can continue without index stats and collection stats // If the API calls failed, collectionStats and indexes remain undefined (safe to continue) diff --git a/src/documentdb/ClusterSession.ts b/src/documentdb/ClusterSession.ts index 2a7ed1ed9..7d8f1809f 100644 --- a/src/documentdb/ClusterSession.ts +++ b/src/documentdb/ClusterSession.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import { type FieldEntry } from '@documentdb-js/schema-analyzer'; +import { UserCancelledError } from '@microsoft/vscode-azext-utils'; import { ParseMode, parse as parseShellBSON } from '@mongodb-js/shell-bson-parser'; import * as l10n from '@vscode/l10n'; import { EJSON } from 'bson'; @@ -12,7 +13,9 @@ import { ext } from '../extensionVariables'; import { getDataAtPath } from '../utils/slickgrid/mongo/toSlickGridTable'; import { toSlickGridTree, type TreeData } from '../utils/slickgrid/mongo/toSlickGridTree'; import { type QueryInsightsStage2Response } from '../webviews/documentdb/collectionView/types/queryInsights'; -import { ClustersClient, type FindQueryParams } from './ClustersClient'; +import { ClustersClient, type ConnectionBinding, type FindQueryParams } from './ClustersClient'; +import { ConnectionUnavailableError } from './ConnectionUnavailableError'; +import { runWithClient } from './runWithClient'; import { SchemaStore } from './SchemaStore'; import { fixupDocumentDbExplain } from './utils/fixupDocumentDbExplain'; import { parseDocumentId } from './utils/parseDocumentId'; @@ -70,15 +73,48 @@ export class ClusterSession { * Private constructor to enforce the use of `initNewSession` for creating new sessions. * This ensures that sessions are properly initialized and managed. */ - private constructor( - private _client: ClustersClient, - private readonly _clusterId: string, - ) { - return; + private constructor(private readonly binding: ConnectionBinding) {} + + public async getClient(): Promise { + return ClustersClient.resolveBoundClient(this.binding, { trigger: 'collectionView' }); + } + + public getEpoch(): number { + return ClustersClient.getEpoch(this.binding.clusterId); + } + + private isCurrent(epoch: number): boolean { + const { clusterId, fingerprint } = this.binding; + return ( + epoch === ClustersClient.getEpoch(clusterId) && + ClustersClient.getLatchReason(clusterId) === undefined && + ClustersClient.getBinding(clusterId)?.fingerprint === fingerprint + ); } - public getClient(): ClustersClient { - return this._client; + public assertCurrent(epoch: number, signal?: AbortSignal): void { + if (signal?.aborted || !this.isCurrent(epoch)) { + throw new UserCancelledError('staleCollectionViewOperation'); + } + } + + // Keep the existing procedure return types until the routers map unavailable results. + public async runWithClient( + operation: (client: ClustersClient, epoch: number) => Promise, + epoch = this.getEpoch(), + ): Promise { + const result = await runWithClient( + this.binding, + async (client) => { + this.assertCurrent(epoch); + return { value: await operation(client, epoch) }; + }, + { trigger: 'collectionView' }, + ); + if ('unavailable' in result) { + throw new ConnectionUnavailableError(result.unavailable.reason); + } + return result.value; } /** @@ -114,7 +150,6 @@ export class ClusterSession { /** * Query Insights caching - * Note: QueryInsightsApis instance is accessed via this._client.queryInsightsApis * * Timestamps are included for potential future features: * - Time-based cache invalidation (e.g., expire after N seconds) @@ -248,6 +283,7 @@ export class ClusterSession { pageNumber: number, pageSize: number, executionIntent: 'initial' | 'refresh' | 'pagination' = 'pagination', + signal?: AbortSignal, ): Promise { const querySkip = queryParams.skip ?? 0; const queryLimit = queryParams.limit ?? 0; @@ -261,9 +297,11 @@ export class ClusterSession { // Early return if trying to skip beyond the query limit // Note: queryLimit=0 means no limit, so only check when queryLimit > 0 if (queryLimit > 0 && pageOffset >= queryLimit) { - // We're trying to page beyond the query's limit - return empty results - this._currentRawDocuments = []; - return 0; + return this.runWithClient((_client, epoch) => { + this.assertCurrent(epoch, signal); + this._currentRawDocuments = []; + return Promise.resolve(0); + }); } // Calculate effective limit: @@ -275,18 +313,6 @@ export class ClusterSession { dbLimit = Math.min(pageSize, remainingInWindow); } - // Check if the user's query has changed (not pagination, just the actual query) - this.resetCachesIfUserQueryChanged(queryParams); - - // Check if page size has changed (invalidates accumulation strategy) - this.resetAccumulationIfPageSizeChanged(pageSize); - - // Force clear query insights caches for initial/refresh operations - // This ensures fresh performance data when user explicitly requests it - if (executionIntent === 'initial' || executionIntent === 'refresh') { - this.clearQueryInsightsCaches(); - } - // Build final query parameters with computed skip/limit const paginatedQueryParams: FindQueryParams = { ...queryParams, @@ -294,14 +320,21 @@ export class ClusterSession { limit: dbLimit, }; - // Track execution time for query insights - const startTime = performance.now(); - const documents: WithId[] = await this._client.runFindQuery( - databaseName, - collectionName, - paginatedQueryParams, - ); - this._lastExecutionTimeMs = performance.now() - startTime; + const epoch = this.getEpoch(); + const { documents, executionTimeMs } = await this.runWithClient(async (client) => { + this.assertCurrent(epoch, signal); + const startTime = performance.now(); + const documents = await client.runFindQuery(databaseName, collectionName, paginatedQueryParams); + return { documents, executionTimeMs: performance.now() - startTime }; + }, epoch); + + this.assertCurrent(epoch, signal); + this.resetCachesIfUserQueryChanged(queryParams); + this.resetAccumulationIfPageSizeChanged(pageSize); + if (executionIntent === 'initial' || executionIntent === 'refresh') { + this.clearQueryInsightsCaches(); + } + this._lastExecutionTimeMs = executionTimeMs; // Update current page documents (always replace, not accumulate) this._currentRawDocuments = documents; @@ -313,10 +346,11 @@ export class ClusterSession { // Feed documents to the shared SchemaStore if (documents.length > 0) { const store = SchemaStore.getInstance(); - store.addDocuments(this._clusterId, databaseName, collectionName, documents); + const { clusterId } = this.binding; + store.addDocuments(clusterId, databaseName, collectionName, documents); ext.outputChannel.trace( - `[SchemaStore] Fed ${String(documents.length)} documents, ${String(store.getDocumentCount(this._clusterId, databaseName, collectionName))} total, ${String(store.getKnownFields(this._clusterId, databaseName, collectionName).length)} known fields`, + `[SchemaStore] Fed ${String(documents.length)} documents, ${String(store.getDocumentCount(clusterId, databaseName, collectionName))} total, ${String(store.getKnownFields(clusterId, databaseName, collectionName).length)} known fields`, ); } @@ -331,10 +365,19 @@ export class ClusterSession { return toSlickGridTree(this._currentRawDocuments); } - async deleteDocuments(databaseName: string, collectionName: string, documentIds: string[]): Promise { - const acknowledged = await this._client.deleteDocuments(databaseName, collectionName, documentIds); + public async deleteDocuments( + databaseName: string, + collectionName: string, + documentIds: string[], + epoch = this.getEpoch(), + ): Promise { + const acknowledged = await this.runWithClient( + (client) => client.deleteDocuments(databaseName, collectionName, documentIds), + epoch, + ); - if (acknowledged) { + // Acknowledge a completed write, but don't update the page from an old operation. + if (acknowledged && this.isCurrent(epoch)) { this._currentRawDocuments = this._currentRawDocuments.filter((doc) => { return !documentIds.some((id) => { const parsedId = parseDocumentId(id); @@ -356,7 +399,7 @@ export class ClusterSession { path: path, headers: this._databaseName && this._collectionName - ? store.getPropertyNamesAtLevel(this._clusterId, this._databaseName, this._collectionName, path) + ? store.getPropertyNamesAtLevel(this.binding.clusterId, this._databaseName, this._collectionName, path) : [], data: getDataAtPath(this._currentRawDocuments, path), }; @@ -372,7 +415,7 @@ export class ClusterSession { if (!this._databaseName || !this._collectionName) { return []; } - return SchemaStore.getInstance().getKnownFields(this._clusterId, this._databaseName, this._collectionName); + return SchemaStore.getInstance().getKnownFields(this.binding.clusterId, this._databaseName, this._collectionName); } // ============================================================================ @@ -393,6 +436,8 @@ export class ClusterSession { * @returns Explain output from queryPlanner verbosity */ public async getQueryPlannerInfo( + client: ClustersClient, + epoch: number, databaseName: string, collectionName: string, filter: Document, @@ -402,14 +447,16 @@ export class ClusterSession { skip?: number; limit?: number; }, + signal?: AbortSignal, ): Promise { + this.assertCurrent(epoch, signal); // Check cache if (this._queryPlannerCache) { return this._queryPlannerCache.result; } // Execute explain("queryPlanner") using QueryInsightsApis from ClustersClient - const rawResult = await this._client.queryInsightsApis.explainFind(databaseName, collectionName, filter, { + const rawResult = await client.queryInsightsApis.explainFind(databaseName, collectionName, filter, { verbosity: 'queryPlanner', sort: options?.sort, projection: options?.projection, @@ -418,10 +465,11 @@ export class ClusterSession { }); // Apply Azure DocumentDB explain fixup (see fixupDocumentDbExplain for details) - const clusterMetadata = await this._client.getClusterMetadata(); + const clusterMetadata = await client.getClusterMetadata(); const explainResult = fixupDocumentDbExplain(rawResult, clusterMetadata) ?? rawResult; // Cache result + this.assertCurrent(epoch, signal); this._queryPlannerCache = { result: explainResult, timestamp: Date.now(), @@ -447,6 +495,8 @@ export class ClusterSession { * @returns Explain output with executionStats */ public async getExecutionStats( + client: ClustersClient, + epoch: number, databaseName: string, collectionName: string, filter: Document, @@ -456,7 +506,9 @@ export class ClusterSession { skip?: number; limit?: number; }, + signal?: AbortSignal, ): Promise { + this.assertCurrent(epoch, signal); // Check cache if (this._executionStatsCache) { return this._executionStatsCache.result; @@ -464,7 +516,7 @@ export class ClusterSession { // Determine verbosity based on cluster type // Azure DocumentDB clusters support allPlansExecution for richer plan data - const clusterMetadata = await this._client.getClusterMetadata(); + const clusterMetadata = await client.getClusterMetadata(); const verbosity = clusterMetadata.domainInfo_isAzure === 'true' && clusterMetadata.domainInfo_api === 'vCore' ? 'allPlansExecution' @@ -472,7 +524,8 @@ export class ClusterSession { // Execute explain using QueryInsightsApis from ClustersClient // This re-runs the query to get authoritative execution metrics - const rawResult = await this._client.queryInsightsApis.explainFind(databaseName, collectionName, filter, { + this.assertCurrent(epoch, signal); + const rawResult = await client.queryInsightsApis.explainFind(databaseName, collectionName, filter, { verbosity, sort: options?.sort, projection: options?.projection, @@ -484,6 +537,7 @@ export class ClusterSession { const explainResult = fixupDocumentDbExplain(rawResult, clusterMetadata) ?? rawResult; // Cache result + this.assertCurrent(epoch, signal); this._executionStatsCache = { result: explainResult, timestamp: Date.now(), @@ -606,7 +660,13 @@ export class ClusterSession { * Caches the transformed Stage 2 response and total collection docs * for use by Stage 3 when building the static analysis summary. */ - public setStage2Response(response: QueryInsightsStage2Response, totalCollectionDocs?: number): void { + public setStage2Response( + epoch: number, + response: QueryInsightsStage2Response, + totalCollectionDocs?: number, + signal?: AbortSignal, + ): void { + this.assertCurrent(epoch, signal); this._stage2ResponseCache = { response, totalCollectionDocs }; } @@ -635,7 +695,7 @@ export class ClusterSession { * * @remarks * This method will be implemented in Phase 3. The AI service is accessed via - * this._client.queryInsightsAIService (similar to queryInsightsApis pattern). + * the resolved client's Query Insights service. */ public getAIRecommendations( _databaseName: string, @@ -649,7 +709,7 @@ export class ClusterSession { } // TODO: Phase 3 implementation - // const recommendations = await this._client.queryInsightsAIService.generateRecommendations( + // const recommendations = await client.queryInsightsAIService.generateRecommendations( // databaseName, // collectionName, // filter, @@ -692,7 +752,7 @@ export class ClusterSession { const sessionId = Math.random().toString(16).substring(2, 15) + Math.random().toString(36).substring(2, 15); - const session = new ClusterSession(client, clusterId); + const session = new ClusterSession(client.binding); ClusterSession._sessions.set(sessionId, session); diff --git a/src/documentdb/ClustersClient.test.ts b/src/documentdb/ClustersClient.test.ts index 3b352cec4..13d74a04e 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -29,6 +29,7 @@ import { ManagedIdentityAuthHandler } from './auth/ManagedIdentityAuthHandler'; import { MicrosoftEntraIDAuthHandler } from './auth/MicrosoftEntraIDAuthHandler'; import { NativeAuthHandler } from './auth/NativeAuthHandler'; import { NoAuthHandler } from './auth/NoAuthHandler'; +import { ClusterSession } from './ClusterSession'; import { addEstablishedConnectionContext, ClustersClient, @@ -39,6 +40,7 @@ import { computeConnectionFingerprint } from './connectionFingerprint'; import { ConnectionUnavailableError } from './ConnectionUnavailableError'; import { CredentialCache } from './CredentialCache'; import { runWithClient } from './runWithClient'; +import { SchemaStore } from './SchemaStore'; import { prepareDriverConnectionString } from './srv/prepareDriverConnectionString'; import { type SrvResolutionSummary } from './srv/srvResolutionSummary'; import { getClusterMetadata, getDomainMetadata } from './utils/getClusterMetadata'; @@ -130,7 +132,11 @@ vi.mock('./utils/getClusterMetadata', () => ({ })); vi.mock('./LlmEnhancedFeatureApis', () => ({ llmEnhancedFeatureApis: vi.fn() })); -vi.mock('./client/QueryInsightsApis', () => ({ QueryInsightsApis: vi.fn() })); +vi.mock('./client/QueryInsightsApis', () => ({ + QueryInsightsApis: vi.fn(function () { + return { explainFind: vi.fn() }; + }), +})); vi.mock('./srv/prepareDriverConnectionString', () => ({ prepareDriverConnectionString: vi.fn() })); vi.mock('./auth/createAuthHandler', async () => { const actual = await vi.importActual('./auth/createAuthHandler'); @@ -160,6 +166,9 @@ describe('regular connection startup diagnostics', () => { const mockConnect = vi.fn(); const mockClose = vi.fn(); const mockListDatabases = vi.fn<() => Promise>(); + const mockFind = vi.fn(); + const mockToArray = vi.fn<() => Promise[]>>(); + const mockDeleteMany = vi.fn<() => Promise>(); let poolEvents: EventEmitter; function pauseNextConnect(): { started: Promise; resolve: () => void; reject: (error: Error) => void } { @@ -193,12 +202,18 @@ describe('regular connection startup diagnostics', () => { }); mockClose.mockResolvedValue(undefined); mockListDatabases.mockReset(); + mockFind.mockReset().mockReturnValue({ toArray: mockToArray }); + mockToArray.mockReset(); + mockDeleteMany.mockReset(); vi.mocked(MongoClient).mockImplementation(function () { poolEvents = new EventEmitter(); return Object.assign(poolEvents, { connect: mockConnect, close: mockClose, - db: () => ({ admin: () => ({ listDatabases: mockListDatabases }) }), + db: () => ({ + admin: () => ({ listDatabases: mockListDatabases }), + collection: () => ({ find: mockFind, deleteMany: mockDeleteMany }), + }), }) as unknown as MongoClient; }); for (const handler of [ @@ -307,6 +322,110 @@ describe('regular connection startup diagnostics', () => { expect(ClustersClient.getBinding(clusterId)).toBe(current.binding); }); + it('keeps session paging and schema accumulation on a same-identity replacement', async (): Promise => { + const original = await ClustersClient.connectInteractive(clusterId); + const session = ClusterSession.getSession(await ClusterSession.initNewSession(clusterId)); + const query = { filter: '{}', skip: 2, limit: 3 }; + mockToArray.mockResolvedValueOnce([{ _id: 'first', previousField: true }]); + await session.runFindQueryWithCache('db', 'items', query, 1, 2); + + ClustersClient.reportFailure(original.binding, new MongoNotConnectedError('idle connection closed')); + const replacement = await session.getClient(); + expect(replacement.generation).toBe(original.generation + 1); + expect(replacement.fingerprint).toBe(original.fingerprint); + const runFind = vi.spyOn(replacement, 'runFindQuery'); + + mockToArray.mockResolvedValueOnce([{ _id: 'last', nextField: true }]); + await expect(session.runFindQueryWithCache('db', 'items', query, 2, 2)).resolves.toBe(1); + expect(runFind).toHaveBeenCalledExactlyOnceWith('db', 'items', { ...query, skip: 4, limit: 1 }); + expect(session.getCurrentPageAsJson().map((page) => JSON.parse(page) as unknown)).toEqual([ + { _id: 'last', nextField: true }, + ]); + expect(SchemaStore.getInstance().getDocumentCount(clusterId, 'db', 'items')).toBe(2); + await expect(session.runFindQueryWithCache('db', 'items', query, 3, 2)).resolves.toBe(0); + expect(session.getCurrentPageAsJson()).toEqual([]); + expect(runFind).toHaveBeenCalledOnce(); + }); + + it('rejects a changed identity before a session can submit a write', async (): Promise => { + await ClustersClient.connectInteractive(clusterId); + const session = ClusterSession.getSession(await ClusterSession.initNewSession(clusterId)); + await ClustersClient.deleteClient(clusterId); + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.MicrosoftEntraID, 'mongodb://different.test/'); + await ClustersClient.getClient(clusterId); + + await expect(session.getClient()).rejects.toMatchObject({ reason: 'identityChanged' }); + await expect(session.deleteDocuments('db', 'items', ['"one"'])).rejects.toMatchObject({ + reason: 'identityChanged', + }); + expect(mockDeleteMany).not.toHaveBeenCalled(); + }); + + it('drops a find completed after reconnect without changing the query, page, or schema', async (): Promise => { + await ClustersClient.connectInteractive(clusterId); + const session = ClusterSession.getSession(await ClusterSession.initNewSession(clusterId)); + const query = { filter: '{}' }; + mockToArray.mockResolvedValueOnce([{ _id: 'current' }]); + await session.runFindQueryWithCache('db', 'items', query, 1, 10); + const page = session.getCurrentPageAsJson(); + + const started = deferred(); + const finish = deferred(); + mockToArray.mockImplementationOnce(async () => { + started.resolve(); + await finish.promise; + return [{ _id: 'stale', staleField: true }]; + }); + const pending = session.runFindQueryWithCache('db', 'items', { filter: '{ staleField: true }' }, 1, 10); + await started.promise; + ClustersClient.latch(clusterId, 'userDisconnected'); + await ClustersClient.deleteClient(clusterId); + ClustersClient.unlatch(clusterId); + await session.getClient(); + finish.resolve(); + + await expect(pending).rejects.toBeInstanceOf(UserCancelledError); + expect(session.getCurrentFindQueryParams()).toEqual(query); + expect(session.getCurrentPageAsJson()).toEqual(page); + expect(SchemaStore.getInstance().getDocumentCount(clusterId, 'db', 'items')).toBe(0); + }); + + it('does not cache execution stats that complete while the session is latched', async (): Promise => { + const client = await ClustersClient.connectInteractive(clusterId); + const session = ClusterSession.getSession(await ClusterSession.initNewSession(clusterId)); + const started = deferred(); + const finish = deferred(); + vi.spyOn(client.queryInsightsApis, 'explainFind').mockImplementationOnce(async () => { + started.resolve(); + await finish.promise; + return { executionStats: { nReturned: 1 } }; + }); + const pending = session.runWithClient((resolved, epoch) => + session.getExecutionStats(resolved, epoch, 'db', 'items', {}), + ); + await started.promise; + ClustersClient.latch(clusterId, 'userDisconnected'); + finish.resolve(); + + await expect(pending).rejects.toBeInstanceOf(UserCancelledError); + expect(session.getRawExplainOutput('db', 'items')).toBeNull(); + }); + + it('does not replay a failed delete or remove the cached document', async (): Promise => { + await ClustersClient.connectInteractive(clusterId); + const session = ClusterSession.getSession(await ClusterSession.initNewSession(clusterId)); + mockToArray.mockResolvedValueOnce([{ _id: 'one' }]); + await session.runFindQueryWithCache('db', 'items', {}, 1, 10); + const page = session.getCurrentPageAsJson(); + const failure = new MongoNotConnectedError('connection closed during delete'); + mockDeleteMany.mockRejectedValueOnce(failure); + + await expect(session.deleteDocuments('db', 'items', ['"one"'])).rejects.toBe(failure); + expect(mockDeleteMany).toHaveBeenCalledExactlyOnceWith({ _id: { $in: ['one'] } }); + expect(session.getCurrentPageAsJson()).toEqual(page); + expect(mockConnect).toHaveBeenCalledOnce(); + }); + 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; @@ -1027,6 +1146,8 @@ describe('regular connection startup diagnostics', () => { }); afterEach(() => { + ClusterSession._sessions.clear(); + SchemaStore.getInstance().clearCluster(clusterId); if (ClustersClient.getLatchReason(clusterId)) { ClustersClient.unlatch(clusterId); } diff --git a/src/services/ai/QueryInsightsAIService.ts b/src/services/ai/QueryInsightsAIService.ts index dbd19776d..dbe39d338 100644 --- a/src/services/ai/QueryInsightsAIService.ts +++ b/src/services/ai/QueryInsightsAIService.ts @@ -9,7 +9,6 @@ import { type IActionContext, } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; -import { type Document } from 'mongodb'; import { CommandType, optimizeQuery, @@ -509,6 +508,9 @@ export class QueryInsightsAIService { }), ); + const session = ClusterSession.getSession(actualSessionId); + const epoch = session.getEpoch(); + // Ask for confirmation before creating the index const confirmed = await getConfirmationWithClick( l10n.t('Create index?'), @@ -529,10 +531,10 @@ export class QueryInsightsAIService { }; } - const session = ClusterSession.getSession(actualSessionId); - const client = session.getClient(); - - const result = await client.createIndex(payload.databaseName, payload.collectionName, payload.indexSpec); + const result = await session.runWithClient( + (client) => client.createIndex(payload.databaseName, payload.collectionName, payload.indexSpec), + epoch, + ); if (result.ok === 1) { // Provide positive feedback with additional context from result.note if available @@ -630,6 +632,9 @@ export class QueryInsightsAIService { ), ); + const session = ClusterSession.getSession(actualSessionId); + const epoch = session.getEpoch(); + // Ask for confirmation before dropping the index (destructive action) const confirmed = await getConfirmationAsInSettings( l10n.t('Delete index?'), @@ -653,10 +658,10 @@ export class QueryInsightsAIService { }; } - const session = ClusterSession.getSession(actualSessionId); - const client = session.getClient(); - - const result = await client.dropIndex(payload.databaseName, payload.collectionName, payload.indexName); + const result = await session.runWithClient( + (client) => client.dropIndex(payload.databaseName, payload.collectionName, payload.indexName), + epoch, + ); if (result.ok === 1) { // Provide positive feedback with additional context from result.note if available @@ -774,6 +779,9 @@ export class QueryInsightsAIService { ), ); + const session = ClusterSession.getSession(actualSessionId); + const epoch = session.getEpoch(); + // Ask for confirmation before modifying the index const operationText = operation === 'hideIndex' ? l10n.t('hide') : l10n.t('unhide'); const confirmed = await getConfirmationWithClick( @@ -797,17 +805,13 @@ export class QueryInsightsAIService { }; } - const session = ClusterSession.getSession(actualSessionId); - const client = session.getClient(); - - // Execute the operation - let result: Document; - if (operation === 'hideIndex') { - result = await client.hideIndex(payload.databaseName, payload.collectionName, indexName); - } else { - // unhideIndex - result = await client.unhideIndex(payload.databaseName, payload.collectionName, indexName); - } + const result = await session.runWithClient( + (client) => + operation === 'hideIndex' + ? client.hideIndex(payload.databaseName, payload.collectionName, indexName) + : client.unhideIndex(payload.databaseName, payload.collectionName, indexName), + epoch, + ); if (result.ok === 1) { // Provide positive feedback with additional context from result.note if available diff --git a/src/webviews/documentdb/collectionView/collectionViewRouter.ts b/src/webviews/documentdb/collectionView/collectionViewRouter.ts index 4950e3778..aebe487f7 100644 --- a/src/webviews/documentdb/collectionView/collectionViewRouter.ts +++ b/src/webviews/documentdb/collectionView/collectionViewRouter.ts @@ -246,6 +246,7 @@ export const collectionsViewRouter = router({ input.pageNumber, input.pageSize, executionIntent, + myCtx.signal, ); // Report execution intent for analytics @@ -355,6 +356,8 @@ export const collectionsViewRouter = router({ // procedure type .mutation(async ({ input, ctx }) => { const myCtx = ctx as RouterContext; + const session = ClusterSession.getSession(myCtx.sessionId); + const epoch = session.getEpoch(); const confirmed = await getConfirmationAsInSettings( l10n.t('Are you sure?'), @@ -362,12 +365,11 @@ export const collectionsViewRouter = router({ 'delete', ); - if (!confirmed) { + if (!confirmed || myCtx.signal?.aborted) { return false; } - const session: ClusterSession = ClusterSession.getSession(myCtx.sessionId); - const acknowledged = await session.deleteDocuments(myCtx.databaseName, myCtx.collectionName, input); + const acknowledged = await session.deleteDocuments(myCtx.databaseName, myCtx.collectionName, input, epoch); if (acknowledged) { showConfirmationAsInSettings( diff --git a/src/webviews/documentdb/collectionView/queryInsights/queryInsightsEventsRouter.ts b/src/webviews/documentdb/collectionView/queryInsights/queryInsightsEventsRouter.ts index 00015a9d6..ec8ef5137 100644 --- a/src/webviews/documentdb/collectionView/queryInsights/queryInsightsEventsRouter.ts +++ b/src/webviews/documentdb/collectionView/queryInsights/queryInsightsEventsRouter.ts @@ -204,6 +204,8 @@ export const queryInsightsEventsRouter = router({ }; try { + const session = ClusterSession.getSession(sessionId); + const epoch = session.getEpoch(); ext.outputChannel.trace( l10n.t('[Query Insights Stage 3 stream] Started for {db}.{collection} (requestKey: {key})', { db: databaseName, @@ -229,19 +231,22 @@ export const queryInsightsEventsRouter = router({ // the (now-deleted) buffered Stage 3 procedure used to build. // Kept structurally identical so the dedicated completion // telemetry (§7) records the same shape of inputs. - const session: ClusterSession = ClusterSession.getSession(sessionId); - // Record the platform on the dedicated completion event so // it lines up with the buffered procedure's rpc event. Best // effort — a metadata fetch failure here must not abort // Stage 3 streaming (the buffered procedure has the same // contract). + const client = await session.getClient(); try { - const clusterMetadata = await session.getClient().getClusterMetadata(); + const clusterMetadata = await client.getClusterMetadata(); completionTelemetry.properties.platform = clusterMetadata?.domainInfo_api ?? 'unknown'; } catch { completionTelemetry.properties.platform = 'unknown'; } + if (abortController.signal.aborted) { + return; + } + session.assertCurrent(epoch); const parsedQueryParams = session.getCurrentFindQueryParamsWithObjects(); const queryObject: QueryObject = { diff --git a/src/webviews/documentdb/collectionView/queryInsights/queryInsightsRouter.ts b/src/webviews/documentdb/collectionView/queryInsights/queryInsightsRouter.ts index 0ade16c31..49c26a197 100644 --- a/src/webviews/documentdb/collectionView/queryInsights/queryInsightsRouter.ts +++ b/src/webviews/documentdb/collectionView/queryInsights/queryInsightsRouter.ts @@ -31,6 +31,7 @@ import { z } from 'zod'; import * as l10n from '@vscode/l10n'; import { ClusterSession } from '../../../../documentdb/ClusterSession'; +import { ClustersClient } from '../../../../documentdb/ClustersClient'; import { ExplainPlanAnalyzer, type ExecutionStatsAnalysis, @@ -116,82 +117,57 @@ export const queryInsightsQueriesRouter = router({ }), ); - let analyzed: QueryPlannerAnalysis; - let executionTime: number; - - // Platform compatibility check: - // Query Insights requires the MongoDB API explain() command with specific verbosity modes - // (queryPlanner and executionStats). Currently, only DocumentDB supports these features. - // - // Supported platforms: - // - Azure Cosmos DB for MongoDB vCore (domainInfo_api !== 'RU') - // - Native MongoDB clusters - const session: ClusterSession = ClusterSession.getSession(sessionId); - const clusterMetadata = await session.getClient().getClusterMetadata(); - - myCtx.actionContext.telemetry.properties.platform = clusterMetadata?.domainInfo_api ?? 'unknown'; - if (clusterMetadata?.domainInfo_api === 'RU') { - // TODO: Platform identification improvements needed - // 1. Create a centralized platform detection service (ClusterSession.getPlatformType()) - // 2. Define platform capabilities enum (SupportsExplain, SupportsAggregation, etc.) - // 3. Check capabilities instead of platform names for better maintainability - // 4. Consider adding feature detection (try explain() and handle gracefully) - // 5. Update UI to show platform-specific feature availability - ext.outputChannel.trace( - l10n.t( - '[Query Insights Stage 1] Query Insights is not supported on Azure Cosmos DB for MongoDB (RU) clusters.', - ), - ); - - // Create error with code for UI-specific handling - const error = new Error( - l10n.t('Query Insights is not supported on Azure Cosmos DB for MongoDB (RU) clusters.'), - ); - // Add error code as a custom property for UI pattern matching - (error as Error & { code?: string }).code = 'QUERY_INSIGHTS_PLATFORM_NOT_SUPPORTED_RU'; - throw error; - } - - // Check for debug override file first - const debugData = readQueryInsightsDebugFile('query-insights-stage1.json'); - if (debugData) { - ext.outputChannel.trace(l10n.t('[Query Insights Stage 1] Using debug data file')); - // Use debug data - analyze it the same way as real data - analyzed = ExplainPlanAnalyzer.analyzeQueryPlanner(debugData); - // Use a default execution time for debug mode - executionTime = 2.5; - } else { - // Get ClusterSession - const session: ClusterSession = ClusterSession.getSession(sessionId); - - // Get execution time from session (tracked during last query execution) - executionTime = session.getLastExecutionTimeMs(); - - // Get query parameters from session with parsed BSON objects - const queryParams = session.getCurrentFindQueryParamsWithObjects(); - - // Get query planner info (cached or fetch) without skip/limit for full query insights - const queryPlannerStart = Date.now(); - const queryPlannerResult = await session.getQueryPlannerInfo( - databaseName, - collectionName, - queryParams.filterObj, - { - sort: queryParams.sortObj, - projection: queryParams.projectionObj, - // Intentionally omit skip/limit for full query insights - }, - ); - const queryPlannerDuration = Date.now() - queryPlannerStart; - ext.outputChannel.trace( - l10n.t('[Query Insights Stage 1] explain(queryPlanner) completed in {ms}ms', { - ms: queryPlannerDuration.toString(), - }), - ); - - // Analyze with ExplainPlanAnalyzer - analyzed = ExplainPlanAnalyzer.analyzeQueryPlanner(queryPlannerResult); - } + const session = ClusterSession.getSession(sessionId); + const { analyzed, executionTime } = await session.runWithClient( + async (client, epoch): Promise<{ analyzed: QueryPlannerAnalysis; executionTime: number }> => { + const clusterMetadata = await client.getClusterMetadata(); + session.assertCurrent(epoch, myCtx.signal); + myCtx.actionContext.telemetry.properties.platform = clusterMetadata?.domainInfo_api ?? 'unknown'; + if (clusterMetadata?.domainInfo_api === 'RU') { + ext.outputChannel.trace( + l10n.t( + '[Query Insights Stage 1] Query Insights is not supported on Azure Cosmos DB for MongoDB (RU) clusters.', + ), + ); + + const error = new Error( + l10n.t('Query Insights is not supported on Azure Cosmos DB for MongoDB (RU) clusters.'), + ); + (error as Error & { code?: string }).code = 'QUERY_INSIGHTS_PLATFORM_NOT_SUPPORTED_RU'; + throw error; + } + + const debugData = readQueryInsightsDebugFile('query-insights-stage1.json'); + if (debugData) { + ext.outputChannel.trace(l10n.t('[Query Insights Stage 1] Using debug data file')); + return { analyzed: ExplainPlanAnalyzer.analyzeQueryPlanner(debugData), executionTime: 2.5 }; + } + + const executionTime = session.getLastExecutionTimeMs(); + const queryParams = session.getCurrentFindQueryParamsWithObjects(); + const queryPlannerStart = Date.now(); + const queryPlannerResult = await session.getQueryPlannerInfo( + client, + epoch, + databaseName, + collectionName, + queryParams.filterObj, + { + sort: queryParams.sortObj, + projection: queryParams.projectionObj, + // Intentionally omit skip/limit for full query insights + }, + myCtx.signal, + ); + ext.outputChannel.trace( + l10n.t('[Query Insights Stage 1] explain(queryPlanner) completed in {ms}ms', { + ms: (Date.now() - queryPlannerStart).toString(), + }), + ); + + return { analyzed: ExplainPlanAnalyzer.analyzeQueryPlanner(queryPlannerResult), executionTime }; + }, + ); // Transform to UI format const transformed = transformStage1Response(analyzed, executionTime); @@ -231,6 +207,8 @@ export const queryInsightsQueriesRouter = router({ let analyzed: ExecutionStatsAnalysis; let explainResult: Document | undefined; let totalCollectionDocs: number | undefined; + const session = ClusterSession.getSession(sessionId); + const epoch = session.getEpoch(); // Check for debug override file first const debugData = readQueryInsightsDebugFile('query-insights-stage2.json'); @@ -242,46 +220,47 @@ export const queryInsightsQueriesRouter = router({ explainResult = debugData; // totalCollectionDocs not available in debug mode — advisories will simply not fire } else { - // Get ClusterSession - const session: ClusterSession = ClusterSession.getSession(sessionId); - - const clusterMetadata = await session.getClient().getClusterMetadata(); - myCtx.actionContext.telemetry.properties.platform = clusterMetadata?.domainInfo_api ?? 'unknown'; - - // Get query parameters from session with parsed BSON objects - const queryParams = session.getCurrentFindQueryParamsWithObjects(); - - // Get execution stats (cached or fetch) without skip/limit for full query insights - const executionStatsStart = Date.now(); - const executionStatsResult = await session.getExecutionStats( - databaseName, - collectionName, - queryParams.filterObj, - { - sort: queryParams.sortObj, - projection: queryParams.projectionObj, - // Intentionally omit skip/limit for full query insights + ({ explainResult, queryFilter, totalCollectionDocs } = await session.runWithClient( + async (client) => { + const clusterMetadata = await client.getClusterMetadata(); + session.assertCurrent(epoch, myCtx.signal); + myCtx.actionContext.telemetry.properties.platform = clusterMetadata?.domainInfo_api ?? 'unknown'; + + const queryParams = session.getCurrentFindQueryParamsWithObjects(); + const executionStatsStart = Date.now(); + const explainResult = await session.getExecutionStats( + client, + epoch, + databaseName, + collectionName, + queryParams.filterObj, + { + sort: queryParams.sortObj, + projection: queryParams.projectionObj, + // Intentionally omit skip/limit for full query insights + }, + myCtx.signal, + ); + ext.outputChannel.trace( + l10n.t('[Query Insights Stage 2] explain completed in {ms}ms', { + ms: (Date.now() - executionStatsStart).toString(), + }), + ); + + session.assertCurrent(epoch, myCtx.signal); + let totalCollectionDocs: number | undefined; + try { + totalCollectionDocs = await client.estimateDocumentCount(databaseName, collectionName); + } catch (error) { + // Non-critical — advisories and selectivity can be omitted. + ClustersClient.reportFailure(client.binding, error); + } + return { explainResult, queryFilter: queryParams.filterObj, totalCollectionDocs }; }, - ); - const executionStatsDuration = Date.now() - executionStatsStart; - ext.outputChannel.trace( - l10n.t('[Query Insights Stage 2] explain completed in {ms}ms', { - ms: executionStatsDuration.toString(), - }), - ); - - // Analyze with ExplainPlanAnalyzer (pass the user's actual filter for empty-query detection) - analyzed = ExplainPlanAnalyzer.analyzeExecutionStats(executionStatsResult, queryParams.filterObj); - explainResult = executionStatsResult; - queryFilter = queryParams.filterObj as Document | undefined; - - // Fetch total collection docs for index-strategy advisories and selectivity cell - try { - totalCollectionDocs = await session.getClient().estimateDocumentCount(databaseName, collectionName); - } catch { - // Non-critical — advisories and selectivity will simply not fire/display - totalCollectionDocs = undefined; - } + epoch, + )); + session.assertCurrent(epoch, myCtx.signal); + analyzed = ExplainPlanAnalyzer.analyzeExecutionStats(explainResult, queryFilter); } // Extract extended stage info (as per design document) @@ -322,8 +301,7 @@ export const queryInsightsQueriesRouter = router({ // Cache the Stage 2 response for Stage 3's static analysis context if (!debugData) { - const session: ClusterSession = ClusterSession.getSession(sessionId); - session.setStage2Response(transformed, totalCollectionDocs); + session.setStage2Response(epoch, transformed, totalCollectionDocs, myCtx.signal); } // --- Stage 2 telemetry --- From 9de6a42cb983e21aa494aa368f15d4d779c04678 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 20:13:27 +0000 Subject: [PATCH 105/380] feat: add the shared unavailable connection banner (WI-6) Reuse the existing Fluent warning block and polite live region with one explicit recovery action. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iterations/01-dev-plan.md | 7 +++ .../_integration/connectionUnavailable.ts | 18 ++++++ .../components/DisconnectedBanner.test.tsx | 45 +++++++++++++++ .../components/DisconnectedBanner.tsx | 57 +++++++++++++++++++ 4 files changed, 127 insertions(+) create mode 100644 src/webviews/_integration/connectionUnavailable.ts create mode 100644 src/webviews/components/DisconnectedBanner.test.tsx create mode 100644 src/webviews/components/DisconnectedBanner.tsx 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 b29f8f488..c1b6be364 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 @@ -1526,6 +1526,13 @@ behave as today. Check the epoch, latch, and identity before applying results to session caches. Build and 193 focused tests passed. Procedure response shapes are unchanged for now; structured unavailable results and the remaining panels are subsequent WI-6 slices. +- **Webview design review:** A fresh Claude Opus 5.5 pass recommended one warning banner + using the existing MessageBlock and polite Announcer. Keep the editor and results in + place, do not move focus when the banner appears, and offer one explicit action. The + shared banner and its focused tests are in place, but not yet wired to panels. Keep + both planned stale-reply browser scenarios; adding the small harness support they need + is preferable to reducing coverage. Host action selection for a view with no credential + repair command is pending operator agreement. --- diff --git a/src/webviews/_integration/connectionUnavailable.ts b/src/webviews/_integration/connectionUnavailable.ts new file mode 100644 index 000000000..e5510c2fc --- /dev/null +++ b/src/webviews/_integration/connectionUnavailable.ts @@ -0,0 +1,18 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { type ConnectionUnavailableReason } from '../../documentdb/ConnectionUnavailableError'; + +export type ConnectionRecoveryAction = 'reconnect' | 'signInAgain' | 'updateCredentials' | 'close'; + +export interface ConnectionUnavailableDetails { + readonly reason: ConnectionUnavailableReason; + readonly text: string; + readonly action: ConnectionRecoveryAction; +} + +export interface ConnectionUnavailableResponse { + readonly unavailable: ConnectionUnavailableDetails; +} diff --git a/src/webviews/components/DisconnectedBanner.test.tsx b/src/webviews/components/DisconnectedBanner.test.tsx new file mode 100644 index 000000000..e3a73e765 --- /dev/null +++ b/src/webviews/components/DisconnectedBanner.test.tsx @@ -0,0 +1,45 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +// @vitest-environment jsdom + +import { act } from 'react'; +import { createRoot } from 'react-dom/client'; // eslint-disable-line import/no-internal-modules +import { expect, it, vi } from 'vitest'; +import { type ConnectionUnavailableDetails } from '../_integration/connectionUnavailable'; +import { DisconnectedBanner } from './DisconnectedBanner'; + +(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +it('offers one explicit recovery action and cannot resubmit while recovery is running', async (): Promise => { + const unavailable: ConnectionUnavailableDetails = { + reason: 'signInRequired', + text: 'Your Microsoft session is unavailable.', + action: 'signInAgain', + }; + const onAction = vi.fn(); + const host = document.createElement('div'); + document.body.appendChild(host); + const root = createRoot(host); + try { + await act(async () => root.render()); + expect(host.textContent).toContain(unavailable.text); + expect(host.querySelectorAll('button')).toHaveLength(1); + expect(host.querySelector('[role="status"]')?.getAttribute('aria-live')).toBe('polite'); + expect(host.querySelector('button')?.textContent).toBe('Retry sign-in'); + await act(async () => host.querySelector('button')?.click()); + expect(onAction).toHaveBeenCalledExactlyOnceWith('signInAgain'); + + await act(async () => + root.render(), + ); + expect(host.querySelector('button')?.disabled).toBe(true); + await act(async () => host.querySelector('button')?.click()); + expect(onAction).toHaveBeenCalledTimes(1); + } finally { + await act(async () => root.unmount()); + host.remove(); + } +}); diff --git a/src/webviews/components/DisconnectedBanner.tsx b/src/webviews/components/DisconnectedBanner.tsx new file mode 100644 index 000000000..dc79b9845 --- /dev/null +++ b/src/webviews/components/DisconnectedBanner.tsx @@ -0,0 +1,57 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { Button } from '@fluentui/react-components'; +import * as l10n from '@vscode/l10n'; +import { type JSX, type Ref } from 'react'; +import { + type ConnectionRecoveryAction, + type ConnectionUnavailableDetails, +} from '../_integration/connectionUnavailable'; +import { Announcer } from './accessibility'; +import { MessageBlock } from './MessageBlock'; + +interface DisconnectedBannerProps { + readonly unavailable: ConnectionUnavailableDetails; + readonly onAction: (action: ConnectionRecoveryAction) => void; + readonly recovering?: boolean; + readonly actionRef?: Ref; +} + +function actionLabel(action: ConnectionRecoveryAction): string { + switch (action) { + case 'reconnect': + return l10n.t('Reconnect'); + case 'signInAgain': + return l10n.t('Retry sign-in'); + case 'updateCredentials': + return l10n.t('Update credentials…'); + case 'close': + return l10n.t('Close tab'); + } +} + +export function DisconnectedBanner({ + unavailable: { reason, text, action }, + onAction, + recovering, + actionRef, +}: DisconnectedBannerProps): JSX.Element { + return ( + <> + onAction(action)}> + {actionLabel(action)} + + } + > + {text} + + + + ); +} From 798161ce985fcb4a9c535a57011f44f16edfe16a Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Tue, 24 Nov 2026 06:24:32 +0000 Subject: [PATCH 106/380] feat: keep disconnected views open under a recovery overlay (WI-6) Record decision 0016 and keep the view mounted and inert until an explicit recovery or close action. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../features/connection-lifecycle/README.md | 6 +- .../connection-lifecycle/decisions.md | 13 +++ .../iterations/01-dev-plan.md | 42 ++++----- .../iterations/01-implementation-plan.md | 15 ++-- .../components/DisconnectedBanner.test.tsx | 45 ---------- .../components/DisconnectedBanner.tsx | 57 ------------ .../components/DisconnectedOverlay.scss | 31 +++++++ .../components/DisconnectedOverlay.test.tsx | 69 +++++++++++++++ .../components/DisconnectedOverlay.tsx | 86 +++++++++++++++++++ 9 files changed, 232 insertions(+), 132 deletions(-) delete mode 100644 src/webviews/components/DisconnectedBanner.test.tsx delete mode 100644 src/webviews/components/DisconnectedBanner.tsx create mode 100644 src/webviews/components/DisconnectedOverlay.scss create mode 100644 src/webviews/components/DisconnectedOverlay.test.tsx create mode 100644 src/webviews/components/DisconnectedOverlay.tsx diff --git a/docs/ai-and-plans/features/connection-lifecycle/README.md b/docs/ai-and-plans/features/connection-lifecycle/README.md index 25a97a0d5..a63502715 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/README.md +++ b/docs/ai-and-plans/features/connection-lifecycle/README.md @@ -49,8 +49,9 @@ Evidence, telemetry and source pointers: [research-findings.md](./research-findi successful results and records a sanitized diagnostic if an account or tenant cannot be listed. - **Keep one client per cluster.** Surfaces resolve it per operation and check its identity fingerprint and generation. -- **Never change identity under an open surface.** It becomes disconnected, keeps its state, says why - and offers one action. +- **Never change identity under an open surface.** It stays open, keeps its state, and shows a + shaded, disabled overlay that explains the reason. Offer **Close** and, when supported, an + explicit recovery 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**. @@ -86,6 +87,7 @@ See [decisions.md](./decisions.md): - 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. +- 0016 keep disconnected webviews open under a full-view overlay with explicit actions. ## Timeline diff --git a/docs/ai-and-plans/features/connection-lifecycle/decisions.md b/docs/ai-and-plans/features/connection-lifecycle/decisions.md index 9e5712c39..9b3aa3739 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/decisions.md +++ b/docs/ai-and-plans/features/connection-lifecycle/decisions.md @@ -27,6 +27,7 @@ created: 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 | +| 0016 | Keep disconnected webviews open under a full-view overlay | Accepted | Operator chose a simple disabled state with explicit actions | 2026-11-24 | Yes; replaces the inline banner and single-action layout | > 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 @@ -424,3 +425,15 @@ the epoch still matches. It cannot clear a latch set by Disconnect, Remove or a 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. + +## 0016. Keep disconnected webviews open under a full-view overlay + +The operator chose a simple disabled state instead of the planned warning banner. Keep the +webview and its contents mounted, but make the background unavailable for interaction. Shade +the whole view and show a calm, centered explanation with a row of actions. + +Always offer **Close**. If the connection has a supported recovery action, offer it alongside +Close. If there is no repair the tab can perform, show only **Close** and leave the tab open +until the user chooses it. Do not retry rejected credentials or navigate away automatically. +Keep this component local to the lifecycle webviews for now rather than adding a general +feature to the webview framework. 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 c1b6be364..e9e0b70bc 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 @@ -1373,7 +1373,7 @@ webview as a structured unavailable result, not a generic query error. - Collection View (all tabs), Document View and the Cluster Dashboard resolve their client per operation through a binding. -- They show an unavailable state (C-5) with a banner and one action. +- They show an unavailable state (C-5) with a full-view overlay, Close, and a repair action when supported. - They keep all user state. - They never apply stale results. - They never run under another identity. @@ -1448,17 +1448,18 @@ approved plan allows; the webview half then stacks on the host half without wait ### Webviews 1. **Shared UI.** - - A `DisconnectedBanner` component: a Fluent `MessageBar` with intent `warning`, the host-provided - reason text and **one** action button. It uses `role="status"` and `aria-live="polite"`. + - A feature-local `DisconnectedOverlay` shades the webview and shows the host-provided reason + text in the center. Show **Close** and at most one supported repair action (decision 0016). + Announce the reason politely and give keyboard focus to an overlay action, not the disabled content. - It shows when a procedure returns `unavailable`, or when the host's `disable(reason)` sends its one message to the panel over the existing webview channel. - Put it in the shared webview components folder, and run the detecting-accessibility-issues skill on it. 2. **Disabling.** - - While the banner shows, every action that talks to the server is disabled: run query, paging, + - While the overlay shows, every action that talks to the server is disabled: run query, paging, refresh, save, delete, insert, index actions, Query Insights stages and AI calls. - - Editors stay **editable**. The user can keep typing. - - A response that arrives while the banner shows is ignored. + - The underlying view is inert. Editors stay mounted and retain their contents and dirty state. + - A response that arrives while the overlay shows is ignored. - **A reply never overwrites a newer edit.** The Document View applies a save or load reply to the editor only if the editor content has not changed since the request was sent; otherwise it keeps the edit and stays dirty. Today's save handler (`documentView.tsx`) replaces the content and clears `isDirty` @@ -1470,14 +1471,15 @@ approved plan allows; the webview half then stacks on the host half without wait - **Dashboard:** the last data (WI-8 stops the polling). 4. **Actions.** - **Reconnect** (same fingerprint): clear the latch if one is set, and resolve again. On success, - remove the banner and re-enable the actions; the live region announces "Reconnected". The query is + remove the overlay and re-enable the actions; the live region announces "Reconnected". The query is not run automatically, and there is **no** "out of date" notice (decision 0010; see #1106). After a Disconnect the credentials are still cached (0011), so this is silent. - **Reconnect after an identity change:** an explicit rebind to the new fingerprint, then show "Now connected as {label}" (OT-3). - **Sign in again:** the WI-5 command. - **Update credentials:** the existing command. - - **Close:** dispose the panel. + - **Close:** dispose the panel only through an explicit action. When no supported repair is + available in the tab, Close is the only action. 5. **L2-dev scenarios** (`scenarios.ts` and `fixtures.ts`): - `collectionView/disconnected-signInRequired`: query text kept, Run disabled, no host calls when Run is clicked; @@ -1501,7 +1503,7 @@ behave as today. - `ClusterSession` no longer stores a client (a type-level or structural test); - a stale result is dropped before any host-side mutation, including a reply that started before a Disconnect and arrives after a Reconnect as the same user; -- the webview ignores a response that arrives while the banner shows; +- the webview ignores a response that arrives while the overlay shows; - one submission for a write whose reply is lost; - an import started from Collection View as identity A, with its file picker left open while the cluster moves to B, writes nothing until the user starts it again; @@ -1526,13 +1528,11 @@ behave as today. Check the epoch, latch, and identity before applying results to session caches. Build and 193 focused tests passed. Procedure response shapes are unchanged for now; structured unavailable results and the remaining panels are subsequent WI-6 slices. -- **Webview design review:** A fresh Claude Opus 5.5 pass recommended one warning banner - using the existing MessageBlock and polite Announcer. Keep the editor and results in - place, do not move focus when the banner appears, and offer one explicit action. The - shared banner and its focused tests are in place, but not yet wired to panels. Keep - both planned stale-reply browser scenarios; adding the small harness support they need - is preferable to reducing coverage. Host action selection for a view with no credential - repair command is pending operator agreement. +- **Webview design decision:** After the advisor's banner draft, the operator chose the + full-view disabled overlay in [decision 0016](../decisions.md#0016-keep-disconnected-webviews-open-under-a-full-view-overlay). + It keeps the content mounted and inert, uses a polite announcement, and shows only Close + when there is no supported repair. The shared component builds and passed its focused + test; panels are not yet wired. Keep both planned stale-reply browser scenarios. --- @@ -1709,7 +1709,7 @@ behave as today. ## WI-8: Cluster Dashboard health polling (PR 6) -**Outcome:** the poll stops when the cluster is unavailable, shows the banner, and resumes with exactly +**Outcome:** the poll stops when the cluster is unavailable, shows the overlay, and resumes with exactly one loop. **Steps:** @@ -1720,18 +1720,18 @@ one loop. of a failed command long enough to classify it. A terminal kind (auth, closed client) is rethrown so that `runWithClient` returns `unavailable`. An unsupported command, such as `serverStatus` on some servers, stays an ordinary partial sample with its entry in `errors`. -2. The webview poll effect depends on the banner state: it stops on `unavailable` or on a `disable` +2. The webview poll effect depends on the overlay state: it stops on `unavailable` or on a `disable` message, and starts again after Reconnect. React's effect cleanup keeps it to one loop; no extra loop token. -3. A ping that resolves while the banner shows is ignored (the WI-6 webview rule), so it cannot clear the - banner. +3. A ping that resolves while the overlay shows is ignored (the WI-6 webview rule), so it cannot clear the + overlay. 4. Visibility pause and backoff are the rest of #1091. Do them here only if they are trivial; otherwise leave them to #1091. **Tests** (fake timers): - no client lookups on ticks or on reveal after Disconnect; -- a late success does not clear the banner; +- a late success does not clear the overlay; - reconnecting starts exactly one loop; - `signInRequired` and `credentialsRejected` stop the loop after one tick, including when they happen **inside** the sampler's ping with the tree untouched; 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 c83e4ecc2..965583acc 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 @@ -384,10 +384,11 @@ The largest item. Host side first, then each view. internally; test one application submission when the server accepts a write but its reply is lost. - **Webviews:** - - Push one connection-state channel per view over tRPC: connected, reconnecting, or disconnected - with a reason. Follow the webview-trpc-messaging and react-webview-architecture skills. - - Disconnected disables every action that talks to the server and shows a banner with the reason - and one action: Reconnect, Sign in again, Update credentials, or Close. + - Return unavailable results from operations and use the existing webview message channel for + teardown. Do not add a connection-state subscription (decision 0012). + - Disconnected dims the entire webview, disables the underlying content, and shows the reason + with **Close** and a supported repair (Reconnect, Retry sign-in, or Update credentials), if + available. The tab never closes automatically (decision 0016). - It **keeps** the editor contents, filter, sort, projection, page position and unsaved document edits. - Views: Collection View (query, documents, indexes and Query Insights tabs), Document View @@ -399,7 +400,7 @@ The largest item. Host side first, then each view. is not permission to restart a transfer under another identity. - **Tests:** - router tests for the three binding outcomes; - - a Collection View scenario: disconnected banner with the query text kept; + - a Collection View scenario: disconnected overlay with the query text kept; - a Document View scenario: dirty edit kept; - inject a disconnect after typing, then deliver a stale page or document read; neither applied results nor drafts may be overwritten, and disabled actions must issue no server calls; @@ -460,12 +461,12 @@ Coordinate with #1091. The minimum for this plan: - the poll uses the WI-6 binding; - after a `signInRequired`, `credentialsRejected` or disconnected outcome, polling **stops** and the - dashboard shows the WI-6 banner instead of starting a connection every 5 s. + dashboard shows the WI-6 overlay instead of starting a connection every 5 s. Visibility pause and backoff are the rest of #1091 and may ship separately. Existing visibility and in-flight guards do not distinguish a missing ping sample from terminal auth failure. With fake timers, verify no client lookups on ticks or reveal after Disconnect, -that a late successful ping cannot clear the banner, and that reconnect starts only one poll loop. +that a late successful ping cannot clear the overlay, and that reconnect starts only one poll loop. ## WI-9: Measure token renewal and recovery after release diff --git a/src/webviews/components/DisconnectedBanner.test.tsx b/src/webviews/components/DisconnectedBanner.test.tsx deleted file mode 100644 index e3a73e765..000000000 --- a/src/webviews/components/DisconnectedBanner.test.tsx +++ /dev/null @@ -1,45 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - -// @vitest-environment jsdom - -import { act } from 'react'; -import { createRoot } from 'react-dom/client'; // eslint-disable-line import/no-internal-modules -import { expect, it, vi } from 'vitest'; -import { type ConnectionUnavailableDetails } from '../_integration/connectionUnavailable'; -import { DisconnectedBanner } from './DisconnectedBanner'; - -(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; - -it('offers one explicit recovery action and cannot resubmit while recovery is running', async (): Promise => { - const unavailable: ConnectionUnavailableDetails = { - reason: 'signInRequired', - text: 'Your Microsoft session is unavailable.', - action: 'signInAgain', - }; - const onAction = vi.fn(); - const host = document.createElement('div'); - document.body.appendChild(host); - const root = createRoot(host); - try { - await act(async () => root.render()); - expect(host.textContent).toContain(unavailable.text); - expect(host.querySelectorAll('button')).toHaveLength(1); - expect(host.querySelector('[role="status"]')?.getAttribute('aria-live')).toBe('polite'); - expect(host.querySelector('button')?.textContent).toBe('Retry sign-in'); - await act(async () => host.querySelector('button')?.click()); - expect(onAction).toHaveBeenCalledExactlyOnceWith('signInAgain'); - - await act(async () => - root.render(), - ); - expect(host.querySelector('button')?.disabled).toBe(true); - await act(async () => host.querySelector('button')?.click()); - expect(onAction).toHaveBeenCalledTimes(1); - } finally { - await act(async () => root.unmount()); - host.remove(); - } -}); diff --git a/src/webviews/components/DisconnectedBanner.tsx b/src/webviews/components/DisconnectedBanner.tsx deleted file mode 100644 index dc79b9845..000000000 --- a/src/webviews/components/DisconnectedBanner.tsx +++ /dev/null @@ -1,57 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - -import { Button } from '@fluentui/react-components'; -import * as l10n from '@vscode/l10n'; -import { type JSX, type Ref } from 'react'; -import { - type ConnectionRecoveryAction, - type ConnectionUnavailableDetails, -} from '../_integration/connectionUnavailable'; -import { Announcer } from './accessibility'; -import { MessageBlock } from './MessageBlock'; - -interface DisconnectedBannerProps { - readonly unavailable: ConnectionUnavailableDetails; - readonly onAction: (action: ConnectionRecoveryAction) => void; - readonly recovering?: boolean; - readonly actionRef?: Ref; -} - -function actionLabel(action: ConnectionRecoveryAction): string { - switch (action) { - case 'reconnect': - return l10n.t('Reconnect'); - case 'signInAgain': - return l10n.t('Retry sign-in'); - case 'updateCredentials': - return l10n.t('Update credentials…'); - case 'close': - return l10n.t('Close tab'); - } -} - -export function DisconnectedBanner({ - unavailable: { reason, text, action }, - onAction, - recovering, - actionRef, -}: DisconnectedBannerProps): JSX.Element { - return ( - <> - onAction(action)}> - {actionLabel(action)} - - } - > - {text} - - - - ); -} diff --git a/src/webviews/components/DisconnectedOverlay.scss b/src/webviews/components/DisconnectedOverlay.scss new file mode 100644 index 000000000..1a61afd28 --- /dev/null +++ b/src/webviews/components/DisconnectedOverlay.scss @@ -0,0 +1,31 @@ +.disconnectedOverlayBackground { + display: contents; +} + +.disconnectedOverlay { + position: fixed; + inset: 0; + z-index: 1000; + display: grid; + place-content: safe center; + justify-items: center; + gap: 10px; + overflow: auto; + padding: 20px; + background: var(--vscode-editor-background); + background: color-mix(in srgb, var(--vscode-editor-background) 90%, transparent); + color: var(--vscode-editor-foreground); + text-align: center; + + p { + max-width: 40ch; + margin: 0; + } +} + +.disconnectedOverlayActions { + display: flex; + flex-wrap: wrap; + justify-content: center; + gap: 10px; +} diff --git a/src/webviews/components/DisconnectedOverlay.test.tsx b/src/webviews/components/DisconnectedOverlay.test.tsx new file mode 100644 index 000000000..9353b7a72 --- /dev/null +++ b/src/webviews/components/DisconnectedOverlay.test.tsx @@ -0,0 +1,69 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +// @vitest-environment jsdom + +import { act } from 'react'; +import { createRoot } from 'react-dom/client'; // eslint-disable-line import/no-internal-modules +import { expect, it, vi } from 'vitest'; +import { type ConnectionUnavailableDetails } from '../_integration/connectionUnavailable'; +import { DisconnectedOverlay } from './DisconnectedOverlay'; + +(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +it('keeps content mounted but inert, and only closes or retries on explicit clicks', async (): Promise => { + const unavailable: ConnectionUnavailableDetails = { + reason: 'signInRequired', + text: 'Your Microsoft session is unavailable.', + action: 'signInAgain', + }; + const onAction = vi.fn(); + const host = document.createElement('div'); + document.body.appendChild(host); + const root = createRoot(host); + try { + const render = async (failure?: ConnectionUnavailableDetails, recovering?: boolean): Promise => { + await act(async () => + root.render( + +