Skip to content

feat: oAuth2/OIDC spec compliance fixes - #2922

Merged
tada5hi merged 2 commits into
masterfrom
2919-oauth2
Mar 20, 2026
Merged

tada5hi merged 2 commits into
masterfrom
2919-oauth2

Conversation

@tada5hi

@tada5hi tada5hi commented Mar 20, 2026 •

Copy link
Copy Markdown
Collaborator

closes #2919

Summary by CodeRabbit

  • New Features

    • Added nonce support for authorization codes
    • Tokens now include issuer (iss) with optional realm-scoped URLs
    • Added token-hash computation for ID token claims
  • Refactor

    • Authorization codes are now atomically consumed during verification (single-use)
    • Verifier no longer exposes standalone code removal operations
    • ID token issuance flow adjusted to update codes after issuance
  • Tests

    • Added token-hash unit tests
    • Updated verifier tests for single-use behavior

@coderabbitai

coderabbitai Bot commented Mar 20, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Added nonce propagation and ID token hashing, made issuer (iss) realm-scoped across token types, introduced atomic cache pop for single-use authorization codes, updated verifier to consume codes, and adjusted grant flow to rely on atomic consumption.

Changes

Cohort / File(s) Summary
Authorize Grant Flow
apps/server-core/src/adapters/http/adapters/oauth2/grant-types/authorize.ts
Removed intermediate variable and explicit code-verifier cleanup; now returns result of token grant run directly and relies on verifier's atomic consumption.
Authorization Code Repository & Cache Pop
apps/server-core/src/app/modules/oauth2/repositories/authorize/code/repository.ts, apps/server-core/src/core/oauth2/authorization/code/repository/types.ts, packages/server-kit/src/services/cache/types.ts, packages/server-kit/src/services/cache/adapters/memory.ts, packages/server-kit/src/services/cache/adapters/redis.ts
Added popOneById to code repository and pop to cache interface/implementations (memory, redis) to support atomic get-and-delete for single-use codes.
Authorization Code Verifier
apps/server-core/src/core/oauth2/authorization/code/verifier/module.ts, apps/server-core/src/core/oauth2/authorization/code/verifier/types.ts, apps/server-core/test/unit/core/oauth2/authorization/code/verifier/module.spec.ts
Verifier now consumes codes via popOneById (atomic); removed external remove/removeById APIs; tests updated to assert single-use consumption.
Nonce Propagation
apps/server-core/src/core/oauth2/authorization/code-request/validator.ts, apps/server-core/src/core/oauth2/authorization/code/issuer/module.ts, apps/server-core/src/core/oauth2/authorization/code/issuer/types.ts, packages/core-kit/src/domains/authorization-code/entity.ts
Added nonce validation on auth requests, persisted nonce on issued authorization codes, added updateIdToken to code issuer to attach ID token post-issuance.
ID Token Hashing Helpers & Tests
apps/server-core/src/core/oauth2/authorization/helpers.ts, apps/server-core/test/unit/core/oauth2/authorization/helpers.spec.ts
Exported base64URLEncode and added buildOAuth2TokenHash(value) which SHA-256s, truncates, and base64url-encodes; unit tests added for correctness and determinism.
Authorization Module (ID token flow)
apps/server-core/src/core/oauth2/authorization/module.ts
Reworked ID token issuance to a two-phase flow: issue access/token/code first, compute and inject at_hash/c_hash, include nonce when present, and update authorization code with issued ID token via updateIdToken.
Token Issuers — realm-scoped iss
apps/server-core/src/core/oauth2/token/issuer/base.ts, apps/server-core/src/core/oauth2/token/issuer/access/module.ts, apps/server-core/src/core/oauth2/token/issuer/open-id/module.ts, apps/server-core/src/core/oauth2/token/issuer/refresh/module.ts, apps/server-core/test/unit/core/oauth2/token/issuer/open-id/module.spec.ts
Added buildIss(input) to base issuer and conditionally include realm-scoped iss ({issuer}/realms/{realm_name}) in access, refresh, and ID token persistence; tests updated for realm behavior.
Refresh / Access Issuer small changes
apps/server-core/src/core/oauth2/token/issuer/refresh/module.ts, apps/server-core/src/core/oauth2/token/issuer/access/module.ts
Include iss when present in token data persisted by refresh and access token issuers.
Interface Additions
apps/server-core/src/core/oauth2/authorization/code/issuer/types.ts
Added updateIdToken(entity, idToken) to authorization code issuer interface to allow updating stored code with ID token after issuance.
Domain Types
packages/core-kit/src/domains/authorization-code/entity.ts
Added optional nonce to OAuth2AuthorizationCode and OAuth2AuthorizationCodeRequest types.
Tests (helpers & openid issuer)
apps/server-core/test/unit/core/oauth2/authorization/helpers.spec.ts, apps/server-core/test/unit/core/oauth2/token/issuer/open-id/module.spec.ts
New tests for token hash helper; updated openid issuer tests to assert realm-scoped iss when realm_name present and fallback behavior otherwise.

Sequence Diagrams

sequenceDiagram
    actor Client
    participant AuthServer as Authorization Server
    participant CodeIssuer as Code Issuer
    participant Cache
    Client->>AuthServer: Authorization Request (with nonce)
    AuthServer->>CodeIssuer: issue(input with nonce)
    CodeIssuer->>Cache: save authorization code (contains nonce)
    CodeIssuer-->>AuthServer: OAuth2AuthorizationCode
    AuthServer-->>Client: Redirect with code
Loading
sequenceDiagram
    actor Client
    participant AuthServer as Authorization Server
    participant Cache
    participant TokenIssuer as Token Issuer
    Client->>AuthServer: Token Request (code)
    AuthServer->>Cache: popOneById(code)
    alt code found (atomic)
        Cache-->>AuthServer: OAuth2AuthorizationCode (removed)
        AuthServer->>TokenIssuer: issue tokens (include nonce)
        TokenIssuer->>TokenIssuer: compute at_hash / c_hash
        TokenIssuer-->>AuthServer: Access Token + ID Token
        AuthServer-->>Client: Token Response
    else code missing
        Cache-->>AuthServer: null
        AuthServer-->>Client: Error (invalid_grant)
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

🐰 A nonce hopped in, tucked safe and neat,
Hashes danced short on token-sized feet,
Issuers learned realms and scoped their name,
Codes pop once—no two plays the same,
I nibble specs, and clap my paws of glee. ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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 title 'feat: oAuth2/OIDC spec compliance fixes' directly summarizes the main change: implementing OAuth2/OIDC specification compliance improvements as detailed in issue #2919.
Linked Issues check ✅ Passed All five coding objectives from issue #2919 are addressed: nonce propagation [added to code request validator and entity], at_hash/c_hash in ID token [computed and injected in authorization module], realm-scoped iss claim [buildIss method added to base issuer and applied across token types], authorization code single-use enforcement [pop method added to cache implementations], and code verifier integration updated accordingly.
Out of Scope Changes check ✅ Passed All changes directly support the five spec compliance objectives from issue #2919: cache pop operations, nonce field additions, hash computation helpers, issuer realm-scoping, and code verification refactoring. No unrelated changes detected.

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

✨ 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 2919-oauth2

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 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: 2

🧹 Nitpick comments (2)
apps/server-core/src/core/oauth2/authorization/code/issuer/module.ts (1)

53-62: Verify TTL behavior on updateIdToken is intentional.

Using this.options.maxAge resets the authorization code's TTL to a fresh duration. If time has elapsed since code issuance, this could extend its validity beyond the original window. Consider whether the remaining TTL should be preserved instead.

💡 Alternative: preserve remaining TTL

If preserving the original expiry is desired, track the original expiration timestamp on the entity and calculate remaining TTL:

 async updateIdToken(
     entity: OAuth2AuthorizationCode,
     idToken: string,
 ) : Promise<void> {
     entity.id_token = idToken;

-    await this.repository.save(entity, {
-        maxAge: this.options.maxAge,
-    });
+    // Pass entity with existing TTL metadata, or omit maxAge to use repository default
+    await this.repository.save(entity);
 }

This would require the repository to handle TTL preservation logic.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/core/oauth2/authorization/code/issuer/module.ts` around
lines 53 - 62, The updateIdToken method currently resets the code TTL by passing
this.options.maxAge into repository.save; change it to preserve the original
remaining TTL instead of extending it. Inspect OAuth2AuthorizationCode for an
expiration timestamp (e.g., expires_at or created_at + original TTL) and compute
remainingTtl = expiresAt - now (min 0), then call this.repository.save(entity, {
maxAge: remainingTtl }) or omit maxAge if remainingTtl <= 0 so the repository
enforces expiry; update/updateIdToken to use that remainingTtl calculation (and
if the entity lacks an expiry field, add one to OAuth2AuthorizationCode and
ensure issuance sets it).
apps/server-core/src/core/oauth2/authorization/helpers.ts (1)

41-41: Consider: Hash algorithm must match the ID token's signing algorithm per OIDC Core §3.3.2.11.

The buildOAuth2TokenHash() function uses a hardcoded SHA-256 algorithm for generating at_hash and c_hash claims. However, per OIDC Core specification, the hash algorithm should match the signing algorithm: SHA-256 for RS256/ES256/HS256, SHA-384 for RS384/ES384/HS384, and SHA-512 for RS512/ES512/HS512.

While the codebase supports multiple signing algorithms (RS256, RS384, RS512, ES256, ES384, ES512, HS256, HS384, HS512), the hash calculation does not adapt to the configured algorithm. To ensure spec compliance, consider refactoring buildOAuth2TokenHash() to accept and use the appropriate hash algorithm based on the realm's signing algorithm configuration.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/core/oauth2/authorization/helpers.ts` at line 41, The
buildOAuth2TokenHash function currently always uses SHA-256; change it to accept
the token/signing algorithm (e.g., a parameter like signingAlg or
realm.signingAlgorithm) and map signing algorithms (RS256/ES256/HS256 ->
SHA-256, RS384/ES384/HS384 -> SHA-384, RS512/ES512/HS512 -> SHA-512), then call
subtle.digest with the mapped hash when computing at_hash and c_hash; update any
callers to pass the realm's configured signing algorithm (or derive it from the
realm/JWK config) so the hash algorithm matches the ID token signing algorithm
per OIDC Core §3.3.2.11.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/server-core/src/core/oauth2/authorization/module.ts`:
- Around line 89-91: The null/undefined guard for identity is placed after
identity is already dereferenced, making it dead code; move the check for
identity (the OAuth2Error.identityInvalid() throw) to before any use of
identity, i.e., before accesses like identity.data.id and identity.type (or
remove the redundant guard if callers guarantee non-null). Ensure the
early-return/throw happens immediately at the start of the function or before
the first use of the identity parameter so no dereference can occur on a
null/undefined value.

In `@packages/server-kit/src/services/cache/adapters/memory.ts`:
- Around line 23-31: The pop method (and likewise get) uses a truthiness check
`if (output)` which treats legitimate falsy cached values (0, '', false) as
miss; change the logic to detect presence by using a Map/Store-specific has
method or by checking for undefined (e.g., compare against undefined) so that
falsy values are returned and only undefined means missing; update the pop<T =
unknown>(key: string) and get<T = unknown>(key: string) implementations to check
for undefined (or use this.instance.has(key) then this.instance.get(key)) and
ensure pop still deletes the key after retrieving a present value.

---

Nitpick comments:
In `@apps/server-core/src/core/oauth2/authorization/code/issuer/module.ts`:
- Around line 53-62: The updateIdToken method currently resets the code TTL by
passing this.options.maxAge into repository.save; change it to preserve the
original remaining TTL instead of extending it. Inspect OAuth2AuthorizationCode
for an expiration timestamp (e.g., expires_at or created_at + original TTL) and
compute remainingTtl = expiresAt - now (min 0), then call
this.repository.save(entity, { maxAge: remainingTtl }) or omit maxAge if
remainingTtl <= 0 so the repository enforces expiry; update/updateIdToken to use
that remainingTtl calculation (and if the entity lacks an expiry field, add one
to OAuth2AuthorizationCode and ensure issuance sets it).

In `@apps/server-core/src/core/oauth2/authorization/helpers.ts`:
- Line 41: The buildOAuth2TokenHash function currently always uses SHA-256;
change it to accept the token/signing algorithm (e.g., a parameter like
signingAlg or realm.signingAlgorithm) and map signing algorithms
(RS256/ES256/HS256 -> SHA-256, RS384/ES384/HS384 -> SHA-384, RS512/ES512/HS512
-> SHA-512), then call subtle.digest with the mapped hash when computing at_hash
and c_hash; update any callers to pass the realm's configured signing algorithm
(or derive it from the realm/JWK config) so the hash algorithm matches the ID
token signing algorithm per OIDC Core §3.3.2.11.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: b150f5a0-def6-4cec-b153-f32b028cec0f

📥 Commits

Reviewing files that changed from the base of the PR and between 5ea4dd4 and ee3f398.

📒 Files selected for processing (21)
  • apps/server-core/src/adapters/http/adapters/oauth2/grant-types/authorize.ts
  • apps/server-core/src/app/modules/oauth2/repositories/authorize/code/repository.ts
  • apps/server-core/src/core/oauth2/authorization/code-request/validator.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/code/repository/types.ts
  • apps/server-core/src/core/oauth2/authorization/code/verifier/module.ts
  • apps/server-core/src/core/oauth2/authorization/code/verifier/types.ts
  • apps/server-core/src/core/oauth2/authorization/helpers.ts
  • apps/server-core/src/core/oauth2/authorization/module.ts
  • apps/server-core/src/core/oauth2/token/issuer/access/module.ts
  • apps/server-core/src/core/oauth2/token/issuer/base.ts
  • apps/server-core/src/core/oauth2/token/issuer/open-id/module.ts
  • apps/server-core/src/core/oauth2/token/issuer/refresh/module.ts
  • apps/server-core/test/unit/core/oauth2/authorization/code/verifier/module.spec.ts
  • apps/server-core/test/unit/core/oauth2/authorization/helpers.spec.ts
  • apps/server-core/test/unit/core/oauth2/token/issuer/open-id/module.spec.ts
  • packages/core-kit/src/domains/authorization-code/entity.ts
  • packages/server-kit/src/services/cache/adapters/memory.ts
  • packages/server-kit/src/services/cache/adapters/redis.ts
  • packages/server-kit/src/services/cache/types.ts
💤 Files with no reviewable changes (1)
  • apps/server-core/src/core/oauth2/authorization/code/verifier/types.ts

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
apps/server-core/src/core/oauth2/authorization/module.ts (1)

110-111: Consider tightening needsIdToken condition to avoid unused token issuance.

When response_type=token with scope=openid, an ID token is issued but neither returned (since id_token isn't in response types) nor stored with a code (since no code exists). The token is persisted to the database by issueWithIdentity but never used.

Consider refining the condition to only issue when the token will actually be used:

♻️ Proposed refinement
-        const needsIdToken = enabledResponseTypes[OAuth2AuthorizationResponseType.ID_TOKEN] ||
-            (data.scope && hasOAuth2Scopes(data.scope, ScopeName.OPEN_ID));
+        const needsIdToken = enabledResponseTypes[OAuth2AuthorizationResponseType.ID_TOKEN] ||
+            (codeEntity && data.scope && hasOAuth2Scopes(data.scope, ScopeName.OPEN_ID));
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/core/oauth2/authorization/module.ts` around lines 110 -
111, The needsIdToken flag is too broad and causes an ID token to be issued for
response_type=token with scope=openid even when it will neither be returned nor
stored; narrow the condition so an ID token is only generated when it will
actually be used by checking response types: modify the needsIdToken calculation
(the variable named needsIdToken that uses enabledResponseTypes and
hasOAuth2Scopes) to require either OAuth2AuthorizationResponseType.ID_TOKEN or
that scope includes openid AND a response type that produces/stores a code
(e.g., OAuth2AuthorizationResponseType.CODE) so issueWithIdentity only persists
an ID token when ID_TOKEN is requested or when a CODE flow will store/consume
it.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@apps/server-core/src/core/oauth2/authorization/module.ts`:
- Around line 110-111: The needsIdToken flag is too broad and causes an ID token
to be issued for response_type=token with scope=openid even when it will neither
be returned nor stored; narrow the condition so an ID token is only generated
when it will actually be used by checking response types: modify the
needsIdToken calculation (the variable named needsIdToken that uses
enabledResponseTypes and hasOAuth2Scopes) to require either
OAuth2AuthorizationResponseType.ID_TOKEN or that scope includes openid AND a
response type that produces/stores a code (e.g.,
OAuth2AuthorizationResponseType.CODE) so issueWithIdentity only persists an ID
token when ID_TOKEN is requested or when a CODE flow will store/consume it.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 1bcab889-569c-4e44-8ea3-cd738597d514

📥 Commits

Reviewing files that changed from the base of the PR and between ee3f398 and 861af1b.

📒 Files selected for processing (2)
  • apps/server-core/src/core/oauth2/authorization/module.ts
  • packages/server-kit/src/services/cache/adapters/memory.ts

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.

Feature: OAuth2 / OpenID Connect spec compliance fixes

1 participant