Repository navigation
feat: include realm_access and global_access role claims in access to… - #3013
Conversation
|
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 (4)
📝 WalkthroughWalkthroughThe PR adds identity-aware role resolution to OAuth2 access token issuance: a new Changes
Sequence DiagramsequenceDiagram
participant Client
participant OAuth2Issuer as OAuth2AccessTokenIssuer
participant RoleProvider as IdentityPermissionProvider
participant Repo as Role/Entity Repos
participant Signer
participant TokenRepo as TokenRepository
Client->>OAuth2Issuer: issue(input)
activate OAuth2Issuer
OAuth2Issuer->>RoleProvider: getRolesFor(identity)
activate RoleProvider
RoleProvider->>Repo: lookup roles by identity type
activate Repo
Repo-->>RoleProvider: roles[]
deactivate Repo
RoleProvider-->>OAuth2Issuer: realm_access + global_access
deactivate RoleProvider
OAuth2Issuer->>Signer: sign(payload with claims)
activate Signer
Signer-->>OAuth2Issuer: signature
deactivate Signer
OAuth2Issuer->>TokenRepo: saveWithSignature(payload, signature)
activate TokenRepo
TokenRepo-->>OAuth2Issuer: token record
deactivate TokenRepo
OAuth2Issuer-->>Client: issued token
deactivate OAuth2Issuer
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 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 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.
Pull request overview
Adds role-claim support to issued OAuth2 access tokens by introducing realm_access and global_access claim shapes and wiring a role provider into the access token issuer.
Changes:
- Extend
OAuth2TokenPayloadwithrealm_access/global_accessand define the claim type. - Add role-claim construction to
OAuth2AccessTokenIssuervia a newIIdentityRoleProviderabstraction (implemented byIdentityPermissionProvider). - Register the new role provider in the OAuth2 module and add unit tests for the issuer behavior.
Reviewed changes
Copilot reviewed 7 out of 7 changed files in this pull request and generated 4 comments.
Show a summary per file
| File | Description |
|---|---|
| packages/specs/src/oauth2/types.ts | Adds new access-grant claim types/fields to the token payload spec. |
| apps/server-core/ui/vite.config.ts | Simplifies Vite config export to a plain object. |
| apps/server-core/test/unit/core/oauth2/token/issuer/access/module.spec.ts | Adds tests covering access token role-claim population and edge cases. |
| apps/server-core/src/core/oauth2/token/issuer/access/module.ts | Builds and injects realm_access / global_access into access token payloads during issuance. |
| apps/server-core/src/core/identity/permission/types.ts | Introduces IIdentityRoleProvider interface for retrieving identity roles. |
| apps/server-core/src/core/identity/permission/module.ts | Implements IIdentityRoleProvider in IdentityPermissionProvider. |
| apps/server-core/src/app/modules/oauth2/module.ts | Wires IdentityPermissionProvider into OAuth2AccessTokenIssuer construction. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
There was a problem hiding this comment.
Actionable comments posted: 2
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/ui/vite.config.ts (1)
16-31:⚠️ Potential issue | 🟡 MinorThis change is unrelated to the PR objectives.
The modification from
defineConfig(() => ({ ... }))todefineConfig({ ... })is a valid simplification of the Vite configuration, but it has no connection to the stated PR goal of addingrealm_accessandglobal_accessrole claims to OAuth2 access tokens. Including unrelated changes makes the PR harder to review and understand.Please consider reverting this change or moving it to a separate PR focused on build configuration improvements.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/ui/vite.config.ts` around lines 16 - 31, The change replaced defineConfig(() => ({ ... })) with defineConfig({ ... }) in the Vite config (vite.config.ts) which is unrelated to adding realm_access/global_access claims; revert the Vite change so defineConfig uses the original arrow-function form or extract this edit into a dedicated PR: restore the original defineConfig(() => ({ ... })) usage (including the base, plugins, resolve.alias and ssr settings) in this branch or move the simplified config into a new commit/PR titled "vite config simplification" to keep the OAuth2 claim changes isolated.
🧹 Nitpick comments (5)
apps/server-core/test/unit/core/oauth2/token/issuer/access/module.spec.ts (1)
100-130: Add coverage for cross-realm roles.This suite never feeds in a role whose
realm_iddiffers from the token'srealm_id. Given the partitioning logic inOAuth2AccessTokenIssuer.buildAccessClaims(see review comment there), please add a case that asserts the expected behavior — most likely such a role should not appear inrealm_accessof a token issued for another realm.🧪 Suggested additional test
it('should not include roles bound to a different realm in realm_access', async () => { const otherRealmId = randomUUID(); const roles: Role[] = [ { id: randomUUID(), name: 'foreign', realm_id: otherRealmId } as Role, { id: randomUUID(), name: 'local', realm_id: realmId } as Role, { id: randomUUID(), name: 'global', realm_id: null } as Role, ]; const provider = createRoleProvider(roles); const issuer = new OAuth2AccessTokenIssuer(repository, signer, {}, provider); await issuer.issue({ sub: userId, sub_kind: OAuth2SubKind.USER, realm_id: realmId }); const insertCall = (repository.insert as ReturnType<typeof vi.fn>).mock.calls[0][0]; expect(insertCall.realm_access).toEqual({ roles: ['local'] }); expect(insertCall.global_access).toEqual({ roles: ['global'] }); });🤖 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/token/issuer/access/module.spec.ts` around lines 100 - 130, Add a unit that covers cross-realm roles: using createRoleProvider to supply a Role with realm_id different from the token's realm_id plus a local and a global role, instantiate OAuth2AccessTokenIssuer and call issuer.issue with realm_id set to the local realm, then inspect the repository.insert mock (repository.insert.mock.calls[0][0]) to assert that OAuth2AccessTokenIssuer.buildAccessClaims excludes the foreign role from realm_access (only includes the local role) and still includes the global role in global_access; reference createRoleProvider, OAuth2AccessTokenIssuer, issuer.issue and repository.insert in the assertion.apps/server-core/src/core/oauth2/token/issuer/access/module.ts (1)
36-47: Minor: skip building the spread when there are no claims to merge.When
buildAccessClaimsreturns{}, the spread is a no-op but still allocates. Not a hot path — purely cosmetic. Feel free to ignore.🤖 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/access/module.ts` around lines 36 - 47, The issue is that when buildAccessClaims() returns an empty object you still spread it into the insert payload (allocating a no-op object); modify the issue method so you only merge accessClaims into the object passed to repository.insert when it contains properties (e.g., check Object.keys(accessClaims).length > 0 or otherwise test for emptiness) — update the issue function (where accessClaims is used) to conditionally include the spread so repository.insert gets the base payload plus ...(accessClaims) only when accessClaims is non-empty.packages/specs/src/oauth2/types.ts (1)
82-95: Tighten the doc strings on the new claim fields.
realm_accessis described as "roles where realm_id matches a realm" — every role has arealm_id, so this is ambiguous. Consider clarifying thatrealm_accesscontains roles scoped to the token'srealm_id, andglobal_accesscontains roles whoserealm_idis null/unset. This is also worth aligning with the partitioning rule actually implemented inOAuth2AccessTokenIssuer.buildAccessClaims(see comment in that file).📝 Suggested wording
/** - * Realm-scoped role claims (roles where realm_id matches a realm). + * Roles scoped to the token's realm (i.e., role.realm_id === payload.realm_id). */ realm_access?: OAuth2AccessGrantClaim, /** - * Global role claims (roles with realm_id = null). + * Roles not scoped to any realm (role.realm_id is null / unset). */ global_access?: OAuth2AccessGrantClaim🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/specs/src/oauth2/types.ts` around lines 82 - 95, Update the docstrings for the new claim fields to be precise: change the comment for realm_access on OAuth2AccessGrantClaim to state it contains roles scoped to the token's realm_id (i.e., roles whose realm_id matches the token's realm_id), and change the comment for global_access to state it contains roles with a null/unset realm_id (global roles). Reference the existing partitioning behavior implemented in OAuth2AccessTokenIssuer.buildAccessClaims when wording these comments so they match the actual logic.apps/server-core/src/core/identity/permission/module.ts (1)
127-143: Consider also filtering byidentity.realmId(or returning the realm scoping intact).Currently this method narrows by
clientIdonly. Callers that care about realm scoping (e.g.OAuth2AccessTokenIssuer.buildAccessClaims) have to re-derive that logic on their own. If/when that issuer is fixed to drop cross-realm roles (see comment onapps/server-core/src/core/oauth2/token/issuer/access/module.ts), it may be cleaner to centralize the rule here, e.g. drop roles whoserealm_idis set and not equal toidentity.realmId. Optional — a clear consumer-side filter is also fine.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/core/identity/permission/module.ts` around lines 127 - 143, The getRolesFor(identity: IdentityPolicyData) method currently only narrows by client/user/robot id; update it to also respect realm scoping by filtering out roles whose realm_id is set and does not match identity.realmId (or by returning roles grouped/scoped by realm intact) before returning. Modify the branches that call clientRepository.getBoundRoles, userRepository.getBoundRoles, robotRepository.getBoundRoles and the subsequent .then(data => this.reduceEntitiesByIdentityClient(data, identity)) so the result is filtered by role.realm_id !== undefined && role.realm_id !== identity.realmId (drop those), or preserve realm-scoped metadata to let callers decide; ensure the logic is applied centrally in getRolesFor (or inside reduceEntitiesByIdentityClient) so callers like OAuth2AccessTokenIssuer.buildAccessClaims no longer need to re-derive the realm filter.apps/server-core/src/app/modules/oauth2/module.ts (1)
174-188: ConsolidateIdentityPermissionProviderinstantiation in the identity module.The inline construction of
IdentityPermissionProviderand its four repository instances is duplicated across multiple modules:
oauth2/module.ts(lines 175–180)http/modules/controller.ts(lines 243–248)http/modules/middleware.ts(lines 128–133)Register
IdentityPermissionProvider(or anIIdentityRoleProvider) as an injection key in the IDENTITY module instead. This:
- Eliminates per-factory instantiation across modules
- Centralizes repository ownership in the identity module
- Removes coupling to
DataSourceand concrete repository classes in oauth2 and http modules- Simplifies mocking for tests
Add a registration in
IdentityModuleand resolve it here:♻️ Sketch
container.register(OAuth2InjectionToken.AccessTokenIssuer, { useFactory: (c) => { const tokenRepository = c.resolve(OAuth2InjectionToken.TokenRepository); const tokenSigner = c.resolve(OAuth2InjectionToken.TokenSigner); - const dataSource = c.resolve<DataSource>(DatabaseInjectionKey.DataSource); - const identityRoleProvider = new IdentityPermissionProvider({ - clientRepository: new ClientRepository(dataSource), - userRepository: new UserRepository(dataSource), - robotRepository: new RobotRepository(dataSource), - roleRepository: new RoleRepository(dataSource), - }); + const identityRoleProvider = c.resolve(IdentityInjectionKey.RoleProvider); return new OAuth2AccessTokenIssuer( tokenRepository, tokenSigner, { maxAge: config.tokenAccessMaxAge, issuer: config.publicUrl, }, identityRoleProvider, ); }, });🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/app/modules/oauth2/module.ts` around lines 174 - 188, Replace the inline construction of IdentityPermissionProvider and its concrete repositories in oauth2/module.ts with a resolved injection from the IdentityModule: register IdentityPermissionProvider (or an IIdentityRoleProvider binding) inside the IdentityModule using the DataSource there (creating ClientRepository, UserRepository, RobotRepository, RoleRepository once), then in this file resolve the provider from the container (c.resolve<IIdentityRoleProvider>(YourIdentityInjectionKey)) and pass that resolved instance into the OAuth2AccessTokenIssuer constructor (where IdentityPermissionProvider and identityRoleProvider are currently referenced) instead of new-ing repositories here; this removes direct DataSource/repository usage and centralizes ownership for easier testing and reuse.
🤖 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/access/module.ts`:
- Around line 56-84: buildAccessClaims currently classifies any role with a
truthy role.realm_id as a realm-scoped role, allowing roles from other realms to
leak into the token's realm_access; change the logic in buildAccessClaims (in
the access token issuer module) to only treat a role as realm-scoped when
role.realm_id === input.realm_id, treat roles with no realm_id as global, and
exclude roles that belong to other realms entirely from both realm_access and
global_access; update the test suite to add a unit test that supplies a role
whose realm_id differs from the token's input.realm_id and assert it is not
present in either returned claim.
In `@apps/server-core/test/unit/core/oauth2/token/issuer/access/module.spec.ts`:
- Around line 132-147: Test title is misleading: the current spec for
OAuth2AccessTokenIssuer (module.spec.ts) asserts that a role with no realm_id is
treated as global, not that an undefined token realm_id forces global access.
Rename the test to reflect "role with no realm_id treated as global" (or
similar) and add a new test where you pass roles with a realm_id (use
createRoleProvider to provide a role with realm_id set) but call issuer.issue
with an input that omits realm_id (sub: userId, sub_kind: OAuth2SubKind.USER)
and assert that insertCall.global_access remains empty and
insertCall.realm_access contains the role for that realm; keep using
OAuth2AccessTokenIssuer, issuer.issue, createRoleProvider, and repository.insert
to locate code.
---
Outside diff comments:
In `@apps/server-core/ui/vite.config.ts`:
- Around line 16-31: The change replaced defineConfig(() => ({ ... })) with
defineConfig({ ... }) in the Vite config (vite.config.ts) which is unrelated to
adding realm_access/global_access claims; revert the Vite change so defineConfig
uses the original arrow-function form or extract this edit into a dedicated PR:
restore the original defineConfig(() => ({ ... })) usage (including the base,
plugins, resolve.alias and ssr settings) in this branch or move the simplified
config into a new commit/PR titled "vite config simplification" to keep the
OAuth2 claim changes isolated.
---
Nitpick comments:
In `@apps/server-core/src/app/modules/oauth2/module.ts`:
- Around line 174-188: Replace the inline construction of
IdentityPermissionProvider and its concrete repositories in oauth2/module.ts
with a resolved injection from the IdentityModule: register
IdentityPermissionProvider (or an IIdentityRoleProvider binding) inside the
IdentityModule using the DataSource there (creating ClientRepository,
UserRepository, RobotRepository, RoleRepository once), then in this file resolve
the provider from the container
(c.resolve<IIdentityRoleProvider>(YourIdentityInjectionKey)) and pass that
resolved instance into the OAuth2AccessTokenIssuer constructor (where
IdentityPermissionProvider and identityRoleProvider are currently referenced)
instead of new-ing repositories here; this removes direct DataSource/repository
usage and centralizes ownership for easier testing and reuse.
In `@apps/server-core/src/core/identity/permission/module.ts`:
- Around line 127-143: The getRolesFor(identity: IdentityPolicyData) method
currently only narrows by client/user/robot id; update it to also respect realm
scoping by filtering out roles whose realm_id is set and does not match
identity.realmId (or by returning roles grouped/scoped by realm intact) before
returning. Modify the branches that call clientRepository.getBoundRoles,
userRepository.getBoundRoles, robotRepository.getBoundRoles and the subsequent
.then(data => this.reduceEntitiesByIdentityClient(data, identity)) so the result
is filtered by role.realm_id !== undefined && role.realm_id !== identity.realmId
(drop those), or preserve realm-scoped metadata to let callers decide; ensure
the logic is applied centrally in getRolesFor (or inside
reduceEntitiesByIdentityClient) so callers like
OAuth2AccessTokenIssuer.buildAccessClaims no longer need to re-derive the realm
filter.
In `@apps/server-core/src/core/oauth2/token/issuer/access/module.ts`:
- Around line 36-47: The issue is that when buildAccessClaims() returns an empty
object you still spread it into the insert payload (allocating a no-op object);
modify the issue method so you only merge accessClaims into the object passed to
repository.insert when it contains properties (e.g., check
Object.keys(accessClaims).length > 0 or otherwise test for emptiness) — update
the issue function (where accessClaims is used) to conditionally include the
spread so repository.insert gets the base payload plus ...(accessClaims) only
when accessClaims is non-empty.
In `@apps/server-core/test/unit/core/oauth2/token/issuer/access/module.spec.ts`:
- Around line 100-130: Add a unit that covers cross-realm roles: using
createRoleProvider to supply a Role with realm_id different from the token's
realm_id plus a local and a global role, instantiate OAuth2AccessTokenIssuer and
call issuer.issue with realm_id set to the local realm, then inspect the
repository.insert mock (repository.insert.mock.calls[0][0]) to assert that
OAuth2AccessTokenIssuer.buildAccessClaims excludes the foreign role from
realm_access (only includes the local role) and still includes the global role
in global_access; reference createRoleProvider, OAuth2AccessTokenIssuer,
issuer.issue and repository.insert in the assertion.
In `@packages/specs/src/oauth2/types.ts`:
- Around line 82-95: Update the docstrings for the new claim fields to be
precise: change the comment for realm_access on OAuth2AccessGrantClaim to state
it contains roles scoped to the token's realm_id (i.e., roles whose realm_id
matches the token's realm_id), and change the comment for global_access to state
it contains roles with a null/unset realm_id (global roles). Reference the
existing partitioning behavior implemented in
OAuth2AccessTokenIssuer.buildAccessClaims when wording these comments so they
match the actual logic.
🪄 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: 0fcca3aa-bd71-49cf-a9d6-e69501555bd9
📒 Files selected for processing (7)
apps/server-core/src/app/modules/oauth2/module.tsapps/server-core/src/core/identity/permission/module.tsapps/server-core/src/core/identity/permission/types.tsapps/server-core/src/core/oauth2/token/issuer/access/module.tsapps/server-core/test/unit/core/oauth2/token/issuer/access/module.spec.tsapps/server-core/ui/vite.config.tspackages/specs/src/oauth2/types.ts
…kens
Summary by CodeRabbit
New Features
realm_access,global_access).Tests
Refactor