Skip to content

Fix non-expiring upstream token handling and storage TTL bugs - #5092

Merged
jhrozek merged 15 commits into
mainfrom
upstream-expiring-issues
Apr 29, 2026
Merged

jhrozek merged 15 commits into
mainfrom
upstream-expiring-issues

Conversation

@jhrozek

@jhrozek jhrozek commented Apr 28, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Users authenticated with non-expiring upstream providers (GitHub OAuth Apps, Slack user tokens, Vault, on-prem providers without expires_in) hit a forced re-authentication every 60 minutes. The auth server fabricated a 1h ExpiresAt for any token that lacked expires_in, then treated those tokens as expired, attempted to refresh them with refresh tokens that didn't exist, hit ErrNoRefreshToken, and dropped the provider from downstream responses with omitting provider with unrefreshable expired token.

A second silent failure compounded the first: in multi-upstream chains that combined a non-expiring provider with an expiring one (e.g., GitHub PAT + Google), the Redis session-index set could be evicted while the non-expiring per-provider key was still alive — GetAllUpstreamTokens would silently drop the non-expiring provider exactly an hour after the session started.

This PR:

  • Removes the fabricated 1h ExpiresAt in convertOAuth2Token. Tokens without expires_in flow through with zero ExpiresAt.
  • Fixes IsExpired/IsExpiredAt to treat zero ExpiresAt as non-expiring (was: returned true → trapped tokens in the cascade).
  • Stops storage backends from evicting zero-ExpiresAt tokens.
  • Adds SessionExpiresAt to UpstreamTokens as a Fosite-session-bound storage TTL fallback so non-expiring tokens have a finite storage lifetime even when the upstream asserts none. Set unconditionally on every callback so the refresh path is safe even if a provider stops asserting expires_in on a later rotation.
  • Fixes a Lua TTL inversion in storeUpstreamTokensScript that re-applied a TTL to a PERSIST'd session index, silently orphaning non-expiring tokens after a subsequent expiring write to the same session.
  • Guards the expires_at log fields against zero-time formatting (was: emitted 0001-01-01T00:00:00Z). Now uses a slog.LogValuer that lazy-renders to "none" for zero time, RFC 3339 otherwise.

Closes #5046

Type of change

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

Test plan

  • Unit tests (task test)
  • Linting (task lint-fix)
  • Race detector (go test -race ./pkg/authserver/...) — clean
  • E2E tests (task test-e2e) — not run; no change at the CLI/operator boundary

New regression coverage:

  • TestRedisStorage_UpstreamTokens/mixed-expiry_session:_expiring_write_after_non-expiring_keeps_index_persistent — the Lua bug
  • TestRedisStorage_UpstreamTokens/fresh_expiring_write_applies_index_TTL — guards the discrimination between fresh-set and PERSIST'd-set
  • TestRedisStorage_UpstreamTokens/longer_expiring_write_after_shorter_extends_index_TTL and /shorter_expiring_write_after_longer_leaves_index_TTL_unchanged — lock down the comparator
  • TestUpstreamTokenRefresher_RefreshAndStore/preserves_SessionExpiresAt_when_provider_omits_expires_in — refresh-path bound
  • TestIntegration_UpstreamTokenService_NonExpiringToken — end-to-end regression for the original cascade

API Compatibility

  • This PR does not break the v1beta1 API.

Does this introduce a user-facing change?

Yes. Suggested release note:

Fixes a regression where MCP sessions using non-expiring upstream providers (GitHub OAuth Apps, Slack user tokens, Vault) were forced into hourly re-authentication. Also fixes a silent partial-token-loss in multi-upstream chains where the session index could be evicted before its non-expiring members.

Special notes for reviewers

  • Scope: this branch fixes Non-expiring upstream tokens incorrectly marked as 1h-expiring #5046 and a related index-eviction bug. It does not fix Upstream refresh tokens orphaned on re-authorization #5047 (re-authorization orphans Google refresh tokens). Upstream refresh tokens orphaned on re-authorization #5047 is a structural bug requiring a storage rekey from (SessionID, providerName) to (UserID, providerName), which is being designed in a separate RFC and will land as a follow-on PR sequence. This branch is a strict improvement on its own and is forward-compatible with the rekey.
  • The Lua change in pkg/authserver/storage/redis.go (commit fec89b040) is the most subtle. The control flow is structured as a decision keyed on (ttlMs, idxExisted, idxTTL). The trick is reading EXISTS before SADD — after SADD the set always exists, so a fresh-set and a previously-PERSIST'd set are indistinguishable from PTTL alone. Inline comments flag the bug-prone branch (idxTTL == -1 after pre-existing set).
  • Commit-by-commit review is intentional: each commit is self-contained and the messages explain motivation. The history was rebased to fold MoE-review fixups into their parents.

🤖 Generated with Claude Code

Large PR Justification

  • there's a lot of tests, mostly

@github-actions github-actions Bot added the size/L Large PR: 600-999 lines changed label Apr 28, 2026
@jhrozek
jhrozek requested a review from tgrunnagle April 28, 2026 15:41
@codecov

codecov Bot commented Apr 28, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.01709% with 7 lines in your changes missing coverage. Please review.
✅ Project coverage is 66.95%. Comparing base (4cfa962) to head (bdb3097).
⚠️ Report is 12 commits behind head on main.

Files with missing lines Patch % Lines
pkg/authserver/upstream/tokens.go 28.57% 5 Missing ⚠️
pkg/authserver/storage/types.go 33.33% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #5092      +/-   ##
==========================================
- Coverage   66.97%   66.95%   -0.03%     
==========================================
  Files         595      595              
  Lines       60080    60116      +36     
==========================================
+ Hits        40236    40248      +12     
- Misses      16779    16803      +24     
  Partials     3065     3065              

☔ View full report in Codecov by Sentry.
📢 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.

@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/L Large PR: 600-999 lines changed labels Apr 28, 2026

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

Large PR Detected

This PR exceeds 1000 lines of changes and requires justification before it can be reviewed.

How to unblock this PR:

Add a section to your PR description with the following format:

## Large PR Justification

[Explain why this PR must be large, such as:]
- Generated code that cannot be split
- Large refactoring that must be atomic
- Multiple related changes that would break if separated
- Migration or data transformation

Alternative:

Consider splitting this PR into smaller, focused changes (< 1000 lines each) for easier review and reduced risk.

See our Contributing Guidelines for more details.


This review will be automatically dismissed once you add the justification section.

@tgrunnagle tgrunnagle left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Multi-Agent Consensus Review

Agents consulted: storage-reviewer, lua-reviewer, oauth-reviewer, test-reviewer, compat-reviewer, quality-reviewer

Consensus Summary

# Finding Consensus Severity Action
1 Refresh path doesn't re-anchor SessionExpiresAt for legacy/edge-case rows 9/10 MEDIUM Discuss / fix
2 Same-provider non-expiring → expiring rewrite leaves index permanently PERSIST'd 9/10 LOW Document in code
3 Stale-token TTL fallback narrowed from DefaultRefreshTokenTTL (30d) to time.Second 8/10 MEDIUM Discuss
4 Missing regression test for legacy Redis JSON decoding (no session_expires_at field) 9/10 LOW Add test
5 Misleading comment about mockoidc refresh-failure mode in non-expiring integration tests 8/10 LOW Fix comment
6 Missing test for refresh rotation across expiring↔non-expiring 7/10 LOW Add test
7 IsExpired/IsExpiredAt contract change should be documented in release notes 8/10 LOW Note in release
8 INFO → DEBUG log demotion without compensating metric 8/10 LOW Discuss observability
9 SessionExpiresAt godoc misleading about who writes it 8/10 LOW Fix doc
10 cleanupExpired comment asserts unenforced invariant 7/10 LOW Strengthen
11 stripExpiresInMiddleware test helper has fragility issues 7/10 LOW Harden

Overall

This is a well-engineered bug fix that correctly diagnoses two distinct issues (the fabricated 1h ExpiresAt and an independent Lua TTL inversion) and fixes them with comprehensive regression coverage. The Lua-script comment block explaining the EXISTS-pre-SADD discrimination is particularly good — it makes the bug-prone branch self-documenting. Wire compatibility is preserved (Go's default json.Unmarshal ignores unknown fields, so v_old↔v_new co-existence works during a rolling deploy), and the pluggable storage-backend semantics for zero ExpiresAt are now consistent between Memory and Redis.

The consensus findings are mostly polish — several documentation/comment inaccuracies, two test gaps, and a couple of observability concerns. The two MEDIUM findings are worth a closer look before merge:

  • F1 identifies a residual gap in the PR's stated invariant (SessionExpiresAt is set unconditionally → refresh path is safe). For pre-PR Redis rows, SessionExpiresAt decodes to zero. If such a row's upstream rotates to no expires_in on the first refresh, the refresher carries SessionExpiresAt=0 forward and the row becomes indefinitely retained. Blast radius is bounded by the legacy 30-day TTL, but the invariant doesn't hold for in-flight legacy data. Worth either a defensive re-anchor in RefreshAndStore when expired.SessionExpiresAt.IsZero(), or a documented operational mitigation.

  • F3 is a silent semantic change in marshalUpstreamTokensWithTTL — when both access token and the 30-day refresh grace have passed, the row's TTL drops from DefaultRefreshTokenTTL (30d) to time.Second. This is a cold path (writing a deeply-stale token), but it's a real behavior change with no regression test.

No blocking issues. The same-provider rewrite limitation (F2) is acknowledged in tests as acceptable; surfacing it in the production Lua-script comment block would help future maintainers.

Documentation

  • pkg/authserver/storage/types.go:67 — SessionExpiresAt godoc claims "set on every write by the callback handler," but the refresher also writes it. Fix to reflect both writers.
  • pkg/authserver/storage/types.go:104 — IsExpired semantic change should appear in the release notes alongside the existing suggested note.
  • pkg/authserver/storage/redis.go:869 — Lua-script comment block is excellent; consider one extra line documenting the same-provider rewrite trade-off for symmetry with the test that pins it.
  • pkg/authserver/integration_test.go:1337 and ~1965 — "if a refresh were triggered, mockoidc would return an error" is incorrect; mockoidc's UserQueue is consumed only at /authorize, not at /token refresh-grant. Tests still pin the regression via access-token comparison, so the comment is the only thing wrong.

Test gaps to consider

  • A small redis_test.go subtest that hand-rolls a legacy JSON byte string (no session_expires_at field) via mr.Set(...) and asserts round-trip stability — pins the wire-shape contract.
  • A refresher_test.go case where expired has zero ExpiresAt + non-zero SessionExpiresAt and the provider returns a token with non-zero ExpiresAt (refresh-rotation across expiring↔non-expiring).

Generated with Claude Code

Comment thread pkg/authserver/refresher.go Resolved
Comment thread pkg/authserver/storage/redis.go Resolved
Comment thread pkg/authserver/storage/redis.go Resolved
Comment thread pkg/authserver/storage/redis_test.go Resolved
Comment thread pkg/authserver/integration_test.go Resolved
Comment thread pkg/authserver/storage/types.go Resolved
Comment thread pkg/authserver/upstream/oauth2.go Resolved
Comment thread pkg/authserver/storage/types.go Resolved
Comment thread pkg/authserver/storage/memory.go Resolved
Comment thread pkg/authserver/integration_test.go Resolved
jhrozek added a commit that referenced this pull request Apr 28, 2026
The previous comment claimed only the callback handler writes this field,
but the refresher also writes it: it carries the value forward unchanged on
every refresh, and (after the legacy-row defensive re-anchor) sets it
from RefreshTokenLifespan when both bounds are zero on the input.

The new test "preserves SessionExpiresAt when provider omits expires_in"
(refresher_test.go) and the legacy-row re-anchor case both depend on these
behaviors. Documenting them on the field makes the contract discoverable
without grepping for write sites.

Addresses #5092 review F9.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
jhrozek and others added 15 commits April 28, 2026 23:36
RFC 6749 §5.1 marks expires_in as RECOMMENDED, not REQUIRED. When a
provider omits it, the client has no basis to invent an expiry. Slack
user tokens and GitHub OAuth App tokens deliberately omit expires_in
because they are genuinely non-expiring and have no refresh token.

The fabricated 1h ExpiresAt caused guaranteed hourly re-authorization
failures for those providers: the token appeared expired, a refresh was
attempted with no refresh token, ErrNoRefreshToken was returned, and
the token was dropped from the service.

Remove defaultTokenExpiration and the fabrication block. Pass
token.Expiry (the Go zero value when expires_in is absent) through
directly so downstream code sees zero ExpiresAt and treats the token
as non-expiring. Guard the expires_at log field to emit "none" instead
of the misleading year-0001 timestamp.

Fixes #5046

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Both methods returned true for a zero ExpiresAt value because
now.After(time.Time{}) is always true (year 1 is in the past).
All production call sites guarded with !ExpiresAt.IsZero() before
calling, so the bug was harmless, but the methods were latent traps
for future callers.

Embed the zero guard inside each method: zero ExpiresAt means the
provider did not assert an expiry, so the token is treated as
non-expiring. Add nil-receiver guards for consistency and defensive
correctness.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Both backends applied a default ~31-day TTL when ExpiresAt was zero,
which would silently evict non-expiring tokens and prevent retrieval.

memory.go: split StoreUpstreamTokens logic so zero ExpiresAt leaves
the timedEntry expiry as the zero value (never evicted). Guard
cleanupExpired to skip entries with a zero expiry.

redis.go: initialise ttl to zero in marshalUpstreamTokensWithTTL and
only set it for non-zero ExpiresAt. The Lua script already handles
ttl=0 by calling SET without PX. Add PERSIST on the session index set
when ttl=0 so a non-expiring token write removes any TTL a prior
expiring-token write set on the index set, preventing the index from
being evicted while the non-expiring token still exists.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Verifies that GetValidTokens returns a stored token with zero ExpiresAt
unchanged and does not attempt a refresh. The failure signal is
structural: no mockoidc user is queued, so any refresh attempt would
cause the test to fail via a mockoidc error.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Non-expiring upstream tokens (zero ExpiresAt — providers that omit
expires_in) previously had no storage TTL, so they were never evicted
by the cleanup loop. The only removal path was explicit deletion, which
only happened on authorization error paths.

Add SessionExpiresAt to UpstreamTokens. The callback handler sets it
to the Fosite refresh token expiry; the refresher carries it forward on
token rotation. Both MemoryStorage and RedisStorage use it as a fallback
TTL when ExpiresAt is zero, ensuring non-expiring upstream tokens are
evicted when the session would have expired.

Tokens where both ExpiresAt and SessionExpiresAt are zero remain
indefinitely stored — the existing behaviour for cases where the session
expiry is unknown.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Previously SessionExpiresAt was only set in the callback when
idpTokens.ExpiresAt was zero. This created a hole in the refresh path:
if the initial callback got a token with non-zero ExpiresAt, the stored
SessionExpiresAt remained zero. If a later refresh response omitted
expires_in, the refresher carried the (zero) SessionExpiresAt forward,
the new row had both ExpiresAt and SessionExpiresAt zero, and storage
backends stored it without any TTL — leaking indefinitely.

Make SessionExpiresAt unconditionally meaningful: set it on every
callback as the Fosite session bound. Storage backends still only
consult it as a fallback when ExpiresAt is zero, so behaviour for
expiring tokens is unchanged. The refresh path is now safe even if a
provider stops asserting expires_in on a later rotation.

Add TestUpstreamTokenRefresher_PreservesSessionExpiresAt to lock down
that the refresher carries SessionExpiresAt forward into the updated
record — easy regression for future refactors.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
The session-index set in Redis must outlive every per-provider key it
points to. The previous logic conflated "fresh set just SADD'd" with
"existing set previously PERSIST'd by a non-expiring member" because
PTTL returns -1 in both cases. The condition `currentTTL < ttlMs` was
therefore always true for -1, causing PEXPIRE to undo a prior PERSIST.

Failure mode: store a non-expiring token (PERSIST'd index), then store
an expiring token for the same session — the index re-acquired a TTL,
evicted at the expiring token's expiry, and the non-expiring token's
per-provider key (which has no TTL) became unreachable through
GetAllUpstreamTokens and DeleteUpstreamTokens. This fired deterministically
for any multi-upstream chain that had a non-expiring provider followed
by an expiring one (e.g., GitHub PAT + Google).

Distinguish the two cases by reading EXISTS BEFORE SADD. Pre-SADD
existence is unambiguous: if the set didn't exist, our SADD just
created it and we own the TTL decision; if it did exist, its current
TTL summarises prior members and a -1 means "intentionally persistent,
leave alone".

Add tests for:
- Reverse-order mixed-expiry (non-expiring → expiring) — the bug
- Fresh expiring write applies index TTL — regression guard
- Same-provider rewrite from non-expiring to expiring — documents
  the intentional limitation that the index stays PERSIST'd until
  DeleteUpstreamTokens cleans up

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Commit 824bc55's body promised "Guard the expires_at log field to
emit 'none' instead of the misleading year-0001 timestamp" but only
removed .Format(time.RFC3339) — slog still serialises a zero time.Time
as "0001-01-01T00:00:00Z". Two log sites in oidc.go (during the
authorization-code-exchange and refresh paths) were never touched and
still called .Format() unconditionally.

Add formatExpiresAt(t time.Time) to the upstream package: returns "none"
for zero time, RFC 3339 otherwise. Apply at all four log sites
(oauth2.go ×2, oidc.go ×2). Drop the now-unused time import in oidc.go.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Two end-to-end regressions covering the cascade-prevention fix and the
chain handler's per-leg storage write:

* TestIntegration_FullFlow_NonExpiringUpstreamToken — drives the full
  /authorize → /callback → /token flow against a mock OIDC server whose
  token endpoint has been wrapped to strip expires_in from responses.
  Asserts the stored token has zero ExpiresAt, GetValidTokens succeeds
  without triggering a refresh, and post-call ExpiresAt is still zero.
  Catches regressions that re-introduce a default expiry anywhere in the
  HTTP-response → convertOAuth2Token → storage path.

* TestIntegration_MultiUpstreamChain_MixedExpiryOrderings — table-driven,
  both orderings of mixed-expiry providers in a two-leg chain. Asserts
  GetAllValidTokens returns both providers regardless of order. Pins the
  chain handler's per-leg storage write and the convertOAuth2Token
  zero-Expiry path through the full HTTP flow. The Redis Lua TTL
  semantics remain covered by the unit-level tests in
  pkg/authserver/storage/redis_test.go.

Helpers:
* captureResponseWriter / stripExpiresInMiddleware — buffer the upstream
  token response and remove expires_in before forwarding. Lets us drive a
  non-expiring token response without forking mockoidc.
* startMockOIDCNoExpiresIn — applies the strip middleware to a mock OIDC
  server. Deliberately does NOT queue a default user, so any unintended
  refresh attempt fails (the failure signal for the cascade-prevention
  test).
* runChainFlow — extracted the two-leg chain navigation from
  TestIntegration_MultiUpstreamSequentialChain, including the
  state-preservation invariant. The original test now uses the helper,
  eliminating duplicated chain-navigation code.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Reusable infrastructure for driving the full /authorize → /callback → /token
flow against Redis-shape storage, plus Redis-variant siblings for the two
new integration tests added in this branch.

The harness:
* `withRedisBackedStorage()` functional option on `testServerOptions`
* `testServer.Miniredis(t)` accessor that fails loudly if the option wasn't
  applied (avoids nil-deref foot-gun from a struct field that's only sometimes
  populated)
* The three setup helpers (`setupTestServer`, `setupTestServerWithOIDCProvider`,
  `setupTestServerWithTwoUpstreams`) gained a variadic `...testServerOption`
  parameter; default behavior unchanged (memory storage)
* Default Redis prefix `test:auth:{ns:test}:` matches production-shape cluster
  routing semantics (hash tag), even though miniredis ignores slots

The Redis-variant tests:
* `TestIntegration_FullFlow_NonExpiringUpstreamToken_Redis` — symmetry coverage
  of the convertOAuth2Token → Redis storage path. Drives the same flow as the
  memory variant against miniredis.
* `TestIntegration_MultiUpstreamChain_MixedExpiryOrderings_Redis` — smoke test
  for the chain handler ↔ Redis storage path through real Lua execution in
  both orderings.

Note on the Lua TTL inversion bug (commit fec89b0): the integration test
intentionally does NOT cover that bug. It only fires when
marshalUpstreamTokensWithTTL produces ttlMs == 0, which requires both
ExpiresAt and SessionExpiresAt to be zero on the UpstreamTokens. Since
callback.go unconditionally sets SessionExpiresAt = now + RefreshTokenLifespan
(commit 1b3bc81), the integration flow always produces ttlMs > 0 and the
buggy Lua branch is unreachable from a real auth chain. The Lua invariant is
locked down at unit level by pkg/authserver/storage/redis_test.go, which can
construct UpstreamTokens with both zero fields directly.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
The PR's invariant — SessionExpiresAt is set unconditionally on every
callback so the refresh path can carry it forward as a storage TTL bound
— holds for fresh writes after this PR ships. Pre-PR Redis rows decode
SessionExpiresAt as zero because the field was absent from the persisted
JSON. If such a legacy row is refreshed and the upstream rotation also
drops expires_in, both bounds would be zero. The Redis backend would
PERSIST the indexed row and the Memory backend would retain it
indefinitely (Redis at least caps blast radius via the legacy 30-day
per-key TTL; Memory has no backstop).

Defensively re-anchor SessionExpiresAt to now+RefreshTokenLifespan when
both bounds on the candidate write would be zero. RefreshTokenLifespan
is threaded from the validated Config through the server struct into
upstreamTokenRefresher — the same value the callback writer uses, so
legacy rows transition into the post-PR invariant on first refresh
rather than being persisted unbounded.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
The Lua script's index-TTL rule "leave a PERSIST'd set alone" is correct
for the cross-provider mixed-expiry case but has a known limitation: when
the SAME (sessionID, providerName) slot is rewritten from non-expiring
to expiring, the index stays PERSIST'd even though the only persistence
anchor is gone. Detecting that would require per-member TTL tracking,
which we deliberately avoided; the index is reaped on
DeleteUpstreamTokens or session GC anyway.

The behaviour is pinned by the redis_test.go case
"same provider rewrite from non-expiring to expiring keeps PERSIST'd
until rewrite", but the production code never said why. A future
maintainer tightening the rule would have hit that test failure and had
to reverse-engineer the rationale from the test name. Spell out the
trade-off next to the invariant so the connection is obvious.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Before the fix on this branch, marshalUpstreamTokensWithTTL fell through
to DefaultRefreshTokenTTL (30 days) when time.Until(ExpiresAt) +
DefaultRefreshTokenTTL was negative — meaning both the access token and
its 30-day refresh grace had elapsed.  The same silent over-retention
applied to the SessionExpiresAt branch introduced in this series.

The fix changed the floor to time.Second so deeply-stale rows evict
promptly.  Without a regression test, a future refactor could silently
revert this clamp — cold-path callers (refresher races, admin rewrites,
legacy-row migrations) would then observe a 30-day grace on tokens that
should have been evicted, causing unintended token retention in Redis.

Add two subtests to TestRedisStorage_UpstreamTokens, one for each
branch, that store a token with stalePast = -(DefaultRefreshTokenTTL +
1h) and assert mr.TTL ≤ 2s.  Both fail loudly if the clamp is reverted.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Pre-PR Redis rows have no "session_expires_at" key. The read path
correctly handles this via a != 0 sentinel, but nothing in the test
suite exercised that path with raw legacy bytes. Without a pinning
test, a future refactor — e.g. switching to
json.NewDecoder().DisallowUnknownFields() or renaming the JSON tag —
would silently break deserialization of existing rows.

Add a subtest that hand-rolls a legacy JSON string (no
"session_expires_at"), injects it into miniredis directly via mr.Set,
calls GetUpstreamTokens, and asserts that all non-time fields
round-trip correctly and that SessionExpiresAt.IsZero() is true.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
The previous comment claimed only the callback handler writes this field,
but the refresher also writes it: it carries the value forward unchanged on
every refresh, and (after the legacy-row defensive re-anchor) sets it
from RefreshTokenLifespan when both bounds are zero on the input.

The new test "preserves SessionExpiresAt when provider omits expires_in"
(refresher_test.go) and the legacy-row re-anchor case both depend on these
behaviors. Documenting them on the field makes the contract discoverable
without grepping for write sites.

Addresses #5092 review F9.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@jhrozek
jhrozek force-pushed the upstream-expiring-issues branch from 80a7f9f to bdb3097 Compare April 28, 2026 22:36
@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 Apr 28, 2026
@github-actions
github-actions Bot dismissed their stale review April 29, 2026 14:54

Large PR justification has been provided. Thank you!

@github-actions

Copy link
Copy Markdown
Contributor

✅ Large PR justification has been provided. The size review has been dismissed and this PR can now proceed with normal review.

@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 Apr 29, 2026
@jhrozek
jhrozek merged commit a98c991 into main Apr 29, 2026
72 of 73 checks passed
@jhrozek
jhrozek deleted the upstream-expiring-issues branch April 29, 2026 15:00
jhrozek added a commit that referenced this pull request Apr 30, 2026
The previous tie-breaker used "highest ExpiresAt wins" with zero (the
no-expiry sentinel) treated as the smallest int64 — so non-expiring
rows always lost to any finite expiry. That was inconsistent with the
rest of the package, which treats zero ExpiresAt as "alive forever":
IsExpired returns false for zero, cleanupExpired skips zero entries,
and marshalUpstreamTokensWithTTL only writes a Redis TTL when ExpiresAt
is non-zero. PR #5092 (a98c991) reshaped the whole storage stack on
that premise — Slack user tokens and GitHub OAuth App tokens
deliberately omit expires_in because they are genuinely non-expiring.

Flip the rule to align with the rest of the package: a non-expiring row
beats any finite expiry; among finite expiries, the latest still wins.
Both backends use a small predicate helper (candidateBeatsWinner for
time.Time, candidateBeatsWinnerInt64 for the Redis epoch) to keep the
comparison readable.

The carry-forward caller is largely unaffected today because Slack /
GitHub OAuth App rows store an empty RefreshToken (non-expiring access
tokens have no RT) and the prior.RefreshToken != "" guard rejects them
either way. The flip matters for future callers that read the access
token from the returned row, and for the rare provider that emits both
zero ExpiresAt and a non-empty refresh token.

Update the interface godoc and rename the existing
zero_expires_at_loses_to_nonzero subtest to zero_expires_at_wins_over_nonzero
in both backends. Add a memory-side two_zero_expires_at_rows case to
match the existing Redis coverage.
jhrozek added a commit that referenced this pull request May 1, 2026
* Add GetLatestUpstreamTokensForUser to storage

Introduces a secondary upstream-token lookup keyed on (userID, providerID)
on the UpstreamTokenStorage interface. The OAuth callback handler will use
this in a follow-on commit to preserve a previously-issued refresh token
when the upstream IdP omits refresh_token on re-authorization (e.g. Google
without prompt=consent), which today silently clobbers the prior good RT
and forces a refresh-token-orphaning loop.

This commit only adds the interface surface plus stub implementations on
both backends that return ErrNotFound. The real Memory and Redis logic, the
callback wiring, and tests land in subsequent commits so each diff stays
small and independently reviewable. The godoc explicitly calls out the
liveness contract (expired rows are returned, callers handle it) and the
cross-identity caller responsibility (verify UpstreamSubject before reusing
the prior RT) so future callers cannot misuse the lookup.

Refs #5047

* Implement GetLatestUpstreamTokensForUser for memory

Replaces the Step 1 stub on MemoryStorage with the real lookup. Iterates
the upstream-tokens map under RLock, filters by (UserID, ProviderID), and
picks the row with the highest ExpiresAt. Expired access tokens are
intentionally returned (matching the interface contract) so the OAuth
callback can carry forward a still-valid refresh token even when the
access token is dead.

Returns a defensive deep copy on hit and the same wrapped ErrNotFound
shape that GetUpstreamTokens uses on miss, so callers cannot accidentally
mutate stored state through the returned pointer.

Adds a 7-case table-driven test covering: no match, one match (with a
deep-copy mutation assertion), latest-by-ExpiresAt across three rows,
different-user/different-provider misses, expired-row tolerance, and
zero-ExpiresAt losing to non-zero.

Refs #5047

* Implement GetLatestUpstreamTokensForUser for redis

Replaces the Step 1 stub on RedisStorage with the real lookup, using the
existing KeyTypeUserUpstream:{userID} reverse-index set already maintained
atomically by storeUpstreamTokensScript. The read path is plain Go (no Lua
script) since atomicity buys nothing on a read-only path: the worst case
is reading a slightly-stale row, which is acceptable for the carry-forward
use case.

Mirrors the SMembers -> MGet -> unmarshal pattern from GetAllUpstreamTokens
and tolerates dangling SMEMBERs (per-provider key TTL-evicted, set member
lingers), nullMarker deletion tombstones, and corrupt JSON. Filters on
the deserialized ProviderID rather than parsing the key string so the
implementation survives any future key-format change. Picks the winner by
the stored unix-timestamp ExpiresAt; zero (the no-expiry sentinel) loses
to any real timestamp.

Adds input validation for empty userID/providerID matching the rest of
the type's public API. The Memory backend has the same gap and should be
fixed as a follow-up; it's left untouched here to keep this commit
scoped to the Redis backend.

Adds a 9-case table-driven unit test covering all the cases from the
Memory backend plus a stale-index-entry case (dangling SMEMBER injected
via miniredis SAdd) and a two-zero-ExpiresAt case (verifies non-strict
ordering without locking down iteration order).

Refs #5047

* Carry forward upstream refresh token on callback

The OAuth callback handler now preserves a previously-issued upstream
refresh token when the IdP omits refresh_token on re-authorization. This
is common across major IdPs: Google omits unless prompt=consent and
access_type=offline are forced; Microsoft Entra omits when consent was
already granted; GitHub, Okta, Auth0, and Keycloak behave similarly. In
every case the prior RT remains valid at the IdP — but today the
callback writes the empty value verbatim, clobbering the stored RT and
forcing the next refresh attempt to fail, which puts the user in a
re-auth-orphans-RT loop.

The carry-forward logic mirrors the existing pattern in
upstreamTokenRefresher.RefreshAndStore. It uses the new storage method
GetLatestUpstreamTokensForUser to find the most recent prior row for
(user, provider) and copies the prior RefreshToken into the new row.
The prior row's UpstreamSubject must equal the current providerSubject
as defense-in-depth; this guard is dormant given the current identity
model (ResolveUser keys on (providerID, providerSubject) and same-
provider account-linking is not implemented) but protects future flows.

Storage failures during the lookup log a Warn and continue with the
empty RT — failing the callback would be a worse user experience than
the (already broken) status quo, and the next refresh attempt will
produce a clean error path the user can retry from.

The implementation lives in a private helper to keep CallbackHandler
under the gocyclo threshold; the call site is between storageTokens
construction and StoreUpstreamTokens so the in-place mutation is
visible at the point of use.

Adds 5 handler tests covering: positive carry-forward, UpstreamSubject
mismatch (no carry), fresh-RT-from-IdP wins (carry-forward
short-circuited), no-prior-row (status quo for first auth), and
storage-error-non-fatal (callback completes with empty RT instead of
returning 500).

Refs #5047

* Add integration test for re-auth refresh token carry-forward

Drives the full authorize -> callback flow against mockoidc and a real
MemoryStorage so the carry-forward behavior is validated end-to-end, not
just at the gomock-handler boundary.

mockoidc unconditionally issues refresh_token on the authorization_code
grant with no API to suppress the field, so the test wires a small
reverse-proxy (rtStrippingProxy) between the auth server and mockoidc.
When the test toggles the strip flag (atomic.Bool — required, otherwise
the race detector flags the read on httptest's request goroutines), the
proxy unmarshals mockoidc's token response, deletes the refresh_token
key, and re-marshals before forwarding. The key is then absent from the
wire JSON exactly as Google, Entra, GitHub, Okta and Auth0 behave on a
silent re-authorization, which is what the underlying bug actually
reproduces in production.

Three legs:
  1. Initial authorize -> callback with RT preserved verbatim. Captures
     the RT for later comparison.
  2. Strip flag flipped on, second authorize -> callback for the same
     user. Asserts the new (different sessionID) row carries the leg-1
     RT forward.
  3. Different upstream subject -> ResolveUser mints a new internal
     user; the carry-forward lookup returns ErrNotFound and the new row
     stays empty. Confirms the carry-forward fires only when warranted.

The UpstreamSubject == providerSubject guard inside the callback is
covered by the handler-level unit test added in the previous commit;
exercising it end-to-end here would require either a contrived storage
hack or same-provider account-linking (not implemented today).

Note on offline_access: real IdPs require this scope before issuing a
refresh token, but mockoidc's ScopesSupported allowlist rejects it as
invalid_scope. The test does not request the scope as a result. This is
a fixture limitation; the carry-forward regression assertion is
unaffected because mockoidc returns the RT regardless.

Refs #5047

* Populate SessionExpiresAt in GetLatestUpstreamTokensForUser

Both backend implementations of GetLatestUpstreamTokensForUser dropped
SessionExpiresAt from the returned struct, while the sibling readers
GetUpstreamTokens (memory) and unmarshalUpstreamTokens (redis) populate
it. The interface return type makes no "partial copy" caveat, so any
future caller doing Get-then-Store would lose the storage TTL fallback
bound that SessionExpiresAt provides on rows whose upstream IdP did not
issue an expires_in.

Today's only caller (maybeCarryForwardRefreshToken) reads only
RefreshToken and UpstreamSubject, so this is latent. Fixing now to
close the contract trap before the deferred Root Cause A rekey
introduces a caller that does treat the result as round-trippable.

* Extract upstream-tokens conversion helpers

The storage package had four sites doing field-by-field construction of
UpstreamTokens — three in the memory backend (defensive deep copies) and
two in the redis backend (storedUpstreamTokens int64→time.Time
conversion). Each site is a place where a future field addition can be
silently missed; the SessionExpiresAt drop in the previous commit is an
example of that class of bug.

Extract a free function cloneUpstreamTokens for the memory backend (used
at 3 sites) and a (*storedUpstreamTokens).toUpstreamTokens method for
the redis backend (used at 2 sites). No behavior change.

* Add round-trip test for UpstreamTokens fields

The existing tests for GetLatestUpstreamTokensForUser asserted only on
RefreshToken — the previous SessionExpiresAt drop slipped through
because no test exercised whole-struct round-tripping. Add a focused
subtest in each backend that builds a fully-populated UpstreamTokens
fixture, stores it, retrieves it, and asserts whole-struct equality.

Catches the SessionExpiresAt regression and any future field that fails
to round-trip through the storage layer.

* Test empty-RT prior row in carry-forward and broaden assertions

The prior.RefreshToken != "" guard in maybeCarryForwardRefreshToken was
untested: every existing case either carried (non-empty prior RT and
matching subject), failed earlier (subject mismatch / fresh IdP RT /
nil prior / storage error), or never reached the guard. The state is
reachable in production — e.g. Google can omit refresh_token even on
first auth without prompt=consent, leaving a leg-1 row with empty RT
that a leg-2 lookup will return.

Add a case where the prior row exists with matching subject but empty
RefreshToken, and assert no carry-forward happens.

Strengthen the shared assertion block with sanity checks on
AccessToken, IDToken, UpstreamSubject and a non-zero ExpiresAt across
all cases. Without them, a regression that early-returns from the
callback before StoreUpstreamTokens would still pass an assertion that
only checks RefreshToken.

* Prefer non-expiring rows in GetLatestUpstreamTokensForUser

The previous tie-breaker used "highest ExpiresAt wins" with zero (the
no-expiry sentinel) treated as the smallest int64 — so non-expiring
rows always lost to any finite expiry. That was inconsistent with the
rest of the package, which treats zero ExpiresAt as "alive forever":
IsExpired returns false for zero, cleanupExpired skips zero entries,
and marshalUpstreamTokensWithTTL only writes a Redis TTL when ExpiresAt
is non-zero. PR #5092 (a98c991) reshaped the whole storage stack on
that premise — Slack user tokens and GitHub OAuth App tokens
deliberately omit expires_in because they are genuinely non-expiring.

Flip the rule to align with the rest of the package: a non-expiring row
beats any finite expiry; among finite expiries, the latest still wins.
Both backends use a small predicate helper (candidateBeatsWinner for
time.Time, candidateBeatsWinnerInt64 for the Redis epoch) to keep the
comparison readable.

The carry-forward caller is largely unaffected today because Slack /
GitHub OAuth App rows store an empty RefreshToken (non-expiring access
tokens have no RT) and the prior.RefreshToken != "" guard rejects them
either way. The flip matters for future callers that read the access
token from the returned row, and for the rare provider that emits both
zero ExpiresAt and a non-empty refresh token.

Update the interface godoc and rename the existing
zero_expires_at_loses_to_nonzero subtest to zero_expires_at_wins_over_nonzero
in both backends. Add a memory-side two_zero_expires_at_rows case to
match the existing Redis coverage.
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.

Upstream refresh tokens orphaned on re-authorization Non-expiring upstream tokens incorrectly marked as 1h-expiring

2 participants