Skip to content

Improve token exchange errors#4313

Merged
rajithacharith merged 1 commit into
thunder-id:mainfrom
thiva-k:fix-token-exchnage-errors
Jul 24, 2026
Merged

Improve token exchange errors#4313
rajithacharith merged 1 commit into
thunder-id:mainfrom
thiva-k:fix-token-exchnage-errors

Conversation

@thiva-k

@thiva-k thiva-k commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

Purpose

The token exchange grant returned a single generic Invalid subject_token for every subject-token failure, so a caller could not tell an expired token from an untrusted issuer or an audience mismatch (#3835, item 2). This PR attributes the reasons that are safe to disclose and reports them in the error_description, applying the same treatment to actor_token and to the jwt-bearer ID-JAG assertion.

Approach

  • Add three sentinel errors in the tokenservice package (ErrTokenExpired, ErrIssuerNotTrusted, ErrAudienceNotAccepted), named for the failure rather than the token that carried it so any validator in the package can return them. The validator wraps them with %w, so errors.Is classifies the failure while the underlying context stays in the server-side debug log.
  • Each grant handler owns its client-facing wording and OAuth2 error code: the token exchange handler branches on the sentinels for subject_token and actor_token (invalid_request); the jwt-bearer handler does the same for the assertion (invalid_grant). Any unattributed failure keeps the original generic description.
  • Disclosure is safe because the token endpoint is client-authenticated and the client already holds the token it presented. All descriptions comply with the RFC 6749 §5.2 error_description character set.
  • ValidateSubjectToken keeps its existing signature, so no interface or mock changes.

Related Issues

@thiva-k
thiva-k requested a review from ThaminduDilshan as a code owner July 24, 2026 04:23
@thiva-k thiva-k added trigger-pr-builder Add when the PR is ready for CI; starts the PR Builder for this and all later pushes Type/Improvement labels Jul 24, 2026
@coderabbitai

coderabbitai Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@thiva-k, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 12 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: c540e8e1-7619-4b9b-b2a5-88a43396485e

📥 Commits

Reviewing files that changed from the base of the PR and between 7b7ed80 and f5ec16d.

📒 Files selected for processing (7)
  • backend/internal/oauth/oauth2/granthandlers/jwt_bearer.go
  • backend/internal/oauth/oauth2/granthandlers/jwt_bearer_test.go
  • backend/internal/oauth/oauth2/granthandlers/token_exchange.go
  • backend/internal/oauth/oauth2/granthandlers/token_exchange_test.go
  • backend/internal/oauth/oauth2/tokenservice/error_constants.go
  • backend/internal/oauth/oauth2/tokenservice/validator.go
  • tests/integration/oauth/token/tokenexchange_test.go
📝 Walkthrough

Walkthrough

Changes

OAuth rejection reporting

Layer / File(s) Summary
Validation error classification
backend/internal/oauth/oauth2/tokenservice/error_constants.go, backend/internal/oauth/oauth2/tokenservice/validator.go
Adds sentinel errors and propagates them for expiration, untrusted issuers, and audience rejection.
Grant error mapping and coverage
backend/internal/oauth/oauth2/granthandlers/jwt_bearer.go, backend/internal/oauth/oauth2/granthandlers/token_exchange.go, backend/internal/oauth/oauth2/granthandlers/*_test.go
Maps assertion, subject-token, and actor-token validation failures to specific OAuth descriptions, with table-driven tests covering each reason and generic fallbacks.
Token exchange rejection contract
docs/content/guides/protocols/oauth-oidc/token-exchange.mdx, tests/integration/oauth/token/tokenexchange_test.go
Documents and verifies reason-specific token exchange rejection descriptions.

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

Sequence Diagram(s)

sequenceDiagram
  participant JWTBearerGrantHandler
  participant TokenExchangeGrantHandler
  participant TokenValidator
  participant OAuthClient
  JWTBearerGrantHandler->>TokenValidator: ValidateIDJAGAssertion
  TokenExchangeGrantHandler->>TokenValidator: ValidateSubjectToken or actor_token
  TokenValidator-->>JWTBearerGrantHandler: Classified validation error
  TokenValidator-->>TokenExchangeGrantHandler: Classified validation error
  JWTBearerGrantHandler-->>OAuthClient: invalid_grant with rejection description
  TokenExchangeGrantHandler-->>OAuthClient: invalid_request or server_error response
Loading

Possibly related PRs

Suggested reviewers: thamindudilshan, rajithacharith

🚥 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 Concise and specific; it clearly matches the main change to improve token exchange error reporting.
Description check ✅ Passed Covers Purpose, Approach, and Related Issues, but omits the checklist and security sections from the template.
✨ 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.

@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 `@backend/internal/oauth/oauth2/tokenservice/validator.go`:
- Around line 265-266: Extend validator_test.go to cover each new issuer,
audience, and expiry classification path, asserting errors.Is against the
corresponding sentinel error even when the underlying errors are mocked.
Preserve the existing validation setup and verify the returned errors retain the
expected sentinel classification.
🪄 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: b680b00c-9ff5-416e-890f-40c5402280fd

📥 Commits

Reviewing files that changed from the base of the PR and between 52141fb and 0680089.

📒 Files selected for processing (7)
  • backend/internal/oauth/oauth2/granthandlers/jwt_bearer.go
  • backend/internal/oauth/oauth2/granthandlers/jwt_bearer_test.go
  • backend/internal/oauth/oauth2/granthandlers/token_exchange.go
  • backend/internal/oauth/oauth2/granthandlers/token_exchange_test.go
  • backend/internal/oauth/oauth2/tokenservice/error_constants.go
  • backend/internal/oauth/oauth2/tokenservice/validator.go
  • docs/content/guides/protocols/oauth-oidc/token-exchange.mdx

Comment thread backend/internal/oauth/oauth2/tokenservice/validator.go
@thiva-k
thiva-k force-pushed the fix-token-exchnage-errors branch from 0680089 to 7b7ed80 Compare July 24, 2026 05:01

@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 `@docs/content/guides/protocols/oauth-oidc/token-exchange.mdx`:
- Around line 111-118: Revise the token rejection documentation around the
subject_token validation table to scope the invalid_request response to
token-validation failures only. Add a note that revocation enforcement being
unavailable causes the handler to return server_error instead, so the section
does not imply every rejected subject_token produces invalid_request.
🪄 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 708a4e3b-8432-4048-b84f-91a7d2d84fdf

📥 Commits

Reviewing files that changed from the base of the PR and between 0680089 and 7b7ed80.

📒 Files selected for processing (8)
  • backend/internal/oauth/oauth2/granthandlers/jwt_bearer.go
  • backend/internal/oauth/oauth2/granthandlers/jwt_bearer_test.go
  • backend/internal/oauth/oauth2/granthandlers/token_exchange.go
  • backend/internal/oauth/oauth2/granthandlers/token_exchange_test.go
  • backend/internal/oauth/oauth2/tokenservice/error_constants.go
  • backend/internal/oauth/oauth2/tokenservice/validator.go
  • docs/content/guides/protocols/oauth-oidc/token-exchange.mdx
  • tests/integration/oauth/token/tokenexchange_test.go
🚧 Files skipped from review as they are similar to previous changes (6)
  • backend/internal/oauth/oauth2/tokenservice/error_constants.go
  • backend/internal/oauth/oauth2/granthandlers/jwt_bearer.go
  • backend/internal/oauth/oauth2/tokenservice/validator.go
  • backend/internal/oauth/oauth2/granthandlers/jwt_bearer_test.go
  • backend/internal/oauth/oauth2/granthandlers/token_exchange_test.go
  • backend/internal/oauth/oauth2/granthandlers/token_exchange.go

Comment thread docs/content/guides/protocols/oauth-oidc/token-exchange.mdx Outdated
@thiva-k
thiva-k force-pushed the fix-token-exchnage-errors branch from 7b7ed80 to f5ec16d Compare July 24, 2026 05:11
@codecov

codecov Bot commented Jul 24, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.50746% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...nd/internal/oauth/oauth2/tokenservice/validator.go 91.66% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@rajithacharith
rajithacharith added this pull request to the merge queue Jul 24, 2026
Merged via the queue into thunder-id:main with commit 262de66 Jul 24, 2026
26 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

trigger-pr-builder Add when the PR is ready for CI; starts the PR Builder for this and all later pushes Type/Improvement

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants