Repository navigation
fix: enforce OAuth2 client authentication and PKCE per RFC 6749/7636 - #3020
Conversation
|
Warning Rate limit exceeded
To keep reviews running without waiting, you can enable usage-based add-on for your organization. This allows additional reviews beyond the hourly cap. Account admins can enable it under billing. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (4)
📝 WalkthroughWalkthroughThis pull request implements OAuth2 client authentication and binding enforcement across token grant types. A new Changes
Sequence DiagramsequenceDiagram
participant Client
participant TokenController
participant GrantHandler
participant CredExtractor
participant ClientAuth
participant IdentityResolver
participant Verifier
participant TokenStore
Client->>TokenController: POST /token (with client credentials)
TokenController->>GrantHandler: runWithRequest(request)
GrantHandler->>CredExtractor: extractClientCredentialsFromRequest(req)
CredExtractor-->>GrantHandler: { clientId, clientSecret }
GrantHandler->>ClientAuth: authenticate(clientId, clientSecret, realmId)
ClientAuth->>IdentityResolver: resolve(IdentityType.CLIENT, clientId)
IdentityResolver-->>ClientAuth: client identity
ClientAuth->>ClientAuth: verify(client.active, client.is_confidential, clientSecret)
ClientAuth-->>GrantHandler: Client (resolved entity)
GrantHandler->>Verifier: verify(..., clientId, clientIsPublic)
Verifier->>Verifier: validate client_id binding
Verifier->>Verifier: enforce PKCE for public clients
Verifier-->>GrantHandler: verification result
GrantHandler->>TokenStore: create token (with client_id)
TokenStore-->>TokenController: OAuth2TokenGrantResponse
TokenController-->>Client: access_token + metadata
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 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 |
There was a problem hiding this comment.
Pull request overview
Enforces stricter OAuth2 token endpoint client authentication and PKCE requirements (RFC 6749 / RFC 7636), and aligns OAuth2 error codes/messages with spec semantics across server-core and shared specs/errors packages.
Changes:
- Add OAuth2 client authenticator + shared credential extraction helper (rejects dual auth methods Basic + body).
- Enforce client binding checks for authorization_code and refresh_token flows; enforce PKCE for public clients.
- Update/extend unit tests and OAuth2 error code constants to cover new validation behavior.
Reviewed changes
Copilot reviewed 24 out of 24 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| packages/specs/src/oauth2/error.ts | Align default OAuth2Error code/message and enrich response-type unsupported error mapping. |
| packages/specs/src/oauth2/constants.ts | Add unsupported_response_type OAuth2ErrorCode. |
| packages/errors/src/constants.ts | Add OAuth-related ErrorCode values for invalid_request and unsupported_response_type. |
| apps/server-core/src/core/oauth2/client/index.ts | Export new OAuth2 client authenticator. |
| apps/server-core/src/core/oauth2/client/authenticator.ts | New OAuth2 token-endpoint client authenticator (confidential vs public handling). |
| apps/server-core/src/core/oauth2/authorization/code/verifier/types.ts | Extend verifier options with clientId and clientIsPublic. |
| apps/server-core/src/core/oauth2/authorization/code/verifier/module.ts | Enforce client binding + PKCE defaults/requirements at token exchange. |
| apps/server-core/src/core/oauth2/authorization/code-request/verifier/module.ts | Enforce PKCE for public clients on code-issuing authorization requests. |
| apps/server-core/src/core/oauth2/grant-types/password.ts | Bind password grant session/token to optional authenticated client. |
| apps/server-core/src/app/modules/http/modules/controller.ts | Wire OAuth2ClientAuthenticator into TokenController. |
| apps/server-core/src/adapters/http/controllers/workflows/token/types.ts | Extend TokenControllerContext to include OAuth2ClientAuthenticator. |
| apps/server-core/src/adapters/http/controllers/workflows/token/module.ts | Provide OAuth2ClientAuthenticator to affected HTTP grant handlers. |
| apps/server-core/src/adapters/http/adapters/oauth2/grant-types/utils/index.ts | Export new credentials helper. |
| apps/server-core/src/adapters/http/adapters/oauth2/grant-types/utils/credentials.ts | New shared credential extraction + dual-auth rejection. |
| apps/server-core/src/adapters/http/adapters/oauth2/grant-types/types.ts | Add client-authenticator fields to grant contexts. |
| apps/server-core/src/adapters/http/adapters/oauth2/grant-types/authorize.ts | Authenticate client at /token (auth code exchange) + pass client info to code verifier. |
| apps/server-core/src/adapters/http/adapters/oauth2/grant-types/password.ts | Authenticate optional client for password grant via shared helper. |
| apps/server-core/src/adapters/http/adapters/oauth2/grant-types/refresh_token.ts | Enforce refresh token client binding + optional client auth via shared helper. |
| apps/server-core/src/adapters/http/adapters/oauth2/grant-types/client-credentials.ts | Switch to shared credential extraction helper. |
| apps/server-core/test/unit/http/controllers/workflows/token/grant-authorize.spec.ts | Expanded authorization_code tests for confidential/public + PKCE + client auth edge cases. |
| apps/server-core/test/unit/http/controllers/workflows/token/grant-refresh-token.spec.ts | Add refresh token client-binding and client-auth coverage. |
| apps/server-core/test/unit/http/controllers/workflows/token/grant-password.spec.ts | Add password-grant confidential client auth coverage. |
| apps/server-core/test/unit/http/controllers/workflows/token/grant-idp-authorize.spec.ts | Update IDP authorization code flow test to include client auth + redirect_uri. |
| apps/server-core/test/unit/core/oauth2/authorization/code/verifier/module.spec.ts | Add verifier tests for client binding and PKCE default behavior. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| const code = url.searchParams.get('code'); | ||
| const code = url.searchParams.get('code')!; | ||
|
|
||
| expect.assertions(3); |
There was a problem hiding this comment.
expect.assertions(3) doesn’t match the number of expect(...) calls in this test (currently 2 inside the isClientError branch), so the test will fail even when behavior is correct. Update the assertion count or add the missing expectation.
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (3)
apps/server-core/test/unit/http/controllers/workflows/token/grant-refresh-token.spec.ts (2)
64-96: Unused initial token from client_credentials grant.The
initialtoken fromcreateWithClientCredentials(Lines 65-70) is fetched but onlyinitial.access_tokenis asserted. The comment explains client_credentials doesn't issue refresh tokens, but the variable adds confusion. Consider removing it or clarifying its purpose.Remove unused client_credentials call
it('should grant refresh when authenticated client matches token client_id', async () => { - const initial = await suite.client - .token - .createWithClientCredentials({ - client_id: confidentialClient.id, - client_secret: confidentialSecret, - }); - - // client_credentials grant doesn't issue a refresh_token; use the - // password grant with explicit client auth instead to obtain a - // refresh_token bound to the confidential client. const passwordResponse = await suite.client .token .createWithPassword({ username: 'admin', password: 'start123', client_id: confidentialClient.id, client_secret: confidentialSecret, }); - expect(initial.access_token).toBeDefined(); expect(passwordResponse.refresh_token).toBeDefined();🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/test/unit/http/controllers/workflows/token/grant-refresh-token.spec.ts` around lines 64 - 96, The test fetches an unused token via suite.client.token.createWithClientCredentials assigned to initial but only asserts initial.access_token and then proceeds to test refresh logic; remove the unnecessary call and the expect(initial.access_token) (or, if you intend to keep it, add a clear comment and a meaningful assertion) so the test only obtains a password grant refresh token via suite.client.token.createWithPassword and then exercises suite.client.token.createWithRefreshToken; specifically edit the test body that references initial and the createWithClientCredentials call to eliminate the confusing unused variable.
108-118: Test may silently pass if no error is thrown.If
createWithRefreshTokensucceeds unexpectedly, thecatchblock won't execute and onlyexpect.assertions(1)will fail. Consider adding afail()call or restructuring to ensure the test fails explicitly when no error is thrown.Suggestion: Use expect().rejects pattern for clearer failure
- expect.assertions(1); - - try { - await suite.client - .token - .createWithRefreshToken({ refresh_token: passwordResponse.refresh_token }); - } catch (e) { - if (isClientError(e)) { - expect(e.response?.data?.code).toEqual(ErrorCode.OAUTH_CLIENT_INVALID); - } - } + await expect( + suite.client + .token + .createWithRefreshToken({ refresh_token: passwordResponse.refresh_token }), + ).rejects.toMatchObject({ + response: { data: { code: ErrorCode.OAUTH_CLIENT_INVALID } }, + });🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/test/unit/http/controllers/workflows/token/grant-refresh-token.spec.ts` around lines 108 - 118, The test can silently pass if createWithRefreshToken does not throw; replace the try/catch with an explicit assertion on rejection by using await expect(suite.client.token.createWithRefreshToken({ refresh_token: passwordResponse.refresh_token })).rejects.toMatchObject({ response: { data: { code: ErrorCode.OAUTH_CLIENT_INVALID } } }) (or, if you prefer minimal change, add a fail() immediately after the awaited call inside the try block so the test fails when no error is thrown); update references to createWithRefreshToken, isClientError, ErrorCode.OAUTH_CLIENT_INVALID and keep expect.assertions to ensure one assertion runs.apps/server-core/test/unit/http/controllers/workflows/token/grant-authorize.spec.ts (1)
175-192: Sameexpect.assertionspattern issue as noted in refresh token tests.The
if (isClientError(e))guard means assertions may not run if a different error type is thrown, causing test to pass incorrectly with just the assertions count failure.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/test/unit/http/controllers/workflows/token/grant-authorize.spec.ts` around lines 175 - 192, The test currently uses an if (isClientError(e)) guard so assertions inside may be skipped for non-client errors; change the catch to assert the error is a client error before accessing response data (e.g., use expect(isClientError(e)).toBe(true) or call fail()/rethrow in the else branch) and then perform the existing assertions against e.response?.data.code === ErrorCode.OAUTH_GRANT_INVALID; update the catch around suite.client.token.createWithAuthorizationCode to ensure expect.assertions(3) always executes by guaranteeing the three expects run for any thrown error.
🤖 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/adapters/http/adapters/oauth2/grant-types/utils/credentials.ts`:
- Around line 55-75: In parseBasicCredentials, the extracted Basic auth
username/password must be URL-decoded before use; update the return from {
clientId: header.username, clientSecret: header.password } to apply
decodeURIComponent to header.username and header.password so the returned
ExtractedClientCredentials contains decodeURIComponent(header.username) and
decodeURIComponent(header.password) (handle undefined/null safely if needed).
In `@packages/specs/src/oauth2/error.ts`:
- Around line 15-16: The base OAuth2Error currently defaults to
ErrorCode.OAUTH_REQUEST_INVALID and a 400-style client error; change the
OAuth2Error constructor defaults (the fields currently set to code:
ErrorCode.OAUTH_REQUEST_INVALID and message: 'OAuth2 request invalid') to a
server-side default (e.g., ErrorCode.OAUTH_SERVER_ERROR and HTTP status 500 or a
generic "OAuth2 server error" message) so server-side factories like
signingKeyMissing() return server errors unless explicitly overridden; ensure
client-error factories explicitly set ErrorCode.OAUTH_REQUEST_INVALID/400 when
appropriate.
---
Nitpick comments:
In
`@apps/server-core/test/unit/http/controllers/workflows/token/grant-authorize.spec.ts`:
- Around line 175-192: The test currently uses an if (isClientError(e)) guard so
assertions inside may be skipped for non-client errors; change the catch to
assert the error is a client error before accessing response data (e.g., use
expect(isClientError(e)).toBe(true) or call fail()/rethrow in the else branch)
and then perform the existing assertions against e.response?.data.code ===
ErrorCode.OAUTH_GRANT_INVALID; update the catch around
suite.client.token.createWithAuthorizationCode to ensure expect.assertions(3)
always executes by guaranteeing the three expects run for any thrown error.
In
`@apps/server-core/test/unit/http/controllers/workflows/token/grant-refresh-token.spec.ts`:
- Around line 64-96: The test fetches an unused token via
suite.client.token.createWithClientCredentials assigned to initial but only
asserts initial.access_token and then proceeds to test refresh logic; remove the
unnecessary call and the expect(initial.access_token) (or, if you intend to keep
it, add a clear comment and a meaningful assertion) so the test only obtains a
password grant refresh token via suite.client.token.createWithPassword and then
exercises suite.client.token.createWithRefreshToken; specifically edit the test
body that references initial and the createWithClientCredentials call to
eliminate the confusing unused variable.
- Around line 108-118: The test can silently pass if createWithRefreshToken does
not throw; replace the try/catch with an explicit assertion on rejection by
using await expect(suite.client.token.createWithRefreshToken({ refresh_token:
passwordResponse.refresh_token })).rejects.toMatchObject({ response: { data: {
code: ErrorCode.OAUTH_CLIENT_INVALID } } }) (or, if you prefer minimal change,
add a fail() immediately after the awaited call inside the try block so the test
fails when no error is thrown); update references to createWithRefreshToken,
isClientError, ErrorCode.OAUTH_CLIENT_INVALID and keep expect.assertions to
ensure one assertion runs.
🪄 Autofix (Beta)
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
Run ID: 9943193b-824d-4776-8df5-641a3571ba28
📒 Files selected for processing (24)
apps/server-core/src/adapters/http/adapters/oauth2/grant-types/authorize.tsapps/server-core/src/adapters/http/adapters/oauth2/grant-types/client-credentials.tsapps/server-core/src/adapters/http/adapters/oauth2/grant-types/password.tsapps/server-core/src/adapters/http/adapters/oauth2/grant-types/refresh_token.tsapps/server-core/src/adapters/http/adapters/oauth2/grant-types/types.tsapps/server-core/src/adapters/http/adapters/oauth2/grant-types/utils/credentials.tsapps/server-core/src/adapters/http/adapters/oauth2/grant-types/utils/index.tsapps/server-core/src/adapters/http/controllers/workflows/token/module.tsapps/server-core/src/adapters/http/controllers/workflows/token/types.tsapps/server-core/src/app/modules/http/modules/controller.tsapps/server-core/src/core/oauth2/authorization/code-request/verifier/module.tsapps/server-core/src/core/oauth2/authorization/code/verifier/module.tsapps/server-core/src/core/oauth2/authorization/code/verifier/types.tsapps/server-core/src/core/oauth2/client/authenticator.tsapps/server-core/src/core/oauth2/client/index.tsapps/server-core/src/core/oauth2/grant-types/password.tsapps/server-core/test/unit/core/oauth2/authorization/code/verifier/module.spec.tsapps/server-core/test/unit/http/controllers/workflows/token/grant-authorize.spec.tsapps/server-core/test/unit/http/controllers/workflows/token/grant-idp-authorize.spec.tsapps/server-core/test/unit/http/controllers/workflows/token/grant-password.spec.tsapps/server-core/test/unit/http/controllers/workflows/token/grant-refresh-token.spec.tspackages/errors/src/constants.tspackages/specs/src/oauth2/constants.tspackages/specs/src/oauth2/error.ts
Summary by CodeRabbit
Release Notes
New Features
Improvements
Tests