Skip to content

feat: validate & harden the rp-initiated logout endpoint (plan 042) - #3198

Merged
tada5hi merged 1 commit into
masterfrom
feat/oauth2-end-session-hardening
Jul 8, 2026
Merged

tada5hi merged 1 commit into
masterfrom
feat/oauth2-end-session-hardening

Conversation

@tada5hi

@tada5hi tada5hi commented Jul 8, 2026 •

Copy link
Copy Markdown
Collaborator

Plan 042 items 4, 2, and 5 — the /logout hardening bundle (follow-ups to #3196/#3197).

Request validation (item 4)

LogoutController previously read id_token_hint / client_id / post_logout_redirect_uri / state / realm_id / realm_name raw from body+query. A new OAuth2EndSessionRequestValidator (mirroring the authorize code-request validator) now runs over the merged input:

  • length caps on every param (id_token_hint ≤ 4096, post_logout_redirect_uri ≤ 2000 + URL check, state ≤ 2048)
  • blank params (?state=) treated as absent, not as failures
  • the realm_id/realm_name hint canonicalized trim().toLowerCase() at the ingress (canonical-identifier-form layer 3, same contract as the token endpoint's readRealmHint) — a mixed-case realm hint previously failed closed and silently dropped the redirect validation
  • on a validation failure the controller falls back to a parameter-less confirm page — every attacker-controlled value dropped, no revoke, no redirect, but the human behind the browser can still sign out (never a JSON error on a top-level navigation)

Bounded expired-hint window (item 2)

New config endSessionHintGracePeriod (END_SESSION_HINT_GRACE_PERIOD, seconds): with a positive value, an id_token_hint expired beyond the window counts as unverified — bounding how long a leaked id_token stays a replayable remote logout. Post-verify exp check in OAuth2EndSessionService (no server-kit change); exp-less payloads fail closed under a bounded window. Default 0 = unbounded, spec/Keycloak parity — the effective bound then remains session lifetime, since a hint can only revoke the live, sub-matched session its sid references.

Endpoint hardening (item 5)

  • Referrer-Policy: no-referrer on every SSR auth page (renderUIPage is the single choke point; the page URLs carry id_token_hint, code, redirect, state)
  • the HTTP access-log middleware now redacts sensitive query params (id_token_hint, id_token, access_token, refresh_token, token, code, client_secret) — a GET /logout?id_token_hint=<jwt> previously wrote the signature-valid token verbatim into the logger.http line
  • deliberately not included (decided with the plan): no Sec-Fetch-Site confirm gate (a legitimate RP-initiated logout is a cross-site top-level navigation; the forced-logout CSRF is already mitigated by the sub-match + hintSub gate) and no /logout-specific rate limit (the global identity-tiered limiter covers it; a hint can only revoke its own sub-matched session, so there is no amplification)

Tests

  • grace-window matrix in end-session/service.spec.ts (default-unbounded, beyond/within window, unexpired, exp-less fail-closed)
  • new end-session/validator.spec.ts (canonicalization, blank-as-absent, caps, URL check)
  • new http/middleware/logger.spec.ts (redaction incl. repeated params, untouched non-sensitive URLs)
  • e2e additions in logout/end-session.spec.ts: hardening headers, mixed-case realm hint resolves the client (asserted via hydration payload), malformed input drops all params without revoking

Full server-core suite green (1172 tests). Note: grant-authorize.spec.ts › "should work with authorize grant for confidential client" is a pre-existing flake (FK violation in SessionTokenRepositoryAdapter.create when a concurrent worker deletes the backing session mid-grant) — it failed two full-suite runs and passed a third with identical code, and passes in isolation; unrelated to this diff.

Summary by CodeRabbit

  • New Features

    • Added support for a configurable grace period when accepting slightly expired logout tokens.
    • Improved logout request handling with case-insensitive realm hints and better support for blank or malformed parameters.
  • Bug Fixes

    • Sensitive query parameters are now hidden from access logs.
    • Auth pages now send a no-referrer policy to reduce accidental leakage of login/logout data.
    • Invalid logout requests now safely fall back to a neutral confirmation page instead of failing with errors.

- add OAuth2EndSessionRequestValidator: length caps on every /logout
  param, blank params treated as absent, realm hint canonicalized
  (trim + lowercase) at the ingress; on validation failure the
  controller falls back to a parameter-less confirm page instead of a
  JSON error (every attacker-controlled value dropped, no revoke)
- add endSessionHintGracePeriod config (END_SESSION_HINT_GRACE_PERIOD):
  seconds past exp an expired id_token_hint is still accepted for a
  server-side revoke; default 0 keeps spec/Keycloak parity (unbounded),
  a positive window bounds how long a leaked id_token stays a
  replayable remote logout (exp-less payloads fail closed)
- set Referrer-Policy: no-referrer on every SSR auth page (the URLs
  carry id_token_hint / code / redirect / state)
- redact sensitive query params (id_token_hint, tokens, code,
  client_secret) from access-log lines - a GET /logout?id_token_hint=
  <jwt> no longer writes a signature-valid token into the log
Copilot AI review requested due to automatic review settings July 8, 2026 09:40

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@coderabbitai

coderabbitai Bot commented Jul 8, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This PR hardens the /logout (RP-initiated end-session) endpoint: a new OAuth2EndSessionRequestValidator sanitizes and canonicalizes request parameters with a confirm-page fallback on failure, OAuth2EndSessionService adds a configurable hintGracePeriod for expired id_token_hint acceptance, and logging/response headers redact sensitive query parameters and add a referrer-policy header. Configuration, docs, and tests are updated accordingly.

Changes

Logout Endpoint Hardening

Layer / File(s) Summary
End-session request validator
apps/server-core/src/core/oauth2/end-session/validator.ts, .../index.ts, test/unit/.../validator.spec.ts
New OAuth2EndSessionRequestValidator uses zod with a blankAsAbsent helper to treat blank params as absent, enforces length/format limits, and canonicalizes realm_id/realm_name; re-exported from the module index and covered by unit tests.
LogoutController integration
apps/server-core/src/adapters/http/controllers/workflows/logout/module.ts, test/unit/.../logout/end-session.spec.ts
LogoutController runs the validator against merged request data inside try/catch, falling back to {} on failure, before calling endSessionService.verify(); new tests cover hardening headers, mixed-case realm hints, and malformed-input fallback.
id_token_hint grace period
apps/server-core/src/core/oauth2/end-session/service.ts, .../types.ts, test/unit/.../service.spec.ts
OAuth2EndSessionService stores hintGracePeriod and adds isWithinHintGraceWindow() to gate acceptance of expired hints during verify(); OAuth2EndSessionServiceContext gains an optional hintGracePeriod; tests cover unbounded/bounded window scenarios.
Configuration wiring
apps/server-core/src/app/modules/config/*, .../http/modules/controller.ts, docs/...
Adds END_SESSION_HINT_GRACE_PERIOD env var, endSessionHintGracePeriod config field/type/normalization/validation, wires it into createLogoutController, and updates deployment/API docs and architecture notes.
Log/response redaction
apps/server-core/src/adapters/http/middleware/built-in/logger.ts, .../ui/render.ts, test/unit/.../logger.spec.ts
Adds redactSensitiveURLParams() to mask sensitive query values in access logs and adds a referrer-policy: no-referrer header on rendered auth pages; new unit tests validate redaction behavior.

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

Possibly related PRs

  • authup/authup#3196: Extends the same RP-initiated logout implementation, modifying the same /logout controller and OAuth2EndSessionService.verify() flow introduced for the original end-session feature.
🚥 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: validation and hardening of the RP-initiated logout endpoint.
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 feat/oauth2-end-session-hardening

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.

@pkg-pr-new

pkg-pr-new Bot commented Jul 8, 2026

Copy link
Copy Markdown

Open in StackBlitz

authup

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

@authup/client-web

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

@authup/server-core

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

@authup/access

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

@authup/client-web-kit

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

@authup/client-web-kit-theme

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

@authup/client-web-nuxt

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

@authup/client-web-theme

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

@authup/core-http-kit

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

@authup/core-kit

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

@authup/core-realtime-kit

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

@authup/errors

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

@authup/i18n

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

@authup/kit

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

@authup/server-adapter-kit

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

@authup/server-adapter-node

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

@authup/server-adapter-socket-io

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

@authup/server-adapter-web

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

@authup/server-kit

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

@authup/server-test-kit

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

@authup/specs

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

commit: 4e69004

@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 (2)
apps/server-core/src/adapters/http/controllers/workflows/logout/module.ts (1)

55-60: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Log validation failures for observability.

The catch block silently swallows all errors, including potential non-validation bugs in the validator (e.g., TypeError). A debug-level log — without echoing the attacker-controlled input — would help distinguish expected validation rejections from unexpected runtime errors during incident investigation.

📝 Suggested addition
         let data: OAuth2EndSessionRequest;
         try {
             data = await this.validator.run(merged);
         } catch (e) {
+            // eslint-disable-next-line no-console
+            console.debug('Logout request validation failed, falling back to parameter-less confirm page', e instanceof Error ? e.message : e);
             data = {};
         }
🤖 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/http/controllers/workflows/logout/module.ts`
around lines 55 - 60, The logout flow’s validation fallback in the `module.ts`
controller currently swallows every exception from `this.validator.run(merged)`,
which hides unexpected runtime bugs. Update the `catch` around
`this.validator.run` to emit a debug-level log with a clear message and the
thrown error, while avoiding any attacker-controlled request data; keep the
existing `data = {}` fallback for expected validation failures. Use the
`validator.run` call in the logout module as the fix location.
apps/server-core/test/unit/core/oauth2/end-session/validator.spec.ts (1)

52-62: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Add max-length rejection tests for remaining fields.

Tests cover id_token_hint and state max-length rejection, but client_id (256), realm_id (256), realm_name (256), and post_logout_redirect_uri (2000) max-length boundaries are untested. Adding these would ensure length limits aren't accidentally relaxed.

🧪 Suggested additional tests
     it('should reject a non-URL post_logout_redirect_uri', async () => {
         await expect(validator.run({ post_logout_redirect_uri: 'not a url' })).rejects.toThrow();
     });
+
+    it('should reject an oversized client_id', async () => {
+        await expect(validator.run({ client_id: 'x'.repeat(300) })).rejects.toThrow();
+    });
+
+    it('should reject an oversized realm_id', async () => {
+        await expect(validator.run({ realm_id: 'x'.repeat(300) })).rejects.toThrow();
+    });
+
+    it('should reject an oversized realm_name', async () => {
+        await expect(validator.run({ realm_name: 'x'.repeat(300) })).rejects.toThrow();
+    });
+
+    it('should reject an oversized post_logout_redirect_uri', async () => {
+        await expect(validator.run({ post_logout_redirect_uri: `https://example.com/${'x'.repeat(2000)}` })).rejects.toThrow();
+    });
 });
🤖 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/core/oauth2/end-session/validator.spec.ts` around
lines 52 - 62, Add max-length rejection coverage in validator.spec for the
remaining EndSessionValidator fields that currently lack boundary tests. Extend
the existing validator.run rejection cases to include oversized client_id,
realm_id, realm_name, and post_logout_redirect_uri inputs, using the same style
as the current id_token_hint and state tests so the length limits enforced by
the validator stay covered.
🤖 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 `@apps/server-core/src/adapters/http/controllers/workflows/logout/module.ts`:
- Around line 55-60: The logout flow’s validation fallback in the `module.ts`
controller currently swallows every exception from `this.validator.run(merged)`,
which hides unexpected runtime bugs. Update the `catch` around
`this.validator.run` to emit a debug-level log with a clear message and the
thrown error, while avoiding any attacker-controlled request data; keep the
existing `data = {}` fallback for expected validation failures. Use the
`validator.run` call in the logout module as the fix location.

In `@apps/server-core/test/unit/core/oauth2/end-session/validator.spec.ts`:
- Around line 52-62: Add max-length rejection coverage in validator.spec for the
remaining EndSessionValidator fields that currently lack boundary tests. Extend
the existing validator.run rejection cases to include oversized client_id,
realm_id, realm_name, and post_logout_redirect_uri inputs, using the same style
as the current id_token_hint and state tests so the length limits enforced by
the validator stay covered.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 701a9ec0-a13b-4b67-b020-f829fcb99708

📥 Commits

Reviewing files that changed from the base of the PR and between 781c097 and 4e69004.

📒 Files selected for processing (20)
  • .agents/architecture.md
  • apps/server-core/src/adapters/http/controllers/workflows/logout/module.ts
  • apps/server-core/src/adapters/http/middleware/built-in/logger.ts
  • apps/server-core/src/adapters/http/ui/render.ts
  • apps/server-core/src/app/modules/config/constants.ts
  • apps/server-core/src/app/modules/config/normalize.ts
  • apps/server-core/src/app/modules/config/read/env.ts
  • apps/server-core/src/app/modules/config/types.ts
  • apps/server-core/src/app/modules/config/validator.ts
  • apps/server-core/src/app/modules/http/modules/controller.ts
  • apps/server-core/src/core/oauth2/end-session/index.ts
  • apps/server-core/src/core/oauth2/end-session/service.ts
  • apps/server-core/src/core/oauth2/end-session/types.ts
  • apps/server-core/src/core/oauth2/end-session/validator.ts
  • apps/server-core/test/unit/core/oauth2/end-session/service.spec.ts
  • apps/server-core/test/unit/core/oauth2/end-session/validator.spec.ts
  • apps/server-core/test/unit/http/controllers/workflows/logout/end-session.spec.ts
  • apps/server-core/test/unit/http/middleware/logger.spec.ts
  • docs/src/guide/deployment/configuration-server-core.md
  • docs/src/guide/development/api-oauth2.md

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