Skip to content

test: unit tests for oauth2 module - #2916

Merged
tada5hi merged 3 commits into
masterfrom
2915-oauth2
Mar 20, 2026
Merged

tada5hi merged 3 commits into
masterfrom
2915-oauth2

Conversation

@tada5hi

@tada5hi tada5hi commented Mar 18, 2026 •

Copy link
Copy Markdown
Collaborator

resolves #2915

Summary by CodeRabbit

  • Bug Fixes

    • OpenID claims now emit updated_at as UNIX epoch seconds (not milliseconds).
  • Enhancements

    • ID token issuance can include issuer and audience when available.
  • Tests

    • Added extensive unit tests covering authorization codes, state management, grant flows, token signing/verifying, scope resolution, claims mapping, and OAuth2 error handling.
  • Documentation

    • Removed an obsolete skill/documentation entry.

@coderabbitai

coderabbitai Bot commented Mar 18, 2026 •

Copy link
Copy Markdown

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: a4e48c3f-a6c5-4e76-b024-970210beb611

📥 Commits

Reviewing files that changed from the base of the PR and between 2f38fae and 18237c2.

📒 Files selected for processing (1)
  • apps/server-core/test/unit/core/oauth2/authorization/code/verifier/module.spec.ts
✅ Files skipped from review due to trivial changes (1)
  • apps/server-core/test/unit/core/oauth2/authorization/code/verifier/module.spec.ts

📝 Walkthrough

Walkthrough

Updated OpenID claim timestamp handling to emit UNIX seconds and optionally include iss and aud in ID token issuance; extensive new unit tests were added across OAuth2 core components and one skill doc was removed.

Changes

Cohort / File(s) Summary
OpenID Claims & ID Token Issuance
apps/server-core/src/core/oauth2/openid/claims.ts, apps/server-core/src/core/oauth2/token/issuer/open-id/module.ts
updated_at transformer now returns UNIX epoch seconds (Math.floor(ms/1000)) for Date/string inputs; ID token insertion payload may include iss from options and aud from client_id.
Authorization Code & State Tests
apps/server-core/test/unit/core/oauth2/authorization/code/verifier/module.spec.ts, apps/server-core/test/unit/core/oauth2/authorization/state/module.spec.ts
New in-memory repo-backed tests for authorization code verification (PKCE, redirect URI, error paths) and state manager (save, verify, single-use, replay protection, IP/userAgent checks).
Grant, Error Helper & Scope Tests
apps/server-core/test/unit/core/oauth2/grant-types/identity.spec.ts, apps/server-core/test/unit/core/oauth2/helpers/error.spec.ts, apps/server-core/test/unit/core/oauth2/scope/resolver.spec.ts
Tests added for IdentityGrantType session/token flows, OAuth2 error-to-OAuth2Error conversion behaviors, and scope→attribute resolution (client/robot/user) including deduplication and input variations.
OpenID Claims Tests
apps/server-core/test/unit/core/oauth2/openid/claims.spec.ts
Tests for OpenID claims builder across CLIENT/ROBOT/USER, verifying name mappings, updated_at handling (Date and string → seconds), selective field inclusion/exclusion.
Token Issuer/Signer/Verifier Tests
apps/server-core/test/unit/core/oauth2/token/issuer/open-id/module.spec.ts, apps/server-core/test/unit/core/oauth2/token/signer/module.spec.ts, apps/server-core/test/unit/core/oauth2/token/verifier/module.spec.ts
Comprehensive tests covering OpenID token issuance (claims, auth_time, iss/aud), signing across key types (OCT/EC/RSA), and verification paths (cache vs crypto), including error scenarios and repository interactions.
Removed Skill Doc
.claude/skills/investigate-pr-comments/SKILL.md
Removed the investigate-pr-comments skill documentation/configuration file entirely.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 I nudged the clocks to seconds neat,

Claimed my name, then tapped the beat.
Iss and Aud hopped into place,
Tests parade across the space.
A rabbit cheers — the warren's neat!

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning The PR includes out-of-scope changes: modifications to the updated_at transformer in the OAuth2 OpenID claims production code and changes to the issueWithIdentity method that are not test-related. Move the production code changes in claims.ts and module.ts to a separate PR focused on updating the transformer/issuer logic. This PR should focus exclusively on test additions.
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 (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'test: unit tests for oauth2 module' directly and clearly summarizes the main change: adding unit tests for the OAuth2 module, which aligns with all file changes in the PR.
Linked Issues check ✅ Passed The PR successfully delivers unit test coverage for OAuth2 functionality as requested in issue #2915, implementing comprehensive tests across authorization codes, states, identity grants, error handling, claims, scopes, and token issuance/verification.

✏️ 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 2915-oauth2
📝 Coding Plan
  • Generate coding plan for human review comments

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/server-core/src/core/oauth2/openid/claims.ts (1)

30-85: ⚠️ Potential issue | 🟡 Minor

Avoid emitting NaN for invalid updated_at strings.

On Line 34, Line 54, and Line 76, an invalid date string yields NaN, which can leak into claim payloads. Please guard parse failures before conversion (and ideally centralize the transformer to avoid divergence across maps).

💡 Suggested patch
+const toUnixTimestampSeconds = (value: unknown) => {
+    if (typeof value === 'string') {
+        const time = new Date(value).getTime();
+        if (Number.isNaN(time)) {
+            return value;
+        }
+
+        return Math.floor(time / 1000);
+    }
+
+    if (value instanceof Date) {
+        return Math.floor(value.getTime() / 1000);
+    }
+
+    return value;
+};
+
 export class OAuth2OpenIDClaimsBuilder {
     protected clientMap : AttributeMap<Client> = {
@@
         updated_at: [
             'updated_at',
-            (value: unknown) => {
-                if (typeof value === 'string') {
-                    return Math.floor(new Date(value).getTime() / 1000);
-                }
-
-                if (value instanceof Date) {
-                    return Math.floor(value.getTime() / 1000);
-                }
-
-                return value;
-            },
+            toUnixTimestampSeconds,
         ],
     };
@@
         updated_at: [
             'updated_at',
-            (value: unknown) => {
-                if (typeof value === 'string') {
-                    return Math.floor(new Date(value).getTime() / 1000);
-                }
-
-                if (value instanceof Date) {
-                    return Math.floor(value.getTime() / 1000);
-                }
-
-                return value;
-            },
+            toUnixTimestampSeconds,
         ],
     };
@@
         updated_at: [
             'updated_at',
-            (value: unknown) => {
-                if (typeof value === 'string') {
-                    return Math.floor(new Date(value).getTime() / 1000);
-                }
-
-                if (value instanceof Date) {
-                    return Math.floor(value.getTime() / 1000);
-                }
-
-                return value;
-            },
+            toUnixTimestampSeconds,
         ],
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/core/oauth2/openid/claims.ts` around lines 30 - 85, The
updated_at transformer in the attribute maps (used in robotMap, userMap and the
other map) can emit NaN when given an invalid date string; extract and
centralize the logic into a single helper (e.g., toEpochSeconds or
parseUpdatedAt) and replace the inline transformer functions with a call to that
helper; the helper should accept unknown, return a number only when the value
parses to a valid Date (Math.floor(date.getTime()/1000)), and otherwise return
the original value (or undefined/null according to existing contract) to avoid
leaking NaN into claim payloads.
🧹 Nitpick comments (5)
apps/server-core/test/unit/core/oauth2/helpers/error.spec.ts (2)

11-11: Typo in source filename: erorr.ts should be error.ts.

The import path correctly references the source file, but the source file itself has a typo in its name (erorr.ts instead of error.ts). Consider renaming the source file in a separate commit.

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

In `@apps/server-core/test/unit/core/oauth2/helpers/error.spec.ts` at line 11,
Rename the source file currently named "erorr.ts" to the correct "error.ts" and
update any imports that reference it (e.g., the import of toOAuth2Error used in
tests and code) so they point to
'../../../../../src/core/oauth2/helpers/error.ts'; ensure the export of
toOAuth2Error inside the renamed file remains unchanged and run tests to verify
no broken imports remain.

46-61: Consider asserting error_description for completeness.

These tests verify the error field but don't check error_description. For the standard Error case, you could assert that the description contains the original message, making the test more thorough.

💡 Optional enhancement
     it('should sanitize unknown errors and wrap with OAuth2 data', () => {
         const err = new Error('unknown failure');
         const result = toOAuth2Error(err);
         expect(result).toBeInstanceOf(AuthupError);
         expect(result.data).toEqual(expect.objectContaining({
             error: OAuth2ErrorCode.INVALID_REQUEST,
+            error_description: expect.any(String),
         }));
     });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/test/unit/core/oauth2/helpers/error.spec.ts` around lines 46
- 61, Update the two tests to also assert error_description: for the Error case
(using const err = new Error('unknown failure')), after verifying instance and
data.error, assert result.data.error_description contains the original
err.message; for the non-object case (toOAuth2Error('string error')), assert
result.data.error_description contains or equals the string provided (or a
sensible default message you expect), referencing toOAuth2Error, AuthupError,
and OAuth2ErrorCode so the assertions clearly validate both error and
error_description fields.
apps/server-core/test/unit/core/oauth2/authorization/state/module.spec.ts (2)

63-72: Minor: Test name could better reflect what's being verified.

The test name says "should return state when IP matches" but the test actually verifies both IP and userAgent matching. Consider renaming for clarity.

📝 Suggested rename
-        it('should return state when IP matches', async () => {
+        it('should return state when IP and userAgent match', async () => {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/test/unit/core/oauth2/authorization/state/module.spec.ts`
around lines 63 - 72, Rename the test description to reflect both checks: update
the spec's it(...) string (in
apps/server-core/test/unit/core/oauth2/authorization/state/module.spec.ts) from
"should return state when IP matches" to something like "should return state
when IP and userAgent match" so the test name accurately describes that
manager.save and manager.verify are asserting both ip and userAgent on the
returned OAuth2AuthorizationState.

50-60: Consider verifying the state was actually persisted.

The test confirms the returned id is a non-empty string, but doesn't verify the state was actually stored. Adding a check would strengthen the test.

💡 Suggested enhancement
     describe('save', () => {
         it('should store state and return an id', async () => {
             const state: OAuth2AuthorizationState = {
                 ip: '127.0.0.1',
                 userAgent: 'Mozilla/5.0',
             };
             const id = await manager.save(state);
             expect(typeof id).toBe('string');
             expect(id.length).toBeGreaterThan(0);
+            expect(repository.has(id)).toBe(true);
         });
     });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/test/unit/core/oauth2/authorization/state/module.spec.ts`
around lines 50 - 60, Test currently only asserts the returned id from
manager.save; enhance it to fetch the persisted record and assert its contents.
After calling const id = await manager.save(state), retrieve the saved state
with the appropriate lookup method (e.g., await manager.get(id) or await
manager.findById(id)) and assert the returned object is defined and that its ip
and userAgent equal the original state (and that its id matches the returned id
if the stored object includes an id). This verifies persistence rather than just
a non-empty id.
apps/server-core/test/unit/core/oauth2/authorization/code/verifier/module.spec.ts (1)

39-41: Align the fake save() signature with the interface contract.

The FakeCodeRepository.save() method on line 39 drops the required parameters from IOAuth2AuthorizationCodeRepository.save(). Even if unused in this test, add input: OAuth2AuthorizationCodeInput, options?: OAuth2AuthorizationCodeRepositorySaveOptions to maintain consistency and avoid contract drift.

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

In
`@apps/server-core/test/unit/core/oauth2/authorization/code/verifier/module.spec.ts`
around lines 39 - 41, The FakeCodeRepository.save() implementation drops
required parameters from the IOAuth2AuthorizationCodeRepository.save() contract;
update the FakeCodeRepository.save signature to accept (input:
OAuth2AuthorizationCodeInput, options?:
OAuth2AuthorizationCodeRepositorySaveOptions) and keep or ignore them in the
body (e.g., retain the current behavior or throw) so the fake matches the
interface signature—adjust the export/implementation in FakeCodeRepository and
any tests that instantiate it accordingly.
🤖 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/token/issuer/open-id/module.ts`:
- Around line 76-77: The ID token assembly in issueWithIdentity() currently only
conditionally adds iss and aud so tokens may be emitted without them; update
issueWithIdentity() to ensure iss and aud are always present by (a) using
this.options.issuer as a required/default issuer (or throw an error if missing)
and (b) using input.client_id (or the resolved client identifier) as the
audience (or throw if absent), and replace the conditional spread
(...(this.options.issuer ? { iss: ... } : {}), ...(input.client_id ? { aud: ...
} : {})) with logic that either sets those claims unconditionally or fails fast
when they cannot be determined so tokens cannot be issued without iss/aud.

In
`@apps/server-core/test/unit/core/oauth2/authorization/code/verifier/module.spec.ts`:
- Around line 21-24: The seed helper currently builds the entity as { id:
randomUUID(), ...code } so a passed-in code.id (including undefined) can
overwrite the generated id; change it to compute a stable id first (e.g. const
id = code.id ?? randomUUID()) and then construct the entity with the id placed
last (e.g. { ...code, id }) so the resolved id cannot be accidentally
overwritten, and continue to use this.id when calling this.store.set(entity.id,
entity) in the seed function.
- Around line 67-153: Tests currently only assert that verifier.verify throws an
OAuth2Error but not which variant; update each failing-case test to assert the
specific error code by checking the thrown error's .code property (e.g.,
expect(err.code).toBe('OAUTH_GRANT_INVALID') or 'OAUTH_REDIRECT_URI_MISMATCH')
after calling verifier.verify in the same tests that exercise redirect URI
mismatches, missing redirect URI, PKCE mismatches, and missing code_verifier;
locate these tests around verifier.verify calls in this spec and replace the
generic toThrow(OAuth2Error) checks with assertions that capture the thrown
error and assert its .code matches the appropriate variant returned by
OAuth2Error.grantInvalid() or OAuth2Error.redirectUriMismatch().

---

Outside diff comments:
In `@apps/server-core/src/core/oauth2/openid/claims.ts`:
- Around line 30-85: The updated_at transformer in the attribute maps (used in
robotMap, userMap and the other map) can emit NaN when given an invalid date
string; extract and centralize the logic into a single helper (e.g.,
toEpochSeconds or parseUpdatedAt) and replace the inline transformer functions
with a call to that helper; the helper should accept unknown, return a number
only when the value parses to a valid Date (Math.floor(date.getTime()/1000)),
and otherwise return the original value (or undefined/null according to existing
contract) to avoid leaking NaN into claim payloads.

---

Nitpick comments:
In
`@apps/server-core/test/unit/core/oauth2/authorization/code/verifier/module.spec.ts`:
- Around line 39-41: The FakeCodeRepository.save() implementation drops required
parameters from the IOAuth2AuthorizationCodeRepository.save() contract; update
the FakeCodeRepository.save signature to accept (input:
OAuth2AuthorizationCodeInput, options?:
OAuth2AuthorizationCodeRepositorySaveOptions) and keep or ignore them in the
body (e.g., retain the current behavior or throw) so the fake matches the
interface signature—adjust the export/implementation in FakeCodeRepository and
any tests that instantiate it accordingly.

In `@apps/server-core/test/unit/core/oauth2/authorization/state/module.spec.ts`:
- Around line 63-72: Rename the test description to reflect both checks: update
the spec's it(...) string (in
apps/server-core/test/unit/core/oauth2/authorization/state/module.spec.ts) from
"should return state when IP matches" to something like "should return state
when IP and userAgent match" so the test name accurately describes that
manager.save and manager.verify are asserting both ip and userAgent on the
returned OAuth2AuthorizationState.
- Around line 50-60: Test currently only asserts the returned id from
manager.save; enhance it to fetch the persisted record and assert its contents.
After calling const id = await manager.save(state), retrieve the saved state
with the appropriate lookup method (e.g., await manager.get(id) or await
manager.findById(id)) and assert the returned object is defined and that its ip
and userAgent equal the original state (and that its id matches the returned id
if the stored object includes an id). This verifies persistence rather than just
a non-empty id.

In `@apps/server-core/test/unit/core/oauth2/helpers/error.spec.ts`:
- Line 11: Rename the source file currently named "erorr.ts" to the correct
"error.ts" and update any imports that reference it (e.g., the import of
toOAuth2Error used in tests and code) so they point to
'../../../../../src/core/oauth2/helpers/error.ts'; ensure the export of
toOAuth2Error inside the renamed file remains unchanged and run tests to verify
no broken imports remain.
- Around line 46-61: Update the two tests to also assert error_description: for
the Error case (using const err = new Error('unknown failure')), after verifying
instance and data.error, assert result.data.error_description contains the
original err.message; for the non-object case (toOAuth2Error('string error')),
assert result.data.error_description contains or equals the string provided (or
a sensible default message you expect), referencing toOAuth2Error, AuthupError,
and OAuth2ErrorCode so the assertions clearly validate both error and
error_description fields.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: d8147049-2732-4047-b05b-52af22d9ddbd

📥 Commits

Reviewing files that changed from the base of the PR and between 34d2cbb and ab9e533.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (11)
  • apps/server-core/src/core/oauth2/openid/claims.ts
  • apps/server-core/src/core/oauth2/token/issuer/open-id/module.ts
  • apps/server-core/test/unit/core/oauth2/authorization/code/verifier/module.spec.ts
  • apps/server-core/test/unit/core/oauth2/authorization/state/module.spec.ts
  • apps/server-core/test/unit/core/oauth2/grant-types/identity.spec.ts
  • apps/server-core/test/unit/core/oauth2/helpers/error.spec.ts
  • apps/server-core/test/unit/core/oauth2/openid/claims.spec.ts
  • apps/server-core/test/unit/core/oauth2/scope/resolver.spec.ts
  • apps/server-core/test/unit/core/oauth2/token/issuer/open-id/module.spec.ts
  • apps/server-core/test/unit/core/oauth2/token/signer/module.spec.ts
  • apps/server-core/test/unit/core/oauth2/token/verifier/module.spec.ts

Comment on lines +76 to +77
...(this.options.issuer ? { iss: this.options.issuer } : {}),
...(input.client_id ? { aud: input.client_id } : {}),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

ID tokens can still be issued without iss/aud.

Line 76 and Line 77 only add these claims conditionally, so issueWithIdentity() can return ID tokens missing issuer or audience. This risks downstream validation and interoperability issues.

🔒 Suggested hardening
     async issueWithIdentity(
         input: OAuth2TokenPayload,
         identity: Identity,
     ): Promise<OAuth2TokenIssuerResponse> {
+        if (!this.options.issuer || !input.client_id) {
+            throw JWTError.payloadInvalid();
+        }
+
         const claims = this.claimsBuilder.fromIdentity(identity);
@@
         const data = await this.repository.insert({
             ...input,
             ...claims,
             kind: OAuth2TokenKind.ID_TOKEN,
             auth_time: utc,
             exp: this.buildExp(input),
             updated_at: utc,
-            ...(this.options.issuer ? { iss: this.options.issuer } : {}),
-            ...(input.client_id ? { aud: input.client_id } : {}),
+            iss: this.options.issuer,
+            aud: input.client_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/token/issuer/open-id/module.ts` around lines
76 - 77, The ID token assembly in issueWithIdentity() currently only
conditionally adds iss and aud so tokens may be emitted without them; update
issueWithIdentity() to ensure iss and aud are always present by (a) using
this.options.issuer as a required/default issuer (or throw an error if missing)
and (b) using input.client_id (or the resolved client identifier) as the
audience (or throw if absent), and replace the conditional spread
(...(this.options.issuer ? { iss: ... } : {}), ...(input.client_id ? { aud: ...
} : {})) with logic that either sets those claims unconditionally or fails fast
when they cannot be determined so tokens cannot be issued without iss/aud.

Comment on lines +21 to +24
seed(code: Partial<OAuth2AuthorizationCode>): OAuth2AuthorizationCode {
const entity = { id: randomUUID(), ...code } as OAuth2AuthorizationCode;
this.store.set(entity.id, entity);
return entity;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Prevent fixture IDs from being accidentally overridden.

On Line 22, { id: randomUUID(), ...code } lets code.id overwrite the generated id (including undefined), which can produce unstable in-memory keys during tests.

Suggested fix
-        const entity = { id: randomUUID(), ...code } as OAuth2AuthorizationCode;
+        const entity = { ...code, id: code.id ?? randomUUID() } as OAuth2AuthorizationCode;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@apps/server-core/test/unit/core/oauth2/authorization/code/verifier/module.spec.ts`
around lines 21 - 24, The seed helper currently builds the entity as { id:
randomUUID(), ...code } so a passed-in code.id (including undefined) can
overwrite the generated id; change it to compute a stable id first (e.g. const
id = code.id ?? randomUUID()) and then construct the entity with the id placed
last (e.g. { ...code, id }) so the resolved id cannot be accidentally
overwritten, and continue to use this.id when calling this.store.set(entity.id,
entity) in the seed function.

@tada5hi
tada5hi merged commit 43ded49 into master Mar 20, 2026
8 checks passed
@tada5hi
tada5hi deleted the 2915-oauth2 branch March 20, 2026 12:07
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 Tests

1 participant