Repository navigation
fix: replace server-side cookie handling with client-side authorization code flow - #2937
Conversation
… for IDP callbacks
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
📝 WalkthroughWalkthroughThe PR refactors OAuth2 authorization-code handling: servers stop setting auth cookies and instead issue single-use authorization codes (using a code issuer and realm resolution). Clients handle code exchange via a new store action; routing interceptors process incoming Changes
Sequence Diagram(s)sequenceDiagram
participant Browser as UserAgent (Browser)
participant Router as Client Router
participant Store as Client Store
participant AppServer as App Server (IdentityProviderController)
participant RealmRepo as RealmRepository
participant CodeIssuer as OAuth2 CodeIssuer
participant TokenEndpoint as TokenController
Browser->>Router: Callback to /identity-provider/callback?code=ext-code&state=...
Router->>Store: detect query.code -> exchangeAuthorizationCode(code)
Store->>AppServer: POST /token (createWithAuthorizationCode) with app authorization code
AppServer->>RealmRepo: resolve(entity.realm_id)
AppServer->>CodeIssuer: issue(authorization code with realm in user data)
CodeIssuer-->>AppServer: authorizationCode.id
AppServer-->>Browser: 302 redirect back to app with ?code=<app-auth-code>
Store->>TokenEndpoint: exchange authorization code for tokens
TokenEndpoint-->>Store: JSON { access_token, refresh_token, expires_in } (no cookies)
Store->>Store: applyTokenGrantResponse, resolveToken(), resolveUser()
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
🚥 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 docstrings
🧪 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.
Actionable comments posted: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
apps/server-core/src/core/oauth2/authorization/code-request/verifier/module.ts (1)
66-72:⚠️ Potential issue | 🔴 CriticalRedirect URI validation can be bypassed when the client has no registered redirect URI.
At Line 66, validation is skipped unless
client.redirect_uriis set. Given nullable client redirect URIs, this allows arbitrarydata.redirect_urivalues through, which is unsafe for authorization code flows.Suggested fix (strict redirect URI enforcement)
- if (client.redirect_uri && data.redirect_uri) { - const redirectUris = client.redirect_uri.split(','); - - if (!isSimpleMatch(data.redirect_uri, redirectUris)) { - throw OAuth2Error.redirectUriMismatch(); - } - } + if (!client.redirect_uri || !data.redirect_uri) { + throw OAuth2Error.redirectUriMismatch(); + } + + const redirectUris = client.redirect_uri.split(','); + if (!isSimpleMatch(data.redirect_uri, redirectUris)) { + throw OAuth2Error.redirectUriMismatch(); + }🤖 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-request/verifier/module.ts` around lines 66 - 72, The current logic skips redirect URI validation when client.redirect_uri is null, allowing arbitrary data.redirect_uri values; change the verifier so that if the client has no registered redirect_uri the request is rejected (e.g., throw OAuth2Error.redirectUriMismatch()), and otherwise parse client.redirect_uri into redirectUris and validate data.redirect_uri with isSimpleMatch as before—ensure you reference client.redirect_uri, data.redirect_uri, isSimpleMatch, and OAuth2Error.redirectUriMismatch() in the updated check so all requests require a matching registered redirect URI.apps/server-core/src/adapters/http/controllers/entities/identity-provider/module.ts (1)
318-331:⚠️ Potential issue | 🟠 MajorPreserve
publicUrlpath prefixes when rebuilding the/authorizeredirect.Line 325 uses
new URL('/authorize', this.options.baseURL), which resets the path to the origin root. Sincethis.options.baseURLis set toconfig.publicUrl, if it includes a prefix such ashttps://example.com/auth/, this branch redirects tohttps://example.com/authorizeinstead ofhttps://example.com/auth/authorize, breaking the IDP callback flow for path-based deployments.Suggested fix
- const url = new URL('/authorize', this.options.baseURL); + const baseURL = this.options.baseURL.endsWith('/') + ? this.options.baseURL + : `${this.options.baseURL}/`; + const url = new URL('authorize', baseURL);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/adapters/http/controllers/entities/identity-provider/module.ts` around lines 318 - 331, The redirect rebuild currently uses new URL('/authorize', this.options.baseURL) which discards any path prefix in this.options.baseURL; change the URL construction to preserve the base path (e.g., create a URL from this.options.baseURL and append or join the 'authorize' segment without a leading slash) so that if this.options.baseURL contains a path prefix the final redirect becomes <basePath>/authorize; update the code around where data.codeRequest, authorizationCode.id and sendRedirect are used (symbols: this.options.baseURL, data.codeRequest, authorizationCode.id, sendRedirect) to set searchParams on the preserved-path URL before calling sendRedirect.
🧹 Nitpick comments (2)
packages/core-kit/src/domains/authorization-code/entity.ts (1)
40-42: Consider splitting unverified vs validated authorization request types.Making
client_idandredirect_urioptional in the shared request type weakens compile-time guarantees and increases downstream mutation/guarding. A separate validated type (with required fields) would keep invariants explicit after verification.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/core-kit/src/domains/authorization-code/entity.ts` around lines 40 - 42, The current shared request type in authorization-code entity makes client_id and redirect_uri optional (client_id, redirect_uri, realm_id), which weakens type guarantees; introduce two explicit types such as UnverifiedAuthorizationRequest (keeping client_id?, redirect_uri?, realm_id?) and ValidatedAuthorizationRequest with required client_id: string and redirect_uri: string (and realm_id as required if applicable), update any validation function (e.g., the authorize/validate function that consumes the unverified type) to perform runtime checks and return or narrow to ValidatedAuthorizationRequest, and then update downstream functions to accept ValidatedAuthorizationRequest so callers can rely on these invariants instead of re-checking optional fields.apps/server-core/test/unit/http/controllers/workflows/token/grant-idp-authorize.spec.ts (1)
93-185: Add regression coverage for the new callback contract.The suite only exercises the
!codeRequestpath and only checks the happy-path exchange. Since this PR's contract is “no server-set token cookies plus a hand-off back through/authorizewhencodeRequestexists”, I'd add one test with an encodedcodeRequestand one raw-response assertion that bothauthorize-inandPOST /tokenomitset-cookie.🤖 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-idp-authorize.spec.ts` around lines 93 - 185, Tests only cover the no-codeRequest happy path; add regression tests that exercise the codeRequest callback contract by calling buildIdentityProviderAuthorizePath and buildIdentityProviderAuthorizeCallbackPath with an encoded codeRequest value and asserting that the authorize-in response and the subsequent token exchange (suite.client.token.createWithAuthorizationCode or a raw POST to /token) do NOT include Set-Cookie headers; specifically, add one test that constructs a codeRequest (encoded in the same format the server expects), sends the callback GET to buildIdentityProviderAuthorizeCallbackPath(...)?codeRequest=..., asserts the 302 hand-off contains the authup code, then performs the token exchange and asserts both the authorize-in response.headers.get('set-cookie') and the token response/raw HTTP response headers do not exist.
🤖 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/app/modules/database/repositories/identity-provider/repository.ts`:
- Around line 166-169: The findRealm method currently throws a bare Error when
realmRepository.resolve(realmId) returns falsy; change this to a distinguishable
failure: either make findRealm return Promise<Realm | null> and return null when
not found (and update callers such as authorizeIn to handle the null case and
map it to the appropriate HTTP response), or create and throw a specific domain
error (e.g., RealmNotFoundError) instead of generic Error so callers can catch
and translate it; ensure the method signature and all call sites (authorizeIn
and any other callers) are updated to handle the new return type or the specific
error type.
In `@apps/server-core/src/core/entities/identity-provider/types.ts`:
- Line 18: Change the findRealm contract to return Promise<Realm | null> instead
of Promise<Realm>, update the implementation of the repository method that
currently throws when a realm is missing (the method implementing findRealm in
the identity-provider repository) to return null for not-found cases, and then
update all callers of findRealm to explicitly handle the null case and map it to
the appropriate OAuth/HTTP error instead of relying on exceptions; ensure the
Realm type remains the same and only the return signature and not-found behavior
are changed.
In `@packages/client-web-kit/src/core/store/create.ts`:
- Around line 364-373: In exchangeAuthorizationCode, reset the resolution flags
before calling resolveToken()/resolveUser() so stale state isn't reused: after
applyTokenGrantResponse(response) (or immediately before resolving), set
tokenResolved = false and userResolved = false (or call existing reset helpers
if present) and then await resolveToken(); await resolveUser(); ensuring
exchangeAuthorizationCode, applyTokenGrantResponse, resolveToken, resolveUser
and the tokenResolved/userResolved state are updated accordingly.
In `@packages/client-web-nuxt/src/runtime/helpers/routing-interceptor.ts`:
- Around line 41-48: The authorization code (variable "code") is left in the URL
after a successful exchange via this.store.exchangeAuthorizationCode, causing
redundant exchanges; after the await this.store.exchangeAuthorizationCode(code)
resolves successfully, remove the "code" query param from the current route
(e.g., via the router's replace or window.history.replaceState) so the page URL
no longer contains the code without triggering a navigation; keep the catch
behavior unchanged (only remove the param on success).
---
Outside diff comments:
In
`@apps/server-core/src/adapters/http/controllers/entities/identity-provider/module.ts`:
- Around line 318-331: The redirect rebuild currently uses new URL('/authorize',
this.options.baseURL) which discards any path prefix in this.options.baseURL;
change the URL construction to preserve the base path (e.g., create a URL from
this.options.baseURL and append or join the 'authorize' segment without a
leading slash) so that if this.options.baseURL contains a path prefix the final
redirect becomes <basePath>/authorize; update the code around where
data.codeRequest, authorizationCode.id and sendRedirect are used (symbols:
this.options.baseURL, data.codeRequest, authorizationCode.id, sendRedirect) to
set searchParams on the preserved-path URL before calling sendRedirect.
In
`@apps/server-core/src/core/oauth2/authorization/code-request/verifier/module.ts`:
- Around line 66-72: The current logic skips redirect URI validation when
client.redirect_uri is null, allowing arbitrary data.redirect_uri values; change
the verifier so that if the client has no registered redirect_uri the request is
rejected (e.g., throw OAuth2Error.redirectUriMismatch()), and otherwise parse
client.redirect_uri into redirectUris and validate data.redirect_uri with
isSimpleMatch as before—ensure you reference client.redirect_uri,
data.redirect_uri, isSimpleMatch, and OAuth2Error.redirectUriMismatch() in the
updated check so all requests require a matching registered redirect URI.
---
Nitpick comments:
In
`@apps/server-core/test/unit/http/controllers/workflows/token/grant-idp-authorize.spec.ts`:
- Around line 93-185: Tests only cover the no-codeRequest happy path; add
regression tests that exercise the codeRequest callback contract by calling
buildIdentityProviderAuthorizePath and
buildIdentityProviderAuthorizeCallbackPath with an encoded codeRequest value and
asserting that the authorize-in response and the subsequent token exchange
(suite.client.token.createWithAuthorizationCode or a raw POST to /token) do NOT
include Set-Cookie headers; specifically, add one test that constructs a
codeRequest (encoded in the same format the server expects), sends the callback
GET to buildIdentityProviderAuthorizeCallbackPath(...)?codeRequest=..., asserts
the 302 hand-off contains the authup code, then performs the token exchange and
asserts both the authorize-in response.headers.get('set-cookie') and the token
response/raw HTTP response headers do not exist.
In `@packages/core-kit/src/domains/authorization-code/entity.ts`:
- Around line 40-42: The current shared request type in authorization-code
entity makes client_id and redirect_uri optional (client_id, redirect_uri,
realm_id), which weakens type guarantees; introduce two explicit types such as
UnverifiedAuthorizationRequest (keeping client_id?, redirect_uri?, realm_id?)
and ValidatedAuthorizationRequest with required client_id: string and
redirect_uri: string (and realm_id as required if applicable), update any
validation function (e.g., the authorize/validate function that consumes the
unverified type) to perform runtime checks and return or narrow to
ValidatedAuthorizationRequest, and then update downstream functions to accept
ValidatedAuthorizationRequest so callers can rely on these invariants instead of
re-checking optional fields.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 1ec3c709-97f0-4758-b9a3-c190cca17a7b
📒 Files selected for processing (22)
apps/client-web-slim/src/app.tsapps/server-core/src/adapters/http/controllers/entities/identity-provider/module.tsapps/server-core/src/adapters/http/controllers/entities/identity-provider/types.tsapps/server-core/src/adapters/http/controllers/workflows/token/module.tsapps/server-core/src/adapters/http/controllers/workflows/token/types.tsapps/server-core/src/adapters/http/middleware/built-in/authorization/module.tsapps/server-core/src/adapters/http/middleware/built-in/authorization/types.tsapps/server-core/src/app/modules/config/constants.tsapps/server-core/src/app/modules/config/parse.tsapps/server-core/src/app/modules/config/read/env.tsapps/server-core/src/app/modules/config/types.tsapps/server-core/src/app/modules/database/repositories/identity-provider/repository.tsapps/server-core/src/app/modules/http/modules/controller.tsapps/server-core/src/app/modules/http/modules/middleware.tsapps/server-core/src/core/entities/identity-provider/types.tsapps/server-core/src/core/oauth2/authorization/code-request/verifier/module.tsapps/server-core/src/core/oauth2/authorization/module.tsapps/server-core/test/unit/http/controllers/workflows/token/grant-idp-authorize.spec.tsdocs/src/guide/deployment/configuration-server-core.mdpackages/client-web-kit/src/core/store/create.tspackages/client-web-nuxt/src/runtime/helpers/routing-interceptor.tspackages/core-kit/src/domains/authorization-code/entity.ts
💤 Files with no reviewable changes (8)
- apps/server-core/src/app/modules/config/read/env.ts
- apps/server-core/src/app/modules/config/constants.ts
- apps/server-core/src/app/modules/http/modules/middleware.ts
- apps/server-core/src/adapters/http/middleware/built-in/authorization/types.ts
- apps/server-core/src/app/modules/config/parse.ts
- docs/src/guide/deployment/configuration-server-core.md
- apps/server-core/src/app/modules/config/types.ts
- apps/server-core/src/adapters/http/controllers/workflows/token/types.ts
closes #2936
Summary by CodeRabbit
New Features
Improvements
Removals
Tests
Documentation