Repository navigation
fix: realm-scoping and provisioning-validation follow-ups - #3177
Conversation
- add IRealmRepository.resolveId (UUID pass-through, canonicalizing name lookup, null => caller fails closed) and sweep all resolve-then-filter blocks across the repository adapters, the permission/policy checker services and the realm-resolver middleware; an unknown realm key no longer silently drops the realm predicate - cache RealmRepositoryAdapter.findOneById under the CachePrefix.REALM id key (60s), matching the existing realm subscriber invalidation - fix EntitySubscriber.afterRemove to read the pre-removal row (databaseEntity): remove() strips the primary key from event.entity, which broke id-keyed cache invalidation and DELETED event payloads
- extract the password grant's realm-hint handling into a shared readRealmHint helper and apply it to the authorization_code and refresh_token grants: realm_id ?? realm_name, canonicalized, resolved once with master fallback, scoped onto client-by-name resolution - fixes the nondeterministic refresh leg: a password login via a name-identified client now refreshes against the same realm's client instead of an unscoped name lookup matching an arbitrary same-named client from another realm - the refresh grant resolves the realm lazily, so a bare refresh (no client auth) performs no realm lookup - document the intended UUID skip: a UUID-identified user/client is resolved globally by primary key; the realm hint constrains name resolution only (pinned by test) BREAKING CHANGE: a name-identified client on the authorization_code or refresh_token grant without a realm hint now always resolves in the master realm; pass realm_id/realm_name or the client UUID for clients in other realms.
… group Nested entity validators in the provisioning tree ran group-less, so every core-kit field mounted under ValidatorGroup.CREATE/UPDATE was skipped — file-provisioned entities were effectively never field-validated, and top-level policies were silently dropped from the validated output. - add ValidatorGroup.PROVISIONING (@authup/kit); core-kit validators mount identifier fields (name, realm_id, policy type) under [CREATE, PROVISIONING], built_in only under PROVISIONING (API groups keep stripping it), and user email as optional under PROVISIONING (the synchronizer backfills a placeholder) - run every nested provisioning validator with the group and assign the output back (createProvisioningEntitiesValidator), so canonicalization and stripping reach the synchronizers; array indices are prefixed onto issue paths - add PolicyProvisioningValidator (attributes, extraAttributes, recursive children) and a root policies mount — file-declared policies are now validated and provisioned - cover previously unmounted relation keys (permission relations policies; role globalPermissionsExclude/RealmScope/Overrides) and replace the client relations wildcard mounts, whose output reassembly is broken in validup 0.5.1 BREAKING CHANGE: invalid provisioning files now abort startup instead of being silently accepted; attribute keys outside the entity schema are stripped.
- vitest + @vue/test-utils + happy-dom setup (test/vitest.config.ts with @vitejs/plugin-vue; the package script passes --config explicitly) - component suite pins the interactive-login realm plumbing: picker- selected realm transmitted, codeRequest.realm_id transmitted including a late-arriving prop, empty realm omitted from the password grant - store-level suite pins the login() gate forwarding ctx.realmId even while the store's own realm ref is still null
Both ldap specs created and dropped the same cn=foo account on the one shared OpenLDAP testcontainer; with spec files running in parallel workers, a sibling's afterAll drop raced a concurrent login.
- architecture.md: token endpoint realm resolution (all three client- authenticating grants), fail-closed realm-key predicate contract, file-source provisioning validation, realm-by-id query caching - testing.md: client-web-kit component test setup - provisioning guide: validation on load, built_in support, fix stale globalPermissionsPolicyName -> globalPermissionsRealmScope naming - oauth2 api guide: realm hint semantics on code/refresh grants - mark plan 038 done
|
Note Reviews pausedUse the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThis PR adds IRealmRepository.resolveId for fail-closed realm-key resolution used across repositories, middleware, checker services, and OAuth2 grant handlers; introduces a PROVISIONING validator group with built_in fields and centralized provisioning entity array validation; adds client-web-kit component testing infrastructure; and fixes an entity-subscriber delete payload edge case. ChangesFail-Closed Realm Resolution
Estimated code review effort: 4 (Complex) | ~60 minutes Provisioning Validator Group and Entity Validators
Estimated code review effort: 4 (Complex) | ~55 minutes Client-Web-Kit Component Test Toolchain
Estimated code review effort: 2 (Simple) | ~15 minutes Entity Subscriber Delete Payload Fix
Estimated code review effort: 2 (Simple) | ~10 minutes Sequence Diagram(s)sequenceDiagram
participant Client
participant TokenController
participant HTTPPasswordGrant
participant readRealmHint
participant RealmRepositoryAdapter
participant UserRepositoryAdapter
Client->>TokenController: POST /token (grant_type=password, realm_id/realm_name, username, password)
TokenController->>HTTPPasswordGrant: runWithRequest(body)
HTTPPasswordGrant->>readRealmHint: readRealmHint(body)
readRealmHint-->>HTTPPasswordGrant: canonicalized realm hint
HTTPPasswordGrant->>RealmRepositoryAdapter: resolve(hint, true)
RealmRepositoryAdapter-->>HTTPPasswordGrant: realm (id)
HTTPPasswordGrant->>UserRepositoryAdapter: authenticate(username, password, realm.id)
UserRepositoryAdapter-->>HTTPPasswordGrant: user or EntityNotFoundError
HTTPPasswordGrant-->>TokenController: grant response
TokenController-->>Client: access_token or error
sequenceDiagram
participant FileProvisioningSource
participant RootProvisioningValidator
participant createProvisioningEntitiesValidator
participant NestedValidator
FileProvisioningSource->>RootProvisioningValidator: run(config, group=PROVISIONING)
RootProvisioningValidator->>createProvisioningEntitiesValidator: validate array (policies/realms/roles/scopes/permissions)
createProvisioningEntitiesValidator->>NestedValidator: run(item, group=PROVISIONING)
NestedValidator-->>createProvisioningEntitiesValidator: validated item or validup error
createProvisioningEntitiesValidator-->>RootProvisioningValidator: transformed array / zod issues
RootProvisioningValidator-->>FileProvisioningSource: validated config or fail-closed error
Possibly related PRs
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ 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 |
authup
@authup/client-web
@authup/server-core
@authup/access
@authup/client-web-kit
@authup/client-web-kit-theme
@authup/client-web-nuxt
@authup/client-web-theme
@authup/core-http-kit
@authup/core-kit
@authup/core-realtime-kit
@authup/errors
@authup/i18n
@authup/kit
@authup/server-adapter-kit
@authup/server-adapter-node
@authup/server-adapter-socket-io
@authup/server-adapter-web
@authup/server-kit
@authup/server-test-kit
@authup/specs
commit: |
There was a problem hiding this comment.
Pull request overview
Implements the remaining plan-038 follow-ups across server-core, core-kit, and client-web-kit: hardening realm-scoped lookups to fail closed, unifying /token realm-hint semantics across grants, introducing a dedicated PROVISIONING validator group for file-based provisioning, adding realm lookup caching + correct cache invalidation on deletes, and standing up component/unit test infrastructure for packages/client-web-kit.
Changes:
- Add
ValidatorGroup.PROVISIONINGand wire provisioning validation to run with that group (including nested entity validation and output canonicalization/stripping). - Enforce fail-closed realm predicates via
IRealmRepository.resolveId()and unify realm-hint parsing for/tokengrants (readRealmHint). - Add realm id query caching and fix TypeORM subscriber delete invalidation; introduce new/expanded regression test suites and docs updates.
Reviewed changes
Copilot reviewed 66 out of 67 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| packages/kit/src/constants.ts | Adds ValidatorGroup.PROVISIONING for file-source validation. |
| packages/core-kit/test/unit/domains/validator-groups.spec.ts | New tests pin CREATE/UPDATE vs PROVISIONING validator behavior. |
| packages/core-kit/src/domains/user/validator.ts | Mounts provisioning group rules (email optional, realm_id/name canonicalization coverage). |
| packages/core-kit/src/domains/scope/validator.ts | Adds PROVISIONING mounts and built_in allowance under provisioning. |
| packages/core-kit/src/domains/role/validator.ts | Adds PROVISIONING mounts and built_in allowance under provisioning. |
| packages/core-kit/src/domains/robot/validator.ts | Extends CREATE mounts to include PROVISIONING where appropriate. |
| packages/core-kit/src/domains/realm/validator.ts | Adds provisioning-only built_in mount and CREATE+PROVISIONING name rules. |
| packages/core-kit/src/domains/policy/validator.ts | Extends mounts to PROVISIONING and allows provisioning-only built_in. |
| packages/core-kit/src/domains/permission/validator.ts | Extends mounts to PROVISIONING and allows provisioning-only built_in. |
| packages/core-kit/src/domains/client/validator.ts | Extends mounts to PROVISIONING and allows provisioning-only built_in. |
| packages/client-web-kit/test/vitest.config.ts | Adds vitest config for component tests (happy-dom + Vue SFC support). |
| packages/client-web-kit/test/utils/index.ts | Test harness to mount LoginForm with Pinia + fake HTTP + kit install wiring. |
| packages/client-web-kit/test/unit/core/store/login.spec.ts | Store-level tests for realm_id forwarding/omission in password login. |
| packages/client-web-kit/test/unit/components/workflows/login-form.spec.ts | Component tests pin interactive realm plumbing (picker/codeRequest/late props). |
| packages/client-web-kit/package.json | Adds test scripts and dev deps for vitest + @vue/test-utils + happy-dom. |
| package-lock.json | Locks newly added dev dependencies for client-web-kit testing. |
| docs/src/guide/development/api-oauth2.md | Documents updated realm-hint semantics across grants and UUID behavior. |
| docs/src/guide/deployment/provisioning.md | Documents fail-closed provisioning validation + provisioning-only fields/relations. |
| apps/server-core/test/unit/modules/provisioning.spec.ts | Extends provisioning integration test to cover policies + built_in + relations. |
| apps/server-core/test/unit/http/controllers/workflows/token/grant-refresh-token.spec.ts | New refresh-token realm-hint/client-by-name determinism coverage. |
| apps/server-core/test/unit/http/controllers/workflows/token/grant-password.spec.ts | Adds test for UUID username global resolution regardless of realm hint. |
| apps/server-core/test/unit/http/controllers/workflows/token/grant-password-ldap.spec.ts | De-flakes LDAP tests by using unique per-spec LDAP usernames. |
| apps/server-core/test/unit/http/controllers/workflows/token/grant-authorize.spec.ts | Adds auth-code exchange tests for realm-hinted client-by-name scoping. |
| apps/server-core/test/unit/http/controllers/entities/realm.spec.ts | Adds cache invalidation tests for id-keyed realm query caching. |
| apps/server-core/test/unit/http/controllers/entities/realm-scoped.spec.ts | Adds fail-closed tests for unknown realm UUIDs on realm-scoped name lookups. |
| apps/server-core/test/unit/core/provisioning/entities/root-validator.spec.ts | New unit tests for root provisioning validation output + relations preservation. |
| apps/server-core/test/unit/core/identity/permission/checker.spec.ts | Ensures unknown realm keys throw instead of dropping realm filters. |
| apps/server-core/test/unit/core/entities/realm/fake-repository.ts | Adds resolveId() to test fake realm repository. |
| apps/server-core/test/unit/adapters/ldap/helpers.ts | Parameterizes LDAP helper account name to avoid cross-test races. |
| apps/server-core/test/data/sources/file.mts | Expands fixture to include policies and policy relations. |
| apps/server-core/src/core/provisioning/synchronizer/base.ts | Updates canonicalization comment to reflect new validation behavior + defense-in-depth. |
| apps/server-core/src/core/provisioning/entities/utils.ts | Adds shared helper to run nested validators with PROVISIONING and reassign output. |
| apps/server-core/src/core/provisioning/entities/root/validator.ts | Validates top-level policies and uses shared nested-array validation helper. |
| apps/server-core/src/core/provisioning/entities/role/relations-validator.ts | Adds validation for new role realm-scope relation keys. |
| apps/server-core/src/core/provisioning/entities/realm/relations-validator.ts | Uses shared helper so nested realm relations validate with PROVISIONING group. |
| apps/server-core/src/core/provisioning/entities/policy/validator.ts | Adds policy provisioning validator (attributes + extraAttributes + recursive children). |
| apps/server-core/src/core/provisioning/entities/policy/index.ts | Exports the new policy provisioning validator. |
| apps/server-core/src/core/provisioning/entities/permission/validator.ts | Adds validation for permission provisioning relations. |
| apps/server-core/src/core/provisioning/entities/permission/relations-validator.ts | New validator for permission->policies relation names list. |
| apps/server-core/src/core/provisioning/entities/permission/index.ts | Exports permission relations validator alongside types/validator. |
| apps/server-core/src/core/provisioning/entities/index.ts | Exports provisioning entity utility helper. |
| apps/server-core/src/core/provisioning/entities/client/relations-validator.ts | Validates nested client permissions/roles arrays under PROVISIONING group. |
| apps/server-core/src/core/identity/resolver/module.ts | Documents intended UUID-global resolution semantics (realm scopes names only). |
| apps/server-core/src/core/identity/policy/checker/service.ts | Fail-closed realm filtering via resolveId() (throws on unknown realm key). |
| apps/server-core/src/core/identity/permission/checker/service.ts | Fail-closed realm filtering via resolveId() (throws on unknown realm key). |
| apps/server-core/src/core/entities/realm/types.ts | Adds IRealmRepository.resolveId(key) contract for fail-closed predicates. |
| apps/server-core/src/app/modules/provisioning/sources/file/module.ts | Runs root provisioning validator with ValidatorGroup.PROVISIONING. |
| apps/server-core/src/app/modules/database/repositories/user/repository.ts | Converts realm predicate to resolveId() and fails closed on unknown realm name. |
| apps/server-core/src/app/modules/database/repositories/scope/repository.ts | Converts realm predicate to resolveId() and fails closed on unknown realm name. |
| apps/server-core/src/app/modules/database/repositories/role/repository.ts | Converts realm predicate to resolveId() and fails closed on unknown realm name. |
| apps/server-core/src/app/modules/database/repositories/robot/repository.ts | Converts realm predicate to resolveId() and fails closed on unknown realm name. |
| apps/server-core/src/app/modules/database/repositories/realm/repository.ts | Adds id-keyed query caching + implements resolveId(). |
| apps/server-core/src/app/modules/database/repositories/policy/repository.ts | Converts realm predicate to resolveId() and fails closed on unknown realm name. |
| apps/server-core/src/app/modules/database/repositories/permission/repository.ts | Converts realm predicate to resolveId() and fails closed on unknown realm name. |
| apps/server-core/src/app/modules/database/repositories/identity-provider/repository.ts | Converts realm predicate blocks to resolveId() and fails closed on unknown realm name. |
| apps/server-core/src/app/modules/database/repositories/client/repository.ts | Converts realm predicate to resolveId() and fails closed on unknown realm name. |
| apps/server-core/src/adapters/http/middleware/built-in/realm-resolver/module.ts | Switches to resolveId() and fails closed for unknown realm names in routing. |
| apps/server-core/src/adapters/http/controllers/workflows/token/module.ts | Injects realmRepository into authorize/refresh grants. |
| apps/server-core/src/adapters/http/adapters/oauth2/grant-types/utils/realm.ts | Adds shared readRealmHint helper (realm_id ?? realm_name, canonicalized). |
| apps/server-core/src/adapters/http/adapters/oauth2/grant-types/utils/index.ts | Exports the new realm-hint helper. |
| apps/server-core/src/adapters/http/adapters/oauth2/grant-types/types.ts | Extends grant contexts to include realmRepository where needed. |
| apps/server-core/src/adapters/http/adapters/oauth2/grant-types/refresh_token.ts | Scopes client-by-name authentication via shared realm-hint resolution. |
| apps/server-core/src/adapters/http/adapters/oauth2/grant-types/password.ts | Uses shared readRealmHint instead of inline realm-hint parsing. |
| apps/server-core/src/adapters/http/adapters/oauth2/grant-types/authorize.ts | Scopes client-by-name authentication via shared realm-hint resolution. |
| apps/server-core/src/adapters/database/subscriber/module.ts | Fixes cache invalidation/publish on remove by preferring databaseEntity. |
| .agents/testing.md | Documents client-web-kit component test setup and required vitest config usage. |
| .agents/architecture.md | Documents PROVISIONING validation + fail-closed realm-key predicate rules. |
💡 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
🧹 Nitpick comments (7)
packages/client-web-kit/test/unit/core/store/login.spec.ts (1)
33-38: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDuplicate
findTokenRequesthelper.This is byte-for-byte the same helper already exported from
test/utils/index.ts(used bylogin-form.spec.tsvia'../../../utils', the same relative depth applies here). Reuse it instead of re-declaring locally.♻️ Proposed fix
import { createFakeClient } from '`@authup/core-http-kit/testing`'; -import type { FakeClient, FakeRequest } from '`@authup/core-http-kit/testing`'; import { describe, expect, it } from 'vitest'; import { createStore, createStoreDispatcher } from '../../../../src/core/store'; +import { findTokenRequest } from '../../../utils'; function buildStore() { const httpClient = createFakeClient({ handlers: { 'POST /token': () => ({ access_token: 'xyz', token_type: 'Bearer', expires_in: 3600, refresh_token: 'abc', }), }, }); const store = createStore({ httpClient, dispatcher: createStoreDispatcher(), }); return { store, httpClient }; } - -function findTokenRequest(httpClient: FakeClient) : FakeRequest | undefined { - return httpClient.requests.find( - (request) => request.method === 'POST' && - new URL(request.url, 'http://localhost').pathname === '/token', - ); -}🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/client-web-kit/test/unit/core/store/login.spec.ts` around lines 33 - 38, The local findTokenRequest helper in login.spec.ts is a duplicate of the shared utility already exported from test/utils/index.ts. Remove the inline helper and import/reuse the existing findTokenRequest from the shared test utils, following the same pattern used by login-form.spec.ts, so the test references the common helper instead of re-declaring it.apps/server-core/src/app/modules/database/repositories/client/repository.ts (1)
101-105: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExtract repeated realm-resolution-and-filter pattern.
The
resolveId(realmKey)→ null-check →andWhere('...realm_id = :realmId', ...)block is duplicated verbatim here and across permission/policy/robot/role/scope repository adapters. Consider extracting a small private helper to reduce duplication and centralize the fail-closed semantics.♻️ Example helper extraction
+ private async resolveRealmIdOrNull(realmKey: string): Promise<string | null> { + return this.realmRepository.resolveId(realmKey); + } + async findOneByName(name: string, realmKey?: string): Promise<Client | null> { const qb = this.repository.createQueryBuilder('client'); qb.where('client.name = :name', { name }); if (realmKey) { - const realmId = await this.realmRepository.resolveId(realmKey); + const realmId = await this.resolveRealmIdOrNull(realmKey); if (!realmId) { return null; } qb.andWhere('client.realm_id = :realmId', { realmId }); } return qb.getOne(); }Also applies to: 120-124
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/server-core/src/app/modules/database/repositories/client/repository.ts` around lines 101 - 105, The repeated realm scoping block in the repository adapters duplicates the same resolveId(realmKey) null-check and realm_id filter logic. Extract this into a small private helper in the relevant repository class (or shared base/helper used by the permission/policy/robot/role/scope adapters), and have the existing call sites use it so the fail-closed behavior stays centralized and consistent.apps/server-core/src/app/modules/database/repositories/identity-provider/repository.ts (1)
84-94: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy liftCorrect fail-closed realm scoping; consider extracting the repeated resolve-guard pattern.
Both methods correctly resolve
realmKeytorealmIdand fail closed (returnnull/[]) when unresolved. The same 5-line block is duplicated across ~10 call sites in this PR (client, permission, policy, robot, role, scope, user repositories). Since this is security-sensitive realm-scoping logic, a shared helper would reduce the risk of a future edit accidentally dropping the guard in one call site.♻️ Example shared helper (illustrative)
// e.g. in a shared repository util module export async function applyRealmScope( qb: SelectQueryBuilder<any>, alias: string, realmRepository: IRealmRepository, realmKey?: string, ): Promise<boolean> { if (!realmKey) return true; const realmId = await realmRepository.resolveId(realmKey); if (!realmId) return false; qb.andWhere(`${alias}.realm_id = :realmId`, { realmId }); return true; }- if (realmKey) { - const realmId = await this.realmRepository.resolveId(realmKey); - if (!realmId) { - return null; - } - qb.andWhere('provider.realm_id = :realmId', { realmId }); - } + if (!(await applyRealmScope(qb, 'provider', this.realmRepository, realmKey))) { + return null; + }Also applies to: 162-172
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/server-core/src/app/modules/database/repositories/identity-provider/repository.ts` around lines 84 - 94, The realm scoping block in IdentityProviderRepository.findOneByName is duplicated fail-closed logic that should be shared to avoid drift across repositories. Extract the repeated realmKey-to-realmId resolve/guard pattern into a common helper (for example, a shared repository utility like applyRealmScope), then update findOneByName and the other affected repository methods to use it so unresolved realms consistently return null/[] and the same scope condition is applied in one place.apps/server-core/test/unit/core/identity/permission/checker.spec.ts (1)
8-8: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick winTest doesn't exercise the intended
resolveId-miss branch.
randomUUID()is a valid v4 UUID, and per theIRealmRepository.resolveIdcontract a UUID key is A UUID key is returned as-is without existence verification (binding an unknown UUID matches zero rows — fail-closed by construction). So this test never reaches the newif (!realmId) throw new EntityNotFoundError();branch inservice.ts(lines 42-44) — it passes because the mismatchedrealm_idcriteria simply fails to find the entity, hitting the pre-existingif (!entity)throw instead. Consider adding a case using a non-UUID, non-existent realm name to specifically cover theresolveIdname-miss path.✅ Suggested additional test case
it('throws EntityNotFoundError for an unknown realm key instead of dropping the filter', async () => { const permissionRepository = suite.dataSource.getRepository(PermissionEntity); const permission = await permissionRepository.save(permissionRepository.create({ name: createNanoID(), built_in: true, })); await expect( service.check(permission.name, {}, createAllowAllActor(), randomUUID()), ).rejects.toBeInstanceOf(EntityNotFoundError); }); + + it('throws EntityNotFoundError for an unresolvable realm name (resolveId miss)', async () => { + const permissionRepository = suite.dataSource.getRepository(PermissionEntity); + const permission = await permissionRepository.save(permissionRepository.create({ + name: createNanoID(), + built_in: true, + })); + + await expect( + service.check(permission.name, {}, createAllowAllActor(), createNanoID()), + ).rejects.toBeInstanceOf(EntityNotFoundError); + });Also applies to: 78-89
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/server-core/test/unit/core/identity/permission/checker.spec.ts` at line 8, The current test uses randomUUID(), which bypasses the new resolveId miss path and only exercises the existing entity lookup failure. Update the permission checker test in checker.spec.ts to use a non-UUID realm name that does not exist, so IRealmRepository.resolveId returns no match and service.ts hits the new if (!realmId) throw EntityNotFoundError() branch. Keep the existing UUID-based case if needed, but add a dedicated name-miss assertion to cover the intended behavior.packages/core-kit/src/domains/policy/validator.ts (1)
41-87: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider a shared
CREATE_OR_PROVISIONINGgroup constant.The
[ValidatorGroup.CREATE, ValidatorGroup.PROVISIONING]literal is repeated identically across policy, realm, robot, and scope validators (and likely others per the PR description). Extracting a shared constant would reduce duplication and the risk of the groups drifting out of sync if this list changes later.♻️ Example shared constant
+// e.g. in a shared validator-groups util +export const CREATE_OR_PROVISIONING = [ValidatorGroup.CREATE, ValidatorGroup.PROVISIONING];- this.mount('name', { group: [ValidatorGroup.CREATE, ValidatorGroup.PROVISIONING] }, nameValidator); + this.mount('name', { group: CREATE_OR_PROVISIONING }, nameValidator);🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/core-kit/src/domains/policy/validator.ts` around lines 41 - 87, The repeated ValidatorGroup.CREATE and ValidatorGroup.PROVISIONING array literal in the policy validator should be replaced with a shared constant to avoid duplication and drift. Introduce a reusable CREATE_OR_PROVISIONING group constant near the validator definitions, then update the mount calls in the policy validator to use that constant; apply the same pattern in the related realm, robot, and scope validators so they all reference the same symbol.apps/server-core/src/core/provisioning/entities/root/validator.ts (1)
28-61: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider extracting the repeated mount pattern.
All five blocks (
policies,realms,roles,scopes,permissions) follow the exact same shape: instantiate a validator, thenmount(key, {optional:true}, createValidator(z.array(z.any()).check(createProvisioningEntitiesValidator(validator)))). A small private helper would remove the duplication and make adding future provisioning entity arrays a one-liner.♻️ Proposed helper to reduce duplication
+ private mountEntities<T>(key: string, validator: Container<T>) { + this.mount(key, { optional: true }, createValidator( + z + .array(z.any()) + .check(createProvisioningEntitiesValidator(validator)), + )); + } + protected initialize() { super.initialize(); const strategyValidator = new ProvisioningStrategyValidator(); this.mount('strategy', { optional: true }, strategyValidator); - const policyValidator = new PolicyProvisioningValidator(); - this.mount('policies', { optional: true }, createValidator( - z - .array(z.any()) - .check(createProvisioningEntitiesValidator(policyValidator)), - )); + this.mountEntities('policies', new PolicyProvisioningValidator()); + this.mountEntities('realms', new RealmProvisioningValidator()); + this.mountEntities('roles', new RoleProvisioningValidator()); + this.mountEntities('scopes', new ScopeProvisioningValidator()); + this.mountEntities('permissions', new PermissionProvisioningValidator()); }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/server-core/src/core/provisioning/entities/root/validator.ts` around lines 28 - 61, The RootProvisioningValidator setup repeats the same mount pattern for policies, realms, roles, scopes, and permissions. Extract this into a small private helper on RootProvisioningValidator that takes the entity key and validator instance, then performs the mount/createValidator/z.array(z.any()).check(createProvisioningEntitiesValidator(...)) flow once. Replace each repeated block with a single helper call so future entity arrays are easier to add.docs/src/guide/deployment/provisioning.md (1)
253-254: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDocs omit the
noneRealmScopevalue.The
globalPermissionsRealmScopefield is validated against the fullRealmScopeenum (none,own,ownOrNull,any), but the docs table only lists three of the four accepted values.📝 Suggested fix
-| `globalPermissionsRealmScope` | `string` | Default `realm_scope` (`own`, `ownOrNull`, `any`) stamped on each `globalPermissions` junction entry. | +| `globalPermissionsRealmScope` | `string` | Default `realm_scope` (`none`, `own`, `ownOrNull`, `any`) stamped on each `globalPermissions` junction entry. |🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/src/guide/deployment/provisioning.md` around lines 253 - 254, The provisioning docs for globalPermissionsRealmScope are missing the accepted RealmScope value `none`, so update the table entry to list the full enum handled by the validation logic. Make sure the description in provisioning.md for globalPermissionsRealmScope reflects all allowed values (`none`, `own`, `ownOrNull`, `any`) and keep the existing globalPermissionsRealmScopeOverrides entry aligned with that terminology.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In
`@apps/server-core/src/core/provisioning/entities/realm/relations-validator.ts`:
- Around line 31-65: The provisioning entity checks mounted in
RealmRelationsValidator rely on createProvisioningEntitiesValidator, but that
helper currently swallows any validator.run() error that is not a Validup error
and allows the original item to pass through. Update
createProvisioningEntitiesValidator in utils.ts to rethrow unexpected errors
instead of returning the input value, while preserving the existing Validup
handling used by the clients, roles, permissions, robots, scopes, and users
validators.
In `@apps/server-core/test/unit/core/entities/realm/fake-repository.ts`:
- Around line 32-40: The resolveId method in FakeEntityRepository should match
production realm-name normalization before calling findOneByName, because exact
string matching currently makes mixed-case or whitespace-padded names resolve
differently. Update the FakeEntityRepository.resolveId flow to normalize the
incoming key the same way the real repository does, then pass that normalized
value into findOneByName so lookups behave consistently.
---
Nitpick comments:
In `@apps/server-core/src/app/modules/database/repositories/client/repository.ts`:
- Around line 101-105: The repeated realm scoping block in the repository
adapters duplicates the same resolveId(realmKey) null-check and realm_id filter
logic. Extract this into a small private helper in the relevant repository class
(or shared base/helper used by the permission/policy/robot/role/scope adapters),
and have the existing call sites use it so the fail-closed behavior stays
centralized and consistent.
In
`@apps/server-core/src/app/modules/database/repositories/identity-provider/repository.ts`:
- Around line 84-94: The realm scoping block in
IdentityProviderRepository.findOneByName is duplicated fail-closed logic that
should be shared to avoid drift across repositories. Extract the repeated
realmKey-to-realmId resolve/guard pattern into a common helper (for example, a
shared repository utility like applyRealmScope), then update findOneByName and
the other affected repository methods to use it so unresolved realms
consistently return null/[] and the same scope condition is applied in one
place.
In `@apps/server-core/src/core/provisioning/entities/root/validator.ts`:
- Around line 28-61: The RootProvisioningValidator setup repeats the same mount
pattern for policies, realms, roles, scopes, and permissions. Extract this into
a small private helper on RootProvisioningValidator that takes the entity key
and validator instance, then performs the
mount/createValidator/z.array(z.any()).check(createProvisioningEntitiesValidator(...))
flow once. Replace each repeated block with a single helper call so future
entity arrays are easier to add.
In `@apps/server-core/test/unit/core/identity/permission/checker.spec.ts`:
- Line 8: The current test uses randomUUID(), which bypasses the new resolveId
miss path and only exercises the existing entity lookup failure. Update the
permission checker test in checker.spec.ts to use a non-UUID realm name that
does not exist, so IRealmRepository.resolveId returns no match and service.ts
hits the new if (!realmId) throw EntityNotFoundError() branch. Keep the existing
UUID-based case if needed, but add a dedicated name-miss assertion to cover the
intended behavior.
In `@docs/src/guide/deployment/provisioning.md`:
- Around line 253-254: The provisioning docs for globalPermissionsRealmScope are
missing the accepted RealmScope value `none`, so update the table entry to list
the full enum handled by the validation logic. Make sure the description in
provisioning.md for globalPermissionsRealmScope reflects all allowed values
(`none`, `own`, `ownOrNull`, `any`) and keep the existing
globalPermissionsRealmScopeOverrides entry aligned with that terminology.
In `@packages/client-web-kit/test/unit/core/store/login.spec.ts`:
- Around line 33-38: The local findTokenRequest helper in login.spec.ts is a
duplicate of the shared utility already exported from test/utils/index.ts.
Remove the inline helper and import/reuse the existing findTokenRequest from the
shared test utils, following the same pattern used by login-form.spec.ts, so the
test references the common helper instead of re-declaring it.
In `@packages/core-kit/src/domains/policy/validator.ts`:
- Around line 41-87: The repeated ValidatorGroup.CREATE and
ValidatorGroup.PROVISIONING array literal in the policy validator should be
replaced with a shared constant to avoid duplication and drift. Introduce a
reusable CREATE_OR_PROVISIONING group constant near the validator definitions,
then update the mount calls in the policy validator to use that constant; apply
the same pattern in the related realm, robot, and scope validators so they all
reference the same symbol.
🪄 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: 6b1f2a79-8799-4b94-aa70-8d7f85353c1b
⛔ Files ignored due to path filters (1)
package-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (66)
.agents/architecture.md.agents/testing.mdapps/server-core/src/adapters/database/subscriber/module.tsapps/server-core/src/adapters/http/adapters/oauth2/grant-types/authorize.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/index.tsapps/server-core/src/adapters/http/adapters/oauth2/grant-types/utils/realm.tsapps/server-core/src/adapters/http/controllers/workflows/token/module.tsapps/server-core/src/adapters/http/middleware/built-in/realm-resolver/module.tsapps/server-core/src/app/modules/database/repositories/client/repository.tsapps/server-core/src/app/modules/database/repositories/identity-provider/repository.tsapps/server-core/src/app/modules/database/repositories/permission/repository.tsapps/server-core/src/app/modules/database/repositories/policy/repository.tsapps/server-core/src/app/modules/database/repositories/realm/repository.tsapps/server-core/src/app/modules/database/repositories/robot/repository.tsapps/server-core/src/app/modules/database/repositories/role/repository.tsapps/server-core/src/app/modules/database/repositories/scope/repository.tsapps/server-core/src/app/modules/database/repositories/user/repository.tsapps/server-core/src/app/modules/provisioning/sources/file/module.tsapps/server-core/src/core/entities/realm/types.tsapps/server-core/src/core/identity/permission/checker/service.tsapps/server-core/src/core/identity/policy/checker/service.tsapps/server-core/src/core/identity/resolver/module.tsapps/server-core/src/core/provisioning/entities/client/relations-validator.tsapps/server-core/src/core/provisioning/entities/index.tsapps/server-core/src/core/provisioning/entities/permission/index.tsapps/server-core/src/core/provisioning/entities/permission/relations-validator.tsapps/server-core/src/core/provisioning/entities/permission/validator.tsapps/server-core/src/core/provisioning/entities/policy/index.tsapps/server-core/src/core/provisioning/entities/policy/validator.tsapps/server-core/src/core/provisioning/entities/realm/relations-validator.tsapps/server-core/src/core/provisioning/entities/role/relations-validator.tsapps/server-core/src/core/provisioning/entities/root/validator.tsapps/server-core/src/core/provisioning/entities/utils.tsapps/server-core/src/core/provisioning/synchronizer/base.tsapps/server-core/test/data/sources/file.mtsapps/server-core/test/unit/adapters/ldap/helpers.tsapps/server-core/test/unit/core/entities/realm/fake-repository.tsapps/server-core/test/unit/core/identity/permission/checker.spec.tsapps/server-core/test/unit/core/provisioning/entities/root-validator.spec.tsapps/server-core/test/unit/http/controllers/entities/realm-scoped.spec.tsapps/server-core/test/unit/http/controllers/entities/realm.spec.tsapps/server-core/test/unit/http/controllers/workflows/token/grant-authorize.spec.tsapps/server-core/test/unit/http/controllers/workflows/token/grant-password-ldap.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.tsapps/server-core/test/unit/modules/provisioning.spec.tsdocs/src/guide/deployment/provisioning.mddocs/src/guide/development/api-oauth2.mdpackages/client-web-kit/package.jsonpackages/client-web-kit/test/unit/components/workflows/login-form.spec.tspackages/client-web-kit/test/unit/core/store/login.spec.tspackages/client-web-kit/test/utils/index.tspackages/client-web-kit/test/vitest.config.tspackages/core-kit/src/domains/client/validator.tspackages/core-kit/src/domains/permission/validator.tspackages/core-kit/src/domains/policy/validator.tspackages/core-kit/src/domains/realm/validator.tspackages/core-kit/src/domains/robot/validator.tspackages/core-kit/src/domains/role/validator.tspackages/core-kit/src/domains/scope/validator.tspackages/core-kit/src/domains/user/validator.tspackages/core-kit/test/unit/domains/validator-groups.spec.tspackages/kit/src/constants.ts
createProvisioningEntitiesValidator swallowed any non-Validup error from validator.run(), leaving the original unvalidated item in place and producing no issues - a silent fail-open. Rethrow non-Validup errors so provisioning validation fails loudly and deterministically at startup.
FakeRealmRepository resolved names via exact string matching, so mixed-case or whitespace-padded keys diverged from production, which canonicalizes name lookups (LOWER(TRIM(value))). Override findOneByName to canonicalize, covering both resolveId and resolve -> findOneByIdOrName.
|
@coderabbitai pause |
✅ Action performedReviews paused. |
Remove the 'as any' / VueWrapper<any> escape hatches added with the plan-038 tests: - validator-groups: every literal is already a valid Partial<T> for the validator's run() input, so the casts were unnecessary. - checker: suite.container is public readonly and resolve<T> is typed; UserEntity implements User so identity.data needs no cast. Annotate the actor const as ActorContext so identity.type narrows to the 'user' literal (the inline call sites get this contextually). - login-form: type the helper's wrapper as ReturnType<typeof mountLoginForm>['wrapper'] instead of VueWrapper<any>.
Implements all six follow-up items deferred from #3175 (plan 038).
1. Fail-closed realm-key predicates (repo-wide)
New
IRealmRepository.resolveId(key)— UUID pass-through (binding an unknown UUID matches zero rows), canonicalizing name lookup,null⇒ caller fails closed. Swept across all 12 resolve-then-filter blocks in the 8 repository adapters, the permission/policy checker services, and the realm-resolver middleware. Previously 9 of those blocks silently dropped the realm filter for unknown realm keys, soGET /realms/<unknown-uuid>/users/<name>returned a cross-realm name match; it now 404s (pinned by tests).2. Unified realm-hint semantics across token grants
authorization_codeandrefresh_tokennow share the password grant's realm-hint semantic via a commonreadRealmHinthelper:realm_id ?? realm_name, canonicalized at the ingress, resolved once with master fallback, scoped onto client-by-name resolution. This makes the refresh leg deterministic — a password login via a name-identified client refreshes against the same realm's client instead of an unscoped lookup matching an arbitrary same-named client (every realm has a built-inwebclient, so collisions were guaranteed). The refresh grant resolves lazily; a bare refresh does no realm lookup.client_credentials/robot_credentialsand the/authorizecode-request verifier keep rawrealm_idsemantics (documented non-goal).3. client-web-kit test infrastructure
vitest + @vue/test-utils + happy-dom stood up in
packages/client-web-kit(first component tests in the monorepo). Regression suites pin the interactive-login realm plumbing that shipped the same one-line bug class twice in #3175: picker-selected realm transmitted;codeRequest.realm_idtransmitted including a late-arriving prop; empty realm omitted from the grant; plus a DOM-free spec for thestore.login()gate.4. Realm lookup caching on
/tokenRealmRepositoryAdapter.findOneByIdis query-cached (60s,CachePrefix.REALMid key — byte-identical to the existing realm subscriber invalidation key). Name-key caching stays deferred (rename invalidation prerequisite). The new invalidation tests surfaced a real pre-existing bug:EntitySubscriber.afterRemovereadevent.entity, whose primary key TypeORM strips on remove — so id-keyed cache invalidation (and DELETED event payloads) were broken for all subscribers. Fixed by preferringevent.databaseEntity.5. UUID identifiers skip the realm predicate — decided: intended
Documented (architecture.md + resolver comment) and pinned by test: UUIDs are globally unique, the realm hint constrains NAME resolution only, and the issued token carries the identity's true realm. Enforcing the predicate would break realm-less id-identified logins because the master fallback erases hint explicitness.
6. File-provisioning validation was a no-op
Nested provisioning validators ran group-less, executing zero core-kit field validators. New
ValidatorGroup.PROVISIONING: identifier fields mounted[CREATE, PROVISIONING],built_inonly under PROVISIONING (API groups keep stripping it), user email optional under PROVISIONING (synchronizer backfills). Nested runs pass the group explicitly, assign validated output back, and prefix array indices onto issue paths. Top-levelpolicies— documented but silently dropped from the validated output until now — are validated via the newPolicyProvisioningValidatorand provisioned (exercised end-to-end by the integration suite).BaseProvisioningSynchronizer.canonicalizeNamestays as defense in depth for the non-validating default/programmatic sources.Verification
npm run testgreen across all workspaces (server-core: 97 files / 992 tests, incl. new HTTP, service-level, and pure validator suites; client-web-kit: 7 new tests; core-kit: 6 new group tests)cn=fooaccount on the shared OpenLDAP container)Known follow-up (out of scope)
The kit's silent-refresh path sends a bare
refresh_tokenwithoutclient_id, so sessions with client-bound tokens already die at the RFC 6749 §6 binding check (pre-existing since #3020). A kit-side fix (sendclient_id+ realm on refresh) can now build on this PR's scoped name lookup and test infrastructure.BREAKING CHANGE: a name-identified client on the authorization_code or refresh_token grant without a realm hint now always resolves in the master realm (pass
realm_id/realm_nameor the client UUID for other realms). Invalid file-provisioning entities now abort startup instead of being silently accepted, and attribute keys outside the entity schema are stripped.Summary by CodeRabbit
New Features
built_in, improved realm-scope settings, and richer policy/permission relations in provisioning files.Bug Fixes