Repository navigation
feat!: per-application session token attribution, inventory API and revocation - #3404
Conversation
auth_sessions.client_id was the only per-application attribution, and resolveSession overwrote it on every authorize that reused a session. One browser session serves several applications (the hosted auth pages and the account console share the IdP origin by design), so the column was last-writer-wins and accurate for none of them. Per-app attribution, one of the two reasons per-realm system clients were split, did not hold. Attribution moves one level down, onto the token: - auth_session_tokens gains a nullable client_id (FK to auth_clients, ON DELETE CASCADE). Every issuer stamps it from the same client it already puts on the payload, so no lookups are added. - auth_sessions.client_id becomes write-once: it now means "the client that first authorized on this session" and is never overwritten. This is the shape both reference implementations use. Authentik's AuthenticatedSession is one per browser and carries no provider field, with the link on BaseGrantModel (AuthorizationCode / AccessToken / RefreshToken); Keycloak pairs one UserSessionModel with per-client AuthenticatedClientSessionModel children. Neither creates sibling sessions per application, and both derive per-application facts below the browser session. It is also the audience source OIDC back-channel logout needs. BREAKING CHANGE: auth_sessions.client_id now names the client that first authorized on a session rather than the most recent one, so GET/DELETE /sessions?filter[clientId] selects on that basis. The two differ only where several applications share one session. Revocation that should reach every session an application served must filter auth_session_tokens.client_id instead.
|
Note Reviews pausedUse the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe change adds nullable per-client attribution to session tokens, preserves first-client ownership on reused sessions, adds session-token management APIs, and updates account-console revocation to remove only the selected application’s tokens. ChangesPer-client session-token attribution
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant AccountConsole
participant SessionTokenController
participant SessionTokenService
participant SessionTokenRepositoryAdapter
AccountConsole->>SessionTokenController: request token revocation
SessionTokenController->>SessionTokenService: pass actor context and client filter
SessionTokenService->>SessionTokenRepositoryAdapter: load authorized matching tokens
SessionTokenService->>SessionTokenRepositoryAdapter: timestamp token rows
SessionTokenController-->>AccountConsole: return revocation result
Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
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. Comment |
authup
@authup/client-account-console
@authup/client-admin-console
@authup/client-auth-console
@authup/server-core
@authup/access
@authup/client-web-kit
@authup/client-web-kit-theme
@authup/client-web-nuxt
@authup/client-web-theme
@authup/core-http-kit
@authup/core-kit
@authup/core-realtime-kit
@authup/errors
@authup/i18n
@authup/kit
@authup/server-adapter-kit
@authup/server-adapter-node
@authup/server-adapter-socket-io
@authup/server-adapter-web
@authup/server-kit
@authup/server-test-kit
@authup/specs
commit: |
There was a problem hiding this comment.
Pull request overview
This PR refines Authup’s session attribution model so that per-application attribution lives on issued token rows (auth_session_tokens.client_id) instead of being “last-writer-wins” on the shared browser session (auth_sessions.client_id). It also introduces an admin-safe way to list/revoke sessions by the applications they actually served via ?usedClientId=—a key prerequisite for correct OIDC back-channel logout audience resolution.
Changes:
- Add nullable
clientIdattribution to session-token domain/entity + persist it from token payloads in both access/refresh issuers. - Make
auth_sessions.client_idwrite-once (“first client to authorize on this browser session”) by updating authorize grant behavior and tests. - Add
usedClientIdquery parameter support toGET/DELETE /sessions, wired through controller → service → repository with anEXISTSreach overauth_session_tokens.client_id.
Reviewed changes
Copilot reviewed 21 out of 21 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
| packages/core-kit/src/domains/session-token/entity.ts | Extends SessionToken with nullable clientId attribution. |
| docs/src/guide/deployment/account-console.md | Updates account-console deployment docs to reflect per-token attribution + write-once session client. |
| apps/server-core/test/unit/http/controllers/workflows/token/session-token-attribution.spec.ts | Adds end-to-end tests covering token-row attribution, write-once session client, and usedClientId reach for revoke/list. |
| apps/server-core/test/unit/http/controllers/workflows/token/account-console-session.spec.ts | Extends console continuity tests to cover forced account-console re-mint on shared session with per-token attribution. |
| apps/server-core/test/unit/core/oauth2/grant-types/authorize.spec.ts | Updates/extends authorize-grant unit tests for write-once session client semantics. |
| apps/server-core/test/unit/core/helpers/fake-session-token-repository.ts | Ensures fake repository persists clientId (defaulting to null). |
| apps/server-core/src/core/oauth2/token/issuer/refresh/module.ts | Persists clientId onto refresh token inventory rows from payload. |
| apps/server-core/src/core/oauth2/token/issuer/access/module.ts | Persists clientId onto access token inventory rows from payload. |
| apps/server-core/src/core/oauth2/session-token/types.ts | Extends session-token create input to accept optional nullable clientId. |
| apps/server-core/src/core/oauth2/grant-types/authorize.ts | Makes auth_sessions.client_id write-once when reusing sessions. |
| apps/server-core/src/core/entities/session/types.ts | Adds service options for usedClientId-driven reads and deletes. |
| apps/server-core/src/core/entities/session/service.ts | Threads clientIds option through getMany/deleteMany; treats usedClientId as an admin-path selector for deletes. |
| apps/server-core/src/core/authentication/session/types.ts | Extends repository query options to carry clientIds constraints. |
| apps/server-core/src/app/modules/oauth2/repositories/session-token/repository.ts | Persists clientId for DB-backed session-token inventory rows. |
| apps/server-core/src/app/modules/authentication/repositories/session.ts | Implements usedClientId reach: session.client_id IN (...) OR EXISTS(auth_session_tokens ...). |
| apps/server-core/src/adapters/http/controllers/entities/session/module.ts | Adds parsing for usedClientId request parameter and wires it into GET/DELETE handlers. |
| apps/server-core/src/adapters/database/migrations/postgres/1785871780234-SessionTokenClientId.ts | Adds nullable auth_session_tokens.client_id + FK for Postgres. |
| apps/server-core/src/adapters/database/migrations/mysql/1785871780234-SessionTokenClientId.ts | Adds nullable auth_session_tokens.client_id + FK for MySQL. |
| apps/server-core/src/adapters/database/domains/session-token/entity.ts | Adds clientId column + nullable FK relation to ClientEntity on session-token table. |
| .agents/references/authentik.md | Records the reference-model alignment (Authentik/Keycloak) for session vs per-token attribution. |
| .agents/architecture.md | Updates architecture docs to reflect attribution now living on token rows and session client being write-once. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| protected applyClientIds(qb: SelectQueryBuilder<Session>, ids?: string[]) { | ||
| if (!ids || ids.length === 0) { | ||
| return; | ||
| } | ||
|
|
||
| qb.andWhere(new Brackets((where) => { | ||
| where.where('session.client_id IN (:...usedClientIds)', { usedClientIds: ids }) | ||
| .orWhere( | ||
| 'EXISTS (SELECT 1 FROM auth_session_tokens ust' + | ||
| ' WHERE ust.session_id = session.id' + | ||
| ' AND ust.client_id IN (:...usedClientIds))', | ||
| { usedClientIds: ids }, | ||
| ); |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (3)
apps/server-core/test/unit/http/controllers/workflows/token/account-console-session.spec.ts (1)
34-37: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDuplicated token-row test helpers across both new specs. Both files implement identical
decodeJwtPayloadandreadTokenRowhelpers to assert the newSessionTokenEntity.clientIdattribution. One shared test helper removes the duplication and keeps the two suites in agreement when the token row changes.
apps/server-core/test/unit/http/controllers/workflows/token/account-console-session.spec.ts#L34-L37: movedecodeJwtPayloadand thereadTokenRowbody at lines 108-118 into a shared test helper module and import them.apps/server-core/test/unit/http/controllers/workflows/token/session-token-attribution.spec.ts#L79-L89: import the same shared helpers and delete the localdecodeJwtPayloadat lines 28-31 andreadTokenRowat lines 79-89.🤖 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 `@apps/server-core/test/unit/http/controllers/workflows/token/account-console-session.spec.ts` around lines 34 - 37, Create one shared test helper module containing decodeJwtPayload and the readTokenRow implementation currently used by both suites. In apps/server-core/test/unit/http/controllers/workflows/token/account-console-session.spec.ts#L34-L37 and its readTokenRow body at lines 108-118, replace the local helpers with imports; in apps/server-core/test/unit/http/controllers/workflows/token/session-token-attribution.spec.ts#L79-L89, import the same helpers and remove both local implementations, preserving existing assertions and behavior.apps/server-core/src/adapters/database/domains/session-token/entity.ts (1)
46-51: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winDeclare an explicit column type for
client_id.The property type is
Client['id'] | null, so the emitteddesign:typemetadata isObject, notString. TypeORM cannot derive a column type from that. Every sibling id column in this entity (session_id,parent_id,refresh_token_id) declarestype: 'uuid'. An implicit type also risks drift against the column type the new migrations create.♻️ Proposed change
`@Column`({ name: 'client_id', + type: 'uuid', nullable: true, default: null, }) clientId: Client['id'] | null;Run the following script to compare the entity column type with the migration column type:
#!/bin/bash set -euo pipefail fd -t f 'SessionTokenClientId' apps/server-core/src/adapters/database/migrations --exec cat -n # how sibling nullable id columns declare their type rg -n -B3 -A6 "name: 'client_id'" apps/server-core/src/adapters/database/domains --glob '*.ts'🤖 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 `@apps/server-core/src/adapters/database/domains/session-token/entity.ts` around lines 46 - 51, Update the clientId column definition in the session-token entity to explicitly declare type: 'uuid', matching the sibling session_id, parent_id, and refresh_token_id columns and the migration schema. Preserve its nullable and default: null settings.apps/server-core/src/adapters/database/migrations/mysql/1785871780234-SessionTokenClientId.ts (1)
29-35: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winAdd an index on
auth_session_tokens.client_id.The new client-based session lookup and revocation use token attribution. PostgreSQL does not create a lookup index for a foreign-key column. Add an explicit index in both migrations. Declare the index in
SessionTokenEntityif schema-drift tooling derives indexes from ORM metadata.
apps/server-core/src/adapters/database/migrations/mysql/1785871780234-SessionTokenClientId.ts#L29-L35: add the matching named index inupand remove it indown.apps/server-core/src/adapters/database/migrations/postgres/1785871780234-SessionTokenClientId.ts#L29-L35: add the matching named index inupand remove it indown.🤖 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 `@apps/server-core/src/adapters/database/migrations/mysql/1785871780234-SessionTokenClientId.ts` around lines 29 - 35, Introduce a named index for auth_session_tokens.client_id in both migration files: add it during up alongside the foreign key, and remove the same index during down. Update SessionTokenEntity with the matching index metadata if ORM schema-drift tooling derives indexes from it. Affected sites: apps/server-core/src/adapters/database/migrations/mysql/1785871780234-SessionTokenClientId.ts lines 29-35 and apps/server-core/src/adapters/database/migrations/postgres/1785871780234-SessionTokenClientId.ts lines 29-35.
🤖 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 @.agents/architecture.md:
- Around line 2736-2740: Update the column description in the schema
documentation so parent_id is explicitly described as a plain nullable UUID with
no self-FK, while client_id alone carries the nullable auth_clients foreign-key
and ON DELETE CASCADE details; keep refresh_token_id’s informational-lineage
description separate.
In `@apps/server-core/test/unit/core/oauth2/grant-types/authorize.spec.ts`:
- Around line 166-175: Ensure the refresh assertion targets this test’s
invocation rather than stale shared state: clear sessionManager.refreshCalls
alongside createCalls before grant.runWith, or assert against the final
refreshCalls entry. Preserve the expectation that the refreshed session has
sessionId and firstClientId.
---
Nitpick comments:
In `@apps/server-core/src/adapters/database/domains/session-token/entity.ts`:
- Around line 46-51: Update the clientId column definition in the session-token
entity to explicitly declare type: 'uuid', matching the sibling session_id,
parent_id, and refresh_token_id columns and the migration schema. Preserve its
nullable and default: null settings.
In
`@apps/server-core/src/adapters/database/migrations/mysql/1785871780234-SessionTokenClientId.ts`:
- Around line 29-35: Introduce a named index for auth_session_tokens.client_id
in both migration files: add it during up alongside the foreign key, and remove
the same index during down. Update SessionTokenEntity with the matching index
metadata if ORM schema-drift tooling derives indexes from it. Affected sites:
apps/server-core/src/adapters/database/migrations/mysql/1785871780234-SessionTokenClientId.ts
lines 29-35 and
apps/server-core/src/adapters/database/migrations/postgres/1785871780234-SessionTokenClientId.ts
lines 29-35.
In
`@apps/server-core/test/unit/http/controllers/workflows/token/account-console-session.spec.ts`:
- Around line 34-37: Create one shared test helper module containing
decodeJwtPayload and the readTokenRow implementation currently used by both
suites. In
apps/server-core/test/unit/http/controllers/workflows/token/account-console-session.spec.ts#L34-L37
and its readTokenRow body at lines 108-118, replace the local helpers with
imports; in
apps/server-core/test/unit/http/controllers/workflows/token/session-token-attribution.spec.ts#L79-L89,
import the same helpers and remove both local implementations, preserving
existing assertions and behavior.
🪄 Autofix
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 Plus
Run ID: 1829697c-6992-48db-8f94-7486647a97d7
📒 Files selected for processing (21)
.agents/architecture.md.agents/references/authentik.mdapps/server-core/src/adapters/database/domains/session-token/entity.tsapps/server-core/src/adapters/database/migrations/mysql/1785871780234-SessionTokenClientId.tsapps/server-core/src/adapters/database/migrations/postgres/1785871780234-SessionTokenClientId.tsapps/server-core/src/adapters/http/controllers/entities/session/module.tsapps/server-core/src/app/modules/authentication/repositories/session.tsapps/server-core/src/app/modules/oauth2/repositories/session-token/repository.tsapps/server-core/src/core/authentication/session/types.tsapps/server-core/src/core/entities/session/service.tsapps/server-core/src/core/entities/session/types.tsapps/server-core/src/core/oauth2/grant-types/authorize.tsapps/server-core/src/core/oauth2/session-token/types.tsapps/server-core/src/core/oauth2/token/issuer/access/module.tsapps/server-core/src/core/oauth2/token/issuer/refresh/module.tsapps/server-core/test/unit/core/helpers/fake-session-token-repository.tsapps/server-core/test/unit/core/oauth2/grant-types/authorize.spec.tsapps/server-core/test/unit/http/controllers/workflows/token/account-console-session.spec.tsapps/server-core/test/unit/http/controllers/workflows/token/session-token-attribution.spec.tsdocs/src/guide/deployment/account-console.mdpackages/core-kit/src/domains/session-token/entity.ts
ff72c5f to
ffe4963
Compare
auth_session_tokens was the one table with no query surface, so questions about it had to be answered by bolting parameters onto /sessions. That is how `?usedClientId=` came about: a session-shaped endpoint answering a token-shaped question, implemented as a repository option carrying raw cross-table SQL. It also could not express the thing that actually matters, revoking one application while the session keeps serving the others. `/session-tokens` is the resource instead. Read and revoke only, since rows are created solely by the grants. - `filter[sessionId]` lists the applications that rode one session, which is the audience OIDC back-channel logout needs. - `filter[clientId]` finds every session an application served, which the session column cannot: it names only the first authorizer. - The pair scopes a revoke to one application on one session, leaving the session alive so the others stay signed in. DELETE means revoke, not remove. The row is stamped and the jti is blocklisted with a TTL pinned to the token's real expiry. Dropping the row would block refresh, since the row is the authority for refresh validity, while leaving an already-issued access token verifying against a stateless JWKS adapter until its own exp. Authorization resolves through the session, because the rows carry neither realm nor subject: the repository joins it unconditionally and pins the columns the gate reads, so a `fields` projection cannot neutralize it. An actor without SESSION_READ is scoped to its own sessions' tokens by an AND-injected condition a client filter cannot displace. A bulk revoke must carry a target filter and is rejected otherwise, since unlike the session bulk revoke there is no self-service fallback to degrade to.
Typed access to the token inventory resource: getMany, getOne, delete and deleteMany over `/session-tokens`. `deleteMany` takes its query as a REQUIRED argument, unlike the session counterpart. The server rejects an unscoped bulk revoke, and an optional parameter would invite writing the one call shape that always fails. The sub-API is named `sessionToken`, matching the `EntityTypeMap` key, so it joins the derived entity-API registry automatically. The cast-free assignment in `pickEntityAPI` is the compile-time proof that it serves the `SessionToken` record type.
"Revoke access" removed the consent rows only. Consent is prompt-level: it stops the next silent issue and leaves already-issued tokens working until they expire, so the application the user just revoked kept working. It now also revokes that application's tokens. Because the rows hang off the session rather than being the session, the other applications on the same session stay signed in, which is what makes this per-application rather than a logout. The call is scoped to this user's own sessions explicitly, by id. The server force-scopes a caller that lacks SESSION_DELETE, but an administrator holds it, so relying on that would have an admin revoke the application for every user from their own account page.
…m dialog `revokeAll` awaits a confirmation dialog and then read `userId` from the store, defaulting to `undefined` when absent. The template only renders the control while a user is present, but the await is a window: a logout or an expired session while the dialog is open clears the store, and every filter below then widens to "no subject". That matters because the server force-scopes only callers WITHOUT the relevant permission. An administrator holds it, so an unscoped call from their own account page would revoke the application's consent rows, and now its tokens, for every user. The subject is captured once after the dialog resolves and the handler bails when it is gone. Also adds the session-token coverage the resource was missing: a non-privileged reader is scoped to its own sessions (the path that fails open if the injected ownership condition ever stops resolving), a cross-subject bulk revoke leaves the other subject's rows untouched, the unconditional session join survives `include=session` / `include=client`, and the typed client's array filter serializes as the console sends it.
|
Note GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 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 `@apps/server-core/src/core/entities/session-token/service.ts`:
- Around line 284-295: Update SessionTokenService.hasTargetCondition to require
an equality-style operator for target fields id, sessionId, and clientId, rather
than accepting every operator. Explicitly reject empty array values such as $in:
[] while preserving recursive filter-group handling and valid non-empty equality
targets.
In `@apps/server-core/test/unit/http/controllers/entities/session-token.spec.ts`:
- Around line 192-201: Update buildTwoAppSession to return firstSecret and
secondSecret, then replace the permissive refresh assertions with strict checks:
verify the untouched application successfully refreshes using firstSecret and
verify the revoked application’s refresh attempt using secondSecret fails.
Remove the catch that converts failures to undefined and assert the revoked
flow’s actual error outcome.
🪄 Autofix
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 Plus
Run ID: 4efa96ac-0e19-4273-bb88-8c0028def771
📒 Files selected for processing (38)
.agents/architecture.md.agents/references/authentik.mdapps/client-account-console/src/pages/applications.vueapps/server-core/src/adapters/database/domains/session-token/entity.tsapps/server-core/src/adapters/database/migrations/mysql/1785871780234-SessionTokenClientId.tsapps/server-core/src/adapters/database/migrations/postgres/1785871780234-SessionTokenClientId.tsapps/server-core/src/adapters/http/controllers/entities/index.tsapps/server-core/src/adapters/http/controllers/entities/session-token/index.tsapps/server-core/src/adapters/http/controllers/entities/session-token/module.tsapps/server-core/src/app/modules/database/repositories/schema-validation.tsapps/server-core/src/app/modules/http/modules/controller.tsapps/server-core/src/app/modules/oauth2/repositories/session-token/repository.tsapps/server-core/src/core/entities/event/entity-event-handler.tsapps/server-core/src/core/entities/index.tsapps/server-core/src/core/entities/session-token/index.tsapps/server-core/src/core/entities/session-token/schema.tsapps/server-core/src/core/entities/session-token/service.tsapps/server-core/src/core/entities/session-token/types.tsapps/server-core/src/core/oauth2/grant-types/authorize.tsapps/server-core/src/core/oauth2/session-token/types.tsapps/server-core/src/core/oauth2/token/issuer/access/module.tsapps/server-core/src/core/oauth2/token/issuer/refresh/module.tsapps/server-core/src/core/query/module.tsapps/server-core/test/unit/core/helpers/fake-session-token-repository.tsapps/server-core/test/unit/core/oauth2/grant-types/authorize.spec.tsapps/server-core/test/unit/http/controllers/entities/session-token.spec.tsapps/server-core/test/unit/http/controllers/workflows/token/account-console-session.spec.tsapps/server-core/test/unit/http/controllers/workflows/token/session-token-attribution.spec.tsdocs/src/guide/deployment/account-console.mdpackages/core-http-kit/src/client/module.tspackages/core-http-kit/src/client/type.tspackages/core-http-kit/src/domains/entities/index.tspackages/core-http-kit/src/domains/entities/session-token/index.tspackages/core-http-kit/src/domains/entities/session-token/module.tspackages/core-http-kit/src/domains/entities/session-token/types.tspackages/core-kit/src/domains/contstants.tspackages/core-kit/src/domains/session-token/entity.tspackages/core-kit/src/domains/types.ts
🚧 Files skipped from review as they are similar to previous changes (10)
- apps/server-core/src/core/oauth2/grant-types/authorize.ts
- apps/server-core/src/core/oauth2/token/issuer/access/module.ts
- apps/server-core/test/unit/core/oauth2/grant-types/authorize.spec.ts
- apps/server-core/src/core/oauth2/token/issuer/refresh/module.ts
- packages/core-kit/src/domains/session-token/entity.ts
- docs/src/guide/deployment/account-console.md
- apps/server-core/src/adapters/database/migrations/postgres/1785871780234-SessionTokenClientId.ts
- .agents/references/authentik.md
- .agents/architecture.md
- apps/server-core/src/adapters/database/domains/session-token/entity.ts
|
@coderabbitai pause |
✅ Action performedReviews paused. |
…voke `hasTargetCondition` asked whether a target KEY appeared anywhere in the filter tree. That is not the same question as whether the query is BOUNDED by one, and the difference is a mass revoke: - `filter[id]=!<uuid>` decodes to `ne` and selects every row but one. - `filter[id]=~x` decodes to `endsWith`. - `not(and(eq(id,'a'),eq(clientId,'b')))` keeps a compound `not` node whose inner leaves are ordinary `eq`, so a walker that recurses into every compound finds one and authorizes the complement. - `or(eq(id,'a'),eq(kind,'access'))` names a target key in one branch while the other selects every access token. The last two are reachable only through the expression dialect, since rapiq collapses `not(eq(..))` into an `ne` leaf but leaves a negated conjunction compound, and `or` has no bracket spelling. The guard now asks about boundedness: `and` is bounded when any conjunct is, `or` only when every branch is, `not` never, and a leaf only under `eq` or a non-empty `in`. This is inverted relative to the session bulk revoke it was modelled on: there, failing the check falls back to the SELF-service path, so permissive is the safe direction. Here, passing it IS the destructive path. Also strictens two assertions that could not fail. The revoke test mapped every refresh failure to `undefined` and then accepted either outcome, and asserted only that an earlier grant had returned a refresh token. They now assert that the untouched application refreshes and the revoked one is rejected, which is what proves the feature works. Reworded the migration docstrings: NULL means "not attributable to an application" and covers both pre-existing rows and minting paths with no client, rather than "never no client" as they claimed.
auth_sessions carries a nullable user_id AND a nullable client_id, and SessionManager.create populates exactly one from `sub` according to `subKind` (the same trick auth_consents uses). They are typed foreign keys for a polymorphic subject, so ON DELETE CASCADE can drop a subject's own sessions. Three other writers were putting the APPLICATION into client_id on user-subject sessions: the password grant, the MFA-login ticket, and the authorize grant. That placed an unrelated id behind a cascade meaning "this client owns this row", so deleting an application deleted a USER's session and, through auth_session_tokens.session_id, every other application's tokens riding it. Deleting the account console would have signed users out of the admin console. The column now has one meaning. The authorize grant leaves it alone, the password grant and the ticket no longer set it, and the MFA-login completion takes the client from the verified ticket payload, which already carries it, rather than from the session row. Which application authorized is auth_session_tokens.client_id, where a session serving several applications can say so. This also removes the write-once branch introduced earlier in this PR: with no one writing the column, there is nothing to make idempotent.
|
@coderabbitai full review |
✅ Action performedFull review finished. |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (2)
apps/server-core/test/unit/http/controllers/entities/session-token.spec.ts (1)
297-324: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winThe array-serialization claim is not covered by the assertions.
The comment states that the test proves an array of session ids serializes as a comma list. The assertions do not prove it.
clientIdisfirst.secondApp.id, andseconduses a different client, so no row ofsecond.sessionIdcan match the scope. An implementation that dropped every array element after the first would still pass this test.Use the same client for both sessions, or assert on rows of
second.sessionIdwith a client that appears in both.♻️ Suggested strengthening
expect(result.count).toBeGreaterThan(0); const revoked = await suite.dataSource .getRepository(SessionTokenEntity) .find({ where: { sessionId: first.sessionId } }); for (const row of revoked) { if (row.clientId === first.secondApp.id) { expect(row.revokedAt).not.toBeNull(); } else { expect(row.revokedAt).toBeNull(); } } + + // Proves the second array element stayed in scope. + const secondRows = await suite.dataSource + .getRepository(SessionTokenEntity) + .find({ where: { sessionId: second.sessionId } }); + expect(secondRows.length).toBeGreaterThan(0);Note: this additional assertion only works if a shared client serves both sessions.
buildTwoAppSessioncurrently creates fresh clients per call, so extend it to accept existing clients, or reuse one client across the two sessions.🤖 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 `@apps/server-core/test/unit/http/controllers/entities/session-token.spec.ts` around lines 297 - 324, Strengthen the “revokes across several sessions through the typed client” test by ensuring both sessions share the same client scope: update buildTwoAppSession to accept existing clients or otherwise reuse first’s client when creating second. Keep the sessionId array containing both session IDs, and assert that rows for second.sessionId with the shared client are revoked while non-matching rows remain unrevoked.apps/server-core/src/core/entities/session-token/service.ts (1)
199-219: 🚀 Performance & Scalability | 🔵 Trivial | 🏗️ Heavy liftThe bulk revoke loop is unbounded and fully sequential.
decodeQueryis limited toparameters: ['filters'], so pagination is dropped andfindAllByQueryreturns every matching row. A privileged caller who passes onlyfilter[clientId]=<busy-app>loads all tokens for that client, then performs one permission evaluation and two awaited I/O calls per row in sequence. For a high-traffic client this holds the request thread for a long time.Consider processing in batches and revoking each batch concurrently with a bounded concurrency, or cap the number of rows the repository returns per call.
🤖 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 `@apps/server-core/src/core/entities/session-token/service.ts` around lines 199 - 219, Update the bulk revoke flow around decodeQuery, findAllByQuery, and the entity loop to avoid loading and processing an unbounded result set sequentially. Preserve permission checks and counting while introducing repository pagination or a fixed result cap, and process each batch with bounded concurrency rather than awaiting every entity serially.
🤖 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 @.agents/references/authentik.md:
- Line 23: Correct the session attribution descriptions so user-subject sessions
keep auth_sessions.client_id null and application attribution exists only on
auth_session_tokens.client_id. In .agents/references/authentik.md:23 replace the
first-authorizing-client claim with client-subject FK semantics; in
apps/server-core/test/unit/http/controllers/workflows/token/account-console-session.spec.ts:165-168
state that the user session remains client-less; at :215-216 remove the claim
that it retains the admin-console client; and in
docs/src/guide/deployment/account-console.md:27-30 state that the user session’s
clientId remains null.
In `@apps/client-account-console/src/pages/applications.vue`:
- Around line 196-209: Update the session revocation flow around
httpClient.session.getMany to page through all sessions rather than fetching
only the first 50. Repeatedly fetch batches, collect each batch’s IDs, and call
httpClient.sessionToken.deleteMany for each batch using the existing clientId
filter, stopping when no sessions remain.
In `@apps/server-core/src/adapters/database/domains/session-token/entity.ts`:
- Around line 46-51: Update the clientId column decorator in the session-token
entity to explicitly set type: 'uuid', preserving its existing name, nullable,
and default settings.
In
`@apps/server-core/src/adapters/http/controllers/entities/session-token/module.ts`:
- Around line 90-100: Update the session-token deletion flow around drop and
SessionTokenService.revoke so the returned entity includes the newly assigned
revokedAt value. Either have the service return the re-read row after
revocation, or stamp revokedAt on the object returned by revoke, while
preserving the existing 202 response contract.
---
Nitpick comments:
In `@apps/server-core/src/core/entities/session-token/service.ts`:
- Around line 199-219: Update the bulk revoke flow around decodeQuery,
findAllByQuery, and the entity loop to avoid loading and processing an unbounded
result set sequentially. Preserve permission checks and counting while
introducing repository pagination or a fixed result cap, and process each batch
with bounded concurrency rather than awaiting every entity serially.
In `@apps/server-core/test/unit/http/controllers/entities/session-token.spec.ts`:
- Around line 297-324: Strengthen the “revokes across several sessions through
the typed client” test by ensuring both sessions share the same client scope:
update buildTwoAppSession to accept existing clients or otherwise reuse first’s
client when creating second. Keep the sessionId array containing both session
IDs, and assert that rows for second.sessionId with the shared client are
revoked while non-matching rows remain unrevoked.
🪄 Autofix
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 Plus
Run ID: efa68bc8-ddd6-4c8f-8c64-c29cb62f61b8
📒 Files selected for processing (41)
.agents/architecture.md.agents/references/authentik.mdapps/client-account-console/src/pages/applications.vueapps/server-core/src/adapters/database/domains/session-token/entity.tsapps/server-core/src/adapters/database/migrations/mysql/1785871780234-SessionTokenClientId.tsapps/server-core/src/adapters/database/migrations/postgres/1785871780234-SessionTokenClientId.tsapps/server-core/src/adapters/http/controllers/entities/index.tsapps/server-core/src/adapters/http/controllers/entities/session-token/index.tsapps/server-core/src/adapters/http/controllers/entities/session-token/module.tsapps/server-core/src/app/modules/database/repositories/schema-validation.tsapps/server-core/src/app/modules/http/modules/controller.tsapps/server-core/src/app/modules/oauth2/repositories/session-token/repository.tsapps/server-core/src/core/entities/event/entity-event-handler.tsapps/server-core/src/core/entities/index.tsapps/server-core/src/core/entities/session-token/index.tsapps/server-core/src/core/entities/session-token/schema.tsapps/server-core/src/core/entities/session-token/service.tsapps/server-core/src/core/entities/session-token/types.tsapps/server-core/src/core/oauth2/grant-types/authorize.tsapps/server-core/src/core/oauth2/grant-types/password.tsapps/server-core/src/core/oauth2/mfa-login/module.tsapps/server-core/src/core/oauth2/session-token/types.tsapps/server-core/src/core/oauth2/token/issuer/access/module.tsapps/server-core/src/core/oauth2/token/issuer/refresh/module.tsapps/server-core/src/core/query/module.tsapps/server-core/test/unit/core/helpers/fake-session-token-repository.tsapps/server-core/test/unit/core/oauth2/grant-types/authorize.spec.tsapps/server-core/test/unit/http/controllers/entities/session-token.spec.tsapps/server-core/test/unit/http/controllers/workflows/token/account-console-session.spec.tsapps/server-core/test/unit/http/controllers/workflows/token/grant-authorize-session.spec.tsapps/server-core/test/unit/http/controllers/workflows/token/session-token-attribution.spec.tsdocs/src/guide/deployment/account-console.mdpackages/core-http-kit/src/client/module.tspackages/core-http-kit/src/client/type.tspackages/core-http-kit/src/domains/entities/index.tspackages/core-http-kit/src/domains/entities/session-token/index.tspackages/core-http-kit/src/domains/entities/session-token/module.tspackages/core-http-kit/src/domains/entities/session-token/types.tspackages/core-kit/src/domains/contstants.tspackages/core-kit/src/domains/session-token/entity.tspackages/core-kit/src/domains/types.ts
| @Column({ | ||
| name: 'client_id', | ||
| nullable: true, | ||
| default: null, | ||
| }) | ||
| clientId: Client['id'] | null; |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
rg -n -C 4 'client_id|SessionTokenClientId' \
apps/server-core/src/adapters/database/domains/session-token/entity.ts \
apps/server-core/src/adapters/database/migrations/mysql/1785871780234-SessionTokenClientId.ts \
apps/server-core/src/adapters/database/migrations/postgres/1785871780234-SessionTokenClientId.ts \
apps/server-core/src/app/modules/database/repositories/schema-validation.tsRepository: authup/authup
Length of output: 15397
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== session-token entity =="
cat -n apps/server-core/src/adapters/database/domains/session-token/entity.ts | sed -n '1,90p'
echo
echo "== client entity =="
rg -n -C 5 '`@Entity`|class Client|id:' apps/server-core/src/adapters/database/domains -g '*client*.ts' -g 'entity.ts' || true
echo
echo "== schema validation references =="
cat -n apps/server-core/src/app/modules/database/repositories/schema-validation.ts | sed -n '1,220p'Repository: authup/authup
Length of output: 50369
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== Client entity =="
cat -n apps/server-core/src/adapters/database/domains/client/entity.ts | sed -n '31,38p'
echo
echo "== schema-validation file =="
wc -l apps/server-core/src/app/modules/database/repositories/schema-validation.ts
cat -n apps/server-core/src/app/modules/database/repositories/schema-validation.ts | sed -n '1,260p'
echo
echo "== TypeORM version/package references =="
for f in package.json apps/server-core/package.json; do
if [ -f "$f" ]; then
echo "-- $f"
node -e "const p=require('./$f'); console.log({dependencies:p.dependencies?.typeorm, devDependencies:p.devDependencies?.typeorm})" 2>/dev/null || true
fi
done
echo
echo "== local TypeScript/TypeORM available? =="
node - <<'JS'
try {
const ts = require('typescript');
const typeorm = require('typeorm');
console.log(JSON.stringify({typescript: ts.version, typeorm: typeorm.VERSION}));
} catch (e) {
console.log('node_modules may be missing: ' + String(e && e.code));
}
JSRepository: authup/authup
Length of output: 6923
Set the postgres client_id column type to uuid.
auth_clients.id is generated as uuid, and the PostgreSQL migration creates auth_session_tokens.client_id as uuid. The current TypeORM inference may leave type: undefined, which can drift from the migration and break boot-time schema validation. Add type: 'uuid' to the client_id column decorator.
🤖 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 `@apps/server-core/src/adapters/database/domains/session-token/entity.ts`
around lines 46 - 51, Update the clientId column decorator in the session-token
entity to explicitly set type: 'uuid', preserving its existing name, nullable,
and default settings.
|
@coderabbitai pause |
✅ Action performedReviews paused. |
Two defects from review, plus the descriptions the subject-FK change left stale. The account console fetched one page of sessions before revoking, while the consent deletion directly above loops. A user with more than the server's page cap kept the application signed in on every session past the first page. It now pages and revokes per batch, which also keeps the session id list out of an unbounded query string. Offset paging rather than the fetch-until-empty loop the consents use: those rows are deleted as they are read, so that loop converges. Sessions survive this operation, so the same shape would never terminate. `SessionTokenService.delete` returned the entity as it was read, so the response reported `revokedAt: null` for a token it had just revoked. The revoke now stamps the in-memory row as well, and a test pins the response body rather than only the database. Corrected `.agents/references/authentik.md` and the account console deployment guide, which still described `auth_sessions.client_id` as "the client that first authorized". It is a subject foreign key and is null for a user's session.
Makes per-application session state real: attributed on the server, queryable over the API, and acted on by the account console. Four commits, reviewable in order.
1. Attribute issued tokens to their client (
feat!)auth_sessions.client_idwas the only per-application attribution, andresolveSessionoverwrote it on every authorize that reused a session. One browser session serves several applications (the hosted auth pages and the account console share the IdP origin by design), so the column was last-writer-wins and accurate for none of them. Per-app attribution, one of the two stated reasons #3371 split the per-realm system clients, did not hold in this topology.auth_session_tokensgains a nullableclient_id(FK toauth_clients,ON DELETE CASCADE). Both issuers stamp it from the client already on the token payload, so no lookups are added. Null where the minting path has no client (an MFA-login completion rides a client-less session) and on pre-existing rows.auth_sessions.client_idbecomes write-once: "the client that first authorized on this session".This is the shape both reference implementations use. Authentik's
AuthenticatedSessionis one per browser and carries no provider field, with the link onBaseGrantModel; Keycloak pairs oneUserSessionModelwith per-clientAuthenticatedClientSessionModelchildren. Neither creates sibling sessions per application. Recorded in.agents/references/authentik.md.2. Expose the token inventory as a resource
auth_session_tokenswas the one table with no query surface, so questions about it had to be answered by bolting parameters onto/sessions. An earlier revision did exactly that with?usedClientId=: a session-shaped endpoint answering a token-shaped question, implemented as a repository option carrying raw cross-table SQL. It also could not express the thing that matters, revoking one application while the session keeps serving the others. It has been replaced./session-tokensis read and revoke only, since rows are created solely by the grants.filter[sessionId]filter[clientId]sessions.client_idcannot: it names only the first authorizerDELETEmeans revoke, not remove. The row is stamped and the jti is blocklisted with a TTL pinned to the token's real expiry. Dropping the row would block refresh (the row is the authority for refresh validity since plan 016) while leaving an already-issued access token verifying against a stateless JWKS adapter until its ownexp.Authorization resolves through the session, since the rows carry neither realm nor subject. The repository joins it unconditionally and pins the columns the gate reads, so a
fieldsprojection cannot neutralize it (the plan-039 discipline, through a relation instead of a column). An actor withoutSESSION_READis scoped to its own sessions' tokens by an AND-injected condition no client filter can displace. A bulk revoke must carry a target filter and is rejected otherwise: unlikeDELETE /sessionsthere is no self-service fallback to degrade to, so an unscoped call has to fail loudly rather than widen.3. Typed client
client.sessionToken.{getMany,getOne,delete,deleteMany}. Named after theEntityTypeMapkey, so it joins the derived entity-API registry automatically; the cast-free assignment inpickEntityAPIis the compile-time proof that it serves theSessionTokenrecord type.deleteManytakes its query as a required argument, unlike the session counterpart: the server rejects an unscoped bulk revoke, and an optional parameter would invite writing the one call shape that always fails.4. The account console actually signs out of a revoked application
"Revoke access" removed consent rows only. Consent is prompt-level, so it stops the next silent issue and leaves already-issued tokens working — the application the user just revoked kept working. It now revokes that application's tokens too, and because the rows hang off the session rather than being it, the other applications on the same session stay signed in.
The call is scoped to the user's own sessions explicitly, by id. The server force-scopes a caller that lacks
SESSION_DELETE, but an administrator holds it, so relying on that would have an admin revoke the application for every user from their own account page.Breaking change
auth_sessions.client_idis no longer written for user-subject sessions.It carries a nullable
user_idand a nullableclient_id, andSessionManager.createpopulates exactly one of them fromsubaccording tosubKind— the same trickauth_consentsuses. They are typed foreign keys for a polymorphic subject, soON DELETE CASCADEcan drop a subject's own sessions.Three writers were instead putting the application into
client_idon user sessions (the password grant, the MFA-login ticket, and the authorize grant). That placed an unrelated id behind a cascade meaning "this client owns this row", so deleting an application deleted a user's session and, throughauth_session_tokens.session_id, every other application's tokens riding it. Deleting the account console would have signed users out of the admin console.The column now has exactly one meaning: the client-subject FK. Consequences:
GET/DELETE /sessions?filter[clientId]=now selects sessions whose subject is that client, symmetric withfilter[userId]. It no longer returns a user's sessions because some application authorized on them./session-tokens?filter[clientId]=, where a session serving several applications can say so.Unblocks
Resolves the open "audience resolution" decision for OIDC back-channel logout, whose correct audience is every RP that rode the ending session. Notifying
session.client_idalone is correct only for single-RP sessions; approximating from consent rows under-notifies, since consent is skipped forbuiltInclients, so neither console would ever be told.Verification
check:types(test-inclusive) clean.migrationstable at full revert.createSchemaBuilder().log()) on both dialects:client_idproduces no column statement, so the migration matches TypeORM's metadata. This contradicts an earlier review suggestion to usevarchar(36)on MySQL —auth_sessions.client_idisvarchar(255)there (1766830857009-Default.ts), andvarchar(36)would introduce drift.session-token-attribution.spec.tspins two applications on one session leavingsession.clientIdat the first while each application's rows carry their own.session-token.spec.tspins the resource: the audience query, finding every session an application served, a per-application revoke that leaves the session and the other application intact, rejection of an unscoped bulk revoke, and single-token revoke.Not verified by execution:
apps/client-account-console/src/pages/applications.vuehas no spec, and I did not run the app to watch a revoke sign the user out. The endpoint it calls is covered end to end (including that the revoked application's refresh is rejected while the untouched one still works), and the change is ~26 lines, but the UI path itself was verified by reading, not by running.One caveat on the suite: the
provisioning.spec.tswildcard-realm case flakes intermittently under parallel workers against the shared sqlite file. It passes in isolation and on re-run, and this branch does not touch provisioning.Summary by CodeRabbit