Skip to content

fix: reuse bearer session on interactive authorization_code login - #3191

Merged
tada5hi merged 1 commit into
masterfrom
fix/authorize-login-duplicate-session
Jul 7, 2026
Merged

tada5hi merged 1 commit into
masterfrom
fix/authorize-login-duplicate-session

Conversation

@tada5hi

@tada5hi tada5hi commented Jul 7, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

An interactive client-web login created two auth_sessions rows:

  1. The SSR /authorize page password-grants a client-less bearer session purely to authenticate POST /authorize.
  2. /login/callback then exchanges the authorization code, whose authorization_code grant create()d a second session.

The bearer session (#1) was abandoned but lingered until expiry — and showed up in the user's sessions list, producing two near-simultaneous sessions per login.

Fix

Thread the bearer's session id through the authorization-code blob and reuse it in the authorization_code grant instead of minting a second session:

  • OAuth2AuthorizationCode gains an optional session_id (the auth-code blob is Redis-backed → no migration).
  • HTTPOAuth2Authorizer.authorizeWithRequest reads useRequestSessionId(event) — the id the authorization middleware stashed from the authenticated bearer (server-derived, never client input) — and threads it through OAuth2Authorization.authorize → OAuth2AuthorizationCodeIssuer.issue → entity.session_id.
  • OAuth2AuthorizeGrant.resolveSession reuses the referenced session iff it still exists and matches the code's sub / sub_kind / realm_id (defense in depth), stamps the authorizing client_id onto the row, and refresh()es it.
  • Fallback preserved: any mismatch, or a session-less authorize flow (external-IdP callback, non-interactive clients), still calls sessionManager.create() — prior behavior is unchanged.

Tests

  • test/unit/core/oauth2/grant-types/authorize.spec.ts — reuse vs. create-fallback branches, including the sub/realm-mismatch fail-safes.
  • test/unit/http/controllers/workflows/token/grant-authorize-session.spec.ts — end-to-end login → authorize → exchange asserting a single session survives (verified to fail without the fix).

Full server-core suite (1094 tests) + check:types green.

Summary by CodeRabbit

  • New Features

    • Interactive login sessions are now reused during authorization-code sign-in, helping keep users in a single session instead of creating duplicates.
    • Token exchanges now preserve session continuity when the original session is still valid.
  • Bug Fixes

    • Fixed cases where returning from web authorization could create extra session records.
    • If a prior session no longer matches, the app safely falls back to creating a new one.

An interactive client-web login created two `auth_sessions` rows: the SSR
`/authorize` page password-grants a client-less bearer session to authenticate
`POST /authorize`, then `/login/callback` exchanges the auth code, whose grant
created a second session. The bearer session was abandoned but lingered until
expiry and surfaced in the sessions list.

Thread the bearer's session id (server-derived, stashed by the authorization
middleware) through the auth-code blob and reuse it in the authorization_code
grant when it still matches the code's sub/sub_kind/realm_id, stamping the
authorizing client onto the row. Session-less flows (external-IdP callback,
non-interactive clients) and any mismatch fall back to creating a fresh session.

The auth-code blob is Redis-backed, so no migration is required.
Copilot AI review requested due to automatic review settings July 7, 2026 07:27
@coderabbitai

coderabbitai Bot commented Jul 7, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 53ed3e69-b201-4cb1-980e-215e3946eab6

📥 Commits

Reviewing files that changed from the base of the PR and between 58fcf93 and c241c88.

📒 Files selected for processing (10)
  • .agents/architecture.md
  • apps/server-core/src/adapters/http/adapters/oauth2/authorization/module.ts
  • apps/server-core/src/core/oauth2/authorization/code/issuer/module.ts
  • apps/server-core/src/core/oauth2/authorization/code/issuer/types.ts
  • apps/server-core/src/core/oauth2/authorization/module.ts
  • apps/server-core/src/core/oauth2/authorization/types.ts
  • apps/server-core/src/core/oauth2/grant-types/authorize.ts
  • apps/server-core/test/unit/core/oauth2/grant-types/authorize.spec.ts
  • apps/server-core/test/unit/http/controllers/workflows/token/grant-authorize-session.spec.ts
  • packages/core-kit/src/domains/authorization-code/entity.ts

📝 Walkthrough

Walkthrough

Adds session_id propagation for interactive OAuth2 authorization flows: the HTTP authorizer captures the current session id and threads it through authorize() into the issued authorization code; the authorize grant then resolves and reuses a matching existing session instead of always creating a new one, with fallback behavior preserved.

Changes

Session Reuse for Interactive authorization_code Grants

Layer / File(s) Summary
Session_id data contract
packages/core-kit/src/domains/authorization-code/entity.ts, apps/server-core/src/core/oauth2/authorization/code/issuer/types.ts, apps/server-core/src/core/oauth2/authorization/types.ts
Adds optional session_id/sessionId fields to OAuth2AuthorizationCode, OAuth2AuthorizationCodeIssuerOptions, and new OAuth2AuthorizationOptions type.
HTTP entry point and issuance wiring
apps/server-core/src/adapters/http/adapters/oauth2/authorization/module.ts, apps/server-core/src/core/oauth2/authorization/module.ts, apps/server-core/src/core/oauth2/authorization/code/issuer/module.ts
HTTP authorizer resolves the request's session id via useRequestSessionId and passes it through authorize(..., { sessionId }) into codeIssuer.issue(), which sets entity.session_id.
Session resolution in authorize grant
apps/server-core/src/core/oauth2/grant-types/authorize.ts
Adds resolveSession to reuse an existing session matching sub/sub_kind/realm_id (refreshing its client_id) or fall back to creating a new session, replacing the unconditional sessionManager.create call.
Tests and documentation
apps/server-core/test/unit/core/oauth2/grant-types/authorize.spec.ts, apps/server-core/test/unit/http/controllers/workflows/token/grant-authorize-session.spec.ts, .agents/architecture.md
Adds unit tests for session reuse/fallback scenarios, an end-to-end test verifying a single session is reused across login and code exchange, and documentation describing the new flow.

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

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant HttpAuthorizer
  participant OAuth2Authorization
  participant OAuth2AuthorizeGrant
  participant SessionManager

  Client->>HttpAuthorizer: GET /authorize (bearer token)
  HttpAuthorizer->>HttpAuthorizer: useRequestSessionId(event)
  HttpAuthorizer->>OAuth2Authorization: authorize(data, identity, { sessionId })
  OAuth2Authorization->>OAuth2Authorization: codeIssuer.issue({ sessionId })
  OAuth2Authorization-->>Client: authorization code (with session_id)

  Client->>OAuth2AuthorizeGrant: exchange code for token
  OAuth2AuthorizeGrant->>OAuth2AuthorizeGrant: resolveSession(authorizationCode)
  alt session_id matches sub/sub_kind/realm_id
    OAuth2AuthorizeGrant->>SessionManager: reuse & refresh session
  else no match
    OAuth2AuthorizeGrant->>SessionManager: create new session
  end
  OAuth2AuthorizeGrant-->>Client: access/refresh tokens (with session_id)
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 clearly matches the main change: reusing the bearer session during interactive authorization_code login.
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 docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/authorize-login-duplicate-session

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.

Copilot AI 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.

Pull request overview

This PR fixes duplicate auth_sessions creation during interactive authorization_code logins by threading the initial bearer session id through the issued authorization code and reusing that session during the token exchange when it still matches the same subject/realm.

Changes:

  • Extend the authorization-code blob to optionally carry a session_id and thread it through the /authorize pipeline into the code issuer.
  • Update the authorization_code grant to reuse an existing matching session (and refresh/stamp client_id) instead of creating a second session, with safe fallback to the prior “create new session” behavior.
  • Add unit + end-to-end tests covering reuse and fallback branches, including mismatch safeguards.

Reviewed changes

Copilot reviewed 10 out of 10 changed files in this pull request and generated no comments.

Show a summary per file
File Description
packages/core-kit/src/domains/authorization-code/entity.ts Adds optional session_id to the authorization-code entity contract.
apps/server-core/src/core/oauth2/grant-types/authorize.ts Reuses an existing session when session_id is present and matches subject/realm; otherwise creates a new session.
apps/server-core/src/core/oauth2/authorization/types.ts Introduces OAuth2AuthorizationOptions to carry sessionId through authorization.
apps/server-core/src/core/oauth2/authorization/module.ts Threads sessionId into authorization-code issuance.
apps/server-core/src/core/oauth2/authorization/code/issuer/types.ts Adds sessionId to code issuer options.
apps/server-core/src/core/oauth2/authorization/code/issuer/module.ts Persists session_id onto the issued authorization-code blob when provided.
apps/server-core/src/adapters/http/adapters/oauth2/authorization/module.ts Passes request-scoped session id (useRequestSessionId) into authorize(...).
apps/server-core/test/unit/core/oauth2/grant-types/authorize.spec.ts Unit tests for session reuse vs create fallback, including mismatch cases.
apps/server-core/test/unit/http/controllers/workflows/token/grant-authorize-session.spec.ts End-to-end test asserting only one session survives interactive login → authorize → exchange.
.agents/architecture.md Documents the “one session per interactive login” session continuity behavior and mechanism.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@pkg-pr-new

pkg-pr-new Bot commented Jul 7, 2026

Copy link
Copy Markdown

Open in StackBlitz

authup

npm i https://pkg.pr.new/authup@3191

@authup/client-web

npm i https://pkg.pr.new/@authup/client-web@3191

@authup/server-core

npm i https://pkg.pr.new/@authup/server-core@3191

@authup/access

npm i https://pkg.pr.new/@authup/access@3191

@authup/client-web-kit

npm i https://pkg.pr.new/@authup/client-web-kit@3191

@authup/client-web-kit-theme

npm i https://pkg.pr.new/@authup/client-web-kit-theme@3191

@authup/client-web-nuxt

npm i https://pkg.pr.new/@authup/client-web-nuxt@3191

@authup/client-web-theme

npm i https://pkg.pr.new/@authup/client-web-theme@3191

@authup/core-http-kit

npm i https://pkg.pr.new/@authup/core-http-kit@3191

@authup/core-kit

npm i https://pkg.pr.new/@authup/core-kit@3191

@authup/core-realtime-kit

npm i https://pkg.pr.new/@authup/core-realtime-kit@3191

@authup/errors

npm i https://pkg.pr.new/@authup/errors@3191

@authup/i18n

npm i https://pkg.pr.new/@authup/i18n@3191

@authup/kit

npm i https://pkg.pr.new/@authup/kit@3191

@authup/server-adapter-kit

npm i https://pkg.pr.new/@authup/server-adapter-kit@3191

@authup/server-adapter-node

npm i https://pkg.pr.new/@authup/server-adapter-node@3191

@authup/server-adapter-socket-io

npm i https://pkg.pr.new/@authup/server-adapter-socket-io@3191

@authup/server-adapter-web

npm i https://pkg.pr.new/@authup/server-adapter-web@3191

@authup/server-kit

npm i https://pkg.pr.new/@authup/server-kit@3191

@authup/server-test-kit

npm i https://pkg.pr.new/@authup/server-test-kit@3191

@authup/specs

npm i https://pkg.pr.new/@authup/specs@3191

commit: c241c88

@tada5hi
tada5hi merged commit b14caf1 into master Jul 7, 2026
13 checks passed
@tada5hi
tada5hi deleted the fix/authorize-login-duplicate-session branch July 7, 2026 08:29
@github-actions github-actions Bot mentioned this pull request Jul 7, 2026
tada5hi added a commit that referenced this pull request Jul 8, 2026
…gout (#3201)

* feat: retain the id_token in the kit store & round-trip client-web logout (plan 042)

The kit store discarded the grant response's id_token, so no kit RP could
pass an id_token_hint to the authup end_session_endpoint — every logout
degraded to the click-gated confirm page.

- add an `idToken` ref to the store (ID_TOKEN_UPDATED dispatcher event,
  CookieName.ID_TOKEN persistence, cleared in cleanup); applyTokenGrantResponse
  retains the existing value when a response carries none (refresh grants)
- client-web pages/logout.vue now performs the RP-initiated round-trip: it
  drops REQUIRED_LOGGED_OUT (so the interceptor no longer logs out before the
  page runs), captures idToken/realmId, runs the local-only store.logout(),
  then redirects to buildEndSessionURL(...) with the id_token hint and a
  post_logout_redirect_uri back to /login

store.logout() stays local-only — the round-trip ends the shared authup
session, never a DELETE /sessions/@me (which would collide with #3191
session reuse).

* fix: omit client_id in logout round-trip so the id_token_hint aud resolves the client

logout.vue passed client_id=web (the name) but the id_token aud is the
web client UUID. The end-session service aud/client_id cross-check then
failed, clearing hintVerified, so the session was never revoked and the
browser never bounced back to /login — every client-web logout silently
degraded to the confirm page, defeating the round-trip. Omitting client_id
lets the service resolve the client from the hint sole aud.
tada5hi added a commit that referenced this pull request Jul 9, 2026
#3200)

* feat: drop implicit & hybrid oauth2 response types (plan 042)

response_type=code is now the only supported response type (OAuth 2.1 /
RFC 9700 posture):

- the code-request validator requires response_type to be exactly
  'code'; token / id_token / none / hybrid combos are rejected
- OAuth2Authorization.authorize() is code-only (defense in depth) —
  the TOKEN/ID_TOKEN issuance branches, at_hash computation and the
  authorize-response accessToken/idToken outputs are gone; an
  openid-scoped code still carries its id_token on the code blob for
  the /token exchange
- AuthorizeController.confirm() no longer writes access_token /
  id_token into the redirect URL (tokens leaked via history, proxy
  logs and Referer - the fix at source is to not produce them at all)
- discovery response_types_supported now advertises only 'code'
- the code-request verifier requires PKCE + state for public clients
  unconditionally (the willIssueCode gate is dead with code-only)
- client-web's client URL generator emits response_type=code

BREAKING: RPs using the implicit or hybrid flow must migrate to the
authorization code flow with PKCE.

* feat: mint the id_token at the token exchange for an authoritative sid (plan 042)

The id_token was minted at authorize time from options.sessionId, so its
`sid` could reference a stale session (the #3191 session-reuse-vs-fallback
path) and the session-less federated IdP flow produced no id_token at all.

Move minting into the authorization_code grant, after resolveSession:

- OAuth2AuthorizeGrant.runWith mints the openid-scoped id_token with
  sid = the real backing session (reuse, fallback, and federated flows
  alike); at_hash (over the fresh access token) and c_hash are recomputed,
  nonce and auth_time ride from the code
- the authentication instant is carried on the auth-code blob as
  OAuth2AuthorizationCode.auth_time (replacing the removed id_token field —
  cache blob, no migration); OAuth2Authorization stamps it and drops its
  openIdTokenIssuer / identityResolver dependencies and id_token minting
- openIdTokenIssuer is wired into the TokenController authorize grant;
  codeIssuer.updateIdToken is removed

Fixes the plan-041 stale-sid residual; the federated openid flow now
returns an id_token whose sid matches the access token's session.

* docs: fix stale id_token-on-code-blob claim in architecture

The response-types section still said an openid-scoped code stores its
id_token on the code blob and the /token exchange returns it, contradicting
the minting-site section in the same file: authorize() no longer mints or
stores the id_token — it stamps auth_time on the blob (the id_token field was
removed) and the /token exchange mints and returns it. Reported by CodeRabbit
on PR #3200.
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.

2 participants