Skip to content

Refresh XSTS tokens rejected before NotAfter - #21

Open
HashimTheArab wants to merge 1 commit into
lunarfrom
agent/xsts-token-expired-retry
Open

Refresh XSTS tokens rejected before NotAfter#21
HashimTheArab wants to merge 1 commit into
lunarfrom
agent/xsts-token-expired-retry

Conversation

@HashimTheArab

@HashimTheArab HashimTheArab commented Jul 15, 2026

Copy link
Copy Markdown
Owner

What changed

  • retry an authenticated Xbox API request once when its 401 response explicitly reports error='token_expired'
  • invalidate only the rejected XSTS token, preserving a newer concurrent replacement
  • clear both SISU's relying-party cache and its cached default authorization response when they contain the rejected token
  • rebuild the request body and signature for the retry
  • leave unrelated 401 responses and requests with caller-provided authorization untouched

This is implemented in the shared NSAL transport, so MPSD, profile, social, presence, and other authenticated Xbox API clients get the same recovery behavior. Token sources that do not implement the optional invalidation interface retain the existing behavior.

Production evidence

These are sanitized excerpts from the mcxboxbroadcast investigation on na-east-2; tokens, user hashes, and account identifiers are omitted.

The locally cached XSTS token claimed it was valid for another ~3.5 hours:

cached XSTS NotAfter: 2026-07-15 06:45 UTC
request time:         ~2026-07-15 03:20 UTC

Xbox rejected that same token on two independently authenticated services:

profile.xboxlive.com -> 401 Unauthorized
WWW-Authenticate: Token realm='xboxlive.com', error='token_expired', Token realm='xboxlive.com', error='token_required'

sessiondirectory.xboxlive.com (MPSD) -> 401 Unauthorized
WWW-Authenticate: Token realm='xboxlive.com', error='token_expired', Token realm='xboxlive.com', error='token_required'

At the same time, a social endpoint accepted the same token:

social.xboxlive.com -> 200 OK

That rules out a simple account-wide ban and shows why local NotAfter validation alone is insufficient: Xbox can invalidate an XSTS token early, and acceptance can differ by relying service.

For the controlled confirmation, only xboxLiveXstsToken was removed from a temporary copy of the Java broadcaster cache. The same Java build (145), with friend sync and notifications disabled, then performed a fresh SISU/XSTS exchange:

Authenticated PlayLunarMC
Creation of Xbox LIVE session was successful!

No production cache or workload was changed during this diagnostic.

Verification

go test -race ./...
go vet ./...
git diff --check
gofmt -l <changed Go files>

All passed. Regression coverage includes the observed multi-challenge header, body replay, re-signing, response-body closure, unrelated 401 handling, and preservation of newer or concurrently acquired cached tokens.

Summary by CodeRabbit

  • Bug Fixes

    • Automatically refreshes expired authentication tokens and retries the request once.
    • Preserves request bodies during authentication retries.
    • Prevents rejected or outdated tokens from being reused during concurrent requests.
    • Keeps valid replacement tokens and authorization data available after invalidation.
  • Tests

    • Added coverage for token-expiration detection, refresh retries, response cleanup, and concurrent token invalidation scenarios.

@coderabbitai

coderabbitai Bot commented Jul 15, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

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

Next review available in: 39 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: a9a1da97-6dac-44b0-80d5-2e48f3eeb644

📥 Commits

Reviewing files that changed from the base of the PR and between b51d917 and eb5a2a3.

📒 Files selected for processing (4)
  • xal/nsal/transport.go
  • xal/nsal/transport_test.go
  • xal/sisu/session.go
  • xal/sisu/session_unit_test.go
📝 Walkthrough

Walkthrough

The transport now buffers request bodies, detects expired XSTS challenges, invalidates supported token sources, and retries once. Session token caching tracks invalidation generations and clears stale cached authorization data.

Changes

XSTS token refresh

Layer / File(s) Summary
Session token invalidation and cache coordination
xal/sisu/session.go, xal/sisu/session_unit_test.go
Session coordinates token acquisition with invalidation generations, removes rejected tokens and matching authorization responses, and tests concurrent refetch behavior.
Expired-token retry and request replay
xal/nsal/transport.go, xal/nsal/transport_test.go
Transport replays buffered request bodies after detecting token_expired, invalidates the rejected token, and validates challenge parsing and retry behavior.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Transport
  participant TokenInvalidator
  participant BaseTransport
  Transport->>BaseTransport: send authenticated request with cached body
  BaseTransport-->>Transport: return 401 token_expired response
  Transport->>TokenInvalidator: InvalidateXSTSToken(rejected token)
  Transport->>BaseTransport: retry authenticated request with refreshed token
  BaseTransport-->>Transport: return retry response
Loading
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: refreshing rejected XSTS tokens before their NotAfter time.
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.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch agent/xsts-token-expired-retry

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.

@HashimTheArab

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 15, 2026

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
xal/sisu/session_unit_test.go (1)

170-209: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Combine into a table-driven test.

TestSessionInvalidatesRejectedXSTSToken and TestSessionInvalidationPreservesReplacementXSTSToken exercise the same behavior (InvalidateXSTSToken with a matching vs. non-matching token), differing only in the input token and expected outcome.

As per coding guidelines, "Prefer table-driven tests when multiple cases exercise the same behavior; keep single-case tests straightforward when a table would add noise."

♻️ Proposed table-driven consolidation
func TestSessionInvalidateXSTSToken(t *testing.T) {
	tests := []struct {
		name        string
		cached      *xsts.Token
		invalidate  *xsts.Token
		wantRemoved bool
	}{
		{
			name:        "removes rejected token",
			cached:      &xsts.Token{Token: "rejected"},
			invalidate:  &xsts.Token{Token: "rejected"},
			wantRemoved: true,
		},
		{
			name:        "preserves newer replacement",
			cached:      &xsts.Token{Token: "replacement"},
			invalidate:  &xsts.Token{Token: "rejected"},
			wantRemoved: false,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			session := (Config{}).New(staticMSATokenSource{}, nil)
			session.xsts[defaultRelyingParty] = tt.cached
			session.resp = &authorizationResponse{AuthorizationToken: tt.cached}

			invalidator, ok := any(session).(interface{ InvalidateXSTSToken(*xsts.Token) })
			if !ok {
				t.Fatal("Session does not support XSTS token invalidation")
			}
			invalidator.InvalidateXSTSToken(tt.invalidate)

			_, cached := session.xsts[defaultRelyingParty]
			if cached == tt.wantRemoved {
				t.Fatalf("token cached = %t, want removed = %t", cached, tt.wantRemoved)
			}
			if (session.resp == nil) != tt.wantRemoved {
				t.Fatalf("resp cleared = %t, want removed = %t", session.resp == nil, tt.wantRemoved)
			}
		})
	}
}
🤖 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 `@xal/sisu/session_unit_test.go` around lines 170 - 209, Combine
TestSessionInvalidatesRejectedXSTSToken and
TestSessionInvalidationPreservesReplacementXSTSToken into one table-driven
TestSessionInvalidateXSTSToken test with subtests covering matching-token
removal and non-matching-token preservation. Parameterize the cached token,
invalidation token, and expected removal state, while retaining the interface
check and assertions for both the relying-party cache and session response.

Source: Coding guidelines

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

Nitpick comments:
In `@xal/sisu/session_unit_test.go`:
- Around line 170-209: Combine TestSessionInvalidatesRejectedXSTSToken and
TestSessionInvalidationPreservesReplacementXSTSToken into one table-driven
TestSessionInvalidateXSTSToken test with subtests covering matching-token
removal and non-matching-token preservation. Parameterize the cached token,
invalidation token, and expected removal state, while retaining the interface
check and assertions for both the relying-party cache and session response.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 554a9dac-a1b2-42af-9e4d-69c6e1a8cdeb

📥 Commits

Reviewing files that changed from the base of the PR and between bcf7f7c and 502bb29.

📒 Files selected for processing (5)
  • xal/nsal/transport.go
  • xal/nsal/transport_test.go
  • xal/sisu/session.go
  • xal/sisu/session_unit_test.go
  • xal/xsts/token_source.go

@HashimTheArab
HashimTheArab force-pushed the agent/xsts-token-expired-retry branch from 502bb29 to 60d1aad Compare July 15, 2026 03:44
@HashimTheArab

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 15, 2026

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@HashimTheArab
HashimTheArab force-pushed the agent/xsts-token-expired-retry branch from 60d1aad to b51d917 Compare July 15, 2026 06:05
@HashimTheArab

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 15, 2026

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

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 `@xal/sisu/session.go`:
- Around line 251-283: Update Session.xstsToken to coalesce concurrent
acquisitions for each relyingParty by coordinating access around the in-flight
request, so only one request runs and waiters reuse its result. Preserve the
existing cached-token fast path, propagate the shared request’s success or error
to waiters, and retain the xstsGeneration check so invalidation still causes a
fresh acquisition.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: 8389bd2f-481d-477c-b913-8f57902d9c73

📥 Commits

Reviewing files that changed from the base of the PR and between 502bb29 and b51d917.

📒 Files selected for processing (4)
  • xal/nsal/transport.go
  • xal/nsal/transport_test.go
  • xal/sisu/session.go
  • xal/sisu/session_unit_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • xal/nsal/transport.go

Comment thread xal/sisu/session.go
@HashimTheArab
HashimTheArab force-pushed the agent/xsts-token-expired-retry branch from b51d917 to f0a174d Compare July 15, 2026 06:08
@HashimTheArab

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 15, 2026

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@HashimTheArab
HashimTheArab force-pushed the agent/xsts-token-expired-retry branch from f0a174d to 4a63800 Compare July 15, 2026 06:21
@HashimTheArab

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 15, 2026

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@HashimTheArab
HashimTheArab force-pushed the agent/xsts-token-expired-retry branch from 4a63800 to 2f5697b Compare July 15, 2026 06:24
@HashimTheArab

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 15, 2026

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@HashimTheArab
HashimTheArab force-pushed the agent/xsts-token-expired-retry branch from 2f5697b to eb5a2a3 Compare July 15, 2026 06:25
@HashimTheArab

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 15, 2026

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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.

1 participant