Skip to content

fix: clear stale metadataFetchErr on successful OAuth discovery fallback - #801

Merged
ezynda3 merged 4 commits into
mark3labs:mainfrom
MariaChrysafis:aklsdjfsdf
Apr 15, 2026
Merged

fix: clear stale metadataFetchErr on successful OAuth discovery fallback#801
ezynda3 merged 4 commits into
mark3labs:mainfrom
MariaChrysafis:aklsdjfsdf

Conversation

@MariaChrysafis

@MariaChrysafis MariaChrysafis commented Apr 14, 2026

Copy link
Copy Markdown
Contributor

Description

Clear metadataFetchErr when getDefaultEndpoints() fallback succeeds, so stale decode errors from earlier discovery attempts don't block OAuth.

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • MCP spec compatibility implementation
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Code refactoring (no functional changes)
  • Performance improvement
  • Tests only (no functional changes)
  • Other (please describe):

Checklist

  • My code follows the code style of this project
  • I have performed a self-review of my own code
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the documentation accordingly

Summary by CodeRabbit

  • Bug Fixes
    • Improved OAuth metadata discovery error handling to ensure error states are properly cleared when fallback endpoints are successfully resolved, preventing stale error conditions from affecting authentication reliability.

Summary by CodeRabbit

  • Bug Fixes
    • Prevented stale error state during OAuth/OIDC discovery so fallback authorization endpoints are determined reliably after multiple discovery attempts.
  • Tests
    • Added test ensuring discovery robustly handles non-JSON (HTML) responses from authorization server endpoints and derives safe default endpoints.

@mark-iii-labs-huly

Copy link
Copy Markdown

Connected to Huly®: MCP_G-368

@coderabbitai

coderabbitai Bot commented Apr 14, 2026

Copy link
Copy Markdown
Contributor

Walkthrough

Clearer metadata error handling: OAuthHandler.getServerMetadata now clears h.metadataFetchErr (h.metadataFetchErr = nil) immediately after successful metadata resolution on multiple fallback/default paths so the error flag only reflects outstanding failures.

Changes

Cohort / File(s) Summary
OAuth handler
client/transport/oauth.go
On several fallback/endpoint-assignment branches, set h.metadataFetchErr = nil after successful resolution so prior discovery errors are not retained.
OAuth tests
client/transport/oauth_test.go
Added TestOAuthHandler_GetServerMetadata_AuthServerReturnsHTML to ensure HTML responses at .well-known endpoints do not poison discovery and default authorize/token/register endpoints are derived from the auth server URL.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

Suggested labels

type: bug

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Title check ❓ Inconclusive The title 'fix' is vague and generic, providing no meaningful information about what is being fixed or which component is affected. Replace with a more descriptive title that indicates the specific issue, such as 'Clear stale OAuth metadata fetch errors on successful fallback' or 'Fix OAuth metadata discovery being poisoned by stale errors'.
✅ Passed checks (2 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Description check ✅ Passed The description provides clear context about the bug, root cause, and solution. Most required sections are incomplete or unchecked, but the core information is present.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

❤️ Share

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

@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 the current code and only fix it if needed.

Inline comments:
In `@client/transport/oauth.go`:
- Line 406: When a discovery path succeeds you must clear any prior error so
stale errors don't persist; ensure every success branch that assigns
h.serverMetadata (including the OpenID discovery success branch that currently
sets h.serverMetadata but can still return the old h.metadataFetchErr) also sets
h.metadataFetchErr = nil. Locate the success branches in the function handling
discovery (where h.serverMetadata is assigned during OAuth and OpenID discovery)
and add h.metadataFetchErr = nil immediately after assigning h.serverMetadata so
all successful discovery paths uniformly clear the error.
🪄 Autofix (Beta)

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: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 15a181cc-4a69-40bd-834c-dee17f787a2a

📥 Commits

Reviewing files that changed from the base of the PR and between c99de0d and 75441a7.

📒 Files selected for processing (1)
  • client/transport/oauth.go

Comment thread client/transport/oauth.go

@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.

🧹 Nitpick comments (1)
client/transport/oauth_test.go (1)

1389-1434: Convert this new scenario to table-driven test format.

The case is good, but this new test should follow the repo’s tests := []struct{ name, ... } pattern for consistency and easier future expansion.

As per coding guidelines, "Write table-driven tests using a tests := []struct{ name, ... } pattern".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@client/transport/oauth_test.go` around lines 1389 - 1434, The test
TestOAuthHandler_GetServerMetadata_AuthServerReturnsHTML should be converted
into a table-driven test using the repository's tests := []struct{ name string;
... } pattern; refactor the function to define a tests slice (including this
scenario as one entry with a descriptive name), loop over tests with
t.Run(tc.name, func(t *testing.T){...}), and move the setup of authServer,
mcpServer, OAuthConfig, handler (NewOAuthHandler, SetBaseURL) and the call to
handler.GetServerMetadata into the per-test subtest body so the same scaffolding
can be reused and additional cases added consistently. Ensure each subtest uses
require/ assert as before and preserves the same assertions for
metadata.AuthorizationEndpoint, TokenEndpoint, and RegistrationEndpoint.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@client/transport/oauth_test.go`:
- Around line 1389-1434: The test
TestOAuthHandler_GetServerMetadata_AuthServerReturnsHTML should be converted
into a table-driven test using the repository's tests := []struct{ name string;
... } pattern; refactor the function to define a tests slice (including this
scenario as one entry with a descriptive name), loop over tests with
t.Run(tc.name, func(t *testing.T){...}), and move the setup of authServer,
mcpServer, OAuthConfig, handler (NewOAuthHandler, SetBaseURL) and the call to
handler.GetServerMetadata into the per-test subtest body so the same scaffolding
can be reused and additional cases added consistently. Ensure each subtest uses
require/ assert as before and preserves the same assertions for
metadata.AuthorizationEndpoint, TokenEndpoint, and RegistrationEndpoint.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 95f12808-6bbc-4068-a9e0-b9938a54cf99

📥 Commits

Reviewing files that changed from the base of the PR and between 75441a7 and f900465.

📒 Files selected for processing (1)
  • client/transport/oauth_test.go

@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.

♻️ Duplicate comments (1)
client/transport/oauth.go (1)

422-422: ⚠️ Potential issue | 🟠 Major

Stale metadataFetchErr can still leak on successful OpenID discovery

Good partial fix, but this still fails when OAuth metadata decode fails first and OpenID discovery succeeds. At Line 475/Line 477, h.serverMetadata can be set while an old h.metadataFetchErr remains, so Line 490 still returns the stale error.

Proposed centralized fix
func (h *OAuthHandler) fetchMetadataFromURL(ctx context.Context, metadataURL string) {
@@
 	var metadata AuthServerMetadata
 	if err := json.NewDecoder(resp.Body).Decode(&metadata); err != nil {
 		h.metadataFetchErr = fmt.Errorf("failed to decode metadata response: %w", err)
 		return
 	}

 	h.serverMetadata = &metadata
+	h.metadataFetchErr = nil
}

Also applies to: 451-451, 487-487

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@client/transport/oauth.go` at line 422, When h.serverMetadata is assigned on
successful OpenID discovery, clear any previous h.metadataFetchErr so a stale
error cannot be returned later; update every code path that sets
h.serverMetadata (the discovery/parse success branches that currently assign
h.serverMetadata) to also set h.metadataFetchErr = nil immediately after the
assignment and do both updates while holding the same lock/mutex used for
metadata access to avoid races.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@client/transport/oauth.go`:
- Line 422: When h.serverMetadata is assigned on successful OpenID discovery,
clear any previous h.metadataFetchErr so a stale error cannot be returned later;
update every code path that sets h.serverMetadata (the discovery/parse success
branches that currently assign h.serverMetadata) to also set h.metadataFetchErr
= nil immediately after the assignment and do both updates while holding the
same lock/mutex used for metadata access to avoid races.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 3ba72806-dd5e-474e-aa06-19ac69791542

📥 Commits

Reviewing files that changed from the base of the PR and between f900465 and 172eece.

📒 Files selected for processing (2)
  • client/transport/oauth.go
  • client/transport/oauth_test.go
✅ Files skipped from review due to trivial changes (1)
  • client/transport/oauth_test.go

@MariaChrysafis MariaChrysafis changed the title fix fix: clear stale metadataFetchErr on successful OAuth discovery fallback Apr 14, 2026
@MariaChrysafis

Copy link
Copy Markdown
Contributor Author

@ezynda3

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