Repository navigation
[Fix] MCP OAuth sign-in can fail, never finish, or stay in the connecting state - #2762
zoomote[bot] wants to merge 8 commits into
Conversation
|
Important Review skippedBot user detected. To trigger a single review, invoke the
|
| Check name | Status | Explanation |
|---|---|---|
| Regression Evidence | Summary: No concrete test gap was found for the changed MCP OAuth, JSON file, and settings behavior in PR #2762 (Zoo-Code-Org/Zoo-Code, author zoomote[bot], head fix/mcp-oauth-signin-lifecycle, … |
|
| Security Boundaries | PR #2762 (Zoo-Code-Org/Zoo-Code, base main, head fix/mcp-oauth-signin-lifecycle) was checked against the Security boundaries criteria. I compared the local checkout (HEAD 9432908, one commit above ori… |
|
| Persistence Integrity | The check fails only when a changed persistence path can lose or corrupt state, and I found no such path that this PR introduces. Diff scope: the shallow clone has no merge base for main. The tree dif… | |
| Lifecycle Resource Cleanup | Result: PASS. I found no changed lifecycle path that can leak a listener, watcher, provider, timer, task, or other resource, or repeat work after cancellation, disposal, or restart. **Scope and ev… |
Full details: Regression Evidence
-
Explanation
Summary: No concrete test gap was found for the changed MCP OAuth, JSON file, and settings behavior in PR
#2762(Zoo-Code-Org/Zoo-Code, author zoomote[bot], headfix/mcp-oauth-signin-lifecycle, basemain). Diff limitation: The sandbox checkout is detached at a root commit (9432908) with no merge base withmain. The exact PR patch could not be computed. I checked the PR's changed modules in the current tree instead. The check does not require a full-diff failure, so this limit does not change the verdict. Evidence by changed behavior (tests at the lowest practical layer): - Callback port andredirect_uri:McpOAuthClientProvider.spec.tscovers the active listener port, a fresh client, and a configured callback. It also rejects unsafe callbacks. - Token refresh andinvalid_grant: The spec tests exact rejection (only a parsed HTTP 400invalid_grantdeletes data, lines ~1016–1021). It also tests keeping newer tokens saved by another window (line ~1346), theclient_secret_none/post/basicrequest forms with Basic encoding (lines ~182–238), and a refresh that is not attempted when stored data mismatches (line ~695). - Retry limit and backoff:McpHub.spec.tschecksOAUTH_TOKEN_RETRY_MAX_ATTEMPTS, the backoff sequence[1000, 2000, 4000], a fresh budget for a changed access token, and the connect-time retry path. - Flow ownership and cancellation:McpOAuthFlow.spec.tschecks one claimant, one completion, and timer clearing for each terminal outcome.mcp-oauth-flow.property.spec.tsandmcp-oauth-ownership.integration.spec.tsimport the realMcpHub,McpOAuthFlow, andMcpOAuthClientProvider. - Connected status before lists:McpHub.spec.ts(~3902) and the property spec (~704) check that the panel updates onconnectedand again when the lists arrive. - Tool abort:useMcpToolTool.spec.tschecks the abort callback forfalse,true, andfalsestates. - JSON file deletion and symlinks:jsonFileRecovery.test.ts(~138–153) checks deletion order, non-resurrection, and preservation of the canonical file on unlink failure.jsonFileLockIdentity.test.ts(~61–126) checks path-resolution errors anddelete/recoverthrough file and directory symlinks. It asserts the target is removed and the file symlink remains (line ~120). - Settings merge and installation:SimpleInstaller.spec.ts(~185–286) checks sibling preservation,nulland absentmcpServers, and removal.safeWriteJson.metadata.test.tschecks POSIX modes with symlinks. - Write-failure reasons:webviewMessageHandler.spec.ts(~3340–3362) checks the displayed error for delete, timeout, and toggle writes. It uses the project source path. It does not cover the global source. This is a minor gap, not a concrete regression case. -mcpEnabled:webviewMessageHandler.spec.ts(~1883–1942) checks both Boolean values through the real handler. - Default creation race:webviewMessageHandler.spec.ts(~3364–3384) checksSKIP_JSON_WRITEfor a competing file. Prior failure: The standing FAIL has no details. There are no specific claims to refute. I rechecked each behavior named in the PR description and found direct tests for them. The concern is therefore refuted on current evidence. Verdict: Every changed behavior I checked has direct tests that exercise the real implementation. The negative, error, and unset cases are covered for the paths I inspected. No visible UI snapshot gap applies, since the PR states no rendered webview change. The check does not fail. Prior failure refuted: The prior FAIL gave no specific claims. Current tree tests cover each changed behavior in the PR: callback port, OAuth refresh and invalid_grant, retry limit and backoff, flow ownership, connected-before-lists, tool abort, JSON symlink deletion, settings merge, write-failure reasons, mcpEnabled handler paths, and default-create race. No concrete test gap was found.
Full details: Security Boundaries
-
Explanation
PR
#2762(Zoo-Code-Org/Zoo-Code, base main, head fix/mcp-oauth-signin-lifecycle) was checked against the Security boundaries criteria. I compared the local checkout (HEAD 9432908, one commit above origin/main 4095df1) with origin/main. I did not find a concrete defect in a changed path that matches the three failure classes. Checks by failure class: 1. Exposed secrets or personal data - Refresh tokens stay inside the provider.tokens()now removesrefresh_tokenbefore the SDK sees the result (McpOAuthClientProvider.ts). - Refresh failures no longer put the HTTP response body into errors. Only the status is kept. - Added log lines name servers, sources, and retry counts. They do not print tokens or secrets. - Basic and post client credentials go only to token or registration endpoints. Those endpoints passassertSafeTokenEndpointfirst. 2. Unvalidated input that is trusted or executed - Token and registration requests useredirect: "manual". They also require HTTPS or loopback HTTP and reject URLs with embedded credentials. - Discovery rejects unsafe issuers. It also rejects a discoveredissuerthat does not match the requested issuer (oauth.ts). - The refresh token is sent only to the stored issuer. A mismatch defers the refresh and does not delete the credential. -openBrowseropens onlyhttp:orhttps:URLs. -safeWriteJsontakes anallowedRootoption. Project MCP writes from McpHub, SimpleInstaller, and the open-settings handler pass the workspace root.resolveFileLockPathresolves symlinks first, so a.roolink ormcp.jsonlink that points outside the workspace is rejected before any write. 3. Bypassed approval or allowlist controls -alwaysAllowanddisabledToolsstill use the same list update path. The change addsSet-based de-duplication and keeps the same add or remove logic. - The watcher wrapper serializes applies per source. It does not remove an approval check that I could find. - The project MCP auto-connect behavior is not changed by this diff. Non-security change noted:deleteJsonFilenow removes the resolved target of a symlink. Its only production caller is TaskHistoryStore. That caller builds paths from extension-generated task IDs under global storage, so no external input reaches the changed deletion path. The PR description records this as an accepted behavior change. Limits: the local HEAD is not the exact PR head commit, and the McpHub diff is large. I read the security-relevant hunks and the OAuth, file-write, and settings-write paths. I did not run tests.
Full details: Persistence Integrity
-
Explanation
The check fails only when a changed persistence path can lose or corrupt state, and I found no such path that this PR introduces. Diff scope: the shallow clone has no merge base for main. The tree diff
git diff main HEADgives the PR's changes (HEAD is 9432908, parent a39023a). I reviewed the persistence-related changes in that diff: -src/utils/safeWriteJson.ts: The write path resolves aliases, then takes the lock, then reads, merges, writes a temp file, and renames. The newSKIP_JSON_WRITEreturn happens inside thetry, so thefinallystill releases the lock. The mode is copied from the target, and the temp file is thenchmoded. TheallowedRootcheck throws before any write. -src/utils/fileLock.ts:withFileLockreturns the operation result or error fromtry/finally. A release failure is only logged. -src/utils/jsonFileRecovery.ts:deleteJsonFilenow unlinks the resolved target, not the symlink. This is a documented behavior change, andTaskHistoryStoreis its only production caller. It deletes the data that the user chose to delete, and the link is left dangling. Later writes recreate the target throughresolveFileLockPath. I do not treat this as loss of state the user did not request. -src/services/mcp/McpHub.ts:McpSettingsDocumentSchemais.passthrough(), and unknown server fields are kept asrecord(unknown), so sibling servers and unknown keys survive.applyServerConfigMutationupdates the in-memory config only aftersafeWriteJsonsucceeds.applyServerDeletionskips the write when the server is absent.withConfigOperationserializes same-source work, and it does not nest queues in a way that deadlocks. The oldupdateServerConfigon main dropped unknown top-level keys; the new one keeps them. -src/services/marketplace/SimpleInstaller.ts: The install merge fails closed on a malformed existing file. It accepts a null or absentmcpServers.removeMcpskips the write when the server is absent. -src/core/webview/webviewMessageHandler.ts:mcpEnabledis saved before the Hub refresh, and the save is awaited.openProjectMcpSettingsnow uses a merge callback that keeps a parsed competing file. A malformed competing file created in a very short race window is still replaced by{mcpServers:{}}. Main had no merge at all, so this race existed before the PR. The PR narrows it and does not introduce it. The PR description also states this residual race. -src/services/mcp/McpOAuthClientProvider.tsandSecretStorageService.ts: A refresh deletes stored credentials only after a parsed HTTP 400invalid_grant, and only when the stored refresh token still matches. Temporary failures keep the credential. A refresh save is rejected when the stored refresh token changed or disappeared, so a sign-out is not undone by an in-flight refresh. Theresource_indicatorandclient_infofields are restored on save. The SecretStorage cross-window race is acknowledged in the PR and is not a changed-code defect. I found no unawaited write in the changed paths. Thevoidcalls I checked are teardown, listener, or read-only calls. The discarded rotated refresh token and the symlink-target deletion are intentional behavior changes, not defects that cause loss in an unrequested case. I did not run the test suite. This verdict is based on static inspection of the current tree and the diff.
Full details: Lifecycle Resource Cleanup
-
Explanation
Result: PASS. I found no changed lifecycle path that can leak a listener, watcher, provider, timer, task, or other resource, or repeat work after cancellation, disposal, or restart. Scope and evidence limits - PR
#2762(fix/mcp-oauth-signin-lifecycleintomain). The primary author iszoomote[bot]. The author does not affect this check. - HEAD9432908is a parentless snapshot. It has no merge base withorigin/main, and the PR basea39023af2fis not in the clone. I reviewed the PR head tree directly. I usedorigin/mainonly to tell PR-introduced code from pre-existing code. - Runtime behavior, real VS Code watcher delivery, and Windows symlink behavior were not exercised. Paths checked (all clean) -McpOAuthFlow.ts(new).finish()runs every cleanup once. Waiting timers clear on claim and on finish.addCleanupruns immediately on an ended flow. -McpHubOAuth flow ownership.oauthFlowsentries are removed in cleanup._initiateOAuthFlowdedupes by connection.performOAuthFlowand_runOAuthFlowrelease their SecretStorage subscriptions and cancellation listeners on finish..finally(() => flow.finish("failed"))guarantees that every flow ends. -deleteConnection,dispose, andreconnectOAuthConnection. Removal revisions andisCurrentOAuthConnectionstop stale setup. Watchers and transports close on removal. Watchers started during setup are removed by dispose or by a later removal. -connectToServerabort branches (!isCurrentAttempt,isDisposed, and catch) close the transport, client, andpendingAuthProvider. -McpOAuthClientProvider.close()cancels and stops the listener and awaits_listenerCleanup. Startup and close are serialized through_ensureServerPromise._sharedRefreshesentries are deleted infinally. -callbackServer.ts. The timeout is cleared on every settle path. ThestopCallbackServerchange clears its timer in the close callback. -withConfigOperationandwithFileLock/acquireFileLock. Queue entries are removed. I found no reentrant nesting that could deadlock. -safeWriteJsonanddeleteJsonFile. Locks release infinally, andacquireFileLockhas one caller. -callTooland the newisAbortedcheck. Concurrent 401 handlers join one flow. The base already awaited the sign-in flow incallTool, so the wait is not new. Observations, not failures -Task.ts(attemptApiRequest, about lines 6134–6151). The newabortPromiseadds anabortlistener that is not removed when the first chunk wins the race. The repo'sraceAborthelper removes its listener. The listener is per-request. The request'sAbortControlleris cleared at stream completion (line 4917), so the listener does not accumulate. The same pattern already exists at line 6122 on origin/main. This is a non-blocking hygiene item. -_streamDataToFiledoes not destroy the write stream on a stringify error. This code is unchanged from origin/main, so it is pre-existing. -watchProjectMcpFileandwatchMcpSettingsFilepush new disposables without removing old ones. This is also pre-existing.
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Review statusThis PR was opened by an automated account. A human maintainer must verify the change intent, provenance, and validation before merging. Current step: Required CI passed. Waiting for automated review of the latest commit. If automated review does not start, a maintainer must restart it. Review-state labels are managed by this workflow; do not edit them manually. |
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
Changed-code mutation testingReport for PR head
Details: mutants, guidance, and reproductionChanged-code mutation testing
Focused tests
Reproduce locallyFrom a full checkout containing both commits: Mutation reports
The workflow uploads generated reports in the Advisory findings
|
…loop, and stale panel status
852856e to
4c1811f
Compare
ea6bdad to
293de2b
Compare
Related GitHub Issue
Closes: #2761
Description
MCP OAuth sign-in could use callback port 0, remain pending, or leave a server in the connecting state.
This PR updates sign-in ownership, token refresh, settings writes, and shared JSON file operations.
McpOAuthFlowto own timers, subscriptions, cancellation, and completion. Stop stale continuations after connection removal or replacement. Keep an error row when cancellation stops a reconnect.none,client_secret_post, andclient_secret_basicfor token requests. Encode Basic client credentials before Base64 encoding.invalid_grant, if the stored refresh token still matches.mcpServersduring installation. Report removal failures and skip absent-server writes.resolveFileLockPath()for JSON writes, deletion, and recovery. Preserve POSIX file modes and follow file aliases, including missing targets. Use one lock cleanup block that preserves the operation result or error. These shared utility changes affect all callers, beyond MCP settings.File symlink deletion:
deleteJsonFile()now removes the resolved target file and leaves the symlink in place.Previously, it removed the symlink. The link can therefore point to a missing target after deletion.
TaskHistoryStoreis the only production caller.Accepted config queue delay: initial loads and watcher applies hold each source queue through connection setup.
A disable or delete for that source waits until all server setup finishes or times out.
A slow server can delay these actions until connection setup finishes or times out.
This delay is accepted. The serialization prevents older watcher work from restoring newer settings.
Local review follow-up
Review findings #1, #2, and #4 through #14 have fixes or regression coverage in the local worktree.
These changes are based on
a39023af2fand are not pushed to this PR yet.mcpEnabledbefore the Hub refresh reads it. Check both Boolean values through the real message handler.SKIP_JSON_WRITEfor a parsed competing file during default creation. Keep its bytes and metadata unchanged.McpSettingsEntryPointsmodels setting order, startup ordering, default creation, visible errors, and unsafe registration.The review supplied these failures before the invariants. The model found no independent defect.
Native replay also required an error row when unsafe registration stops before transport creation.
The models check their stated scope. They do not prove the implementation correct.
The standalone
McpSettingsWritersstate-reduction refactor is removed from this PR worktree.Its patch is saved for a separate follow-up. This removal does not resolve the PR size finding.
Test Procedure
Local checks for the review follow-up, based on
a39023af2fplus uncommitted work:updateProjectMcpServersmutation that bypasses the source queue fails the new pending-apply assertion.ClineProvider.spec.tssuite and the new connect-time retry case.pnpm --dir src exec vitest related --run core/webview/webviewMessageHandler.ts services/mcp/McpHub.ts services/mcp/McpOAuthClientProvider.ts utils/safeWriteJson.ts.git diff --checkpassed.pnpm knipandpnpm knip:productionpassed. This narrow test and wording correction did not rerun them.McpSettingsEntryPointsandMcpSettingsWriters. Both fixed configurations passed, and all 11 failure configurations failed.McpSettingsApplygate passed. It was not changed in this correction.configInjectedto_initiateOAuthFlow. The new test rejects it after token retry exhaustion.The latest narrow correction leaves the malformed-JSON create race and fixed-English message localization unchanged.
The merge API returns
nullfor both missing files and malformed JSON.The unchanged-value
mcpEnabledreconnect behavior is outside this follow-up.The OAuth HTTP tests require local loopback listeners.
This run did not repeat the full repository suite, real VS Code watcher delivery, or macOS and Windows checks.
These local results do not state the current CI status.
Earlier checks recorded for
4724f2941739remain historical.They included 2,145 focused tests and an earlier full-suite report.
They do not validate the current PR head or this local follow-up.
The PR includes these TLA+ specs under
docs/architecture/tla/:McpOAuthRedirectUrl,McpOAuthFlowEnd,McpOAuthStatusHandoff,McpOAuthPanelSettle, andMcpConnectionOwnership.McpOAuthRetry,McpServerToggle, andMcpToolAbort.McpOAuthRefreshTokenandMcpCredentialOwnership.McpSettingsWriters,McpSettingsApply,McpSettingsInputs, andJsonWriteMetadata.The local follow-up adds
McpSettingsEntryPoints. Run its gate with:Each fixed configuration must pass. Each failure configuration must fail.
Recorded Stream (new provider only)
N/A — no new provider in this PR.
Pre-Submission Checklist
src/test-utils/,@/utils/test-utils) are used only for mechanical duplication; test intent and scenario-specific mocks remain visible.*.visual.tsxsnapshot inwebview-ui/. Seewebview-ui/AGENTS.md→ "When a UI change needs a snapshot".Visual Snapshots
No rendered webview state changes in this PR. The sign-in toast, progress bar, and server status labels keep their existing appearance; only their lifecycle timing and error text change. A committed
*.visual.tsxsnapshot therefore does not apply.Videos (interaction / animation only)
N/A — no new interactive flow, animation, or rendered state.
Documentation Updates
Additional Notes
PR size remains open (current review #3). The last measured full worktree had 928 changed executable lines in the extension mutation selector.
The limit is 500. A split or a maintainer-reviewed narrow exclusion is still required.
The size gate stops before a complete mutation result. The targeted replay is not a full mutation-diff pass.
The PR includes OAuth flow ownership, refresh protection, settings writers, and shared JSON utilities.
The suggested split seams are settings writers and toggles, and refresh token protection.
These seams have not been verified as independent PRs.
Refresh coordination covers providers that share one storage service in one window.
SecretStorage has no compare-and-swap operation. Separate windows can still race.
File alias checks assume stable symlinks during an operation.
The separate local verification did not exercise real VS Code watcher delivery or Windows symlink behavior.
Get in Touch
Discord: 0x7777777_
Related PRs