Skip to content

fix: gate verify-headers replay guard on pre-request pending_verification state, project needs_reauth over unstable, and block premature shared-OAuth completion - #5973

Merged
Pratham-Mishra04 merged 1 commit into
devfrom
08-08-fix_correct_per-user_mcp_state-projection_and_reauthorize_completion_bugs
Aug 8, 2026
Merged

fix: gate verify-headers replay guard on pre-request pending_verification state, project needs_reauth over unstable, and block premature shared-OAuth completion#5973
Pratham-Mishra04 merged 1 commit into
devfrom
08-08-fix_correct_per-user_mcp_state-projection_and_reauthorize_completion_bugs

Conversation

@Pratham-Mishra04

Copy link
Copy Markdown
Collaborator

Summary

Fixes two bugs in the MCP client verification and OAuth reauthorization flows:

  1. Verify-headers repair was permanently broken for already-verified per-user-headers clients. The concurrent-replay guard used a bare DiscoveredTools != nil check, which caused every legitimate admin-credential repair attempt to short-circuit before reaching the UpsertCredential step — leaving the credential permanently stuck at needs_update once a client had been verified once.

  2. Shared-OAuth reauthorization could complete prematurely. When an upstream/mock authorization server rejected a reauth request with a dead-end error page (instead of redirecting back via the OAuth callback), complete-oauth could still succeed using the stale credential already on file. The existing per-user-oauth freshness check (shared token presence) doesn't apply to shared-oauth clients, which always have an active token in flight during reauth.

Changes

  • isConcurrentVerifyReplay: Replaces the bare DiscoveredTools != nil guard with a two-condition check: a replay is only detected when the client was genuinely in pending_verification state at the start of the request AND the reloaded row now has tools. A client that was already verified (any other state) falls through to completion regardless of whether tools are present, ensuring the admin-credential retention step always runs during a repair.

  • isPrematureOAuthCompletion: Adds a freshness check for shared-OAuth reauthorization using the OAuth flow row rather than token status. TableOauthConfig.Status is write-once and never regresses once "authorized", so it can't distinguish a stale credential from a freshly-rotated one during a failed reauth. A flow row still in "pending" and not yet expired means the callback never ran, and completion is rejected with a 409 Conflict.

  • getMCPClientRuntimeState: Extracts a helper to read the live MCPConnectionState from the running manager for a single client by ID, since GetMCPClientConfigByID does not populate state (it is not a DB column).

  • projectPerUserAdminCredentialState: Extends the needs_reauth projection to also apply over Unstable runtime states, not just Healthy. A dead admin credential never self-heals, so needs_reauth is a more actionable signal than Unstable and must win. Disabled and PendingVerification still pass through unchanged.

  • Adds unit tests for isConcurrentVerifyReplay, isPrematureOAuthCompletion, and the updated projectPerUserAdminCredentialState projection cases.

Type of change

  • Bug fix

Affected areas

  • Transports (HTTP)

How to test

go test ./transports/bifrost-http/handlers/...
  • TestIsConcurrentVerifyReplay: verifies the three cases — genuine concurrent race, legitimate repair on an already-verified client, and first-time verification with no race.
  • TestIsPrematureOAuthCompletion: verifies nil flow, pending+unexpired (premature), pending+expired (abandoned), and failed flow rows.
  • TestProjectPerUserAdminCredentialState: verifies that Unstable with a dead admin credential projects to needs_reauth, Unstable with an active credential stays Unstable, and PendingVerification/Disabled pass through unchanged.

Breaking changes

  • No

Security considerations

The premature-OAuth-completion guard prevents a reauthorization from silently succeeding with a stale or broken credential when the upstream authorization server rejects the flow before the callback runs. Without it, an admin could believe reauth succeeded while the client continues operating on an invalid credential.

Checklist

  • I added/updated tests where appropriate
  • I verified builds succeed (Go and UI)

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

This was referenced Aug 8, 2026

Pratham-Mishra04 commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

This stack of pull requests is managed by Graphite. Learn more about stacking.

@coderabbitai

coderabbitai Bot commented Aug 8, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Summary by CodeRabbit

  • Bug Fixes

    • Improved header verification to distinguish legitimate credential repairs from concurrent replay attempts.
    • Prevented OAuth completion while an active browser authorization flow is still in progress.
    • Improved credential status reporting during unstable or pending verification states.
    • Ensured runtime state is refreshed after service discovery for more accurate connection handling.
  • Reliability

    • Added safeguards for expired, failed, and incomplete OAuth authorization flows.

Walkthrough

The MCP handler now distinguishes concurrent header-verification replays from credential repairs, blocks premature OAuth completion, and projects stale admin credentials as needs_reauth across selected runtime states. Table-driven tests cover these behaviors.

Changes

MCP verification lifecycle

Layer / File(s) Summary
Header verification replay handling
transports/bifrost-http/handlers/mcp.go, transports/bifrost-http/handlers/mcp_verifyheaders_replay_test.go
Header verification captures the initial runtime state and reloads the client after discovery. Replay rejection requires an initially pending state and newly discovered tools.
OAuth completion guard
transports/bifrost-http/handlers/mcp.go, transports/bifrost-http/handlers/mcp_oauth_premature_completion_test.go
Shared OAuth completion rejects active, unexpired admin authorization flows and allows expired or failed flows.
Credential state projection
transports/bifrost-http/handlers/mcp.go, transports/bifrost-http/handlers/mcp_peruser_state_projection_test.go
Stale admin credentials project unstable per-user OAuth and header clients to needs_reauth; active OAuth tokens preserve unstable state.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

Suggested reviewers: akshaydeo, danpiths, bearts

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the PR's main fixes, although it includes several related changes in one long sentence.
Description check ✅ Passed The description explains the bugs, changes, tests, affected area, security impact, and breaking-change status in the required structure.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch 08-08-fix_correct_per-user_mcp_state-projection_and_reauthorize_completion_bugs

Comment @coderabbitai help to get the list of available commands.

Pratham-Mishra04 commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

Merge activity

  • Aug 8, 10:33 AM UTC: A user started a stack merge that includes this pull request via Graphite.
  • Aug 8, 11:46 AM UTC: Graphite rebased this pull request as part of a merge.
  • Aug 8, 11:47 AM UTC: @Pratham-Mishra04 merged this pull request with Graphite.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@transports/bifrost-http/handlers/mcp.go`:
- Around line 497-504: Serialize initial header verification in the handler
before upstream discovery by atomically claiming the pending-verification
bootstrap state, so only one request can proceed to runtime activation and
credential retention. Ensure failed discovery or bootstrap releases the claim,
while successful verification persists the established tools and retained
headers; update the replay guard around isConcurrentVerifyReplay accordingly.
Add a concurrent handler test that makes both requests reload before the first
persistence and verifies the second cannot activate or retain credentials.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: a46b5b5a-bfa6-4818-a5b6-9d8b5800d7ca

📥 Commits

Reviewing files that changed from the base of the PR and between cbcaf6b and 6d002c3.

📒 Files selected for processing (4)
  • transports/bifrost-http/handlers/mcp.go
  • transports/bifrost-http/handlers/mcp_oauth_premature_completion_test.go
  • transports/bifrost-http/handlers/mcp_peruser_state_projection_test.go
  • transports/bifrost-http/handlers/mcp_verifyheaders_replay_test.go

Comment on lines +497 to +504
//
// Gated on isConcurrentVerifyReplay (not a bare DiscoveredTools != nil
// check): a client that wasn't pending_verification when this request
// started isn't racing another request's bootstrap, it's a legitimate
// repair of an already-verified client — that case must fall through
// and run to completion, or the admin credential (retained further
// below) could never be repaired once a client has been verified once.
if isConcurrentVerifyReplay(wasPendingVerificationBeforeThisRequest, clientConfig.DiscoveredTools != nil) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Serialize initial header verification.

If two requests start in pending_verification, both capture true. If both upstream discovery calls finish before either request persists DiscoveredTools, both reload rows without tools and bypass this guard. Both requests can then activate and persist different tool maps and retained admin headers. The later request wins without replay detection.

Atomically claim the bootstrap verification before discovery, and release the claim on failure. Do not let a second bootstrap request reach runtime activation or credential retention. Add a concurrent handler test that forces both requests to reload before the first persistence.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@transports/bifrost-http/handlers/mcp.go` around lines 497 - 504, Serialize
initial header verification in the handler before upstream discovery by
atomically claiming the pending-verification bootstrap state, so only one
request can proceed to runtime activation and credential retention. Ensure
failed discovery or bootstrap releases the claim, while successful verification
persists the established tools and retained headers; update the replay guard
around isConcurrentVerifyReplay accordingly. Add a concurrent handler test that
makes both requests reload before the first persistence and verifies the second
cannot activate or retain credentials.

@Pratham-Mishra04
Pratham-Mishra04 changed the base branch from 08-08-fix_persist_discovered_tools_before_triggering_cluster_propagation_in_verify-headers_verify-exchange_to_close_a_stale-read_race to graphite-base/5973 August 8, 2026 11:42
@Pratham-Mishra04
Pratham-Mishra04 changed the base branch from graphite-base/5973 to dev August 8, 2026 11:45
@Pratham-Mishra04
Pratham-Mishra04 requested a review from a team as a code owner August 8, 2026 11:45
@Pratham-Mishra04
Pratham-Mishra04 force-pushed the 08-08-fix_correct_per-user_mcp_state-projection_and_reauthorize_completion_bugs branch from 6d002c3 to 2e96e7f Compare August 8, 2026 11:45
@Pratham-Mishra04
Pratham-Mishra04 merged commit 8eeee78 into dev Aug 8, 2026
14 of 15 checks passed
@Pratham-Mishra04
Pratham-Mishra04 deleted the 08-08-fix_correct_per-user_mcp_state-projection_and_reauthorize_completion_bugs branch August 8, 2026 11:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants