Repository navigation
test: unit tests for oauth2 module - #2916
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
✅ Files skipped from review due to trivial changes (1)
📝 WalkthroughWalkthroughUpdated OpenID claim timestamp handling to emit UNIX seconds and optionally include Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
📝 Coding Plan
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 |
There was a problem hiding this comment.
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 | 🟡 MinorAvoid emitting
NaNfor invalidupdated_atstrings.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.tsshould beerror.ts.The import path correctly references the source file, but the source file itself has a typo in its name (
erorr.tsinstead oferror.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 assertingerror_descriptionfor completeness.These tests verify the
errorfield but don't checkerror_description. For the standardErrorcase, 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
idis 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 fakesave()signature with the interface contract.The
FakeCodeRepository.save()method on line 39 drops the required parameters fromIOAuth2AuthorizationCodeRepository.save(). Even if unused in this test, addinput: OAuth2AuthorizationCodeInput, options?: OAuth2AuthorizationCodeRepositorySaveOptionsto 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
⛔ Files ignored due to path filters (1)
package-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (11)
apps/server-core/src/core/oauth2/openid/claims.tsapps/server-core/src/core/oauth2/token/issuer/open-id/module.tsapps/server-core/test/unit/core/oauth2/authorization/code/verifier/module.spec.tsapps/server-core/test/unit/core/oauth2/authorization/state/module.spec.tsapps/server-core/test/unit/core/oauth2/grant-types/identity.spec.tsapps/server-core/test/unit/core/oauth2/helpers/error.spec.tsapps/server-core/test/unit/core/oauth2/openid/claims.spec.tsapps/server-core/test/unit/core/oauth2/scope/resolver.spec.tsapps/server-core/test/unit/core/oauth2/token/issuer/open-id/module.spec.tsapps/server-core/test/unit/core/oauth2/token/signer/module.spec.tsapps/server-core/test/unit/core/oauth2/token/verifier/module.spec.ts
| ...(this.options.issuer ? { iss: this.options.issuer } : {}), | ||
| ...(input.client_id ? { aud: input.client_id } : {}), |
There was a problem hiding this comment.
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.
| seed(code: Partial<OAuth2AuthorizationCode>): OAuth2AuthorizationCode { | ||
| const entity = { id: randomUUID(), ...code } as OAuth2AuthorizationCode; | ||
| this.store.set(entity.id, entity); | ||
| return entity; |
There was a problem hiding this comment.
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.
resolves #2915
Summary by CodeRabbit
Bug Fixes
Enhancements
Tests
Documentation