Skip to content

fix(auth): accept persistent session tokens in AuthMiddleware - #24

Merged
guarzo merged 2 commits into
mainfrom
fix/auth-middleware-persistent-session
May 4, 2026
Merged

fix(auth): accept persistent session tokens in AuthMiddleware#24
guarzo merged 2 commits into
mainfrom
fix/auth-middleware-persistent-session

Conversation

@guarzo

@guarzo guarzo commented May 4, 2026

Copy link
Copy Markdown
Owner

Summary

  • FinalizeLogin returns a bearer token issued by the persistent SessionStore, but AuthMiddleware only validated tokens against the OAuth login-state map — so in the packaged Electron build (file://, no cookie) every authenticated API call returned 401 and no accounts/characters showed up.
  • AuthMiddleware now checks the persistent session store first and falls back to the OAuth state lookup for legacy tokens, mirroring what GetSession/ValidateSession already do.
  • Dev was unaffected because the OAuth callback also sets the cookie session, which the middleware's cookie path accepts.

Test plan

  • go build ./...
  • go test ./internal/http/...
  • Manually verify in packaged Electron build: log in, confirm /api/accounts returns data without "Invalid or incomplete token" warnings.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Enhanced Bearer token authentication with session store validation and fallback support
    • Improved error handling and clearer messages for invalid or expired tokens

FinalizeLogin issues bearer tokens from the persistent SessionStore, but
AuthMiddleware only validated tokens against the OAuth login-state map.
In dev the cookie path masked this; in the packaged Electron build
(file://) there is no cookie, so every authenticated API call returned
401 and no accounts/characters were displayed.

AuthMiddleware now checks the persistent session store first and falls
back to the OAuth state lookup for legacy tokens. The session-validation
handler already followed this order, which is why login appeared to
succeed while data fetches failed.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented May 4, 2026

Copy link
Copy Markdown

Warning

Rate limit exceeded

@guarzo has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 8 minutes and 30 seconds before requesting another review.

To keep reviews running without waiting, you can enable usage-based add-on for your organization. This allows additional reviews beyond the hourly cap. Account admins can enable it under billing.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 2126d0c7-a720-4ac6-8eb6-fdefca56b7eb

📥 Commits

Reviewing files that changed from the base of the PR and between 869a579 and 7fd4ded.

📒 Files selected for processing (1)
  • internal/http/middleware_test.go
📝 Walkthrough

Walkthrough

A new PersistentSessionValidator interface enables bearer token authentication against a persistent session store. The AuthMiddleware now accepts this validator and attempts persistent session validation first; if successful, the request is authenticated immediately. Otherwise, it falls back to the legacy login state resolution flow. Router and test wiring are updated to pass the validator parameter.

Changes

Bearer Token Authentication with Persistent Session Support

Layer / File(s) Summary
Interface & Signature
internal/http/middleware.go
PersistentSessionValidator interface added with ValidateSession(sessionID string) bool method. AuthMiddleware signature updated to accept persistentSessions PersistentSessionValidator parameter.
Bearer Token Validation Logic
internal/http/middleware.go
Bearer token handling now prefers persistent session validation; if available and valid, request is authenticated without further checks. Falls back to legacy loginSvc.ResolveAccountAndStatusByState flow requiring callbackComplete; returns 401 {"error":"invalid or expired token"} if both paths fail.
Integration & Wiring
internal/server/router.go, internal/http/middleware_test.go
Persistent session store initialization allowed to fail gracefully (logs warning, continues with nil store). Auth middleware registered with persistentSessionStore parameter in both production router and test setup.

Sequence Diagram

sequenceDiagram
    actor Client
    participant AuthMiddleware
    participant PersistentValidator
    participant LoginService
    participant NextHandler

    Client->>AuthMiddleware: Request with Bearer token
    
    alt Persistent Validator Available
        AuthMiddleware->>PersistentValidator: ValidateSession(token)
        alt Session Valid
            PersistentValidator-->>AuthMiddleware: true
            AuthMiddleware->>NextHandler: Authenticate & Forward
            NextHandler-->>Client: Response
        else Session Invalid
            PersistentValidator-->>AuthMiddleware: false
            AuthMiddleware->>LoginService: ResolveAccountAndStatusByState(token)
            LoginService-->>AuthMiddleware: account, status
            alt callbackComplete
                AuthMiddleware->>NextHandler: Authenticate & Forward
                NextHandler-->>Client: Response
            else Not Complete
                AuthMiddleware-->>Client: 401 invalid or expired token
            end
        end
    else No Persistent Validator
        AuthMiddleware->>LoginService: ResolveAccountAndStatusByState(token)
        LoginService-->>AuthMiddleware: account, status
        alt callbackComplete
            AuthMiddleware->>NextHandler: Authenticate & Forward
            NextHandler-->>Client: Response
        else Not Complete
            AuthMiddleware-->>Client: 401 invalid or expired token
        end
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 A token hops through sessions deep,
Persistent stores its secrets keep—
But if they fail, the old way's tried,
With callback checks as guide,
Now bearer tokens need not weep! 🔐

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title directly describes the main change: AuthMiddleware now accepts and validates persistent session tokens, which is the core fix addressing the 401 errors in packaged builds.
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.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/auth-middleware-persistent-session
✨ Simplify code
  • Create PR with simplified code
  • Commit simplified code in branch fix/auth-middleware-persistent-session

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

@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 `@internal/http/middleware_test.go`:
- Around line 67-69: The test helper createTestRouter currently passes nil for
the new validator into AuthMiddleware, so add a small stub implementation of the
validator interface in this test file and update createTestRouter calls to
inject it; then add two tests: one that constructs a persistent-session bearer
token and ensures the validator's ValidateSession returns true so the request is
authenticated via ValidateSession, and one where ValidateSession returns false
for a persistent token and AuthMiddleware falls back to calling
ResolveAccountAndStatusByState on the mocked sessionService (assert the fallback
path is used and the account is resolved). Reference the AuthMiddleware,
ValidateSession (validator method), ResolveAccountAndStatusByState
(sessionService method) and createTestRouter to locate where to inject the stub
and add the new test cases.
🪄 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: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 7247ccde-2a89-4fcd-8b4a-b8fa8cbed9f1

📥 Commits

Reviewing files that changed from the base of the PR and between 770cedb and 869a579.

📒 Files selected for processing (3)
  • internal/http/middleware.go
  • internal/http/middleware_test.go
  • internal/server/router.go

Comment thread internal/http/middleware_test.go Outdated
Adds a stub PersistentSessionValidator and two AuthMiddleware tests:
one where the validator accepts the bearer token, and one where it
rejects so the middleware falls back to ResolveAccountAndStatusByState.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
@guarzo
guarzo merged commit b97661e into main May 4, 2026
2 checks passed
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