Skip to content

Make secondary chain legs optionally non-fatal - #7311

Merged
rdimitrov merged 9 commits into
mainfrom
tgrunnagle/7310-non-fatal-secondary-legs
Nov 26, 2026
Merged

rdimitrov merged 9 commits into
mainfrom
tgrunnagle/7310-non-fatal-secondary-legs

Conversation

@tgrunnagle

@tgrunnagle tgrunnagle commented Nov 25, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Today any failed leg of a multi-upstream chain ends the whole authorization. A user who cancels a secondary provider's consent screen, or hits a secondary provider outage, gets no authorization code and loses every upstream, the identity provider included. Embedders that already present a missing upstream in-band (for example a connect link in a tool-call response) can complete the authorization without the failed leg.
  • Adds an opt-in authserver.Config.NonFatalSecondaryLegs. When set, a failed non-first leg is recorded as skipped, the walk continues to the next missing leg, and the authorization code is issued without the skipped leg. With the option unset, behaviour is unchanged.
  • This is a narrow first step toward vMCP: graceful degradation when one upstream IdP fails in multi-upstream auth #5162. It covers the walk only. Backend filtering and a retry endpoint stay with vMCP: graceful degradation when one upstream IdP fails in multi-upstream auth #5162.

Closes #7310

Type of change

  • Bug fix
  • New feature
  • Refactoring (no behavior change)
  • Dependency update
  • Documentation
  • Other (describe):

Test plan

  • Unit tests (task test)
  • E2E tests (task test-e2e)
  • Linting (task lint)
  • Manual testing (describe below)

Changes

File Change
pkg/authserver/config.go New Config.NonFatalSecondaryLegs, documented on the field
pkg/authserver/server_impl.go, pkg/authserver/server/provider.go Plumb the option to the handlers, mirroring DeviceFlowEnabled
pkg/authserver/storage/types.go, memory.go, redis.go New PendingAuthorization.SkippedUpstreams; memory clones it, Redis persists it as skipped_upstreams,omitempty
pkg/authserver/server/handlers/handler.go nextMissingUpstream passes over skipped legs; resolveChain rejects a first-leg pending that carries a chain or skipped legs, and on later legs validates the chain, then SkippedUpstreams via validateSkipped
pkg/authserver/server/handlers/callback.go Skip paths for an IdP error, a failed exchange or ID-token validation, and a failed authorization-URL build; completeChain and redirectToNextLeg extracted from continueChainOrComplete, which now loops
pkg/authserver/README.md, docs/arch/11-auth-server-storage.md Describe the option, what stays fatal, the stored skipped set, and the rolling-upgrade and rollback order
pkg/authserver/server/handlers/callback_nonfatal_legs_test.go, handler_chain_test.go, pkg/authserver/storage/pending_skipped_upstreams_test.go, pkg/authserver/server_impl_test.go, pkg/authserver/server/provider_test.go New and adjusted tests, including the option's plumbing

Does this introduce a user-facing change?

Only for embedders that set Config.NonFatalSecondaryLegs. It is not exposed through RunConfig or the operator CRDs.

  • Before: any failure on any leg ends the authorization with an error to the client, and no upstream tokens are usable by the client.
  • After, option set: these failures on a non-first leg are skipped and the client receives an authorization code without that leg's token: an error the IdP returns in place of a code, a failed code exchange or ID-token validation, and a failure to build the leg's authorization URL. Tokens stored by earlier legs are kept, and so is a credential an earlier authorization stored for the skipped leg. A skipped leg is not prompted again in the same walk. Each skip logs once at WARN with the provider name and a failure class (idp_error, code_exchange, identity_resolution, authorization_url). An IdP-error skip is also preceded by the existing "upstream IDP returned error" WARN.
  • After, option unset: no change.

These stay fatal whatever the option says: every first-leg failure, a missing/unknown/replayed state, a failed browser-binding check, the consent-stage check, a pending whose stored redirect URI cannot be parsed, an upstream provider that is not configured, and storage failures loading or storing the pending authorization.

Special notes for reviewers

  • Binding and state checks run before any skip decision. Skipping past them would let a forwarded callback URL complete someone else's authorization, so the IdP-error skip is taken only after validateAndConsumePending.
  • SingleLeg authorizations are never skipped. They have no chain, so skipping would issue a code with nothing connected.
  • A callback leg is skippable only when its pending has ResolvedUserID set. A callback that would establish the user is always fatal.
  • A failed authorization-URL build may be skipped even when the continuing pending is the first leg's, because the user's identity is already established by then.
  • "Upstream provider not found" (a configuration error) stays fatal on both the callback and the next leg. It is not in the issue's skippable list.
  • Exchange and URL-build error detail is logged at DEBUG on the skip path because it may echo the upstream's response. The WARN carries only the provider and failure class; a failed exchange is classed identity_resolution when the error wraps upstream.ErrIdentityResolutionFailed (nonce, ID-token or subject validation) and code_exchange otherwise, so operators can tell the two apart at the default level. The existing "upstream IDP returned error" WARN in handleUpstreamError is unchanged, so an IdP-error skip logs that line plus the skip line.
  • A first leg carries neither a chain nor skipped legs, so resolveChain rejects a first-leg pending that names either before the filter runs. On a later leg it validates the carried chain, then validateSkipped checks the skipped set against that chain: no first upstream, no outsiders, no duplicates. The skip WARN is logged only once the chain has validated, so a rejected pending leaves no skip record.
  • Any ExchangeCodeForIdentity error on a later leg is skippable, including a transient token-endpoint failure and a nonce or ID-token failure. This is deliberate: nothing is stored for the skipped leg, and identity comes only from the first leg, so the skip gains an attacker nothing.
  • Accepted trade-off: a skip leaves an earlier credential for the skipped provider in place, because deleting it could throw away a good refresh token on a transient failure. With the default session-keyed storage a skipped leg never has one. With storage that keeps credentials across authorizations (for example storage.UserKeyedUpstreamStorage), a kept credential the walk could not refresh still fails the whole session in TokenValidator and the refresh guard. That all-or-nothing behaviour is outside this PR and will be handled with the user-keyed storage work; the field doc and docs/arch state the caveat.
  • Rollout: an older replica drops skipped_upstreams and prompts the skipped leg again, and a replica with the option off still honours skips another replica recorded for the life of the pending. Both are documented in docs/arch/11 rather than changed: upgrade every replica before enabling the option, and turn it off and let in-flight authorizations drain before rolling back.
  • The issue names AC1.6's test TestValidateChain_RejectsInvalidSkippedUpstreams; it is TestResolveChain_RejectsInvalidSkippedUpstreams here because it exercises resolveChain, the path that rejects the pending. AC1.5's test is likewise TestCallback_NonFatalSecondaryLeg_UnskippableFailuresStayFatal, since it also covers SingleLeg, unresolved-user and tampered pendings.

Verification

At 00dbe6b, clean tree:

  • task lint-fix: exit 0, "0 issues."
  • task test: exit 0, no failures (grep for ❌ / build failed / --- FAIL = 0)

At 8a38d77 (review fixes), for ./pkg/authserver/...: go test -race exit 0 with no failures, golangci-lint run 0 issues, go vet exit 0.

At 873aedb (main merged in, README conflict resolved), for ./pkg/authserver/...: go test -race exit 0 with no failures, golangci-lint run 0 issues.

No pre-existing failures in the baseline. Build was not run separately; packages compile as part of the test run. E2E tests were not run.

Acceptance criteria:

  • AC1.1: TestCallback_NonFatalSecondaryLeg_IdPErrorSkipsTheLeg (leg 2 access_denied redirects to provider-3, then 303 with code)
  • AC1.2: TestCallback_NonFatalSecondaryLeg_ExchangeFailureCompletesTheChain (token-request and identity-validation failures), plus TestCallback_NonFatalSecondaryLeg_SkippedLegKeepsItsStoredToken for a skipped leg with an earlier credential
  • AC1.3: TestCallback_NonFatalSecondaryLeg_AuthorizeURLFailureSkips (3 cases, each asserting one skip WARN per failed leg)
  • AC1.4: TestNextMissingUpstream_IgnoresSkippedLegs
  • AC1.5: TestCallback_NonFatalSecondaryLeg_UnskippableFailuresStayFatal (also covers SingleLeg, a pending with no resolved user, and a corrupt stored redirect URI)
  • AC1.6: TestResolveChain_RejectsInvalidSkippedUpstreams (also covers first-leg pendings that carry a chain or skipped legs, and asserts the upstream filter never runs for a rejected pending)
  • AC1.7: TestCallback_SecondaryLegFailureIsFatalByDefault
  • AC1.8: TestCallback_NonFatalSecondaryLeg_IdPErrorSkipsTheLeg (asserts the walk's WARN lines and exactly one parsed skip record with level, msg, provider, failure_class); the exchange and authorization-URL tests assert their skip records too
  • AC2.1: TestPendingAuthorization_SkippedUpstreamsRoundTrip (memory and Redis)
  • DoD: task lint and task test pass; option documented on Config.NonFatalSecondaryLegs in pkg/authserver/config.go

🤖 Generated with Claude Code

tgrunnagle and others added 2 commits November 25, 2026 11:52
A user who cancels a secondary provider's consent screen, or meets a
secondary provider outage, loses the whole authorization today, the
identity provider included. Embedders that already offer a connect
link for a missing upstream can do better.

Add the opt-in authserver.Config.NonFatalSecondaryLegs. When set, an
IdP error, a failed code exchange, or a failure to build the
authorization URL on a non-first leg records that leg in the new
PendingAuthorization.SkippedUpstreams, logs one WARN, and continues
the walk; the authorization code is issued without the leg. The
first leg, state and browser-binding checks, and storage failures
stay fatal. Memory and Redis storage persist the new field, and
resolveChain rejects a skipped set that names the first upstream or
a name outside the carried chain.

Closes #7310

Co-Authored-By: Claude Opus 5.5 <[email protected]>
canSkipLeg excludes SingleLeg authorizations so a cancelled or failed
connect-one-backend flow never issues a code with nothing connected,
but no test pinned it. Add IdP-error and exchange-failure cases for a
SingleLeg pending on a later upstream with NonFatalSecondaryLegs set.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot added the size/L Large PR: 600-999 lines changed label Nov 25, 2026
@codecov

codecov Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.96970% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.36%. Comparing base (786be66) to head (873aedb).

Files with missing lines Patch % Lines
pkg/authserver/server/handlers/callback.go 97.33% 2 Missing ⚠️
pkg/authserver/server/handlers/handler.go 94.44% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #7311      +/-   ##
==========================================
- Coverage   82.39%   82.36%   -0.04%     
==========================================
  Files         936      936              
  Lines       95494    95567      +73     
==========================================
+ Hits        78680    78710      +30     
- Misses      16809    16852      +43     
  Partials        5        5              

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@tgrunnagle tgrunnagle left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review

This is a new opt-in feature (authserver.Config.NonFatalSecondaryLegs) plus the refactor of continueChainOrComplete it needs, with tests. The approach is sound. With the option unset, behaviour is unchanged.

  • Skip ordering. Every skip decision runs after validateAndConsumePending, so state, browser-binding, expiry and single-use checks stay fatal. An unknown or replayed state takes the not-found arm, where no pending exists to skip.
  • First leg and SingleLeg. The first (identity) leg can never be skipped. canSkipLeg excludes upstreams[0] and SingleLeg, and canSkipCallbackLeg also requires ResolvedUserID.
  • Termination. The new walk loop terminates, because each iteration adds one distinct non-first chain member that nextMissingUpstream then excludes.
  • SkippedUpstreams validation. SkippedUpstreams is validated on every consumer path through resolveChain, and both storage backends clone it on store and load.
  • Identity check. verifyChainIdentity still checks the first leg, which can never be skipped, before a code is issued.

All kept findings are LOW: log-line accounting for the IdP-error path, a stale doc comment, how resolveChain was restructured, and test gaps around the new guards.

Cross-cutting.

  • Docs. The option is embedder-only and off by default, so docs/ and docs/arch/ need no change beyond the README bullet and the field doc comment that ship here.
  • Size. The PR is about 300 non-test lines across 8 files, within the project's limits.
  • PR body. It states the deliberate narrowing (SingleLeg, ResolvedUserID, "provider not found" stays fatal).
  • Compatibility. The Redis field is omitempty, so pendings written before it load with nothing skipped.

Recommendation: approve once the author has weighed the findings below; none is a bug that would cause incorrect behavior, a security issue, or data loss on merge.

Findings

# Severity Finding Location Raised by
1 LOW An IdP error on a skipped leg logs two WARN lines, but the docs say "once" pkg/authserver/server/handlers/callback.go:783 correctness, readability, docs
2 LOW A skipped code-exchange failure loses its error detail at the default log level pkg/authserver/server/handlers/callback.go:231 security
3 LOW handleUpstreamError doc comment lists only the pre-change outcomes pkg/authserver/server/handlers/callback.go:782 (doc comment at 745-748) readability
4 LOW resolveChain is wrapped in an immediately-invoked closure to add one trailing check pkg/authserver/server/handlers/handler.go:636 readability, scope
5 LOW ResolvedUserID guard and ar != nil check have no test that would fail without them pkg/authserver/server/handlers/callback_nonfatal_legs_test.go:301 tests
6 LOW WARN assertions cover only the idp_error class pkg/authserver/server/handlers/callback_nonfatal_legs_test.go:213 tests
7 LOW No test for a skipped leg that already holds a stored token pkg/authserver/server/handlers/callback_nonfatal_legs_test.go:161 tests
8 LOW Two test names do not match what they assert, and one assertion is hard to read pkg/authserver/server/handlers/callback_nonfatal_legs_test.go:427 readability

How to test

  1. task test (or scope to pkg/authserver/...) and task lint: both should pass.
  2. Break the skip ordering: move the canSkipCallbackLeg branch in handleUpstreamError above validateAndConsumePending. The browser-binding case in TestCallback_NonFatalSecondaryLeg_BindingAndFirstLegFailuresStayFatal should fail.
  3. Remove the slices.Contains(skipped, name) check in nextMissingUpstream. TestNextMissingUpstream_IgnoresSkippedLegs and the IdP-error walk test should fail.
  4. Remove !pending.SingleLeg from canSkipLeg. The SingleLeg cases should fail.
  5. Remove pending.ResolvedUserID != "" from canSkipCallbackLeg. Nothing fails today, which is the test gap noted below.

Reviewed by dev:review-pr (finders: correctness, readability, security, tests, scope discipline, documentation). Generated with Claude Code.

tgrunnagle and others added 2 commits November 25, 2026 12:45
Addresses #7311 review comments:
- LOW callback.go:783 (4700545431): docs now say an IdP-error skip
  also carries the existing upstream-error WARN
- LOW callback.go:231 (4700545442): split identity_resolution from
  code_exchange so the WARN names the cause
- LOW callback.go:782 (4700545451): handleUpstreamError doc names
  the skip outcome
- LOW handler.go:636 (4700545461): validate SkippedUpstreams first
  in resolveChain instead of wrapping it in a closure

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Addresses #7311 review comments:
- LOW callback_nonfatal_legs_test.go:301 (4700545480): cases for a
  pending with no resolved user and a corrupt stored redirect URI
- LOW callback_nonfatal_legs_test.go:213 (4700545495): assert the
  skip WARN for code_exchange, identity_resolution and each
  authorization_url skip
- LOW callback_nonfatal_legs_test.go:161 (4700545509): a skipped
  leg keeps its earlier stored credential
- LOW callback_nonfatal_legs_test.go:427 (4700545515): rename tests
  to what they cover; count every WARN on the IdP-error walk

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/L Large PR: 600-999 lines changed size/XL Extra large PR: 1000+ lines changed labels Nov 25, 2026

@tgrunnagle tgrunnagle left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review

Incremental review of the 2 commits since 668baa70c. All eight findings from the previous review are resolved in the code (threads replied to and resolved). The new commits are targeted fixes and leave the approach unchanged.

Resolved since the last review

  • Two WARN lines on an IdP-error skip against "logged once" docs (pkg/authserver/config.go, pkg/authserver/README.md, logSkippedLeg): the docs and comments now describe the extra existing WARN, and the test asserts both messages.
  • Code-exchange failure detail at the default level (callback.go): exchangeFailureClass splits code_exchange from identity_resolution, and no token-request failure wraps upstream.ErrIdentityResolutionFailed.
  • handleUpstreamError doc comment (callback.go): now names the skip outcome.
  • resolveChain closure (handler.go): validateSkipped runs first and the original branches are untouched; no regression in which pendings are rejected.
  • Test gaps for the ResolvedUserID guard and ar != nil check, the WARN classes, and a skipped leg with a stored token: each new case fails if the guard it targets is removed.
  • Test names and the assertion closure: renamed, and replaced by skipRecords/skipRecord.

Findings

# Severity Finding Location Raised by
1 LOW Stray blank line at the top of TestCallback_NonFatalSecondaryLeg_AuthorizeURLFailureSkips pkg/authserver/server/handlers/callback_nonfatal_legs_test.go:299 correctness, readability
2 LOW The validate-before-filter ordering in resolveChain is not pinned by a test pkg/authserver/server/handlers/callback_nonfatal_legs_test.go:542 correctness, tests
3 LOW The rewrapped README line is about 100 characters wide pkg/authserver/README.md:180 readability

None of these affects behavior. The change keeps its earlier shape: opt-in, off by default, binding and state checks still fatal.

Recommendation: approve once the author has weighed the nits above.

How to test

  1. task test and task lint should pass.
  2. Reorder resolveChain so validateSkipped runs after computeChain: nothing fails today (the first finding above).
  3. Remove pending.ResolvedUserID != "" from canSkipCallbackLeg, or ar != nil from handleUpstreamError: TestCallback_NonFatalSecondaryLeg_UnskippableFailuresStayFatal should now fail.
  4. Check skipped after the stored-token lookup in nextMissingUpstream: TestCallback_NonFatalSecondaryLeg_SkippedLegKeepsItsStoredToken should fail.

Reviewed by dev:review-pr (incremental; finders: correctness, readability, tests). Generated with Claude Code.

Comment thread pkg/authserver/README.md Resolved
Addresses #7311 review comments:
- LOW callback_nonfatal_legs_test.go:299 (4700902862): drop the
  stray blank line
- LOW callback_nonfatal_legs_test.go:542 (4700902874): assert the
  rejection error and that the filter never runs
- LOW README.md:180 (4700902881): re-wrap the bullet

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@tgrunnagle
tgrunnagle marked this pull request as ready for review November 25, 2026 21:18
@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/XL Extra large PR: 1000+ lines changed labels Nov 25, 2026

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

Nice work, the ordering is right: every skip happens after the state, binding and consume checks, and SingleLeg and the first leg stay fatal. A few things inline, plus two that don't have a line to hang on.

The behaviour change should get a paragraph in docs/arch/11-auth-server-storage.md, since CLAUDE.md asks for a docs/ update when a request can now succeed where it used to fail. Worth covering the rollout there too: an older replica drops skipped_upstreams and re-prompts the leg, and a replica with the option off still honours skips another replica recorded (nextMissingUpstream doesn't look at the option). I'm fine with the latter as long as it's written down. Ignoring the list when the option is off is the alternative if you'd rather it be strict.

Also worth a line in the PR body: any ExchangeCodeForIdentity error is skippable, including a transient 503 or a nonce mismatch. I think that's fine since nothing gets stored for that leg and identity is only checked on the first leg, but it should read as deliberate.

Comment thread pkg/authserver/config.go Resolved
Comment thread pkg/authserver/server_impl.go Resolved
jhrozek and others added 3 commits November 26, 2026 14:26
Addresses #7311 review comments:
- handler.go:643 (4706980181): a first-leg pending that carries a
  chain or skipped legs is rejected; later legs validate the chain
  before the skipped set, so the set is checked against the chain
  the walk actually uses
- callback.go:1133 (4706980191): canSkipLeg needs more than one
  upstream, so a handler without upstreams cannot panic on an
  IdP-error callback
- callback.go:1155 (4706980197): log the skip once the chain has
  validated, so a rejected pending leaves no skip WARN and a stale
  pending keeps its stale-pending error
- callback.go:1159 (4706980202): assert the skip paths read chain
  state with the resolved user in context

Co-authored-by: Mecatl <[email protected]>
Addresses #7311 review comment server_impl.go:240
(4706980210): assert the option reaches the authorization server
config from authserver.Config, so dropping either copy fails a test.

Co-authored-by: Mecatl <[email protected]>
Addresses #7311 review comments:
- config.go:2142 (4706980172): a skip leaves an earlier credential
  in place, and the token validator and refresh guard still treat an
  unusable stored credential as fatal for the session; list every
  failure that stays fatal; name identity resolution failures
- review body: add a docs/arch section covering what is skipped,
  what stays fatal, the stored skipped set, and the rolling-upgrade
  and rollback order

Co-authored-by: Mecatl <[email protected]>
@jhrozek

jhrozek commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Trey is on PTO and this was in the way of something I'm working on, so I pushed the review fixes myself. The two points from the review body are covered too: docs/arch/11 has a new section with the rollout and rollback order (an option-off replica still honours recorded skips; that's documented rather than changed), and the PR body now says transient and nonce exchange failures are skippable on purpose, along with the kept-credential trade-off.

…atal-secondary-legs

# Conflicts:
#	pkg/authserver/README.md
@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/XL Extra large PR: 1000+ lines changed labels Nov 26, 2026
@rdimitrov
rdimitrov merged commit 2cc6fb9 into main Nov 26, 2026
47 of 48 checks passed
@rdimitrov
rdimitrov deleted the tgrunnagle/7310-non-fatal-secondary-legs branch November 26, 2026 14:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/XL Extra large PR: 1000+ lines changed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

authserver: opt-in non-fatal secondary chain legs

3 participants