Skip to content

fix: enforce OAuth2 client authentication and PKCE per RFC 6749/7636 - #3020

Merged
tada5hi merged 2 commits into
masterfrom
fix/oauth2-client-auth-and-pkce
Apr 28, 2026
Merged

tada5hi merged 2 commits into
masterfrom
fix/oauth2-client-auth-and-pkce

Conversation

@tada5hi

@tada5hi tada5hi commented Apr 28, 2026 •

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

Release Notes

  • New Features

    • Added OAuth2 client authentication across authorization, password, and refresh token grant flows.
    • Implemented PKCE (Proof Key for Code Exchange) requirement for public clients during authorization.
    • Enhanced refresh token security with client binding and authentication enforcement.
  • Improvements

    • Improved client credential extraction and validation across token endpoints.
    • Added comprehensive error handling for OAuth2 validation failures.
  • Tests

    • Expanded test coverage for client authentication scenarios and PKCE validation.

Copilot AI review requested due to automatic review settings April 28, 2026 13:04
@coderabbitai

coderabbitai Bot commented Apr 28, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@tada5hi has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 30 minutes and 52 seconds before requesting another review.

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 68a0ba92-c8d9-4ac6-8f32-32515a6cd1fb

📥 Commits

Reviewing files that changed from the base of the PR and between 7d71045 and 4237ded.

📒 Files selected for processing (4)
  • .agents/architecture.md
  • apps/server-core/src/adapters/http/adapters/oauth2/grant-types/utils/credentials.ts
  • apps/server-core/test/unit/http/controllers/workflows/token/grant-authorize.spec.ts
  • packages/specs/src/oauth2/error.ts
📝 Walkthrough

Walkthrough

This pull request implements OAuth2 client authentication and binding enforcement across token grant types. A new OAuth2ClientAuthenticator verifies client credentials during token requests. Client credentials are extracted from requests using a centralized utility. PKCE is enforced for public clients, and client binding is validated during authorization code and refresh token verification.

Changes

Cohort / File(s) Summary
Client Authentication Core
apps/server-core/src/core/oauth2/client/authenticator.ts, apps/server-core/src/core/oauth2/client/index.ts
New OAuth2ClientAuthenticator class validates clientId, checks active status, verifies confidential client secrets via ClientCredentialsService, and returns resolved Client entity. Module re-exports new authenticator.
Grant Type Implementations
apps/server-core/src/adapters/http/adapters/oauth2/grant-types/authorize.ts, ...password.ts, ...refresh_token.ts
Updated authorize, password, and refresh-token grant handlers to extract client credentials, authenticate clients, and pass resolved client context into token verification/issuance steps.
Credentials Extraction Utility
apps/server-core/src/adapters/http/adapters/oauth2/grant-types/utils/credentials.ts, ...utils/index.ts
New extractClientCredentialsFromRequest() utility parses client_id/client_secret from request body or Basic Authorization header, rejects dual-transport attempts, and defaults missing secret to empty string.
Verification & Validation
apps/server-core/src/core/oauth2/authorization/code-request/verifier/module.ts, ...code/verifier/module.ts, ...code/verifier/types.ts
Authorization-code request verifier now enforces PKCE for public clients. Token-code verifier validates clientId binding, requires code_challenge for public clients, and refactors PKCE hash comparison logic.
Type Definitions
apps/server-core/src/adapters/http/adapters/oauth2/grant-types/types.ts, apps/server-core/src/adapters/http/controllers/workflows/token/types.ts
Updated grant and controller context types to include clientAuthenticator dependency. New HTTPOAuth2RefreshTokenGrantContext type adds authenticator to refresh-token grant context.
Password Grant Core Logic
apps/server-core/src/core/oauth2/grant-types/password.ts
Password grant input changed from User to { user, client? } object. Token payload now derives client_id from optional client parameter alongside user data.
Controller Wiring
apps/server-core/src/adapters/http/controllers/workflows/token/module.ts, apps/server-core/src/app/modules/http/modules/controller.ts
Token controller now instantiates OAuth2ClientAuthenticator and injects it into authorize, password, and refresh-token grant implementations.
Error Codes & Constants
packages/errors/src/constants.ts, packages/specs/src/oauth2/constants.ts, packages/specs/src/oauth2/error.ts
Added OAUTH_REQUEST_INVALID and OAUTH_RESPONSE_TYPE_UNSUPPORTED error codes. Error factories now emit consistent OAUTH_REQUEST_INVALID for request validation failures and explicit UNSUPPORTED_RESPONSE_TYPE for unsupported response types.
Test Suite Updates
apps/server-core/test/unit/core/oauth2/authorization/code/verifier/module.spec.ts, ...unit/http/controllers/workflows/token/grant-*.spec.ts
Authorization-code verifier tests now validate clientId binding and PKCE enforcement. Grant handler tests extended with confidential/public client scenarios, credential validation paths, client binding assertions, and cross-transport rejection cases.

Sequence Diagram

sequenceDiagram
    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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

🐰 A client hops forth with secrets in hand,
PKCE in pocket across OAuth land,
Verifiers bind tokens with care,
Public and confidential, treated fair! 🔐✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.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 clearly and specifically summarizes the main changes: enforcing OAuth2 client authentication and PKCE validation according to RFC standards, which aligns with the comprehensive refactoring across client authenticators, grant types, and PKCE verification logic.
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.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/oauth2-client-auth-and-pkce

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.

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.

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);

Copilot AI Apr 28, 2026

Copy link

Choose a reason for hiding this comment

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

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.

Copilot uses AI. Check for mistakes.
@tada5hi

tada5hi commented Apr 28, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Apr 28, 2026

Copy link
Copy Markdown
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@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 (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 initial token from createWithClientCredentials (Lines 65-70) is fetched but only initial.access_token is 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 createWithRefreshToken succeeds unexpectedly, the catch block won't execute and only expect.assertions(1) will fail. Consider adding a fail() 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: Same expect.assertions pattern 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

📥 Commits

Reviewing files that changed from the base of the PR and between 9c9030c and 7d71045.

📒 Files selected for processing (24)
  • apps/server-core/src/adapters/http/adapters/oauth2/grant-types/authorize.ts
  • apps/server-core/src/adapters/http/adapters/oauth2/grant-types/client-credentials.ts
  • apps/server-core/src/adapters/http/adapters/oauth2/grant-types/password.ts
  • apps/server-core/src/adapters/http/adapters/oauth2/grant-types/refresh_token.ts
  • apps/server-core/src/adapters/http/adapters/oauth2/grant-types/types.ts
  • apps/server-core/src/adapters/http/adapters/oauth2/grant-types/utils/credentials.ts
  • apps/server-core/src/adapters/http/adapters/oauth2/grant-types/utils/index.ts
  • apps/server-core/src/adapters/http/controllers/workflows/token/module.ts
  • apps/server-core/src/adapters/http/controllers/workflows/token/types.ts
  • apps/server-core/src/app/modules/http/modules/controller.ts
  • apps/server-core/src/core/oauth2/authorization/code-request/verifier/module.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/client/authenticator.ts
  • apps/server-core/src/core/oauth2/client/index.ts
  • apps/server-core/src/core/oauth2/grant-types/password.ts
  • apps/server-core/test/unit/core/oauth2/authorization/code/verifier/module.spec.ts
  • apps/server-core/test/unit/http/controllers/workflows/token/grant-authorize.spec.ts
  • apps/server-core/test/unit/http/controllers/workflows/token/grant-idp-authorize.spec.ts
  • apps/server-core/test/unit/http/controllers/workflows/token/grant-password.spec.ts
  • apps/server-core/test/unit/http/controllers/workflows/token/grant-refresh-token.spec.ts
  • packages/errors/src/constants.ts
  • packages/specs/src/oauth2/constants.ts
  • packages/specs/src/oauth2/error.ts

Comment thread packages/specs/src/oauth2/error.ts Resolved
@tada5hi
tada5hi merged commit bac38b1 into master Apr 28, 2026
2 of 3 checks passed
@tada5hi
tada5hi deleted the fix/oauth2-client-auth-and-pkce branch April 28, 2026 13:42
@github-actions github-actions Bot mentioned this pull request Apr 28, 2026
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