diff --git a/.github/skills/error-translation/SKILL.md b/.github/skills/error-translation/SKILL.md index 692077e78..66577d14e 100644 --- a/.github/skills/error-translation/SKILL.md +++ b/.github/skills/error-translation/SKILL.md @@ -28,6 +28,28 @@ for, and errors that are already obsolete by the time they appear. Anything with a side effect belongs at the call site, which alone knows whether the user is watching, whether the operation was a read or a write, and which surface is right. +## Connection-lifecycle errors + +The lifecycle uses four typed error families. Preserve their classes and original `cause`; C-2 +types are contracts, not prose to infer from a message: + +| Error | Meaning | +| --------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `EntraSignInRequiredError` | Silent acquisition returned no session or the configured authentication provider changed; `reason` is `noSession` or `providerChanged`. | +| `EntraIdentityMismatchError` | Interactive acquisition returned a different Microsoft account from the pinned one. | +| `TokenCallbackError` | Any other OIDC callback throw for Microsoft Entra ID or managed identity. Its bounded `authMethod` records which one, and `cause` retains the original failure. | +| `ConnectionUnavailableError { reason }` | A bound client cannot be used. The reason is `signInRequired`, `credentialsRejected`, `credentialsMissing`, `credentialsUpdating`, `credentialsChanged`, `identityChanged`, `userDisconnected`, `connectionRemoved`, or `unreachable`. | + +Register `EntraSignInRequiredErrorExplainer` with provider id `entraSignInRequired` before the +general Entra explainer because the first explanation wins. That provider follows cyclic-safe +`cause` links and `MongoServerSelectionError.reason.servers[*].error`, and recognizes only the +typed sign-in-required and identity-mismatch errors. It explains those failures without exposing +private causes and asks the user to sign in with the original account when identities differ. + +Do not translate `ConnectionUnavailableError` through an infrastructure provider. The call site +knows whether the right response is a tree recovery action, a disabled webview dialog, or bounded +shell or playground output. Preserve the `reason`; webviews map it to **Retry** or **Close view**. + ## Adding a provider Implement `ErrorExplanationProvider` and register it in @@ -193,5 +215,6 @@ l10n.t('The container was removed outside VS Code.') - [errorExplanationService.ts](../../../src/services/errorExplanationService.ts) - [connectionReachabilityService.ts](../../../src/services/connectionReachabilityService.ts) prepares a connection _before_ connecting; this service explains a failure _afterwards_ +- [EntraSignInRequiredErrorExplainer.ts](../../../src/documentdb/auth/entraErrors/EntraSignInRequiredErrorExplainer.ts) - [tree-cluster-architecture](../tree-cluster-architecture/SKILL.md) for `clusterId` versus `treeId` - [telemetry-instrumentation](../telemetry-instrumentation/SKILL.md) diff --git a/.github/skills/tree-cluster-architecture/SKILL.md b/.github/skills/tree-cluster-architecture/SKILL.md index fa8153e17..37642b9a4 100644 --- a/.github/skills/tree-cluster-architecture/SKILL.md +++ b/.github/skills/tree-cluster-architecture/SKILL.md @@ -63,6 +63,21 @@ Rules: - Never assume a stable ID is also a tree path unless the provider explicitly guarantees `clusterId === treeId`. - Never change tree construction without checking reverse lookup from `clusterId`. +## Connection Binding Contract + +A long-lived surface binds to `{ clusterId, fingerprint, generation }`, not to a `ClustersClient` +instance. Resolve the client for every operation through the binding with +`ClustersClient.resolveBoundClient()` or `runWithClient()`. Never retain a `ClustersClient` in view, +router, shell, playground, task, or clipboard state. + +- A new generation with the same fingerprint is a transparent same-connection replacement. +- A different fingerprint is an identity or settings change. Never rebind an existing surface. +- Check latches and the binding again at operation and async-reply boundaries. +- An operation may hold the resolved client only for the duration of that operation. A stale reply + must not mutate the new connection or replay a failed write. +- Shell and playground workers may keep their own connection, but pin the originating identity and + obey the same fingerprint and epoch checks when they respawn. + ## Design Rendering and Lookup Together When adding a cluster hierarchy or a tree/list mode, specify these four functions before coding: @@ -194,10 +209,19 @@ actions such as "Update credentials…" via `errorRecoveryActions` Keep a fixed relative order: configuration/targeted repairs, diagnosis/inspection, shell, destructive recovery, and **Retry always last** (including "Retry setup…"). -Providers prepend repairs; Update connection string precedes Update credentials when both exist. +Providers prepend repairs; **Update connection string** precedes **Update credentials** when both +exist. Then `ClusterItemBase` renders **Retry sign-in** when a verified Entra identity can recover, +followed by **Diagnose connection…** and **Open shell**. **Retry** is last. When **Retry sign-in** or +the stored-credential rejection action replaces Retry, do not add an ordinary Retry row too. Failure classification changes availability, never ordering. When healthy resources coexist with recovery actions, render the healthy resources first and the recovery block last. +A connected cluster's `TreeItem.contextValue` includes the `connected` tag while a client exists +and no lifecycle latch blocks it. Preserve the base context value and use this tag to gate +Disconnect. A user-disconnected cluster renders its single **Reconnect** action instead of database +children; Remove and rejected credentials use their own states and must not be exposed as +user-disconnected. + Do not add a child whose purpose is to show a message (an error label, a "sign-in required" row, a tooltip-only info node), even with an icon. Better wording belongs in the modal and in the Diagnose connection panel, not in the tree. @@ -210,6 +234,8 @@ Before approving a cluster tree change, answer yes to all: - [ ] Base cluster context tag is preserved. - [ ] `clusterId`, `treeId`, and `viewId` have documented owners. - [ ] Credentials and clients use `clusterId` only. +- [ ] Long-lived surfaces retain bindings, not `ClustersClient` instances. +- [ ] Per-operation resolution checks the fingerprint and generation. - [ ] Every rendered layout has a reverse lookup strategy. - [ ] Cluster and collection lookup share one resolver. - [ ] Synthetic ownership is exact and isolated from stored lookup. @@ -217,3 +243,5 @@ Before approving a cluster tree change, answer yes to all: - [ ] A real render-to-lookup round-trip test covers every layout. - [ ] Standard cluster commands work or are explicitly gated off. - [ ] Failures show a modal; tree children are recovery actions only, never error or info rows. +- [ ] Recovery actions keep provider repairs first, diagnosis and shell next, and Retry last. +- [ ] The `connected` context tag gates Disconnect and disappears while a lifecycle latch applies. diff --git a/CHANGELOG.md b/CHANGELOG.md index 699a9e3e8..756d5c6d8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Change Log +## 1.2.0 (Unreleased) + +> Draft entries for an unpublished release. They may change before the release is finalized. + +### New Features & Improvements + +- **Resilient Connections**: Renews Microsoft Entra ID tokens silently, refreshes Azure discovery credentials, and replaces closed or transient failed clients with the same binding on a later foreground operation. [#990](https://github.com/microsoft/vscode-documentdb/issues/990), [#1102](https://github.com/microsoft/vscode-documentdb/issues/1102) +- **Explicit Connection Teardown**: Adds Disconnect and Reconnect, a shared disconnect and deletion flow, a Close all or Keep open (disabled) choice, and protection for active copy, export, or import work. [#566](https://github.com/microsoft/vscode-documentdb/issues/566), [#1059](https://github.com/microsoft/vscode-documentdb/issues/1059) +- **Identity-Bound Open Views**: Keeps open views and editor state tied to the connection that created them. Expired sign-in or unavailable connections receive bounded recovery, while changed saved settings require a new view instead of changing identity behind it. [#1102](https://github.com/microsoft/vscode-documentdb/issues/1102) + ## 1.1.0 ### New Features diff --git a/docs/ai-and-plans/features/connection-lifecycle/README.md b/docs/ai-and-plans/features/connection-lifecycle/README.md index a55a585c0..7421adc26 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/README.md +++ b/docs/ai-and-plans/features/connection-lifecycle/README.md @@ -6,13 +6,20 @@ created: 2026-11-19 code: - src/documentdb/ClustersClient.ts - src/documentdb/ClusterSession.ts + - src/documentdb/runWithClient.ts + - src/documentdb/connectionTeardown.ts - src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts + - src/documentdb/auth/entraErrors/EntraSignInRequiredErrorExplainer.ts + - src/documentdb/shell/ShellSessionManager.ts + - src/documentdb/playground/PlaygroundEvaluator.ts - src/tree/documentdb/ClusterItemBase.ts + - src/webviews/components/DisconnectedOverlay.tsx --- # Connection lifecycle -**Status:** planned (iteration 1) · **Issues:** +**Status:** implemented in the feature branch; documentation draft ready; release and final +integration pending · **Issues:** - [#1102](https://github.com/microsoft/vscode-documentdb/issues/1102) - [#1059](https://github.com/microsoft/vscode-documentdb/issues/1059) @@ -41,6 +48,28 @@ defects: Evidence, telemetry and source pointers: [research-findings.md](./research-findings.md). +## Code map + +| Area | Primary implementation | +| -------------------------------- | --------------------------------------------------------------------------------------------- | +| Client and binding lifecycle | `ClustersClient`, `ClusterSession`, `runWithClient` | +| Entra token renewal and errors | `MicrosoftEntraIDAuthHandler`, `entraSession`, `entraErrors/*`, `entraTokenFailures` | +| Shell and playground token relay | `ShellSessionManager`, `PlaygroundEvaluator`, `WorkerSessionManager`, `playgroundWorker` | +| Disconnect and removal | `connectionTeardown`, Disconnect command, connection and folder removal callers | +| Bound webviews and stale replies | `connectionSurfaces`, `DisconnectedOverlay`, bound-view routers and controllers | +| Tree recovery | `ClusterItemBase`, provider `errorRecoveryActions`, `showClusterConnectFailure` | +| Dashboard lifecycle polling | Cluster Dashboard controller, router and sampler | +| Measurement | established-connection lifecycle telemetry; the pending WI-9 operator volume/dashboard review | + +## WI-10 documentation choice + +The lifecycle manual stays in +[connecting-to-databases.md](../../../user-manual/connecting-to-databases.md) rather than adding a +separate page. The existing page already owns failed-connection recovery, so the continuation is +discoverable without another navigation level. The three requested workflow pages link to that +section. The operator chose no screenshots; no placeholders were added. Release notes and changelog +entries are unpublished drafts and do not represent a shipped release. + ## Intent - **Recover database connections silently** from token expiry and idle drops. For database @@ -103,6 +132,7 @@ See [decisions.md](./decisions.md): - 0017 limit unavailable webview recovery to Retry and Close view. - 0018 saved connection edits permanently lock existing views. - 0019 require a fresh Dashboard delete after Disconnect and retain tree-only Paste. +- 0020 defer the late-failure comparison across releases and retain descriptive telemetry. ## Timeline @@ -111,3 +141,7 @@ See [decisions.md](./decisions.md): | 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) | +| 2026-11-23 | WI-1 through WI-5 implement renewal, Azure auth, bindings and recovery | +| 2026-11-24 | WI-6 through WI-8 implement bound views, teardown and Dashboard behavior | +| 2026-11-25 | WI-2 review fixes and WI-9 lifecycle measurements | +| 2026-11-26 | WI-10 documentation draft, skill updates and unpublished 1.2.0 notes | diff --git a/docs/ai-and-plans/features/connection-lifecycle/decisions.md b/docs/ai-and-plans/features/connection-lifecycle/decisions.md index 6eeac6991..89641b895 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/decisions.md +++ b/docs/ai-and-plans/features/connection-lifecycle/decisions.md @@ -18,7 +18,7 @@ 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 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 | — | +| 0007 | The Disconnect choice is a VS Code modal with nothing remembered; a setting can set the default | Accepted (modified by 0018) | Operator: modal cannot pre-select; saved edits are close-only | 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 | — | @@ -30,6 +30,8 @@ created: 2026-11-19 | 0016 | Keep disconnected webviews open under a full-view overlay | Accepted (modified by 0017) | Operator chose a simple disabled state with explicit actions | 2026-11-24 | Yes; replaces the inline banner and single-action layout | | 0017 | Limit unavailable webview recovery to Retry and Close view | Accepted (modified by 0018) | Operator wants credential repair in the tree and no extra recovery workflow in a tab | 2026-11-24 | Yes; removes in-view credential repair | | 0018 | Saved connection edits permanently lock existing views | Accepted | Operator prefers simple reconnect for unchanged settings over recovery after edits | 2026-11-24 | Yes; removes same-identity recovery after a saved edit | +| 0019 | Require a fresh Dashboard delete after Disconnect and keep Paste Collection in the tree | Accepted | Operator: a lifecycle change cancels the pending delete and never replays it | 2026-11-24 | — | +| 0020 | Defer the cross-release comparison of late failures | Accepted | Operator: keep descriptive telemetry and defer the comparison | 2026-11-26 | Yes; removes the WI-9 before/after comparison for 1.2.0 | > 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 @@ -199,7 +201,9 @@ operator input on the dev plan's provisional answer A2. - 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. +- The choice applies to Disconnect and Remove Connection. Decision 0018 makes a saved identity or + settings edit close-only instead: existing views keep their contents but are not moved to the + new connection. Rejected: @@ -487,3 +491,14 @@ in the tree only. Copy stores a tree reference, not a snapshot of the data or credentials. The later tree Paste uses the current connection; it does not resume a Dashboard operation. Binding the whole clipboard and index-copy flow was not part of this change. + +## 0020. Defer the cross-release comparison of late failures + +The operator chose to keep descriptive telemetry and defer the WI-9 before/after comparison +for 1.2.0. Auth and closed-client unavailability can now be returned as normal RPC responses, +which the SDK records as successes without a failure signature. An apparent drop across releases +could be a reporting change rather than improved recovery. + +Keep renewal, client age and entry generation, and ARM challenge queries for a single version. +Do not add an instrumentation path or keep a socket-only comparison in this release. CP-5 still +checks pre-release ingestion and records that the late-failure trend is unmeasured. 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 449bdd0fd..41501d54e 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 @@ -1872,6 +1872,16 @@ one loop. **Progress:** +- The WI-9 commit records only checked post-startup Entra database lookups. Host lookup eligibility + follows the published client; worker eligibility is captured when the ready or executing worker + requests the token. Neither uses the first callback as a startup proxy. +- Case 1 passed: `npm run build` and 349 focused tests in 8 files. Ingestion is **pending**; the + [telemetry queries](../telemetry.md) are ready to run. The dashboard worktree has unrelated + changes in progress and was left untouched. +- PR7 review superseded the before/after comparison in items 2 and 5. Auth and closed-client + unavailability are not measured equivalently across releases. The operator deferred the + comparison and kept descriptive telemetry for CP-5 ([decision 0020](../decisions.md#0020-defer-the-cross-release-comparison-of-late-failures)). + --- ## WI-10: Documentation (PR 7) @@ -1896,6 +1906,11 @@ one loop. **Progress:** +- The operator chose text-only 1.2.0 release notes. The user manual extends + `connecting-to-databases.md` rather than adding a second page. +- The local GitHub Pages build rendered the manual and draft release notes. The three + manual links and the release index link resolve, and the internal feature docs stay excluded. + --- ## PR F: `feature/connection-lifecycle` → `main` @@ -1920,4 +1935,6 @@ one loop. # Outcome -_To be written at hand-over._ +- **WI-9 telemetry: pending ingestion.** Run the [feature queries](../telemetry.md) on + pre-release data before CP-5. The cross-release trend is unmeasured for 1.2.0. Record the + packaged operator validation here at OP-6. diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr7-telemetry-and-docs-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr7-telemetry-and-docs-review.md new file mode 100644 index 000000000..0138ae079 --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr7-telemetry-and-docs-review.md @@ -0,0 +1,91 @@ +# PR7 pre-review: Connection recovery telemetry and docs + +[PR #1135](https://github.com/microsoft/vscode-documentdb/pull/1135) · WI-9 and WI-10 · reviewed head `668ead86a` + +Claude Opus 5.5 performed the first pass. OpenAI GPT-6.2-Sol independently validated the +findings and added two. That run used long context; the standard-context verification +required by CONTRIBUTING §6.1 remains open. There were no Copilot threads when checked. +Neither reviewer found a runtime issue in the bounded renewal emitter. Neither ran the +queries against live data. + +## F1. The baseline can show a false drop in classified failures (high for WI-9) + +The original before/after query used error fields that the new tree `connect` path masks but +the baseline did not. The +same failure can move to the unclassified bucket without any change in its frequency. +Tree expansion can also return recovery actions as a normal result. + +**Recommendation:** Compare only stable RPC procedures and versions that share the same +`causeType` scheme, with the same exposure rules for both cohorts. Keep unclassified +counts visible and label tree data as descriptive, not comparable. If no comparable +cohort has enough exposure, report insufficient evidence. Do not change runtime +telemetry or relax redaction. + +**Author decision:** Approved as recommended. Limit the rate comparison to stable RPC +scopes; do not add a telemetry field or change redaction. + +**Fixed:** [`fe91067a8`](https://github.com/microsoft/vscode-documentdb/commit/fe91067a8) +limits the classified comparison to two database RPCs and uses `causeType` alone. Tree +events stay descriptive, and unclassified failures remain visible. + +**Superseded by Copilot follow-up:** The RPCs can also return typed unavailability normally, +which is reported as SDK success. The operator [deferred the comparison](../decisions.md#0020-defer-the-cross-release-comparison-of-late-failures) +and retained descriptive telemetry for 1.2.0. + +## F2. Disconnect does not wait behind an active task (medium) + +The [release notes](../../../../release-notes/1.2.md) say Disconnect waits, and the +[manual](../../../../user-manual/connecting-to-databases.md#disconnect-and-reconnect) +does not explicitly tell the user to retry. The command refuses teardown and leaves +both the task and the connection running. + +**Recommendation:** State in both pages that the user must try Disconnect again after +the task finishes or is stopped. No command change. + +**Author decision:** Approved as recommended. Clarify that the user must retry Disconnect. + +**Fixed:** [`f7607d039`](https://github.com/microsoft/vscode-documentdb/commit/f7607d039) +explains in both pages that the task and connection keep running and the user must retry. + +## F3. Recovery rows can inflate replacement success counts (medium) + +The [replacement query](../telemetry.md) excludes cached failures, but a first failed +tree expansion can return recovery rows while its event still reports success. It can +already carry the replacement generation at that point. + +**Recommendation:** Exclude both first-time and cached recovery rows. Count confirmed +recovery only for operations whose success indicates that database work succeeded. + +**Author decision:** Approved as recommended. Do not count first-time or cached recovery +rows as successful replacement operations. + +**Fixed:** [`fe91067a8`](https://github.com/microsoft/vscode-documentdb/commit/fe91067a8) +counts only successful cluster expansions on a replacement generation, excluding both +first-time and cached recovery rows. + +## F4. A retained Dashboard can still require Retry (medium) + +The [manual](../../../../user-manual/connecting-to-databases.md#disconnect-and-reconnect) +and [release notes](../../../../release-notes/1.2.md) imply that only other views need +Retry. The Dashboard retries automatically only if reconnect opens the already +bound panel. Auto-open can be disabled. + +**Recommendation:** Describe the conditional automatic retry and tell users to select +**Retry** if the Dashboard stays disabled. No behavior change. + +**Author decision:** Approved as recommended. Clarify when a retained Dashboard still +needs Retry. + +**Fixed:** [`f7607d039`](https://github.com/microsoft/vscode-documentdb/commit/f7607d039) +explains that the existing Dashboard retries automatically only when Reconnect opens it. +If it stays disabled, select **Retry**. + +## Remaining handoff requirements + +A second validation attempt could not verify its context tier or vendor and did not +review the changes. PR7 remains in draft until standard-context validation is confirmed. +Live query and ingestion verification remains pending for CP-5. + +Local Case 2 passed: formatting, localization check, lint, build, strict workspace +test type-checking, 9,963 tests across 444 suites (one skipped), and VSIX packaging. +No localization strings changed in PR7. diff --git a/docs/ai-and-plans/features/connection-lifecycle/telemetry.md b/docs/ai-and-plans/features/connection-lifecycle/telemetry.md new file mode 100644 index 000000000..fd9b2c274 --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/telemetry.md @@ -0,0 +1,140 @@ +--- +feature: connection-lifecycle +kind: notes +status: active +created: 2026-11-25 +--- + +# Connection lifecycle telemetry + +**Pending ingestion verification.** Run these queries in the extension's Application Insights Logs workspace. +Paste the common setup before any one query body. Set the actual extension version (including +the prerelease suffix for CP-5) and UTC window to inspect. + +```kusto +let StartAt = startofday(ago(7d)); +let EndAt = StartAt + 7d; +let ReleaseVersion = "1.2.0"; +let Events = + customEvents + | where timestamp >= StartAt and timestamp < EndAt + | extend version = coalesce(tostring(customDimensions["common.extversion"]), + tostring(customDimensions.extensionVersion), tostring(column_ifexists("application_Version", "")), "(missing)") + | where version == ReleaseVersion + | extend eventScope = tolower(extract(@"([^/]+)$", 1, name)), + sdkResult = tolower(tostring(customDimensions.result)); +let Operations = + Events + | extend parentContext = tostring(customDimensions.parentNodeContext) + | extend family = case( + eventScope == "connect", "connect", + eventScope startswith "documentdb.rpc.", "rpc", + (eventScope == "getchildren" or eventScope endswith ".getchildren") + and isnotempty(parentContext) and parentContext !~ "root", "getchildren", + "") + | where isnotempty(family) + | extend connectionResult = tolower(tostring(customDimensions.connectionResult)) + | extend operationResult = case( + sdkResult == "canceled" or connectionResult in ("canceled", "cancelled"), "canceled", + sdkResult == "failed" or connectionResult == "failed", "failed", + sdkResult == "succeeded" or connectionResult == "success", "succeeded", + "(missing)") + | extend ageMs = todouble(customMeasurements.connectionAgeMs), + generation = tolong(customMeasurements.clientGeneration), + failureKind = tostring(customDimensions.connectionFailureKind), + failureType = tostring(customDimensions.causeType), + recoveryRows = tostring(customDimensions.usedCachedErrorNode) =~ "true" + or tostring(customDimensions.cachedErrorNode) =~ "true" + | extend signature = case( + operationResult != "failed", "", + family != "rpc", "notClassified", + failureType in~ ("18", "391", "AuthenticationFailed", "Unauthorized", + "EntraSignInRequiredError", "EntraIdentityMismatchError"), "auth", + failureType in~ ("MongoNotConnectedError", "MongoTopologyClosedError"), "closedClient", + failureType in~ ("MongoNetworkError", "MongoNetworkTimeoutError", "ECONNRESET", "EPIPE"), "socket", + "otherOrUnclassified"); +``` + +## Daily database token lookups and lifetime + +`connection.tokenRenewal` counts post-startup Entra database token lookup outcomes. For `extension`, +`returned` means the token passed the host callback's checks. For `shell` and `playground`, it means +the host checked and sent a token response; the worker can still reject or discard it before its +callback completes. On any surface, `returned` does **not** mean the token changed, MSAL made a +network request, or the database accepted the token. Lifetime is the +JWT's positive `exp − iat` in seconds, not its remaining validity. An opaque or invalid lifetime is +missing, not zero. Compare returned rows with and without a lifetime; failures don't have one. + +```kusto +Events +| where eventScope == "connection.tokenrenewal" +| extend surface = coalesce(tostring(customDimensions.surface), "(missing)"), + outcome = coalesce(tostring(customDimensions.renewalOutcome), "(missing)"), + lifetime = todouble(customMeasurements.tokenLifetimeSeconds) +| extend lifetime = iff(lifetime > 0, lifetime, real(null)) +| summarize lookups = count(), + lifetimeSamples = countif(isnotnull(lifetime)), + missingLifetime = countif(isnull(lifetime)), + percentiles(lifetime, 50, 90) + by version, day = bin(timestamp, 1d), surface, outcome +| order by day asc, surface asc, outcome asc +``` + +This is background activity: exclude `connection.tokenrenewal` from active-use event scopes. +Expect roughly one lookup per active Entra client-hour, not one per operation. Use daily counts by +surface to check the observed volume against the telemetry budget. No lookups means no evidence. + +## Observed outcomes by client age and entry generation + +`successfulExpansionsEnteringGen2Plus` counts successful cluster expansions that reported +generation 2 or later **at entry** and did not return first-time or cached recovery rows. It +does not count an expansion that enters on generation 1 and replaces it during the operation. +Discovery expansions do not report a generation here. The count is neither unique recoveries nor +proof that renewal triggered them. Other operations are shown for context only: an RPC can return a +typed unavailable result without reporting an SDK failure. Missing ages and generations are shown +explicitly. + +```kusto +Operations +| extend ageBand = case( + isnull(ageMs) or ageMs < 0, "(missing)", + ageMs < 3600000, "<1h", ageMs < 7200000, "1–2h", ageMs < 14400000, "2–4h", "4h+"), + generationBand = case(isnull(generation) or generation < 1, "(missing)", generation == 1, "1", "2+"), + lifecycleKind = coalesce(failureKind, "(missing)") +| summarize operations = count(), + successfulExpansionsEnteringGen2Plus = countif( + family == "getchildren" and tolower(parentContext) matches regex @"\btreeitem_documentdbcluster\b" + and operationResult == "succeeded" and generation >= 2 and not(recoveryRows)) + by version, family, ageBand, generationBand, operationResult, lifecycleKind, signature +| order by family asc, ageBand asc, generationBand asc +``` + +## Cross-release comparison deferred + +In 1.2.0, a database RPC can return auth or closed-client unavailability as a normal +response, recorded as `Succeeded` without `causeType`. Older versions could report the same +outcome as an RPC failure. Matching procedures and signatures therefore does not make the +counts comparable. Use the queries here to describe a single release and verify ingestion, +not to claim that late failures fell. The comparison and any additional instrumentation are +deferred; see [decision 0020](./decisions.md#0020-defer-the-cross-release-comparison-of-late-failures). + +## ARM challenge versus final operation result + +Use the existing Azure SDK challenge dimensions and the final framework `result` on the **same** +event. A token was acquired when `challengeSuccess=true`; count `true` with `succeeded` separately +from `true` with `failed`, `canceled`, or a missing result. For a scope that wraps multiple requests +or both ARM and database work, this is the enclosing operation's result, not a per-request ARM +status. Use an ARM-only single-request scope when verifying that ARM accepted the retried request. +Zero observed challenges is inconclusive. + +```kusto +Events +| where tostring(customDimensions.challenge) =~ "true" +| extend challengeOutcome = tolower(tostring(customDimensions.challengeSuccess)) +| extend challengeOutcome = case(challengeOutcome == "true", "tokenAcquired", + challengeOutcome == "false", "noToken", "(missing)"), + finalResult = coalesce(sdkResult, "(missing)") +| summarize challengedOperations = count() + by version, day = bin(timestamp, 1d), eventScope, challengeOutcome, finalResult +| order by day asc, eventScope asc +``` diff --git a/docs/index.md b/docs/index.md index 0a2f4ef79..278519f84 100644 --- a/docs/index.md +++ b/docs/index.md @@ -85,6 +85,7 @@ The User Manual provides guidance on using the extension. It contains detailed d Explore the history of updates and improvements to the extension. Each release brings new features, enhancements, and fixes to improve your experience. +- [1.2 (unpublished draft)](./release-notes/1.2) - [1.1](./release-notes/1.1) - [1.0](./release-notes/1.0), [1.0.1](./release-notes/1.0#patch-release-v101), [1.0.2](./release-notes/1.0#patch-release-v102) - [0.11](./release-notes/0.11), [0.11.1](./release-notes/0.11#patch-release-v0111), [0.11.2](./release-notes/0.11#patch-release-v0112) diff --git a/docs/release-notes/1.2.md b/docs/release-notes/1.2.md new file mode 100644 index 000000000..24aa55459 --- /dev/null +++ b/docs/release-notes/1.2.md @@ -0,0 +1,83 @@ +--- +title: 'v1.2' +parent: 'Release Notes' +nav_order: 1020 +--- + +# DocumentDB extension for Visual Studio Code v1.2 + +> **Unpublished draft:** this page describes planned 1.2.0 behavior for review. It is not a +> statement that version 1.2 has shipped, and the text may change before release. + +Version 1.2 is planned to make database connections survive routine token renewal and idle drops, +while keeping open views safe when credentials, identities, or connection settings change. It also +adds an explicit Disconnect workflow with clear choices for open tabs. + +## What's New in v1.2 (draft) + +### ⭐ Connections That Stay Usable + +Microsoft Entra ID token renewal is planned to remain silent during normal use. The extension keeps +the connection pinned to the account and tenant that established it, including in the Interactive +Shell and Query Playground. Closed clients and recoverable transient failures can be replaced on a +later foreground operation without restarting VS Code. + +When silent sign-in is no longer possible, the extension asks for an explicit action at the surface +where work is happening. The tree offers **Retry sign-in**, while the shell and playground can offer +**Sign in again**. The operation never moves an existing session to a different Microsoft account. + +Azure discovery also renews its Azure Resource Manager credentials rather than retaining a frozen +token from an earlier provider tree. This work addresses +[#990](https://github.com/microsoft/vscode-documentdb/issues/990) and +[#1102](https://github.com/microsoft/vscode-documentdb/issues/1102). + +See [Keep connections usable](https://microsoft.github.io/vscode-documentdb/user-manual/connecting-to-databases#keep-connections-usable). + +### ⭐ Disconnect, Reconnect, and Keep Your Place + +Connected clusters gain a **Disconnect** action. Before ending live work, the extension asks what to +do with open view tabs: **Close all** or **Keep open (disabled)**. A setting can choose either +behavior in advance, while unsaved document changes still require explicit confirmation. + +Retained Collection View, Document View, and Cluster Dashboard contents stay available for +inspection or copying under a connection dialog. If **Reconnect** automatically opens the retained +Dashboard for the same connection, the Dashboard retries on its own. If it stays disabled, select +**Retry**, as you would in other retained webviews. Use **Close view** when the connection changed or +was removed. Retry does not replay the operation that failed. + +If a tracked copy, export, or import is using the cluster, the task and connection keep running. +Select **Disconnect** again after the task finishes or you stop it. The same teardown rules apply +when a saved connection is deleted, with the additional step of removing its saved +connection and cached credentials. See +[#566](https://github.com/microsoft/vscode-documentdb/issues/566) and +[#1059](https://github.com/microsoft/vscode-documentdb/issues/1059). + +Learn how retained views, shells, and playgrounds resume in the +[connection lifecycle guide](https://microsoft.github.io/vscode-documentdb/user-manual/connecting-to-databases#disconnect-and-reconnect). + +### ⭐ Open Work Stays Bound to Its Original Connection + +Saving changes with **Update Credentials…** or **Update Connection String…**, even just a password, +permanently disables operations in existing Collection View, Document View, and Cluster Dashboard +tabs. You can still copy their contents. Open a new view from the tree to use the saved settings. + +Shell and Playground are different: a Shell you choose to leave running can keep its previous +settings, and a restarted worker can use a password-only update without a new terminal or connection +pick. A different host, user, or identity requires a new Shell or an explicit Playground connection +pick. + +## Key Limits and Improvements + +- **No replay of uncertain writes.** Reconnecting or clicking Retry never resubmits the failed + operation. Check the server before repeating a write that did not report an outcome. +- **Resume in the same shell or playground.** After reconnecting with unchanged settings, run + again in the existing terminal or file. Scrollback and query text stay, but worker-local state + such as variables is lost. +- **Follow-up network work is outside this release.** Kubernetes tunnel recreation and broader + network resilience remain tracked in + [#1105](https://github.com/microsoft/vscode-documentdb/issues/1105). + +## Changelog + +See the unpublished draft entry for this release: +[CHANGELOG.md#120](https://github.com/microsoft/vscode-documentdb/blob/main/CHANGELOG.md#120-unreleased) diff --git a/docs/user-manual/connecting-to-databases.md b/docs/user-manual/connecting-to-databases.md index 64811b8cf..bbb754b92 100644 --- a/docs/user-manual/connecting-to-databases.md +++ b/docs/user-manual/connecting-to-databases.md @@ -26,3 +26,66 @@ The actions available depend on the connection and the failure: Retry is always last. These shorter labels apply to the recovery rows under a failed cluster; context-menu and Command Palette titles can differ. + +## Keep connections usable + +The extension normally recovers from an expired Microsoft Entra ID token or an idle connection +without restarting VS Code. Silent recovery uses the account and tenant that established the +connection. It does not open a sign-in prompt from a background refresh. + +If Microsoft sign-in can no longer be renewed, the tree offers **Retry sign-in**. The Interactive +Shell and Query Playground can instead offer **Sign in again**. Sign in with the identity originally +used for that connection. The old view is not moved to a different account. + +## Disconnect and reconnect + +Right-click a connected cluster and select **Disconnect** to end its live connections. If a copy, +export, or import is using the cluster, both the task and connection keep running. Select +**Disconnect** again after the task finishes or you stop it. + +When open connection views exist and the setting `documentDB.connections.openTabsOnDisconnect` is +`ask`, the **Disconnect?** modal offers: + +- **Close all**, which closes open connection views. Closing a dirty Document View first asks + whether to **Discard changes**. +- **Keep open (disabled)**, which keeps view contents but prevents database operations. + +This choice applies to Collection View, Document View, and Cluster Dashboard tabs. It does not close +the Interactive Shell terminal or the Query Playground file; Disconnect stops their database +workers. + +The setting can use `closeAll` or `keepOpenDisabled` as a default instead of showing the choice each +time. It never bypasses the unsaved-document confirmation. **Delete Connection…** uses the same +choice, but also removes the saved connection and its cached credentials. + +A retained Collection View, Document View, or Cluster Dashboard is covered by a dialog that explains +why it is unavailable: + +- Select **Retry** after repairing or reconnecting the connection. Retry checks the binding and + does not replay the operation that failed. +- Select **Close view** to close the tab. A dirty Document View warns before closing. +- Use the **X** to dismiss the dialog when you need to copy from the view. Database operations stay + disabled, and the next operation shows the dialog again. + +Use the cluster's **Reconnect** action in the tree to restore the same connection. If reconnect +automatically opens the retained Dashboard for that connection, it retries on its own. If it +stays disabled, select **Retry**, as you would in other retained webviews. + +After reconnecting to the same connection with unchanged settings, run a command in the existing +Interactive Shell or run the retained Query Playground again. No new terminal or connection pick +is needed. The terminal scrollback and Playground text remain, but worker-local state such as +variables and open cursors is lost. Interrupted commands are not replayed. + +## After changing connection details + +Saving a change with **Update Credentials…** or **Update Connection String…** permanently disables +database operations in the existing Collection View, Document View, and Cluster Dashboard tabs. +This includes a password-only edit. Their contents remain available for inspection or copying. +Select **Close view** and open a new view from the tree to use the saved settings. + +Shell and Playground follow different rules. If you choose to keep a running Shell connected when +prompted, its worker can continue using the previous settings. After a password-only edit, a new +worker can use the updated password in the existing terminal or Playground without a new connection +pick. To use a different host, user, or sign-in identity, open a new Shell or explicitly select the +connection again in the Playground. Cancelling an edit or saving unchanged settings does not lock +the open views. diff --git a/docs/user-manual/interactive-shell.md b/docs/user-manual/interactive-shell.md index 09ca684ab..cbb8ffcca 100644 --- a/docs/user-manual/interactive-shell.md +++ b/docs/user-manual/interactive-shell.md @@ -54,6 +54,9 @@ Type "help" for available commands. myDatabase> ``` +For token renewal, Microsoft sign-in recovery, Disconnect, and the limits of reusing an existing +shell after a connection change, see [Keep connections usable](./connecting-to-databases#keep-connections-usable). + ## Shell Commands The following built-in commands are available at the prompt: @@ -250,4 +253,4 @@ The help output also prints the full Settings search query for manual access. --- -> **Related**: [Query Playground](./query-playground) | [How It Works Behind the Scenes](./query-runtime) +> **Related**: [Query Playground](./query-playground) | [Connection lifecycle](./connecting-to-databases#keep-connections-usable) | [How It Works Behind the Scenes](./query-runtime) diff --git a/docs/user-manual/managing-azure-discovery.md b/docs/user-manual/managing-azure-discovery.md index d5c574d46..16d9d9214 100644 --- a/docs/user-manual/managing-azure-discovery.md +++ b/docs/user-manual/managing-azure-discovery.md @@ -178,3 +178,4 @@ When adding a new connection via the **"Add New Connection"** wizard: - [Azure Cosmos DB for MongoDB (RU) Service Discovery](./service-discovery-azure-cosmosdb-for-mongodb-ru) - [Azure DocumentDB Service Discovery](./service-discovery-azure-cosmosdb-for-mongodb-vcore) - [Azure VMs (DocumentDB) Service Discovery](./service-discovery-azure-vms) +- [Connection lifecycle, sign-in renewal, and teardown](./connecting-to-databases#keep-connections-usable) diff --git a/docs/user-manual/query-playground.md b/docs/user-manual/query-playground.md index a5bd3c7d4..de20d9cbd 100644 --- a/docs/user-manual/query-playground.md +++ b/docs/user-manual/query-playground.md @@ -38,6 +38,8 @@ There are several ways to open a new Query Playground: The three inline icons next to each collection node are (from left to right): Open Collection View, **New Query Playground**, and Open Interactive Shell. When a playground opens, a CodeLens header at the top displays the connection status, showing which cluster and database the file is connected to. +If the connection expires or is disconnected, see [Keep connections usable](./connecting-to-databases#keep-connections-usable) +for the exact sign-in and reconnect behavior. ## Writing Queries @@ -206,4 +208,4 @@ or use `.maxTimeMS()` on a supported query to set a server-side limit. --- -> **Related**: [Interactive Shell](./interactive-shell) | [How It Works Behind the Scenes](./query-runtime) +> **Related**: [Interactive Shell](./interactive-shell) | [Connection lifecycle](./connecting-to-databases#keep-connections-usable) | [How It Works Behind the Scenes](./query-runtime) diff --git a/src/commands/signInAgain/signInAgain.test.ts b/src/commands/signInAgain/signInAgain.test.ts index 9a179d04d..b6bffabc0 100644 --- a/src/commands/signInAgain/signInAgain.test.ts +++ b/src/commands/signInAgain/signInAgain.test.ts @@ -6,6 +6,7 @@ import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext-utils'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import * as vscode from 'vscode'; +import { type AuthCallerPolicy } from '../../documentdb/auth/authCallerPolicy'; import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; import { EntraIdentityMismatchError, @@ -25,7 +26,10 @@ const pin = { tenantId: 'tenant', } as const; const clusterId = 'cluster'; -const mocks = vi.hoisted(() => ({ configureAuth: vi.fn() })); +const mocks = vi.hoisted(() => ({ + configureAuth: vi.fn(), + capturePolicy: vi.fn<(policy: AuthCallerPolicy) => void>(), +})); vi.mock('../../documentdb/ClustersClient', () => ({ addEstablishedConnectionContext: vi.fn(), @@ -40,6 +44,10 @@ vi.mock('../../documentdb/ClustersClient', () => ({ vi.mock('../../documentdb/auth/entraSession', () => ({ getEntraSession: vi.fn() })); vi.mock('../../documentdb/auth/MicrosoftEntraIDAuthHandler', () => ({ MicrosoftEntraIDAuthHandler: class { + constructor(_credentials: unknown, policy: AuthCallerPolicy) { + mocks.capturePolicy(policy); + } + public async configureAuth( _timings: undefined, _trace: undefined, @@ -106,6 +114,28 @@ describe('signInAgain', () => { ); }); + it('observes renewal only for the client established by this sign-in', async (): Promise => { + vi.mocked(getEntraSession).mockResolvedValueOnce({ + account: { id: pin.accountId, label: pin.accountLabel }, + } as vscode.AuthenticationSession); + const getTokenLookupEpoch = vi.fn<() => number | undefined>(() => 1); + vi.mocked(ClustersClient.startAfterSignIn).mockImplementationOnce(async () => { + const [policy] = mocks.capturePolicy.mock.lastCall!; + expect(policy.getTokenLookupEpoch?.()).toBeUndefined(); + return { getTokenLookupEpoch } as unknown as ClustersClient; + }); + + await signInAgain(actionContext(), { clusterId }); + + const [policy] = mocks.capturePolicy.mock.lastCall!; + expect(policy.onTokenLookup).toBeTypeOf('function'); + expect(policy.getTokenLookupEpoch?.()).toBe(1); + getTokenLookupEpoch.mockReturnValue(2); + expect(policy.getTokenLookupEpoch?.()).toBe(2); + getTokenLookupEpoch.mockReturnValue(undefined); + expect(policy.getTokenLookupEpoch?.()).toBeUndefined(); + }); + it.each([undefined, new Error('User did not consent to login.')])( 'dismisses without reconnecting or retrying session acquisition', async (error): Promise => { diff --git a/src/commands/signInAgain/signInAgain.ts b/src/commands/signInAgain/signInAgain.ts index 4eba12306..aa5c6b6d5 100644 --- a/src/commands/signInAgain/signInAgain.ts +++ b/src/commands/signInAgain/signInAgain.ts @@ -13,6 +13,7 @@ import { } from '../../documentdb/auth/entraErrors/entraCallbackErrors'; import { getEntraSession } from '../../documentdb/auth/entraSession'; import { MicrosoftEntraIDAuthHandler } from '../../documentdb/auth/MicrosoftEntraIDAuthHandler'; +import { emitTokenRenewal } from '../../documentdb/auth/tokenRenewalTelemetry'; import { sameEntraIdentity } from '../../documentdb/auth/WorkerTokenRelay'; import { addEstablishedConnectionContext, ClustersClient } from '../../documentdb/ClustersClient'; import { classifyConnectionFailure } from '../../documentdb/connectionFailures'; @@ -120,10 +121,13 @@ async function signInAgainInternal( }; let starting = false; + let establishedClient: ClustersClient | undefined; try { const handler = new MicrosoftEntraIDAuthHandler(credentials, { interactive: false, pinnedEntraIdentity: identity, + getTokenLookupEpoch: () => establishedClient?.getTokenLookupEpoch(), + onTokenLookup: (observation) => emitTokenRenewal('extension', observation), }); const auth = await handler.configureAuth(undefined, undefined, async (request) => { if (!isCurrent()) { @@ -166,6 +170,7 @@ async function signInAgainInternal( reportClosed(); return undefined; } + establishedClient = client; if ( ClustersClient.getExistingClient(clusterId) === client && !ClustersClient.getLatchReason(clusterId) && diff --git a/src/documentdb/ClustersClient.test.ts b/src/documentdb/ClustersClient.test.ts index ac9f4e58d..d19919e2a 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -20,11 +20,13 @@ 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 * as tokenResource from './auth/documentdbTokenResource'; import { EntraIdentityMismatchError, EntraSignInRequiredError, TokenCallbackError, } from './auth/entraErrors/entraCallbackErrors'; +import * as entraSession from './auth/entraSession'; import { ManagedIdentityAuthHandler } from './auth/ManagedIdentityAuthHandler'; import { MicrosoftEntraIDAuthHandler } from './auth/MicrosoftEntraIDAuthHandler'; import { NativeAuthHandler } from './auth/NativeAuthHandler'; @@ -170,6 +172,7 @@ describe('regular connection startup diagnostics', () => { const mockToArray = vi.fn<() => Promise[]>>(); const mockDeleteMany = vi.fn<() => Promise>(); let poolEvents: EventEmitter; + const configureEntraAuth = MicrosoftEntraIDAuthHandler.prototype.configureAuth; function pauseNextConnect(): { started: Promise; resolve: () => void; reject: (error: Error) => void } { const started = deferred(); @@ -567,7 +570,7 @@ describe('regular connection startup diagnostics', () => { expect(authHandlerFactory.createAuthHandler).toHaveBeenLastCalledWith( AuthMethodId.MicrosoftEntraID, expect.objectContaining({ clusterId }), - { interactive: true }, + expect.objectContaining({ interactive: true }), ); expect(ClustersClient.getLastVerifiedIdentity(clusterId)).toEqual(verifiedIdentity); }); @@ -600,7 +603,7 @@ describe('regular connection startup diagnostics', () => { expect(authHandlerFactory.createAuthHandler).toHaveBeenLastCalledWith( AuthMethodId.MicrosoftEntraID, expect.objectContaining({ clusterId }), - { interactive: false, pinnedEntraIdentity: currentIdentity }, + expect.objectContaining({ interactive: false, pinnedEntraIdentity: currentIdentity }), ); expect(ClustersClient.getLastVerifiedIdentity(clusterId)).toBe(published); } @@ -1438,16 +1441,127 @@ describe('regular connection startup diagnostics', () => { const factory = vi.mocked(authHandlerFactory.createAuthHandler); expect(factory).toHaveBeenCalledTimes(1); - expect(factory).toHaveBeenCalledWith(authMethod, expect.objectContaining({ clusterId }), { + const policy = { interactive, - }); + ...(interactive + ? { getTokenLookupEpoch: expect.any(Function), onTokenLookup: expect.any(Function) } + : {}), + }; + expect(factory).toHaveBeenCalledWith(authMethod, expect.objectContaining({ clusterId }), policy); const handler = factory.mock.results[0]?.value as unknown; expect(handler).toBeInstanceOf(handlerClass); - expect(handler).toHaveProperty('policy', { interactive }); + expect(handler).toHaveProperty('policy', policy); expect(handlerClass.prototype.configureAuth).toHaveBeenCalledTimes(1); }, ); + it('counts completed Entra lookups on the current client, independent of database acceptance', async () => { + CredentialCache.setAuthCredentials( + clusterId, + AuthMethodId.MicrosoftEntraID, + 'mongodb://example.mongocluster.cosmos.azure.com/', + ); + vi.mocked(MicrosoftEntraIDAuthHandler.prototype.configureAuth).mockImplementation(configureEntraAuth); + vi.spyOn(tokenResource, 'resolveInteractiveTokenResource').mockResolvedValue({ + cloudCategory: 'public', + reason: 'host', + scope: 'test-scope', + resource: 'test-resource', + details: {}, + }); + vi.spyOn(entraSession, 'readEntraSignInEnvironment').mockReturnValue({ + providerId: 'microsoft', + cloudName: 'AzureCloud', + authority: 'https://login.microsoftonline.com/', + }); + const now = 1_800_000_000; + vi.setSystemTime(now * 1000); + const timedToken = `header.${Buffer.from(JSON.stringify({ iat: now - 600, exp: now + 3000 })).toString('base64url')}.signature`; + const account = { id: 'test-account', label: 'Test account' }; + const session = { id: 'test-session', account, accessToken: timedToken, scopes: [] }; + const getSession = vi.spyOn(entraSession, 'getEntraSession').mockResolvedValue(session); + const getCallback = (): NonNullable => { + const options = vi.mocked(MongoClient).mock.lastCall?.[1]; + const callback = options?.authMechanismProperties?.OIDC_CALLBACK; + if (!callback) { + throw new Error('Expected an OIDC callback'); + } + return callback; + }; + const params = { version: 1, timeoutContext: new AbortController().signal } as const; + const lookup = (): Promise => getCallback()(params); + const renewalEvents = (): RecordedTelemetry[] => + mockTelemetryEvents.filter(({ eventName }) => eventName === 'connection.tokenRenewal'); + const serverRejection = new MongoServerError({ code: 18, message: 'test server rejection' }); + + mockConnect.mockImplementationOnce(async () => { + await lookup(); + await lookup(); + throw serverRejection; + }); + await expect(ClustersClient.connectInteractive(clusterId)).rejects.toBe(serverRejection); + expect(renewalEvents()).toEqual([]); + + // Startup itself succeeds without calling the callback. Its first later callback counts. + const client = await ClustersClient.connectInteractive(clusterId); + expect(renewalEvents()).toEqual([]); + mockListDatabases.mockImplementationOnce(async () => { + expect(await lookup()).toEqual({ accessToken: timedToken, expiresInSeconds: 2999 }); + throw serverRejection; + }); + await expect(client.listDatabases()).rejects.toBe(serverRejection); + + vi.advanceTimersByTime(600_000); + getSession.mockResolvedValueOnce({ ...session, accessToken: 'opaque-test-token' }); + await expect(lookup()).resolves.toEqual({ accessToken: 'opaque-test-token' }); + getSession.mockResolvedValueOnce(undefined); + await expect(lookup()).rejects.toBeInstanceOf(EntraSignInRequiredError); + + await getCallback()({ ...params, timeoutContext: AbortSignal.abort() }); + expect( + renewalEvents().map(({ telemetry, error }) => [telemetry.properties, telemetry.measurements, error]), + ).toEqual([ + [ + { surface: 'extension', renewalOutcome: 'returned', result: 'Succeeded' }, + { tokenLifetimeSeconds: 3600, duration: 0 }, + undefined, + ], + [{ surface: 'extension', renewalOutcome: 'returned', result: 'Succeeded' }, { duration: 0 }, undefined], + [{ surface: 'extension', renewalOutcome: 'noSession', result: 'Succeeded' }, { duration: 0 }, undefined], + ]); + + const didStart = deferred(); + const finish = deferred(); + getSession.mockImplementationOnce(async () => { + didStart.resolve(); + await finish.promise; + return session; + }); + const spanningSave = lookup(); + await didStart.promise; + // An unchanged save latches and unlatches without retiring this client. + ClustersClient.latch(clusterId, 'credentialsUpdating'); + await lookup(); + ClustersClient.unlatch(clusterId); + finish.resolve(); + await spanningSave; + expect(renewalEvents()).toHaveLength(3); + expect(ClustersClient.getExistingClient(clusterId)).toBe(client); + + await lookup(); + expect(renewalEvents()).toHaveLength(4); + + const retiredLookup = getCallback(); + ClustersClient.reportFailure(client.binding, new MongoNotConnectedError('driver closed')); + await retiredLookup(params); + expect(await ClustersClient.getClient(clusterId)).not.toBe(client); + await retiredLookup(params); + const closedLookup = getCallback(); + await ClustersClient.deleteClient(clusterId); + await closedLookup(params); + expect(renewalEvents()).toHaveLength(4); + }); + it('passes its startup ID to auth configuration', async (): Promise => { let traceContext: AuthTraceContext | undefined; vi.mocked(MicrosoftEntraIDAuthHandler.prototype.configureAuth).mockImplementationOnce( diff --git a/src/documentdb/ClustersClient.ts b/src/documentdb/ClustersClient.ts index 7faae61a5..b4e960bba 100644 --- a/src/documentdb/ClustersClient.ts +++ b/src/documentdb/ClustersClient.ts @@ -51,6 +51,7 @@ import { createAuthHandler } from './auth/createAuthHandler'; import { EntraSignInRequiredError } from './auth/entraErrors/entraCallbackErrors'; import { getAzureHostSuffix } from './auth/oidcAllowedHosts'; import { readJwtTimes } from './auth/tokenExpiry'; +import { emitTokenRenewal } from './auth/tokenRenewalTelemetry'; import { QueryInsightsApis, type ExplainVerbosity } from './client/QueryInsightsApis'; import { isRetiredConnectionBinding, retireConnectionBindings } from './connectionBindingRetirement'; import { classifyConnectionFailure, type ConnectionFailure } from './connectionFailures'; @@ -633,6 +634,12 @@ export class ClustersClient { const authHandler = createAuthHandler(authMethod, credentials, { interactive: allowInteractive && !pinnedEntraIdentity, ...(pinnedEntraIdentity ? { pinnedEntraIdentity } : {}), + ...(authMethod === AuthMethodId.MicrosoftEntraID + ? { + getTokenLookupEpoch: () => this.getTokenLookupEpoch(), + onTokenLookup: (observation) => emitTokenRenewal('extension', observation), + } + : {}), }); // Configure auth and get connection options @@ -1135,6 +1142,17 @@ export class ClustersClient { return !this._closed && this._replacement === undefined; } + public getTokenLookupEpoch(): number | undefined { + if ( + !this.canReuse() || + ClustersClient.getExistingClient(this.clusterId) !== this || + ClustersClient.getLatchReason(this.clusterId) + ) { + return undefined; + } + return ClustersClient.getEpoch(this.clusterId); + } + public static hasReusableClient(clusterId: string): boolean { return ClustersClient._clients.get(clusterId)?.canReuse() ?? false; } diff --git a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts index 31061882a..a6713232a 100644 --- a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts +++ b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts @@ -284,7 +284,7 @@ describe('MicrosoftEntraIDAuthHandler', () => { const onTokenLookup = vi.fn(); const handler = new MicrosoftEntraIDAuthHandler( buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'), - { interactive: true, onTokenLookup }, + { interactive: true, getTokenLookupEpoch: () => 0, onTokenLookup }, ); const { options, verifiedIdentity } = await handler.configureAuth(undefined, { startupCorrelationId: 'startup-id', @@ -402,7 +402,7 @@ describe('MicrosoftEntraIDAuthHandler', () => { const onCallbackTokenObserved = vi.fn>(); const { options } = await new MicrosoftEntraIDAuthHandler( buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'), - { interactive: true, onTokenLookup, observer: { onCallbackTokenObserved } }, + { interactive: true, getTokenLookupEpoch: () => 0, onTokenLookup, observer: { onCallbackTokenObserved } }, ).configureAuth(); if (failure === 'providerChanged') { getConfiguredAuthProviderId.mockReturnValue('microsoft-sovereign-cloud'); @@ -477,7 +477,7 @@ describe('MicrosoftEntraIDAuthHandler', () => { const onTokenLookup = vi.fn(); const { options } = await new MicrosoftEntraIDAuthHandler( buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'), - { interactive: true, onTokenLookup }, + { interactive: true, getTokenLookupEpoch: () => 0, onTokenLookup }, ).configureAuth(); recordEntraTokenFailure('cluster-1', { cloudCategory: 'custom', authMethod: 'interactive' }); const priorFailure = getRecentEntraTokenFailure('cluster-1'); @@ -604,7 +604,7 @@ describe('MicrosoftEntraIDAuthHandler', () => { const onCallbackTokenObserved = vi.fn>(); const { options } = await new MicrosoftEntraIDAuthHandler( buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'), - { interactive: true, onTokenLookup, observer: { onCallbackTokenObserved } }, + { interactive: true, getTokenLookupEpoch: () => 0, onTokenLookup, observer: { onCallbackTokenObserved } }, ).configureAuth(); const cause = new Error('AADSTS65002: private-cause'); getSessionFromVSCode.mockRejectedValueOnce(cause); diff --git a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts index 671f5a530..edff7db94 100644 --- a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts +++ b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts @@ -3,6 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import { isUserCancelledError } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; import { randomUUID } from 'crypto'; import { type OIDCCallbackParams, type OIDCResponse } from 'mongodb'; @@ -31,16 +32,8 @@ import { clearEntraTokenFailure, recordEntraTokenFailure } from './entraErrors/e import { getEntraSession, readEntraSignInEnvironment, type EntraSignInEnvironment } 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; -} +import { jwtLifetimeSeconds, readJwtTimes } from './tokenExpiry'; +import { type EntraTokenLookupObservation } from './tokenRenewalTelemetry'; function assertEntraSignInEnvironment(expected: EntraSignInEnvironment | undefined): EntraSignInEnvironment { let current: EntraSignInEnvironment; @@ -69,13 +62,22 @@ function assertEntraSignInEnvironment(expected: EntraSignInEnvironment | undefin export class MicrosoftEntraIDAuthHandler implements AuthHandler { constructor( private readonly clusterCredentials: CachedClusterCredentials, - public readonly policy: EntraCallerPolicy = { interactive: true }, + public readonly policy: AuthCallerPolicy = { interactive: true }, ) {} private notify(notify: (observer: AuthPhaseObserver) => void): void { notifyAuthPhaseObserver(this.policy.observer, notify); } + private getTokenLookupEpoch(): number | undefined { + try { + return this.policy.onTokenLookup ? this.policy.getTokenLookupEpoch?.() : undefined; + } catch { + // Telemetry eligibility must not affect authentication. + return undefined; + } + } + public async configureAuth( timings?: ConnectionStartupTimings, traceContext?: AuthTraceContext, @@ -232,7 +234,7 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { callbackAuthMethod: AuthMethodId.MicrosoftEntraID, oidcCallback: async (_params: OIDCCallbackParams): Promise => { const currentInvocation = ++invocation; - let observation: EntraTokenLookupObservation = { outcome: 'failed' }; + let returned = false; try { assertEntraSignInEnvironment(signInEnvironment); let renewed: vscode.AuthenticationSession | undefined; @@ -246,27 +248,20 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { 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 } - : {}), - }; + const { expSec } = readJwtTimes(accessToken); + returned = true; return expSec === undefined ? { accessToken } : { accessToken, expiresInSeconds: Math.max(0, Math.floor(expSec - Date.now() / 1000)) }; } catch (error) { - if (error instanceof EntraSignInRequiredError) { - observation = { outcome: 'noSession' }; - throw error; - } - if (error instanceof EntraIdentityMismatchError || error instanceof EntraDestinationRejectedError) { + if ( + error instanceof EntraSignInRequiredError || + error instanceof EntraIdentityMismatchError || + error instanceof EntraDestinationRejectedError + ) { throw error; } recordEntraTokenFailure(clusterId, { @@ -280,26 +275,42 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { 'interactiveEntra.oidcCallback', { invocation: currentInvocation, - outcome: observation.outcome === 'returned' ? 'returned' : 'threw', + outcome: returned ? 'returned' : 'threw', }, authCorrelationId, traceContext, ); - try { - this.policy.onTokenLookup?.(observation); - } catch { - // Observers never change the auth flow. - } } }, }); const properties = configuration.options.authMechanismProperties; const callback = properties?.OIDC_CALLBACK; - if (this.policy.observer?.onCallbackTokenObserved && properties && callback) { + if ((this.policy.onTokenLookup || this.policy.observer?.onCallbackTokenObserved) && properties && callback) { properties.OIDC_CALLBACK = async (params): Promise => { + const lookupEpoch = this.getTokenLookupEpoch(); + const notifyLookup = (observation: EntraTokenLookupObservation): void => { + if ( + lookupEpoch !== undefined && + !params.timeoutContext?.aborted && + this.getTokenLookupEpoch() === lookupEpoch + ) { + try { + this.policy.onTokenLookup?.(observation); + } catch { + // Observers never change the auth flow. + } + } + }; try { // Report acquisition only after the configured callback re-checks destination trust. const response = await callback(params); + if (lookupEpoch !== undefined) { + const lifetimeSeconds = jwtLifetimeSeconds(readJwtTimes(response.accessToken)); + notifyLookup({ + outcome: 'returned', + ...(lifetimeSeconds !== undefined ? { lifetimeSeconds } : {}), + }); + } this.notify((observer) => observer.onCallbackTokenObserved?.({ outcome: 'acquired', @@ -309,6 +320,18 @@ export class MicrosoftEntraIDAuthHandler implements AuthHandler { ); return response; } catch (error) { + if ( + !isUserCancelledError(error) && + !(error instanceof TokenCallbackError && isUserCancelledError(error.cause)) + ) { + let outcome: EntraTokenLookupObservation['outcome'] = 'failed'; + if (error instanceof EntraSignInRequiredError) { + outcome = 'noSession'; + } else if (error instanceof EntraIdentityMismatchError) { + outcome = 'identityMismatch'; + } + notifyLookup({ outcome }); + } if ( error instanceof EntraSignInRequiredError || error instanceof EntraIdentityMismatchError || diff --git a/src/documentdb/auth/WorkerTokenRelay.ts b/src/documentdb/auth/WorkerTokenRelay.ts index 42f8e32be..b47b96b10 100644 --- a/src/documentdb/auth/WorkerTokenRelay.ts +++ b/src/documentdb/auth/WorkerTokenRelay.ts @@ -3,7 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { UserCancelledError } from '@microsoft/vscode-azext-utils'; +import { isUserCancelledError, UserCancelledError } from '@microsoft/vscode-azext-utils'; import { traceAuthFlow, traceEntraDestination, type AuthTraceContext } from '../../utils/authTrace'; import { ClustersClient } from '../ClustersClient'; import { @@ -30,6 +30,8 @@ import { import { clearEntraTokenFailure, recordEntraTokenFailure } from './entraErrors/entraTokenFailures'; import { getEntraSession, readEntraSignInEnvironment, type EntraSignInEnvironment } from './entraSession'; import { EntraDestinationRejectedError } from './oidcAllowedHosts'; +import { jwtLifetimeSeconds, readJwtTimes } from './tokenExpiry'; +import { emitTokenRenewal } from './tokenRenewalTelemetry'; export function sameEntraIdentity(a: VerifiedEntraIdentity, b: VerifiedEntraIdentity): boolean { return a.providerId === b.providerId && a.accountId === b.accountId && a.tenantId === b.tenantId; @@ -64,11 +66,12 @@ export class WorkerTokenRelay { ) {} async relay( - { requestId }: Extract, + { requestId, driverAbortFlag }: Extract, postResponse: (response: MainToWorkerMessage) => void, isCurrentWorker: () => boolean, timings?: ConnectionStartupTimings, trace?: AuthTraceContext, + postStartup = false, epoch = this.epoch, ): Promise { const isCurrentEpoch = (): boolean => @@ -85,8 +88,15 @@ export class WorkerTokenRelay { }; const activeTrace = (): AuthTraceContext | undefined => isCurrentWorker() && isCurrentEpoch() ? trace : undefined; - const { connectionString, authMechanism, tenantId, managedIdentityClientId } = this.init; + const { connectionString, authMechanism, tenantId, managedIdentityClientId, persistent } = this.init; const managed = authMechanism === 'ManagedIdentity'; + const abortFlag = + driverAbortFlag instanceof SharedArrayBuffer && driverAbortFlag.byteLength === Int32Array.BYTES_PER_ELEMENT + ? new Int32Array(driverAbortFlag) + : undefined; + const shouldObserve = (): boolean => + postStartup && authMechanism === 'MicrosoftEntraID' && (!abortFlag || Atomics.load(abortFlag, 0) === 0); + const surface = persistent ? 'shell' : 'playground'; const assertDestination = (): void => { const decision = evaluateEntraDestinationFromSettings(connectionString); traceEntraDestination(decision, requestId, activeTrace()); @@ -234,6 +244,12 @@ export class WorkerTokenRelay { clearEntraTokenFailure(this.clusterId); traceAuthFlow('workerTokenRelay.completed', { mode, outcome: 'returned' }, requestId, activeTrace()); postResponse({ type: 'tokenResponse', requestId, accessToken }); + if (shouldObserve()) { + emitTokenRenewal(surface, { + outcome: 'returned', + lifetimeSeconds: jwtLifetimeSeconds(readJwtTimes(accessToken)), + }); + } } catch (error) { if (!canReply()) { return; @@ -266,6 +282,15 @@ export class WorkerTokenRelay { ? { errorName: 'EntraDestinationRejectedError' as const } : {}), }); + if (shouldObserve() && !isUserCancelledError(error)) { + let outcome: 'noSession' | 'identityMismatch' | 'failed' = 'failed'; + if (reason === 'signInRequired') { + outcome = 'noSession'; + } else if (reason === 'identityMismatch') { + outcome = 'identityMismatch'; + } + emitTokenRenewal(surface, { outcome }); + } } }; diff --git a/src/documentdb/auth/authCallerPolicy.ts b/src/documentdb/auth/authCallerPolicy.ts index b357a2db2..a28b149f4 100644 --- a/src/documentdb/auth/authCallerPolicy.ts +++ b/src/documentdb/auth/authCallerPolicy.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import { type VerifiedEntraIdentity } from './AuthHandler'; +import { type EntraTokenLookupObservation } from './tokenRenewalTelemetry'; /** * Host-only callbacks that report the authentication phases in the order they really happen. @@ -44,6 +45,9 @@ export interface AuthCallerPolicy { readonly interactive: boolean; readonly pinnedEntraIdentity?: VerifiedEntraIdentity; readonly observer?: AuthPhaseObserver; + /** Entra only. Returns the current client epoch, or undefined if renewal telemetry is not eligible. */ + readonly getTokenLookupEpoch?: () => number | undefined; + readonly onTokenLookup?: (observation: EntraTokenLookupObservation) => void; } /** diff --git a/src/documentdb/auth/tokenExpiry.ts b/src/documentdb/auth/tokenExpiry.ts index 0d6f4dd7f..c279ff99f 100644 --- a/src/documentdb/auth/tokenExpiry.ts +++ b/src/documentdb/auth/tokenExpiry.ts @@ -27,6 +27,12 @@ export function readJwtTimes(token: string): { iatSec?: number; expSec?: number } } +/** The JWT's full lifetime, not its remaining validity or an opaque-token fallback. */ +export function jwtLifetimeSeconds({ iatSec, expSec }: ReturnType): number | undefined { + const lifetime = iatSec !== undefined && expSec !== undefined ? expSec - iatSec : undefined; + return lifetime !== undefined && Number.isFinite(lifetime) && lifetime > 0 ? lifetime : undefined; +} + /** * Seconds until an absolute expiry timestamp (milliseconds since the epoch), floored at zero. * diff --git a/src/documentdb/auth/tokenRenewalTelemetry.ts b/src/documentdb/auth/tokenRenewalTelemetry.ts new file mode 100644 index 000000000..56fe50753 --- /dev/null +++ b/src/documentdb/auth/tokenRenewalTelemetry.ts @@ -0,0 +1,32 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { callWithTelemetryAndErrorHandling } from '@microsoft/vscode-azext-utils'; + +export interface EntraTokenLookupObservation { + readonly outcome: 'returned' | 'noSession' | 'identityMismatch' | 'failed'; + readonly lifetimeSeconds?: number; +} + +export function emitTokenRenewal( + surface: 'extension' | 'shell' | 'playground', + { outcome, lifetimeSeconds }: EntraTokenLookupObservation, +): void { + void callWithTelemetryAndErrorHandling('connection.tokenRenewal', (context) => { + context.errorHandling.suppressDisplay = true; + context.telemetry.properties.surface = surface; + context.telemetry.properties.renewalOutcome = outcome; + if ( + outcome === 'returned' && + lifetimeSeconds !== undefined && + Number.isFinite(lifetimeSeconds) && + lifetimeSeconds > 0 + ) { + context.telemetry.measurements.tokenLifetimeSeconds = lifetimeSeconds; + } + }).catch(() => { + // Telemetry delivery must not affect authentication. + }); +} diff --git a/src/documentdb/playground/PlaygroundEvaluator.ts b/src/documentdb/playground/PlaygroundEvaluator.ts index f49b4fd87..d2f1c40ee 100644 --- a/src/documentdb/playground/PlaygroundEvaluator.ts +++ b/src/documentdb/playground/PlaygroundEvaluator.ts @@ -174,9 +174,16 @@ export class PlaygroundEvaluator implements vscode.Disposable { break; } }, - onTokenRequest: async (request, post, isCurrent, timings, trace) => { + onTokenRequest: async (request, post, isCurrent, timings, trace, postStartup) => { const relay = this._relay; - await relay?.relay(request, post, () => this._relay === relay && isCurrent(), timings, trace); + await relay?.relay( + request, + post, + () => this._relay === relay && isCurrent(), + timings, + trace, + postStartup, + ); }, onWorkerExit: (exitCode: number) => { ext.outputChannel.debug(`${logPrefix} Worker exited with code ${String(exitCode)}`); diff --git a/src/documentdb/playground/WorkerSessionManager.test.ts b/src/documentdb/playground/WorkerSessionManager.test.ts index 537b236af..5cc0c5bdb 100644 --- a/src/documentdb/playground/WorkerSessionManager.test.ts +++ b/src/documentdb/playground/WorkerSessionManager.test.ts @@ -1053,6 +1053,124 @@ describe('WorkerSessionManager', () => { return { manager, initPromise, requestId: initMessage.requestId, worker }; } + it.each([true, false])( + 'counts only checked post-startup Entra relay outcomes (persistent=%s)', + async (persistent) => { + const clusterId = 'test-cluster'; + const environment = { + providerId: 'microsoft', + cloudName: 'AzureCloud', + authority: 'https://login.microsoftonline.com/', + }; + const readEnvironment = vi + .spyOn(entraSession, 'readEntraSignInEnvironment') + .mockReturnValue(environment); + const resolveResource = vi.spyOn(tokenResource, 'resolveInteractiveTokenResource').mockResolvedValue({ + cloudCategory: 'public', + reason: 'host', + scope: 'test-scope', + resource: 'test-resource', + details: {}, + }); + const account = { id: 'test-account', label: 'Test account' }; + const now = 1_800_000_000; + vi.setSystemTime(now * 1000); + const accessToken = `header.${Buffer.from(JSON.stringify({ iat: now - 60, exp: now + 3540 })).toString('base64url')}.signature`; + const session = { id: 'test-session', account, accessToken, scopes: [] }; + const getSession = vi.spyOn(entraSession, 'getEntraSession').mockResolvedValue(session); + const relay = new WorkerTokenRelay( + clusterId, + { + type: 'init', + requestId: '', + connectionString: 'mongodb://example.mongocluster.cosmos.azure.com/', + clientOptions: {}, + databaseName: 'test', + authMechanism: AuthMethodId.MicrosoftEntraID, + persistent, + }, + ClustersClient.getEpoch(clusterId), + 'relay-id', + undefined, + ); + const onTokenRequest = vi.fn>( + relay.relay.bind(relay), + ); + callbacks.onTokenRequest = onTokenRequest; + const manager = new WorkerSessionManager(callbacks); + try { + const active = await startWorker(persistent, {}, manager); + const request = async (requestId: string): Promise => { + active.worker._emit('message', { type: 'tokenRequest', requestId }); + await onTokenRequest.mock.results.at(-1)?.value; + }; + const renewalEvents = (): RecordedTelemetry[] => + mockTelemetryEvents.filter(({ eventName }) => eventName === 'connection.tokenRenewal'); + await request('startup-lookup'); + await request('another-startup-lookup'); + expect(renewalEvents()).toEqual([]); + active.worker._emit('message', { type: 'initResult', requestId: active.requestId, success: true }); + await active.initPromise; + + await request('renewal-with-lifetime'); + getSession.mockResolvedValueOnce({ ...session, accessToken: 'opaque-test-token' }); + await request('opaque-renewal'); + getSession.mockResolvedValueOnce(undefined); + await request('missing-session'); + getSession.mockResolvedValueOnce({ ...session, account: { ...account, id: 'different-account' } }); + await request('identity-mismatch'); + readEnvironment.mockReturnValueOnce({ ...environment, providerId: 'microsoft-sovereign-cloud' }); + await request('provider-changed'); + getSession.mockRejectedValueOnce(new Error('test provider failure')); + await request('refresh-failed'); + getSession.mockRejectedValueOnce(new UserCancelledError()); + await request('canceled-lookup'); + const driverAbortFlag = new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT); + getSession.mockImplementationOnce(async () => { + Atomics.store(new Int32Array(driverAbortFlag), 0, 1); + return session; + }); + active.worker._emit('message', { + type: 'tokenRequest', + requestId: 'driver-stopped-waiting', + driverAbortFlag, + }); + await onTokenRequest.mock.results.at(-1)?.value; + ClustersClient.invalidate(clusterId); + await expect(request('stale-lookup')).rejects.toBeInstanceOf(UserCancelledError); + + const surface = persistent ? 'shell' : 'playground'; + expect( + renewalEvents().map(({ telemetry, error }) => [ + telemetry.properties, + telemetry.measurements, + error, + ]), + ).toEqual([ + [ + { surface, renewalOutcome: 'returned', result: 'Succeeded' }, + { tokenLifetimeSeconds: 3600, duration: 0 }, + undefined, + ], + [{ surface, renewalOutcome: 'returned', result: 'Succeeded' }, { duration: 0 }, undefined], + [{ surface, renewalOutcome: 'noSession', result: 'Succeeded' }, { duration: 0 }, undefined], + [ + { surface, renewalOutcome: 'identityMismatch', result: 'Succeeded' }, + { duration: 0 }, + undefined, + ], + [{ surface, renewalOutcome: 'noSession', result: 'Succeeded' }, { duration: 0 }, undefined], + [{ surface, renewalOutcome: 'failed', result: 'Succeeded' }, { duration: 0 }, undefined], + ]); + } finally { + manager.dispose(); + getSession.mockRestore(); + resolveResource.mockRestore(); + readEnvironment.mockRestore(); + } + }, + ); + it.each(['signInRequired', 'identityMismatch', 'destinationRejected', 'refreshFailed'] as const)( 'reconstructs %s at both boundaries and marks a warm worker broken', async (reason): Promise => { diff --git a/src/documentdb/playground/WorkerSessionManager.ts b/src/documentdb/playground/WorkerSessionManager.ts index ed9024eb2..eff101c29 100644 --- a/src/documentdb/playground/WorkerSessionManager.ts +++ b/src/documentdb/playground/WorkerSessionManager.ts @@ -102,6 +102,7 @@ export interface WorkerSessionCallbacks { isCurrent: () => boolean, timings?: ConnectionStartupTimings, traceContext?: AuthTraceContext, + postStartup?: boolean, ) => Promise; /** Called when the worker exits (crash or termination). */ onWorkerExit?: (exitCode: number) => void; @@ -757,6 +758,8 @@ export class WorkerSessionManager implements vscode.Disposable { isCurrent, this._startup?.costTimings, connection, + // Snapshot at receipt: time spent queued in the relay cannot make a startup lookup a renewal. + this._workerState === 'ready' || this._workerState === 'executing', ); } catch (error) { if (isCurrent()) { diff --git a/src/documentdb/playground/playgroundWorker.test.ts b/src/documentdb/playground/playgroundWorker.test.ts index 82fde16e9..a96836a19 100644 --- a/src/documentdb/playground/playgroundWorker.test.ts +++ b/src/documentdb/playground/playgroundWorker.test.ts @@ -128,11 +128,21 @@ describe('playground worker OIDC configuration at the driver boundary', () => { if (!callback) { throw new Error('Expected the OIDC callback'); } - const token = callback({ version: 1, timeoutContext: new AbortController().signal }); + const controller = new AbortController(); + const token = callback({ version: 1, timeoutContext: controller.signal }); const request = transport.postMessage.mock.calls .map((call) => call[0] as WorkerToMainMessage) .find((message) => message.type === 'tokenRequest'); expect(request).toBeDefined(); + if (authMechanism === 'MicrosoftEntraID') { + expect(request?.driverAbortFlag).toBeInstanceOf(SharedArrayBuffer); + const abortFlag = new Int32Array(request!.driverAbortFlag!); + expect(Atomics.load(abortFlag, 0)).toBe(0); + controller.abort(); + expect(Atomics.load(abortFlag, 0)).toBe(1); + } else { + expect(request?.driverAbortFlag).toBeUndefined(); + } receive({ type: 'tokenResponse', requestId: request!.requestId, 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 12673add2..a9c998d5b 100644 --- a/src/documentdb/playground/playgroundWorker.ts +++ b/src/documentdb/playground/playgroundWorker.ts @@ -208,17 +208,32 @@ async function handleInit(msg: Extract): connectionString, policy, baseOptions: options, - oidcCallback: async (): Promise<{ accessToken: string; expiresInSeconds: number }> => { + oidcCallback: async ({ timeoutContext }): Promise<{ accessToken: string; expiresInSeconds: number }> => { const requestId = randomUUID(); const tokenPromise = new Promise((resolve, reject) => { pendingTokenRequests.set(requestId, { resolve, reject }); }); + const driverAbortFlag = + !usesManagedIdentity && timeoutContext + ? new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT) + : undefined; + const abortFlag = driverAbortFlag && new Int32Array(driverAbortFlag); + const markAborted = (): void => { + if (abortFlag) Atomics.store(abortFlag, 0, 1); + }; + if (abortFlag) { + timeoutContext.addEventListener('abort', markAborted, { once: true }); + if (timeoutContext.aborted) { + markAborted(); + } + } const tokenRequest: WorkerToMainMessage = { type: 'tokenRequest', requestId, tenantId: msg.tenantId, source: usesManagedIdentity ? 'managedIdentity' : 'vscode', clientId: usesManagedIdentity ? msg.managedIdentityClientId : undefined, + ...(driverAbortFlag ? { driverAbortFlag } : {}), }; reportProgress('acquiringToken'); reportTiming('tokenWait', requestId, true); @@ -227,6 +242,9 @@ async function handleInit(msg: Extract): try { accessToken = await tokenPromise; } finally { + if (abortFlag) { + timeoutContext.removeEventListener('abort', markAborted); + } reportTiming('tokenWait', requestId, false); } reportProgress('authenticating'); diff --git a/src/documentdb/playground/workerTypes.ts b/src/documentdb/playground/workerTypes.ts index ddf017718..9d49b622b 100644 --- a/src/documentdb/playground/workerTypes.ts +++ b/src/documentdb/playground/workerTypes.ts @@ -229,6 +229,8 @@ export type WorkerToMainMessage = readonly source?: 'vscode' | 'managedIdentity'; /** Client ID of a user-assigned managed identity, when `source` is 'managedIdentity'. */ readonly clientId?: string; + /** One shared Int32 set to 1 if the driver stops waiting for this Entra lookup. Telemetry only. */ + readonly driverAbortFlag?: SharedArrayBuffer; } | { readonly type: 'log'; diff --git a/src/documentdb/shell/ShellSessionManager.ts b/src/documentdb/shell/ShellSessionManager.ts index 162accb07..ee35dd6de 100644 --- a/src/documentdb/shell/ShellSessionManager.ts +++ b/src/documentdb/shell/ShellSessionManager.ts @@ -140,14 +140,22 @@ export class ShellSessionManager implements vscode.Disposable { break; } }, - onTokenRequest: async (request, post, isCurrent, timings, trace) => { + onTokenRequest: async (request, post, isCurrent, timings, trace, postStartup) => { const relay = this._relay; // Warm Shells survive host-only invalidation. Fence each refresh at receipt; // startup still uses the epoch captured before opening the connection. const epoch = this._initialized ? ClustersClient.getEpoch(this._connectionInfo.clusterId) : relay?.epoch; - await relay?.relay(request, post, () => this._relay === relay && isCurrent(), timings, trace, epoch); + await relay?.relay( + request, + post, + () => this._relay === relay && isCurrent(), + timings, + trace, + postStartup, + epoch, + ); }, onWorkerExit: callbacks?.onWorkerExit, };