Repository navigation
feat: provisioning module - #2836
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 📝 WalkthroughWalkthroughThe pull request replaces the static database seeder mechanism with a comprehensive provisioning system. This system supports loading entity definitions from files or default sources, validates them through a hierarchy of validators, and synchronizes them with the database using a graph-based synchronizer pattern. Configuration now manages client system credentials instead of admin names. Changes
Sequence Diagram(s)sequenceDiagram
participant App as Application
participant PM as ProvisionerModule
participant DPS as DefaultProvisioningSource
participant FPS as FileProvisioningSource
participant CPS as CompositeProvisioningSource
participant GS as GraphProvisioningSynchronizer
participant RS as RealmSynchronizer
participant DB as Database
App->>PM: start(container)
PM->>DPS: load()
DPS-->>PM: RootProvisioningEntity
PM->>FPS: load()
FPS-->>PM: RootProvisioningEntity
PM->>CPS: new(sources)
PM->>CPS: load()
CPS->>DPS: load()
CPS->>FPS: load()
CPS-->>PM: merged RootProvisioningEntity
PM->>GS: new(context)
PM->>GS: synchronize(data)
GS->>RS: synchronizeMany(realms)
RS->>DB: findOne/save Realm
RS->>DB: synchronizeMany(users/clients/roles)
DB-->>RS: synchronized
RS-->>GS: completed
GS-->>PM: RootProvisioningEntity
PM-->>App: started
sequenceDiagram
participant Source as ProvisioningSource
participant Validator as RootProvisioningValidator
participant Sync as GraphProvisioningSynchronizer
participant RoleSync as RoleSynchronizer
participant RolePerm as RolePermission
participant DB as Database
Source->>Validator: validate(data)
Validator->>Validator: validate strategies, realms, roles, permissions
Validator-->>Source: validated data
Source->>Sync: synchronize(RootProvisioningEntity)
Sync->>RoleSync: synchronizeMany(roles[])
RoleSync->>RoleSync: normalize strategy (MERGE/REPLACE/CREATE_ONLY)
RoleSync->>DB: find existing Role by name & realm_id
alt MERGE
RoleSync->>RoleSync: merge attributes
else REPLACE
RoleSync->>DB: delete existing RolePermission
end
RoleSync->>DB: resolve globalPermissions (wildcard or explicit)
RoleSync->>RolePerm: create/link RolePermission entries
RoleSync->>DB: save all changes
RoleSync-->>Sync: RoleProvisioningEntity[]
Sync-->>Source: RootProvisioningEntity (synchronized)
Estimated Code Review Effort🎯 4 (Complex) | ⏱️ ~75 minutes Poem
🚥 Pre-merge checks | ✅ 5 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 Fix all issues with AI agents
In `@packages/server-core/src/adapters/database/seeder/module.ts`:
- Around line 54-57: The default for clientSystemEnabled is currently true in
the seeder (clientSystemEnabled: options.clientSystemEnabled ?? true) which will
create a system client by default; either change this default to false (replace
the fallback true with false in module.ts) if the system client should not be
created automatically, or if the system client should always exist, update the
JSDoc for the corresponding type in types.ts to document "default: true" so the
behavior is explicitly described; locate the symbols clientSystemEnabled,
clientSystemName, and clientSystemSecretHashed to ensure related defaults remain
consistent when you make the change.
- Around line 237-244: The seeder is using the wrong entity: replace the
repository lookup that uses RobotRoleEntity with ClientRoleEntity and ensure
ClientRoleEntity is imported; specifically, update the getRepository call
currently referencing RobotRoleEntity (used to create/save clientRole via
clientRoleRepository, clientRoleData, clientRole) to use ClientRoleEntity so the
client_roles table is targeted and add the ClientRoleEntity import at the top of
the file.
In `@packages/server-core/src/adapters/database/seeder/types.ts`:
- Around line 34-37: The JSDoc for clientSystemEnabled says "default: false" but
the constructor in module.ts uses options.clientSystemEnabled ?? true, so they
disagree; update one to match the intended default—either change the constructor
default to false (replace the nullish-coalescing default to false in the
constructor that sets clientSystemEnabled) or change the JSDoc to "default:
true" to reflect the current behavior; locate references to clientSystemEnabled
and the constructor in module.ts to ensure both the comment and runtime default
are consistent.
In `@packages/server-core/src/core/entities/schema/importer/file/module.ts`:
- Around line 26-48: The import() method currently reads the container config
into the local variable config but returns a hardcoded EntitySchema with empty
arrays; replace that by extracting the entities from config (e.g.,
config.clients, config.realms, config.users, config.roles, config.permissions),
normalizing them to arrays, validating each item with the appropriate validators
(e.g., UserValidator, RoleValidator, PermissionValidator or similar helpers
present in this module), and populating the returned EntitySchema with the
validated entries; ensure you throw or log meaningful errors for invalid entries
and preserve the existing Container usage and this.options.cwd flow.
🧹 Nitpick comments (3)
packages/server-core/src/core/entities/schema/types.ts (1)
12-19: Consider extendingEntitySchemato model entity relationships.The TODO on Line 12 is valid — a flat structure doesn't capture relationships like which users/clients belong to which realm. For synchronization, ordering and dependency resolution will be important (e.g., realms must exist before realm-scoped users). Worth tracking as a follow-up.
Would you like me to open an issue to track modeling nested entity relationships in
EntitySchema?packages/server-core/src/core/entities/schema/importer/file/module.ts (2)
17-18:userValidatoris instantiated but never used.The
UserValidatoris imported, stored as a field, but not referenced anywhere in theimport()method. If validation is planned for a follow-up, consider removing the dead code until it's needed, or wire it into the import logic now.
50-52:readPropertyAsArrayis defined but never called.This helper is exactly what's needed to populate the
EntitySchemafrom the loaded config (see comment onimport()). Currently dead code.
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Fix all issues with AI agents
In `@packages/server-core/src/adapters/database/seeder/module.ts`:
- Around line 218-225: The existing-client branch in the seeder doesn't set
client.built_in and client.is_confidential before saving, causing inconsistent
state; modify the else branch (the block that currently checks
this.options.clientSystemSecretReset and sets client.secret and client.active
then calls clientRepository.save(client)) to also assign client.built_in = true
and client.is_confidential = true (or the appropriate value used in the
new-client path) unconditionally prior to calling clientRepository.save,
ensuring parity with the new-client creation path and preserving auth behavior.
- Around line 207-217: The seeded client created in the seeder (via
clientRepository.create) is missing the flags required for credential
verification and consistency with other seeded entities; update the object
passed to clientRepository.create (the client created for
this.options.clientSystemName) to include is_confidential: true and built_in:
true before assigning client.secret (clientCredentialsService.protect) and
saving (clientRepository.save) so ClientCredentialsService.verify() will succeed
and the client is marked built-in.
🧹 Nitpick comments (1)
packages/server-core/src/adapters/database/seeder/module.ts (1)
206-225: System client secret is never returned to the caller.For the robot,
response.robotis set with the plaintext secret so the caller can display/store it on first creation. The client secret is generated (line 206) but never surfaced viaresponse. If the secret is auto-generated (createNanoID(64)), the operator has no way to retrieve it.Consider adding
response.client = clientwith the plaintext secret (before it's hashed) on first creation and on reset, mirroring the robot pattern.
There was a problem hiding this comment.
Actionable comments posted: 19
🤖 Fix all issues with AI agents
In `@packages/server-core/src/app/modules/config/types.ts`:
- Around line 183-197: Update the incorrect JSDoc comments for the client admin
fields: replace the "robot" wording with "client" and clarify admin wording for
clientAdminEnabled, clientAdminName, and clientAdminSecret—e.g., change "Enable
a global robot account" to "Enable a global client/admin account", "The name of
the default robot" to "The name of the default admin client", and "The secret of
the default admin user" to "The secret of the default admin client" so the
comments accurately describe clientAdminEnabled, clientAdminName, and
clientAdminSecret.
In `@packages/server-core/src/app/modules/provisioning/module.ts`:
- Around line 136-138: The TODO comment "pass loaded data to synchronizer" is
stale because data is already passed to rootSynchronizer.synchronize(data);
remove that TODO or replace it with a clarified note describing any remaining
work (e.g., if additional context or transformed data should be passed, state
exactly what and where). Update the comment near
rootSynchronizer.synchronize(data) or delete it so the code and comments are
consistent, referencing the rootSynchronizer.synchronize(data) call to locate
the spot.
- Around line 70-71: CompositeProvisioningSource.load() currently only merges
roles, realms, and permissions and thus drops ProvisioningData.scopes (and any
future top-level fields); update CompositeProvisioningSource.load() to also
merge scopes the same way those arrays are merged (e.g., if sourceData.scopes is
present, push/concat into the composite output and dedupe if needed) or, better,
implement a generic merge of all top-level ProvisioningData fields from each
source (iterate Object.keys(sourceData) and for array fields concat/merge, for
objects deep-merge, otherwise assign) so DefaultProvisioningSource-produced
scopes are preserved and rootSynchronizer.synchronize(data) receives scopes for
scopeSynchronizer.synchronizeMany() to run.
In
`@packages/server-core/src/app/modules/provisioning/sources/composite/module.ts`:
- Around line 17-48: The composite Provisioning source's load() method fails to
include or merge the scopes field into the returned ProvisioningData; update the
load() function in module.ts to initialize scopes on the output (like
roles/realms/permissions) and aggregate scopes from each child by reading
sourceData.scopes and pushing/merging them into output.scopes (use the same
pattern as for roles/realms/permissions, consider preserving uniqueness if
required); locate the load() method and the references to
output.roles/output.realms/output.permissions and add analogous handling for
output.scopes and sourceData.scopes.
In `@packages/server-core/src/app/modules/provisioning/sources/file/module.ts`:
- Around line 26-43: The load() implementation currently uses Container to pull
a raw 'schema' object and passes it to readPropertyAsArray without validation
(via isObject only), exposing provisioning flows to untrusted YAML/JSON; update
load() in this file to run the container output through the validator before
using it: validate the top-level shape of ProvisioningData (realms, roles,
permissions must be arrays/objects) and reject with a clear error if validation
fails, or integrate the existing validator utility/class used elsewhere to
transform/validate the schema object prior to calling readPropertyAsArray;
ensure you reference the same validator that validates repository entities so
malformed file input cannot reach repository operations.
- Around line 39-43: The returned ProvisioningData object in module.ts omits the
optional scopes field, so file-based scope provisioning never gets synchronized;
update the return object in the function that currently returns
realms/roles/permissions to also include scopes:
this.readPropertyAsArray(config, 'scopes') (using the existing
readPropertyAsArray helper), ensuring the shape matches ProvisioningData and
allowing GraphProvisioningSynchronizer to pick up scopes.
In
`@packages/server-core/src/app/modules/provisioning/synchronizer/client/module.ts`:
- Around line 152-164: Role assignments created in the loop using
clientRoleRepository.create and then save can produce duplicates on re-sync;
update the logic in the block that iterates over roles to deduplicate or upsert
instead of blindly inserting: for each role (roles[i]) check if a client role
already exists for the tuple (client_id: data.id, client_realm_id:
data.realm_id, role_id: role.id, role_realm_id: role.realm_id) via
clientRoleRepository.findOne (or use a repository upsert/insert...onConflict
mechanism), only create/save when not present, or use an upsert/save with
conflict handling to avoid duplicate client role rows.
- Around line 96-108: Rename the local variable rolePermission to
clientPermission in the loop creating ClientPermission entities (the code that
calls this.clientPermissionRepository.create and
this.clientPermissionRepository.save) to match the entity/repository names, and
make the operation idempotent by checking for an existing ClientPermission
(e.g., via this.clientPermissionRepository.findOneBy with
client_id/client_realm_id/permission_id/permission_realm_id) before
creating/saving or use an upsert strategy so repeated synchronizations do not
insert duplicates.
In
`@packages/server-core/src/app/modules/provisioning/synchronizer/permission/module.ts`:
- Around line 23-30: The synchronize method currently calls
repository.save(input.data) which can insert duplicates when entities lack an id
or unique-key match (e.g., DefaultProvisioningSource only supplies name and
client_id/realm_id are NULL); update synchronize in PermissionProvisioningModule
to first locate an existing permission by the composite key (query
repository.findOne/findOneBy using name plus client_id and realm_id from
input.data, treating missing client_id/realm_id appropriately) and if found set
input.data.id = existing.id before calling save, or replace the save with
repository.upsert()/createQueryBuilder().insert().onConflict(...) to perform an
upsert using the (name, client_id, realm_id) conflict target and an explicit
update strategy so repeated provisioning updates the existing row instead of
inserting duplicates.
In
`@packages/server-core/src/app/modules/provisioning/synchronizer/realm/module.ts`:
- Around line 45-46: The synchronize method is calling
repository.save(input.data) where input.data is a Partial<Realm>, which causes
INSERTs on re-provisioning and triggers a unique constraint error on name;
change the logic in synchronize to make provisioning idempotent by first
checking for an existing Realm by name (e.g., repository.findOne/findOneBy using
the Realm name from RealmProvisioningContainer) and if found merge/update that
entity (preserving its id) before saving, or alternatively use
repository.upsert() with the name as the conflict target and proper conflict
resolution so repeated runs update instead of inserting; update the code paths
in the synchronize function and any helpers to use the chosen approach.
In
`@packages/server-core/src/app/modules/provisioning/synchronizer/robot/module.ts`:
- Around line 144-156: Rename the erroneously copy-pasted variable clientRole to
robotRole in the loop that creates RobotRole records so the identifier matches
the entity being created; specifically update the const declaration and its
subsequent await this.robotRoleRepository.save(...) call inside the loop in
module.ts (the block that calls this.robotRoleRepository.create({...}) for each
role) and ensure there are no remaining references to clientRole elsewhere in
that scope.
- Around line 88-100: The loop in the synchronizer creates a variable named
rolePermission but it represents a RobotPermission and can produce duplicates on
repeated runs; rename the variable to robotPermission and make creation
idempotent by checking robotPermissionRepository for an existing record (match
on robot_id, robot_realm_id, permission_id, permission_realm_id) before calling
create/save (or perform an upsert if supported). Update the block that iterates
over permissions to use robotPermissionRepository.findOne/findOneBy to avoid
duplicate RobotPermission records and only create/save when no existing record
is found.
In
`@packages/server-core/src/app/modules/provisioning/synchronizer/role/module.ts`:
- Around line 54-64: The loop creating role-permission rows is non-idempotent
and causes N+1 saves: update the logic in the block that uses
rolePermissionRepository.create/save (the loop over permissions, using data.id
and data.realm_id) to perform a batch upsert instead of individual saves; either
query existing assignments by role_id and permission_id to skip duplicates or
use the repository’s upsert/insert...onConflict method to merge on
(permission_id, role_id), build an array of rolePermission entities (including
permission_realm_id) and call a single bulk save/upsert operation to ensure
idempotency and avoid N+1 database calls.
In
`@packages/server-core/src/app/modules/provisioning/synchronizer/scope/module.ts`:
- Around line 23-30: The synchronize method currently calls
repository.save(input.data) which will INSERT when there is no id and thus
trigger unique constraint errors on ScopeEntity (Unique(['name','realm_id'])) on
repeated runs; change synchronize (ScopeProvisioningContainer) to first query
the repository for an existing scope by name and realm_id (use the same lookup
key used in role/user synchronizers), if found merge its id and any existing
fields into input.data (or update fields explicitly) before calling
repository.save so save performs an UPDATE instead of an INSERT, and ensure any
association resolution logic follows the pattern in the role/user synchronizers.
In
`@packages/server-core/src/app/modules/provisioning/synchronizer/user/module.ts`:
- Around line 204-216: The code creates a variable named clientRole for a
UserRole and blindly saves it, risking confusing naming and duplicate records on
re-sync; rename the variable to userRole and make the creation idempotent by
checking for an existing record via this.userRoleRepository (e.g., findOne by
user_id + user_realm_id + role_id + role_realm_id) before creating/saving, or
perform an upsert/merge through the repository so duplicate UserRole entries are
not inserted during re-sync.
- Around line 118-130: The variable created for the UserPermission entity is
misnamed `rolePermission`; rename it to `userPermission` where it's assigned and
where it's passed to `this.userPermissionRepository.save(...)` in the loop that
iterates `permissions` (the block using
`this.userPermissionRepository.create({...})` and
`this.userPermissionRepository.save(...)`) so the variable name correctly
reflects the entity being created and matches naming across other synchronizers.
In `@packages/server-core/src/app/modules/provisioning/types.ts`:
- Around line 57-65: Update the JSDoc in the UserProvisioningContainer type:
change the two comments currently saying "Assign client to realm permissions."
and "Assign client to global permissions." to read "Assign user to realm
permissions." and "Assign user to global permissions." respectively so the
documentation matches the UserProvisioningContainer semantics (refer to the
realmPermissions and globalPermissions fields in UserProvisioningContainer).
- Around line 27-49: The JSDoc for RobotProvisioningContainer incorrectly
references "client" and "user"; update the comments for the properties on
RobotProvisioningContainer (realmPermissions, globalPermissions, realmRoles,
globalRoles) to refer to "robot" instead of "client" or "user" so the docs
accurately describe robot provisioning; locate the RobotProvisioningContainer
type and replace the four comment lines accordingly.
- Line 108: Fix the typo in the JSDoc/TSDoc comment that reads "Assign client to
global permisisons." — change "permisisons" to "permissions" so the comment
reads "Assign client to global permissions." Update the comment block in
packages/server-core/src/app/modules/provisioning/types.ts where that phrase
appears (the comment above the relevant type/field declaration) to ensure
correct spelling.
🧹 Nitpick comments (7)
packages/server-core/src/app/factory.ts (1)
25-25: ImportProvisionerModulefrom the barrel instead of the direct path.All other modules are imported from
'./modules/index.ts'. SinceProvisionerModuleis already re-exported through the provisioning barrel (viapackages/server-core/src/app/modules/provisioning/index.ts), it should be imported consistently with the other modules.♻️ Proposed fix
import { AuthenticationModule, CacheModule, ComponentsModule, ConfigModule, DatabaseModule, HTTPModule, IdentityModule, LdapModule, LoggerModule, MailModule, OAuth2Module, + ProvisionerModule, RuntimeModule, SwaggerModule, VaultModule, } from './modules/index.ts'; -import { ProvisionerModule } from './modules/provisioning/module.ts';packages/server-core/src/app/modules/provisioning/module.ts (1)
59-139: Consider caching repeatedcontainer.resolve()calls.Several repositories (e.g.,
PermissionEntity,RoleEntity,ClientEntity) are resolved multiple times. While functionally fine if the container returns singletons, extracting them into local variables would reduce noise and make the wiring easier to read.Example
async start(container: IDIContainer): Promise<void> { const config = container.resolve<Config>(ConfigInjectionKey); + + const permissionRepo = container.resolve<Repository<Permission>>(PermissionEntity); + const roleRepo = container.resolve<Repository<Role>>(RoleEntity); + const clientRepo = container.resolve<Repository<Client>>(ClientEntity); + const realmRepo = container.resolve<Repository<Realm>>(RealmEntity); + const scopeRepo = container.resolve<Repository<Scope>>(ScopeEntity); + const userRepo = container.resolve<Repository<User>>(UserEntity); + const robotRepo = container.resolve<Repository<Robot>>(RobotEntity); + const rolePermissionRepo = container.resolve<Repository<RolePermission>>(RolePermissionEntity); + const clientRoleRepo = container.resolve<Repository<ClientRole>>(ClientRoleEntity); + const clientPermissionRepo = container.resolve<Repository<ClientPermission>>(ClientPermissionEntity); + const userRoleRepo = container.resolve<Repository<UserRole>>(UserRoleEntity); + const userPermissionRepo = container.resolve<Repository<UserPermission>>(UserPermissionEntity); + const robotRoleRepo = container.resolve<Repository<RobotRole>>(RobotRoleEntity); + const robotPermissionRepo = container.resolve<Repository<RobotPermission>>(RobotPermissionEntity); // ... then reference these locals in synchronizer constructorspackages/server-core/src/app/modules/provisioning/synchronizer/realm/module.ts (1)
48-98: Input containers are mutated in-place within.map()callbacks.The
child.data.realm_id = data.idassignments mutate the original input objects. While this is likely harmless in a single-pass provisioning flow, it could cause subtle bugs if input containers are ever reused or inspected after synchronization.Consider returning new objects instead:
♻️ Example for one block (apply same pattern to others)
const clients = input.meta.clients.map( (child) => { - child.data.realm_id = data.id; - child.data.realm = data; - return child; + return { + ...child, + data: { ...child.data, realm_id: data.id, realm: data }, + }; }, );packages/server-core/src/app/modules/provisioning/synchronizer/client/module.ts (1)
168-186:mapmutates input objects in place — side effect on caller's data.
child.data.client_id = data.idmutates the original objects. If the caller retains references, its data is silently altered. Either spread into new objects or document the mutation contract.Proposed fix
if (input.meta && input.meta.permissions) { const children = input.meta.permissions.map((child) => { - child.data.client_id = data.id; - child.data.client = data; - return child; + return { + ...child, + data: { + ...child.data, + client_id: data.id, + client: data, + }, + }; }); await this.permissionSynchronizer.synchronizeMany(children); } if (input.meta && input.meta.roles) { const children = input.meta.roles.map((child) => { - child.data.client_id = data.id; - child.data.client = data; - return child; + return { + ...child, + data: { + ...child.data, + client_id: data.id, + client: data, + }, + }; }); await this.roleSynchronizer.synchronizeMany(children); }packages/server-core/src/app/modules/provisioning/sources/default/module.ts (1)
36-36: RedundantmasterRealm.meta = masterRealm.meta || {}reassignments.
metais initialized as{}on lines 29–31. The guards on lines 36, 53, and 70 are unnecessary.Also applies to: 53-53, 70-70
packages/server-core/src/app/modules/provisioning/synchronizer/root/module.ts (1)
35-53: Synchronization results are discarded —inputis returned unmodified.The
synchronizeManycalls are awaited but their return values (which contain persisted data with generated IDs) are not captured back intoinput. This means the returnedProvisioningDatastill contains the original partial entities without IDs. If any caller relies on the returned data having persisted IDs, this would be a problem. If the return value is not consumed downstream, this is fine.packages/server-core/src/app/modules/provisioning/synchronizer/robot/module.ts (1)
30-30: Remove unusedclientRepositoryfield from robot synchronizer.The
clientRepositoryfield is declared and assigned from context but never referenced in thesynchronizemethod. Remove it from both the class and theRobotProvisioningSynchronizerContexttype to keep the API surface clean.
There was a problem hiding this comment.
Actionable comments posted: 17
🤖 Fix all issues with AI agents
In `@packages/core-kit/src/domains/realm/validator.ts`:
- Around line 40-50: The validator mounts `display_name` twice; in the second
mount inside the validator (the call to this.mount that currently uses
'display_name' with createValidator(zod.string().min(5).max(4096).nullable())),
change the field key to 'description' so the validator mounts 'display_name'
(min 3/max 256) and 'description' (min 5/max 4096) correctly; update the second
this.mount invocation to use 'description' while keeping the existing
createValidator(...) call and nullable constraint.
- Line 18: RealmValidator.initialize currently omits the superclass
initialization; update the RealmValidator class so its initialize() method calls
super.initialize() at the start (matching other validators like UserValidator,
ScopeValidator, RoleValidator, etc.), ensuring any base setup runs before
RealmValidator-specific initialization in initialize().
In `@packages/core-kit/src/domains/scope/index.ts`:
- Line 11: The export in index.ts incorrectly references './validaitor.ts';
update the export statement in the scope domain (the line exporting from
'./validaitor.ts') to import from the correctly spelled file './validator.ts' so
it matches the other domains and resolves the misspelling.
In `@packages/core-kit/src/domains/scope/validaitor.ts`:
- Around line 1-68: The filename contains a typo: "validaitor.ts" should be
"validator.ts"; rename the file accordingly and update any imports/exports that
reference it (notably the scope domain's index that imports the class) so they
point to the new "validator.ts". Ensure the exported class ScopeValidator and
its mount usage remain unchanged, and update the import path in the scope index
(where ScopeValidator is imported) to the corrected filename.
In
`@packages/server-core/src/adapters/http/controllers/entities/realm/handlers/write.ts`:
- Line 12: RealmValidator mounts display_name twice and never mounts
description; change the second Container.mount call that currently uses the key
"display_name" to use "description" instead, and apply the intended constraints
(min(5).max(4096).nullable()) to description so display_name keeps its original
min(3).max(256).nullable() constraints; update the RealmValidator definition to
ensure no duplicate mounts for display_name and that description is validated
appropriately (adjust any related tests if present).
In `@packages/server-core/src/app/modules/provisioning/check.ts`:
- Around line 15-18: The type guard currently rejects valid
ProvisioningContainer<DATA, META> values because it requires input.relations to
be a non-null object; change the relations check so it allows relations to be
undefined or an object (e.g. replace isObject(input.relations) with
(input.relations === undefined || isObject(input.relations))). Keep the existing
isObject checks for input and input.data and ensure the function signature (the
type-guard returning input is ProvisioningContainer<DATA, META>) remains
unchanged.
In `@packages/server-core/src/app/modules/provisioning/entities/index.ts`:
- Around line 8-14: The entities barrel file is missing a re-export for the
realm submodule, causing consumers that import RealmProvisioningContainer and
RealmProvisioningValidator from the barrel to break; add a line exporting the
realm submodule (matching the style of other exports) so
RealmProvisioningContainer and RealmProvisioningValidator become available via
the barrel (update the same file that currently exports client, permission,
robot, role, root, scope, user).
In
`@packages/server-core/src/app/modules/provisioning/entities/realm/relations-validator.ts`:
- Around line 26-74: The .check callbacks use validator.run(...) but discard its
return value, risking lost transformations; update each mounted array validator
(clients, roles, permissions, robots, users) to capture and assign the validated
result back into the array (e.g., set ctx.value[i] = await
clientValidator.run(ctx.value[i]) and likewise for roleValidator.run,
permissionValidator.run, robotValidator.run, userValidator.run) so any
transformation/enrichment from those validators is preserved.
In `@packages/server-core/src/app/modules/provisioning/entities/role/types.ts`:
- Around line 16-19: Fix the JSDoc typo in the RoleProvisioningRelations type:
change the comment above the realmPermissions property from "Assign robot to
realm permissions." to "Assign role to realm permissions." so the documentation
matches the RoleProvisioningRelations type and the realmPermissions field.
In
`@packages/server-core/src/app/modules/provisioning/entities/role/validator.ts`:
- Around line 13-17: RoleProvisioningValidator currently mounts only the 'data'
validator (RoleValidator) so relation fields aren't checked; import the existing
RoleProvisioningRelationsValidator from relations-validator.ts and in
RoleProvisioningValidator.initialize() create an instance (e.g. const
relationsValidator = new RoleProvisioningRelationsValidator();) and call
this.mount('relations', relationsValidator); to ensure globalPermissions and
realmPermissions are validated alongside data.
In
`@packages/server-core/src/app/modules/provisioning/synchronizer/realm/module.ts`:
- Around line 48-50: The call to repository.findOneBy({ name: input.data.name })
can pass undefined because input.data is Partial<Realm>; update module.ts to
guard for a missing name before querying (e.g., in the method containing this
code check input.data && input.data.name), and if name is absent either
normalize/require it earlier in the provisioning container input type or
throw/return a validation error; ensure the repository.findOneBy call only runs
with a defined string name to avoid unpredictable TypeORM behavior (refer to
repository.findOneBy and the local variable data in this module).
- Around line 47-53: synchronize currently ignores updates when
repository.findOneBy returns an existing entity; merge input.data into the found
entity and persist the updated entity instead of skipping save. Locate the
synchronize method and where it sets data from repository.findOneBy; when data
exists, copy the fields from input.data onto data (preserving identifiers) and
call this.repository.save(data) so changes like display_name/description are
persisted before continuing to relation processing.
In
`@packages/server-core/src/app/modules/provisioning/synchronizer/robot/module.ts`:
- Around line 41-48: The synchronize method currently returns the existing DB
entity untouched when a robot is found; instead merge the incoming input.data
onto the found entity before saving so updated fields are persisted. In the
synchronize function, after robotRepository.findOneBy returns a record (variable
data), copy/assign the properties from input.data into data (preserving
identifiers like id/realm_id as needed), then call robotRepository.save(data) to
update the record; ensure RobotProvisioningContainer still returns the
saved/merged entity. Use the existing symbols synchronize,
RobotProvisioningContainer, robotRepository.findOneBy, and robotRepository.save
to locate and implement this merge-and-save behavior.
In
`@packages/server-core/src/app/modules/provisioning/synchronizer/role/module.ts`:
- Around line 32-40: The synchronize method in module.ts currently never updates
existing role records found by repository.findOneBy; when data exists the code
jumps straight to relation handling and ignores changes in input.data (e.g.,
display_name, description). Modify synchronize (RoleProvisioningContainer
handling) to detect when data is found, copy/assign the changed fields from
input.data onto the existing data object, then call repository.save(data) to
persist updates before proceeding to relation handling; alternatively, if
create-only behavior is intended, add a concise comment above the if (!data)
block stating that existing records are intentionally not updated. Ensure you
reference the existing repository.findOneBy/save calls and input.data properties
when making the change.
In
`@packages/server-core/src/app/modules/provisioning/synchronizer/root/module.ts`:
- Around line 38-56: The synchronize method returns the original input but
discards the enriched results from permissionSynchronizer.synchronizeMany,
roleSynchronizer.synchronizeMany, scopeSynchronizer.synchronizeMany, and
realmSynchronizer.synchronizeMany; update synchronize to await and assign each
result back into the corresponding input property (e.g., input.permissions =
await this.permissionSynchronizer.synchronizeMany(input.permissions)) so the
returned RootProvisioningData contains the synchronized/enriched entities
(IDs/timestamps) instead of the original unmodified objects.
In
`@packages/server-core/src/app/modules/provisioning/synchronizer/user/module.ts`:
- Around line 50-56: The current block unconditionally mutates input.data.email
using buildUserFakeEmail(input.data.name) which overwrites any provided email
and mutates the caller object; change it so you only generate a fake email when
input.data.email is falsy and avoid mutating the original input by creating a
local object to save (e.g., const userData = { ...input.data, email:
input.data.email || buildUserFakeEmail(input.data.name) }) and then call
this.userRepository.save(userData) (references: input.data, buildUserFakeEmail,
this.userRepository.save).
In `@packages/server-core/test/data/sources/file.mts`:
- Around line 11-27: Replace any role objects that use the unsupported key
"meta" with "relations" so RoleProvisioningSynchronizer can read
globalPermissions; specifically change entries where you have meta: {
globalPermissions: [...] } to relations: { globalPermissions: [...] } (including
the realm's nested roles). Ensure the shape matches RoleProvisioningRelations so
RoleProvisioningSynchronizer and any checks of input.relations.globalPermissions
will pick up the permissions.
🧹 Nitpick comments (20)
packages/server-core/src/app/modules/provisioning/check.ts (1)
12-15: Generic parameterMETAdoesn't match the correspondingRinProvisioningContainer<A, R>.The second generic is called
METAhere but maps toR(relations) in theProvisioningContainertype. Consider renaming toRELATIONS(or similar) for consistency and clarity.packages/server-core/src/adapters/http/controllers/entities/scope/handlers/write.ts (1)
34-34: TypegroupasValidatorGroupfor compile-time safety.The variable is assigned only
ValidatorGroup.UPDATEorValidatorGroup.CREATEand is already imported. Using the enum type instead ofstringensures only valid values are assigned.Suggested change
- let group: string; + let group: ValidatorGroup;packages/server-core/src/app/modules/provisioning/synchronizer/robot/module.ts (1)
92-176: Sequential DB round-trips in loops could be batched.Each iteration performs a
findOneBy+ conditionalsave, resulting in 2×N queries per relation type. Since this is provisioning code (infrequent execution), it's not urgent, but if the permission/role lists grow, consider fetching all existing links in one query upfront and then bulk-inserting the missing ones.packages/server-core/src/app/modules/provisioning/entities/permission/types.ts (1)
11-14: Consider using a dedicated relations type instead ofObjectLiteral.Other provisioning containers (e.g.,
RobotProvisioningContainer,UserProvisioningContainer) define explicit relation types (RobotProvisioningRelations,UserProvisioningRelations) for type safety. Here,ObjectLiteral(Record<string | number, any>) loses that benefit. If permissions genuinely have no relation fields, a narrower type likeRecord<string, never>or simply omitting the second type parameter (ifProvisioningContainersupports a default) would be clearer.packages/server-core/src/app/modules/provisioning/entities/robot/types.ts (1)
10-32: Minor style inconsistency: missing trailing comma on Line 26.All other members in
RobotProvisioningRelationsuse trailing commas, butrealmRoleson Line 26 does not. Not a syntax error, but inconsistent.- realmRoles?: string[] + realmRoles?: string[],packages/core-kit/src/domains/permission/index.ts (1)
11-11: Minor: inconsistent file extension in re-export.The new export uses an explicit
.tsextension while existing exports on lines 8–10 omit extensions. This works if the toolchain supports both styles, but for consistency you may want to align them.packages/server-core/src/app/modules/provisioning/synchronizer/client/module.ts (2)
51-58: Synchronizer skips updates for existing clients.When a client already exists (found by name + realm_id), the method returns early without applying any updates from
input.data. A synchronizer that reconciles filesystem state with DB state should also update changed fields (e.g.,description,redirect_uri, etc.) on re-sync.Consider merging
input.datainto the existing entity:Proposed fix
if (!data) { data = await this.clientRepository.save(input.data); + } else { + data = await this.clientRepository.save( + this.clientRepository.merge(data, input.data), + ); }
190-208: Input mutation: child containers are modified in place.
input.relations.permissionsandinput.relations.roleschildren are mutated directly (settingclient_idandclientonchild.data). This is a side effect on the caller's data. If the caller re-uses the input object, the mutations persist. Using.map()with spread/copy would be safer, though this may be acceptable if inputs are single-use.packages/server-core/src/app/modules/provisioning/synchronizer/user/module.ts (1)
44-56: Synchronizer skips updates for existing users (same pattern as client synchronizer).When a user already exists, changed fields from the provisioning input are not applied. For a synchronizer meant to reconcile filesystem and DB state, consider merging updates as suggested in the client synchronizer review.
packages/core-kit/src/domains/robot/index.ts (1)
8-11: Inconsistent file extension in re-exports.Lines 8–10 use extensionless specifiers (
'./entity','./helpers','./error'), while Line 11 uses an explicit.tsextension ('./validator.ts'). Consider aligning the style for consistency.Suggested fix
-export * from './validator.ts'; +export * from './validator';packages/server-core/test/unit/modules/provisioning.spec.ts (1)
41-69: Missing resource cleanup after provisioning synchronization test.The second test starts several modules (ConfigModule, LoggerModule, CacheModule, TestDatabaseModule, ProvisionerModule) but never tears them down. If the test suite grows or runs in parallel, stale DB connections or cached state could leak across tests.
Consider adding an
afterEachorafterAllblock (or calling astop/destroymethod on the DI container and modules) to clean up resources.packages/server-core/src/app/modules/provisioning/entities/realm/relations-validator.ts (1)
18-75: Consider extracting a helper to reduce repetition across the five mount calls.All five mounts follow the identical pattern:
mount(key, { optional: true }, createValidator(zod.array(zod.any()).check(async (ctx) => { ... }))). A small helper likemountArrayValidator(key, validator)would reduce the boilerplate and make it easier to add new relation types.♻️ Example helper extraction
export class RealmProvisioningRelationsValidator extends Container<RealmProvisioningRelations> { protected initialize() { - const clientValidator = new ClientProvisioningValidator(); - const roleValidator = new RoleProvisioningValidator(); - const permissionValidator = new PermissionProvisioningValidator(); - const robotValidator = new RobotProvisioningValidator(); - const userValidator = new UserProvisioningValidator(); - - this.mount('clients', { optional: true }, createValidator( - zod - .array(zod.any()) - .check(async (ctx) => { - for (let i = 0; i < ctx.value.length; i++) { - await clientValidator.run(ctx.value[i]); - } - }), - )); - // ... repeated 4 more times + this.mountArrayRelation('clients', new ClientProvisioningValidator()); + this.mountArrayRelation('roles', new RoleProvisioningValidator()); + this.mountArrayRelation('permissions', new PermissionProvisioningValidator()); + this.mountArrayRelation('robots', new RobotProvisioningValidator()); + this.mountArrayRelation('users', new UserProvisioningValidator()); + } + + private mountArrayRelation(key: keyof RealmProvisioningRelations, itemValidator: Container<any>) { + this.mount(key, { optional: true }, createValidator( + zod.array(zod.any()).check(async (ctx) => { + for (let i = 0; i < ctx.value.length; i++) { + await itemValidator.run(ctx.value[i]); + } + }), + )); } }packages/server-core/src/app/modules/provisioning/module.ts (1)
66-77: Consider wrapping the provisioning pipeline in structured error handling.If
composite.load()orrootSynchronizer.synchronize(data)throws, the error propagates unhandled fromstart(). For a startup-critical module, consider catching and logging a meaningful error (or wrapping in a domain-specific error) so that bootstrap failures are clearly diagnosable rather than surfacing a raw repository or validation exception.packages/server-core/src/app/modules/provisioning/entities/scope/types.ts (1)
11-11: Consider using a narrower relations type instead ofObjectLiteral.If scopes currently have no provisioning relations, using
ObjectLiteral(Record<string | number, any>) is overly permissive and bypasses type-checking on therelationsfield. A stricter type likeRecord<string, never>or a dedicated empty interface would catch accidental misuse at compile time.packages/server-core/src/app/modules/provisioning/synchronizer/realm/module.ts (1)
55-105: Repetitive relation-mapping blocks could be extracted into a helper.All five relation blocks follow the same pattern: check if relation array exists, map to attach
realm_id/realm, and delegate to a child synchronizer. A small helper would reduce duplication.packages/server-core/src/app/modules/provisioning/entities/user/types.ts (1)
36-36: Missing trailing comma afterrealmRolesproperty.Line 36 is missing a trailing comma, unlike the other properties in this type. While TypeScript accepts this, it's inconsistent with the rest of the type definition.
- realmRoles?: string[] + realmRoles?: string[],packages/server-core/src/app/modules/provisioning/entities/realm/types.ts (1)
15-27: Missing trailing commas onrobotsandclientsproperties (lines 18, 20).Inconsistent with the other properties in the same type that use trailing commas.
- robots?: RobotProvisioningContainer[] + robots?: RobotProvisioningContainer[], - clients?: ClientProvisioningContainer[] + clients?: ClientProvisioningContainer[],packages/server-core/src/app/modules/provisioning/entities/root/validator.ts (1)
25-63: Validation errors from sub-validators may not surface as Zod issues.Each
.check()callback callsawait realmValidator.run(ctx.value[i])etc. Ifrun()throws, the error will propagate as an unhandled exception rather than as a structured Zod validation issue. If the intent is to collect all validation errors, consider wrapping eachrun()call and usingctx.issues.push(...)(Zod 4's refinement API) to report failures. If throwing is the desired behavior, this is fine as-is.packages/server-core/src/app/modules/provisioning/sources/composite/module.ts (1)
36-36:mergeshould beprotected— it's an internal implementation detail.The method is currently implicitly public, but it's only used internally by
load().packages/server-core/src/app/modules/provisioning/sources/default/module.ts (1)
38-38: RedundantmasterRealm.relationsnull-guard — already initialized on line 31.
masterRealm.relationsis assigned{}on line 31-33, so the|| {}checks on lines 38, 55, and 72 are unnecessary.Also applies to: 55-55, 72-72
|
@coderabbitai resume |
✅ Actions performedReviews resumed. |
There was a problem hiding this comment.
Actionable comments posted: 6
🤖 Fix all issues with AI agents
In
`@packages/server-core/src/app/modules/provisioning/entities/root/validator.ts`:
- Around line 31-69: The array element validators inside each this.mount(...,
createValidator(zod.array(...).check(async (ctx) => { ... }))) currently await
realmValidator.run / roleValidator.run / scopeValidator.run /
permissionValidator.run without catching errors; wrap each await call in a
try-catch inside the .check callback and on error call ctx.addIssue(...)
(including the caught error message and context/path) and return false so Zod
records the validation issue instead of letting the rejection bubble; update the
.check callbacks for the 'realms', 'roles', 'scopes', and 'permissions' mounts
accordingly.
- Line 10: The Zod import is using a default import which fails for Zod v4;
replace the default import in this validator module by switching "import zod
from 'zod'" to the namespace form (import * as zod from 'zod') so all usages
like zod.object(), zod.string(), etc. resolve correctly; apply the same change
to other validator files following the same pattern to ensure validators (e.g.,
any schema definitions or functions inside validator.ts that call zod.*) import
Zod as a namespace.
In `@packages/server-core/src/app/modules/provisioning/strategy/validator.ts`:
- Around line 37-42: The 'type' validator was mounted on mergeContainer instead
of altContainer; fix by calling altContainer.mount('type',
createValidator(zod.enum(['replace','createOnly']))) so the enum(['merge'])
validator on mergeContainer is not overwritten and altContainer receives its
validators; locate the mount call near the
Container<ProvisioningEntityReplaceStrategy>() creation and replace the target
container from mergeContainer to altContainer for that mount invocation.
In
`@packages/server-core/src/app/modules/provisioning/synchronizer/robot/module.ts`:
- Around line 62-64: The REPLACE branch uses
ProvisioningEntityStrategyType.REPLACE and calls
this.robotRepository.remove(attributes) then saves input.attributes, which will
cascade-delete unmanaged relations (tokens, sessions) if DB cascades are
configured; instead, either (A) delete only the managed sub-relations (robot
permissions and robot roles) via their specific repositories/services before
calling save, or (B) perform an in-place update (e.g., load existing robot,
update its permissions/roles and call save/update) so unrelated relations are
preserved; if full removal is intentional, add a clear comment/doc explaining
that this will permanently drop cascaded relations. Update the code around
robotRepository.remove, robotRepository.save, and attributes/input.attributes
accordingly.
In
`@packages/server-core/src/app/modules/provisioning/synchronizer/role/module.ts`:
- Around line 62-98: The synchronizer currently only processes
input.relations.globalPermissions; add symmetric handling for
input.relations.realmPermissions: check if input.relations.realmPermissions
exists, determine wildcard '*' or explicit names, query
this.permissionRepository with realm_id equal to attributes.realm_id and
client_id IsNull() (or with name In(...) when not wildcard), then iterate the
returned permissions and for each ensure a RolePermission exists via
this.rolePermissionRepository.findOneBy({ role_id: attributes.id, permission_id:
permission.id }) and create+save one (setting role_id, role_realm_id:
attributes.realm_id, permission_id, permission_realm_id: permission.realm_id) if
missing. Reuse the same helpers (IsNull, In) and the same repositories
(permissionRepository, rolePermissionRepository) and mirror the logic used for
globalPermissions.
In
`@packages/server-core/src/app/modules/provisioning/synchronizer/user/module.ts`:
- Around line 46-95: The synchronize method prematurely saves a new user after
userRepository.findOneBy, making the later else unreachable and corrupting
MERGE/REPLACE semantics; remove the early save when attributes is falsy and let
the strategy switch or final else perform creation. Concretely, in synchronize
stop calling this.userRepository.save(input.attributes) immediately after
findOneBy so attributes stays falsy when not found, then update the MERGE case
to handle a missing attributes by constructing a base object (ensuring email via
buildUserFakeEmail when strategy.attributes includes 'email' or
input.attributes.name) before merging with pickRecord, keep REPLACE deleting
existing only when attributes exists and then saving input.attributes (ensuring
fake email if needed), and keep the final else to create the record (with
fake-email guard) when no attributes existed and no strategy created it.
🧹 Nitpick comments (13)
packages/server-core/src/app/modules/provisioning/synchronizer/client/module.ts (2)
210-228: Input mutation via.map()side effects.Lines 212-213 and 222-223 mutate
child.attributesin-place inside.map(). This modifies the caller's originalinputobject, which could cause subtle bugs if the input is reused elsewhere. Consider spreading to create new objects.Example for permissions block
if (input.relations && input.relations.permissions) { const children = input.relations.permissions.map((child) => { - child.attributes.client_id = attributes.id; - child.attributes.client = attributes; - return child; + return { + ...child, + attributes: { + ...child.attributes, + client_id: attributes.id, + client: attributes, + }, + }; }); await this.permissionSynchronizer.synchronizeMany(children); }
53-78: Input validation occurs upstream, but consider defensive validation in synchronizers for robustness.The
RootProvisioningValidatorvalidates the entire provisioning data structure beforesynchronize()is called, including nestedClientProvisioningEntityobjects throughClientProvisioningValidator→ClientValidator. TheClientValidatorenforces thatnameis required on CREATE, so in normal operation,namewill always be present when the synchronizer receives input.However, synchronizers currently assume validated input without defensive checks. While this works given the existing validation architecture, adding a guard would make the synchronizer more resilient to validation bypasses or future refactoring. Consider validating
nameat the start ofsynchronize():Optional guard for defensive programming
async synchronize(input: ClientProvisioningEntity): Promise<ClientProvisioningEntity> { const strategy = normalizeEntityProvisioningStrategy(input.strategy); + if (!input.attributes.name) { + throw new Error('Client name is required for provisioning.'); + } + let attributes = await this.clientRepository.findOneBy({ name: input.attributes.name, realm_id: input.attributes.realm_id || IsNull(), });packages/server-core/src/app/modules/provisioning/synchronizer/realm/types.ts (1)
10-11: Minor import inconsistency.
ScopeProvisioningEntityis imported from'../../entities/index.ts'(Line 10) while all other entity types are imported from their specific subdirectories (Lines 11-15). Consider importing from'../../entities/scope/index.ts'for consistency.Suggested fix
-import type { ScopeProvisioningEntity } from '../../entities/index.ts'; +import type { ScopeProvisioningEntity } from '../../entities/scope/index.ts';packages/server-core/src/app/modules/provisioning/entities/root/types.ts (1)
8-12: Inconsistent import path formats in lines 8–12.Lines 10–11 import from
'../role'and'../scope'without file extensions, while lines 8–9 use'../permission/index.ts'and'../realm/index.ts'with explicit extensions, and line 12 uses'../types.ts'. For consistency, update lines 10–11 to match the style of lines 8–9.Suggested fix
-import type { RoleProvisioningEntity } from '../role'; -import type { ScopeProvisioningEntity } from '../scope'; +import type { RoleProvisioningEntity } from '../role/index.ts'; +import type { ScopeProvisioningEntity } from '../scope/index.ts';packages/server-core/src/app/modules/provisioning/synchronizer/realm/module.ts (1)
78-138: Consider extracting repeated relation-wiring into a helper.All six relation blocks follow the same pattern: check
input.relations?.X, map each child to attachrealm_idandrealm, then callthis.XSynchronizer.synchronizeMany(...). A small generic helper would eliminate the repetition.Example helper sketch
+ private async synchronizeRelation<T extends { attributes: Record<string, any> }>( + items: T[] | undefined, + realm: Realm, + synchronizer: IProvisioningSynchronizer<T>, + ): Promise<void> { + if (!items) return; + const enriched = items.map((child) => { + child.attributes.realm_id = realm.id; + child.attributes.realm = realm; + return child; + }); + await synchronizer.synchronizeMany(enriched); + }packages/server-core/src/app/modules/provisioning/entities/realm/relations-validator.ts (1)
19-89: Consider extracting the repeated mount pattern into a helper.All six relation mounts follow an identical structure:
zod.array(zod.any()).check(async (ctx) => { for-loop with validator.run() }). A small factory method would reduce boilerplate.Example
private mountArrayValidator<T>( key: string, validator: Container<T>, ): void { this.mount(key, { optional: true }, createValidator( zod.array(zod.any()).check(async (ctx) => { for (let i = 0; i < ctx.value.length; i++) { ctx.value[i] = await validator.run(ctx.value[i]); } }), )); }This also captures the return value of
validator.run(), addressing the discarded-result concern.packages/server-core/src/app/modules/provisioning/entities/user/types.ts (1)
10-42: Missing comma afterrealmRoleson Line 36.All other members in this type have trailing commas (lines 14, 19, 24, 31, 41) except
realmRoleson line 36. Not a syntax error, but inconsistent.- realmRoles?: string[] + realmRoles?: string[],packages/server-core/src/app/modules/provisioning/synchronizer/permission/module.ts (2)
29-33:||treats any falsy value (e.g.'') as null — prefer??for null-coalescing.
input.attributes.realm_id || IsNull()will fall through toIsNull()for any falsy value, not justnull/undefined. While IDs are typically non-empty UUIDs, using??is more semantically correct and defensive.This same pattern appears across all synchronizers (role, robot, permission).
♻️ Suggested fix
- realm_id: input.attributes.realm_id || IsNull(), - client_id: input.attributes.client_id || IsNull(), + realm_id: input.attributes.realm_id ?? IsNull(), + client_id: input.attributes.client_id ?? IsNull(),
12-12: Inconsistent import path — missing.tsextension.Line 12 uses
'../../entities/permission'without the.tsextension, while lines 13–15 all include.ts. Minor inconsistency.packages/server-core/src/app/modules/provisioning/sources/composite/module.ts (2)
19-23:scopesnot initialized in the output, unlike the other three fields.
roles,realms, andpermissionsare initialized to[]on lines 20-22, butscopesis omitted. Themerge()method handles this via lazy init (target.scopes = target.scopes || []), so it's not a bug, but it's inconsistent. Addingscopes: []here would align all four fields.♻️ Suggested fix
const output : RootProvisioningEntity = { roles: [], realms: [], permissions: [], + scopes: [], };
36-60:merge()is public but appears to be an internal helper.Consider marking it as
protectedorprivateto keep the public API surface minimal.packages/server-core/src/app/modules/provisioning/synchronizer/user/module.ts (2)
65-67:input.attributesis mutated in-place across multiple branches.Lines 65, 83, and 91 all assign to
input.attributes.email, which mutates the caller's object. Consider working on a shallow copy (e.g.,{ ...input.attributes }) to avoid surprising side effects for callers that may reuse the input.
99-167: Consider extracting the repeated global/realm/client resolution pattern into a helper.The same three-block pattern (global → realm → client-scoped lookup with wildcard support) appears identically for both permissions (lines 99–167) and roles (lines 193–261). A shared helper like
resolveEntities(repository, input.relations, attributes)would cut ~130 lines of near-duplicate code.
|
|
||
| import { createValidator } from '@validup/adapter-zod'; | ||
| import { Container } from 'validup'; | ||
| import zod from 'zod'; |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Check the Zod version in package.json
find . -name "package.json" -type f | head -5 | xargs grep -l "zod" | head -1 | xargs cat | grep -A 2 -B 2 '"zod"'Repository: authup/authup
Length of output: 172
🏁 Script executed:
#!/bin/bash
# Check how other files import from zod
rg "import.*from ['\"]zod['\"]" --type ts --type tsx -C 1 | head -50Repository: authup/authup
Length of output: 84
🌐 Web query:
Zod 4 default export import pattern, does Zod 4 support "import zod from 'zod'"
💡 Result:
Zod 4 does not provide a default export, so this is not supported:
import zod from "zod"; // ❌ no default exportUse one of these instead (Zod 4 docs use namespace import):
import * as z from "zod"; // ✅ recommendedIf you specifically want the identifier zod:
import * as zod from "zod"; // ✅Other notes:
import { z } from "zod"may still work for compatibility, but Zod 4 generally recommends the namespace import form. [1] (Some community guidance also warns{ z }can hurt tree-shaking in v4.) [2]
Sources: Zod v4 package docs showing import * as z from "zod" [1]; community write-up on v4 import patterns/tree-shaking [2].
🏁 Script executed:
#!/bin/bash
# Check how other files import from zod, using different approach
rg "import.*from ['\"]zod['\"]" --type ts -C 1 | head -60Repository: authup/authup
Length of output: 4672
🏁 Script executed:
#!/bin/bash
# Also check if the specific file exists and what it contains
cat -n packages/server-core/src/app/modules/provisioning/entities/root/validator.ts | head -20Repository: authup/authup
Length of output: 1006
Fix Zod import: Zod 4.3.6 does not support default export.
import zod from 'zod' will fail at runtime. Zod 4 requires namespace import: use import * as zod from 'zod' instead. This pattern is used throughout the codebase and needs to be corrected in all validator files.
🤖 Prompt for AI Agents
In `@packages/server-core/src/app/modules/provisioning/entities/root/validator.ts`
at line 10, The Zod import is using a default import which fails for Zod v4;
replace the default import in this validator module by switching "import zod
from 'zod'" to the namespace form (import * as zod from 'zod') so all usages
like zod.object(), zod.string(), etc. resolve correctly; apply the same change
to other validator files following the same pattern to ensure validators (e.g.,
any schema definitions or functions inside validator.ts that call zod.*) import
Zod as a namespace.
| this.mount('realms', { optional: true }, createValidator( | ||
| zod | ||
| .array(zod.any()) | ||
| .check(async (ctx) => { | ||
| for (let i = 0; i < ctx.value.length; i++) { | ||
| await realmValidator.run(ctx.value[i]); | ||
| } | ||
| }), | ||
| )); | ||
|
|
||
| this.mount('roles', { optional: true }, createValidator( | ||
| zod | ||
| .array(zod.any()) | ||
| .check(async (ctx) => { | ||
| for (let i = 0; i < ctx.value.length; i++) { | ||
| await roleValidator.run(ctx.value[i]); | ||
| } | ||
| }), | ||
| )); | ||
|
|
||
| this.mount('scopes', { optional: true }, createValidator( | ||
| zod | ||
| .array(zod.any()) | ||
| .check(async (ctx) => { | ||
| for (let i = 0; i < ctx.value.length; i++) { | ||
| await scopeValidator.run(ctx.value[i]); | ||
| } | ||
| }), | ||
| )); | ||
|
|
||
| this.mount('permissions', { optional: true }, createValidator( | ||
| zod | ||
| .array(zod.any()) | ||
| .check(async (ctx) => { | ||
| for (let i = 0; i < ctx.value.length; i++) { | ||
| await permissionValidator.run(ctx.value[i]); | ||
| } | ||
| }), | ||
| )); |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Search for Container class definition and run() method
find . -name "*.ts" -o -name "*.js" | xargs grep -l "class Container" | head -5Repository: authup/authup
Length of output: 39
🏁 Script executed:
#!/bin/bash
# Look for validup package and Container definition
fd -t f "package.json" | xargs grep -l "validup" | head -5Repository: authup/authup
Length of output: 179
🏁 Script executed:
#!/bin/bash
# Search for how run() is implemented
rg "run\(" packages/server-core/src/app/modules/provisioning/entities/root/validator.ts -B 2 -A 2Repository: authup/authup
Length of output: 913
🏁 Script executed:
#!/bin/bash
# Check the imports in the validator file
head -30 packages/server-core/src/app/modules/provisioning/entities/root/validator.tsRepository: authup/authup
Length of output: 1287
🏁 Script executed:
#!/bin/bash
# Find validup package location
find . -path ./node_modules -prune -o -name "validup" -type d -print 2>/dev/null | head -10Repository: authup/authup
Length of output: 39
🏁 Script executed:
#!/bin/bash
# Check if validup is a local package
ls -la packages/ | grep -i validRepository: authup/authup
Length of output: 39
🏁 Script executed:
#!/bin/bash
# Look for validup in package.json dependencies
cat packages/server-core/package.json | grep -A 5 -B 5 "validup"Repository: authup/authup
Length of output: 872
🏁 Script executed:
#!/bin/bash
# Check the entire packages directory structure
ls -la packages/Repository: authup/authup
Length of output: 1006
🏁 Script executed:
#!/bin/bash
# Search for other uses of .run() in the codebase
rg "\.run\(" packages/ --type ts -B 2 -A 2 | head -100Repository: authup/authup
Length of output: 10355
🏁 Script executed:
#!/bin/bash
# Look for try-catch patterns around validator.run()
rg "try\s*{" packages/server-core/src/app/modules/provisioning -A 10 | grep -A 10 "\.run"Repository: authup/authup
Length of output: 134
🏁 Script executed:
#!/bin/bash
# Check if there are other Container implementations or examples
rg "extends Container" packages/ --type ts -A 5Repository: authup/authup
Length of output: 35377
🏁 Script executed:
#!/bin/bash
# Search for Zod .check() usage patterns in the codebase
rg "\.check\(" packages/ --type ts -B 2 -A 3 | head -80Repository: authup/authup
Length of output: 8422
🏁 Script executed:
#!/bin/bash
# Check the TODO comment context in permission-binding evaluator
cat -n packages/server-core/src/security/policy/variants/permission-binding/evaluator.ts | grep -A 5 "todo: catch"Repository: authup/authup
Length of output: 326
🏁 Script executed:
#!/bin/bash
# Look at realm/relations-validator.ts to see if it has same pattern
cat packages/server-core/src/app/modules/provisioning/entities/realm/relations-validator.ts | head -100Repository: authup/authup
Length of output: 3426
🏁 Script executed:
#!/bin/bash
# Search for how rootValidator is being called/used
rg "rootValidator\.run" packages/ --type ts -B 3 -A 3Repository: authup/authup
Length of output: 785
🏁 Script executed:
#!/bin/bash
# Check the provisioning file module to see error handling context
cat -n packages/server-core/src/app/modules/provisioning/sources/file/module.ts | grep -B 5 -A 5 "rootValidator.run"Repository: authup/authup
Length of output: 480
🏁 Script executed:
#!/bin/bash
# Check if there are other provisioning validators with same pattern
find packages/server-core/src/app/modules/provisioning/entities -name "*.ts" -type f | xargs grep -l "\.check(async" | head -10Repository: authup/authup
Length of output: 221
🏁 Script executed:
#!/bin/bash
# Count how many provisioning validators have this pattern
rg "\.check\(async.*=>.*\.run\(" packages/server-core/src/app/modules/provisioning --type ts | wc -lRepository: authup/authup
Length of output: 58
🏁 Script executed:
#!/bin/bash
# Look at the exact pattern of error handling needed - check if `@validup` docs are in repo
find . -name "*.md" -o -name "*.txt" | xargs grep -l "validup" 2>/dev/null | head -5Repository: authup/authup
Length of output: 135
Error handling for sub-validators in .check() callbacks needs to be explicit.
Each array field is validated as zod.array(zod.any()) with a .check() side-effect that calls validator.run(). If run() throws, the error will bubble as an unhandled rejection inside the .check() callback rather than being captured as a Zod issue. This pattern exists in at least two provisioning validators (root and realm/relations). Other code in the codebase wraps .run() calls in try-catch blocks. A TODO comment at packages/server-core/src/security/policy/variants/permission-binding/evaluator.ts:58 acknowledges this same error handling gap. Wrap each await validator.run() call in try-catch to properly catch and report validation errors.
🤖 Prompt for AI Agents
In `@packages/server-core/src/app/modules/provisioning/entities/root/validator.ts`
around lines 31 - 69, The array element validators inside each this.mount(...,
createValidator(zod.array(...).check(async (ctx) => { ... }))) currently await
realmValidator.run / roleValidator.run / scopeValidator.run /
permissionValidator.run without catching errors; wrap each await call in a
try-catch inside the .check callback and on error call ctx.addIssue(...)
(including the caught error message and context/path) and return false so Zod
records the validation issue instead of letting the rejection bubble; update the
.check callbacks for the 'realms', 'roles', 'scopes', and 'permissions' mounts
accordingly.
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/server-core/src/app/modules/config/read/env.ts (1)
102-105:⚠️ Potential issue | 🟠 MajorBug: wrong variable checked for
emailVerificationguard.Line 103 checks
typeof registration !== 'undefined'instead oftypeof emailVerification !== 'undefined'. This meansemailVerificationwill only be assigned ifregistrationhappens to be defined, and could assignundefinedtooptions.emailVerificationwhenemailVerificationenv var is unset butregistrationis set.This is a pre-existing bug but worth fixing while you're in this file.
Proposed fix
const emailVerification = readBool(ConfigEnvironmentVariableName.EMAIL_VERIFICATION); - if (typeof registration !== 'undefined') { + if (typeof emailVerification !== 'undefined') { options.emailVerification = emailVerification; }
🤖 Fix all issues with AI agents
In
`@packages/server-core/src/app/modules/provisioning/synchronizer/user/module.ts`:
- Around line 166-186: The sync currently only adds UserPermission/UserRole
records (see permissions loop and userPermissionRepository.save), so stale
assignments remain; update the reconciliation to, after resolving the full
permissions and roles arrays, fetch existing UserPermission and UserRole rows
for the user via userPermissionRepository.findBy and userRoleRepository.findBy,
compute which DB entries have permission_id/role_id not present in the desired
permissions.map(p=>p.id)/roles.map(r=>r.id) sets, and remove those stale entries
with userPermissionRepository.remove / userRoleRepository.remove; scope this
deletion to the REPLACE sync mode (or skip if syncMode is MERGE) and apply the
same pattern for the code region handling roles (also referenced around the
260–280 block).
🧹 Nitpick comments (5)
packages/server-core/src/app/modules/config/read/env.ts (1)
119-132: Local variable names say "admin" while config properties say "system".The local variables (
clientAdminEnabled,clientAdminSecret,clientAdminSecretReset) use "admin" terminology while the env vars and config option properties all use "system" (CLIENT_SYSTEM_*,clientSystem*). Consider renaming toclientSystemEnabled,clientSystemSecret,clientSystemSecretResetfor consistency and readability.Proposed rename
- const clientAdminEnabled = readBool(ConfigEnvironmentVariableName.CLIENT_SYSTEM_ENABLED); - if (typeof clientAdminEnabled !== 'undefined') { - options.clientSystemEnabled = clientAdminEnabled; + const clientSystemEnabled = readBool(ConfigEnvironmentVariableName.CLIENT_SYSTEM_ENABLED); + if (typeof clientSystemEnabled !== 'undefined') { + options.clientSystemEnabled = clientSystemEnabled; } - const clientAdminSecret = read(ConfigEnvironmentVariableName.CLIENT_SYSTEM_SECRET); - if (clientAdminSecret) { - options.clientSystemSecret = clientAdminSecret; + const clientSystemSecret = read(ConfigEnvironmentVariableName.CLIENT_SYSTEM_SECRET); + if (clientSystemSecret) { + options.clientSystemSecret = clientSystemSecret; } - const clientAdminSecretReset = readBool(ConfigEnvironmentVariableName.CLIENT_SYSTEM_SECRET_RESET); - if (typeof clientAdminSecretReset !== 'undefined') { - options.clientSystemSecretReset = clientAdminSecretReset; + const clientSystemSecretReset = readBool(ConfigEnvironmentVariableName.CLIENT_SYSTEM_SECRET_RESET); + if (typeof clientSystemSecretReset !== 'undefined') { + options.clientSystemSecretReset = clientSystemSecretReset; }packages/server-core/src/app/modules/provisioning/sources/default/module.ts (1)
49-49: Redundant null-coalescing assignments formasterRealm.relations.
masterRealm.relationsis already initialized as{}on line 34–36, so themasterRealm.relations = masterRealm.relations || {};guards on lines 49, 75, and 101 are unnecessary.♻️ Remove redundant assignments
- masterRealm.relations = masterRealm.relations || {}; masterRealm.relations.users = [- masterRealm.relations = masterRealm.relations || {}; masterRealm.relations.clients = [- masterRealm.relations = masterRealm.relations || {}; masterRealm.relations.robots = [Also applies to: 75-75, 101-101
packages/server-core/src/app/modules/provisioning/synchronizer/user/module.ts (3)
94-164: Heavy code duplication between permission and role resolution blocks.The global/realm/client resolution pattern (wildcard check →
findBywith or withoutIn(names)→ push to array) is repeated identically six times (three for permissions, three for roles). This is a good candidate for a shared helper, e.g.:private async resolveEntities<T>( repository: Repository<T>, names: string[] | undefined, filters: Record<string, unknown>, ): Promise<T[]> { if (!names) return []; const hasWildcard = names.some(n => n === '*'); return repository.findBy( hasWildcard ? filters : { ...filters, name: In(names) }, ); }This would cut ~120 lines down to ~20 and make scope-handling logic easier to maintain.
Also applies to: 188-258
167-184: N+1 queries: each permission/role link is checked and saved individually.For a user with many permissions/roles, this generates 2× DB round-trips per relation (one
findOneBy+ onesave). Consider bulk-fetching existing links upfront and batch-inserting the missing ones:const existingUPs = await this.userPermissionRepository.findBy({ user_id: attributes.id }); const existingSet = new Set(existingUPs.map(up => up.permission_id)); const toInsert = permissions .filter(p => !existingSet.has(p.id)) .map(p => this.userPermissionRepository.create({ ... })); if (toInsert.length) await this.userPermissionRepository.save(toInsert);Also applies to: 261-278
96-164: Repeatedinput.relations && input.relations.Xguards could use optional chaining.Minor readability improvement —
input.relations?.globalPermissions, etc.Also applies to: 190-258
| if (permissions.length > 0) { | ||
| for (let i = 0; i < permissions.length; i++) { | ||
| const permission = permissions[i]; | ||
|
|
||
| let userPermission = await this.userPermissionRepository.findOneBy({ | ||
| user_id: attributes.id, | ||
| permission_id: permission.id, | ||
| }); | ||
|
|
||
| if (!userPermission) { | ||
| userPermission = this.userPermissionRepository.create({ | ||
| user_id: attributes.id, | ||
| user_realm_id: attributes.realm_id, | ||
| permission_id: permission.id, | ||
| permission_realm_id: permission.realm_id, | ||
| }); | ||
|
|
||
| await this.userPermissionRepository.save(userPermission); | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
Permissions and roles are only ever added, never removed — stale assignments persist after re-sync.
When a permission or role is removed from the provisioning input (YAML/JSON), the corresponding UserPermission / UserRole record in the database is never deleted. Over successive syncs, users accumulate grants that no longer match the filesystem definition.
Given the PR objective of "reconciling filesystem state with DB state," consider deleting UserPermission/UserRole records that are present in the DB but absent from the resolved permissions/roles arrays after the aggregation step. For example, after building the full permissions list:
// Remove stale user-permission links
const existingUPs = await this.userPermissionRepository.findBy({ user_id: attributes.id });
const desiredPermIds = new Set(permissions.map(p => p.id));
const stale = existingUPs.filter(up => !desiredPermIds.has(up.permission_id));
if (stale.length > 0) {
await this.userPermissionRepository.remove(stale);
}Same pattern for roles. If additive-only is intentional for MERGE, scope the cleanup to REPLACE only.
Also applies to: 260-280
🤖 Prompt for AI Agents
In
`@packages/server-core/src/app/modules/provisioning/synchronizer/user/module.ts`
around lines 166 - 186, The sync currently only adds UserPermission/UserRole
records (see permissions loop and userPermissionRepository.save), so stale
assignments remain; update the reconciliation to, after resolving the full
permissions and roles arrays, fetch existing UserPermission and UserRole rows
for the user via userPermissionRepository.findBy and userRoleRepository.findBy,
compute which DB entries have permission_id/role_id not present in the desired
permissions.map(p=>p.id)/roles.map(r=>r.id) sets, and remove those stale entries
with userPermissionRepository.remove / userRoleRepository.remove; scope this
deletion to the REPLACE sync mode (or skip if syncMode is MERGE) and apply the
same pattern for the code region handling roles (also referenced around the
260–280 block).
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Fix all issues with AI agents
In
`@packages/server-core/src/app/modules/provisioning/synchronizer/permission/module.ts`:
- Around line 46-48: The REPLACE branch currently calls
this.repository.save(input.attributes) which inserts a duplicate because
input.attributes lacks the primary key; instead, set the existing entity id onto
the attributes object found earlier (the attributes variable populated from
findOneBy) or merge input.attributes into that attributes object before calling
this.repository.save(attributes) so save receives an entity with the existing id
(same approach used by the MERGE branch).
In
`@packages/server-core/src/app/modules/provisioning/synchronizer/realm/module.ts`:
- Around line 69-71: The REPLACE branch in the synchronizers (case
ProvisioningEntityStrategyType.REPLACE) is saving input.attributes directly
which lacks the existing entity.id so TypeORM inserts instead of updating; fix
by carrying the found entity's id into the saved object—either merge the
existing entity with input.attributes (e.g., repository.merge(foundEntity,
input.attributes)) or assign foundEntity.id onto the attributes before calling
repository.save—apply this change to the realm, user, scope, role, robot, and
permission synchronizers so save() performs an UPDATE rather than an INSERT.
In
`@packages/server-core/src/app/modules/provisioning/synchronizer/robot/module.ts`:
- Around line 62-64: The REPLACE branch currently calls
this.robotRepository.save(input.attributes) which inserts a new row because
input.attributes lacks the existing entity id; update the REPLACE handling to
preserve the existing entity's id before saving (mirror the MERGE branch):
locate where ProvisioningEntityStrategyType.REPLACE is handled in module.ts and
either call this.robotRepository.merge(existingEntity, input.attributes) and
save that merged object, or assign existingEntity.id onto input.attributes prior
to this.robotRepository.save(...); apply the same pattern to the User and Role
synchronizer REPLACE branches.
🧹 Nitpick comments (3)
packages/server-core/src/app/modules/provisioning/synchronizer/permission/module.ts (1)
29-33: Consider guarding against a missingnameininput.attributes.
input.attributesis typed asPartial<Permission>, sonamecould beundefined. If it is,findOneBy({ name: undefined, ... })may produce unexpected query results (matching rows wherenameis anything or failing silently depending on the TypeORM version). A defensive check or a required-name type refinement would prevent subtle lookup bugs.packages/server-core/src/app/modules/provisioning/synchronizer/realm/module.ts (1)
77-137: Consider extracting the repetitive relation-enrichment pattern.All six relation blocks follow an identical pattern: check existence, map children to inject
realm_idandrealm, then callsynchronizeMany. This could be DRYed into a helper, but it's readable as-is.Note that
.map()mutateschild.attributesin place (side effect on input). If immutability matters upstream, spread into a new object instead.♻️ Example helper extraction
private async synchronizeRelation<T extends { attributes: { realm_id?: string; realm?: Realm } }>( items: T[] | undefined, realm: Realm, synchronizer: IProvisioningSynchronizer<T>, ): Promise<void> { if (!items) return; const enriched = items.map((child) => ({ ...child, attributes: { ...child.attributes, realm_id: realm.id, realm }, })); await synchronizer.synchronizeMany(enriched); }packages/server-core/src/app/modules/provisioning/synchronizer/robot/module.ts (1)
112-196: Stale permissions and roles are never removed during synchronization.The synchronizer adds missing
RobotPermissionandRobotRolerecords but never removes ones that are no longer present in the filesystem input. Over successive sync runs, revoked permissions/roles will persist in the database.This is particularly relevant for the
REPLACEstrategy, where the expectation is that the DB state matches the filesystem definition exactly. Consider deletingRobotPermission/RobotRolerecords whosepermission_id/role_idis not in the resolved set after upserting.Example approach for permissions (after the create loop)
+ if (permissions.length > 0) { + // Remove stale robot-permission associations + const existingRobotPerms = await this.robotPermissionRepository.findBy({ + robot_id: attributes.id, + }); + const activePermIds = new Set(permissions.map((p) => p.id)); + for (const erp of existingRobotPerms) { + if (!activePermIds.has(erp.permission_id)) { + await this.robotPermissionRepository.remove(erp); + } + } + }
There was a problem hiding this comment.
Actionable comments posted: 6
🤖 Fix all issues with AI agents
In
`@packages/server-core/src/app/modules/provisioning/entities/client/validator.ts`:
- Around line 24-25: The validator mounts the relations field as required but
the entity type ClientProvisioningEntity declares relations?:
ClientProvisioningRelations as optional, so update the mount call to mark it
optional (i.e., mount('relations', relationsValidator, { optional: true })) to
align the validator with the type; do the same change for the other provisioning
validators (RobotProvisioning*, UserProvisioning*, RoleProvisioning*,
RealmProvisioning*), ensuring each mount('relations', <...>RelationsValidator, {
optional: true }) uses the optional flag.
In
`@packages/server-core/src/app/modules/provisioning/entities/role/validator.ts`:
- Around line 25-26: The mount for relations is required but the entity type
declares relations as optional; update the mount call that registers
RoleProvisioningRelationsValidator so it allows missing keys by passing the
optional flag — i.e., change the this.mount('relations', relationsValidator)
usage in RoleProvisioningEntity validator to this.mount('relations',
relationsValidator, { optional: true }) (and apply the same pattern for other
provisioning validators that mount relations like user/robot/realm/client) so
omitting relations no longer fails validation.
In
`@packages/server-core/src/app/modules/provisioning/entities/scope/validator.ts`:
- Line 8: Rename the misspelled source file
packages/core-kit/src/domains/scope/validaitor.ts to validator.ts and update any
exports/indices to export from the new filename; then update all imports that
reference the old typo (e.g. the import of ScopeValidator) so they point to the
corrected module name. Specifically ensure the class/identifier ScopeValidator
remains exported from the renamed file and that any barrel files or package
exports in core-kit re-export from domains/scope/validator.ts, and change the
import in the referencing module (the current import of ScopeValidator) to use
the corrected path/name.
In
`@packages/server-core/src/app/modules/provisioning/entities/user/validator.ts`:
- Around line 24-25: The validator currently mounts relations as required;
update the mount call for the relations field to mark it optional to match the
type UserProvisioningEntity.relations (declare in types.ts). Locate the
UserProvisioningRelationsValidator instance (relationsValidator) and change the
mount invocation on the validator from this.mount('relations',
relationsValidator) to mount the same validator with the optional flag (e.g.,
this.mount('relations', relationsValidator, { optional: true })) so the field is
not required during validation.
In
`@packages/server-core/src/app/modules/provisioning/synchronizer/robot/module.ts`:
- Around line 93-111: The realm-permissions block currently queries with
realm_id: attributes.realm_id which duplicates the global (NULL) query when
attributes.realm_id is null; update the logic in the module's synchronizer
method so you only run the input.relations.realmPermissions branch when
attributes.realm_id is not null (e.g., guard the block with a check that
attributes.realm_id !== null/undefined) before calling
permissionRepository.findBy and pushing into the permissions array; apply the
same guard to the realmRoles handling to avoid overlapping queries with global
(NULL) role queries.
- Around line 113-197: The REPLACE strategy currently only adds missing
RobotPermission/RobotRole records but never removes stale ones; update the
synchronizer logic handling RobotPermission and RobotRole so that when strategy
=== 'REPLACE' you remove any existing associations for the given robot that are
not present in the resolved set from input.relations. Concretely, before or
after creating new entries, query robotPermissionRepository.findBy({ robot_id:
attributes.id }) and delete entries whose permission_id is not in the resolved
permissions list (and do the same with robotRoleRepository.findBy({ robot_id:
attributes.id }) vs. resolved roles); use repository.delete or remove to delete
those stale RobotPermission and RobotRole records so the DB matches the input
exactly under REPLACE.
🧹 Nitpick comments (8)
packages/server-core/src/app/modules/provisioning/synchronizer/realm/module.ts (1)
78-138: Consider extracting the repeated child-enrichment-and-sync pattern.All six blocks follow the identical pattern: check
input.relations.<key>, map children to injectrealm_idandrealm, then callsynchronizeMany. This could be reduced to a small helper, improving readability and reducing the chance of divergence if the pattern changes.Sketch
private async synchronizeChildren<T extends { attributes: { realm_id?: string; realm?: Realm } }>( children: T[] | undefined, synchronizer: IProvisioningSynchronizer<T>, realm: Realm, ): Promise<void> { if (!children) return; const enriched = children.map((child) => { child.attributes.realm_id = realm.id; child.attributes.realm = realm; return child; }); await synchronizer.synchronizeMany(enriched); }Then each block becomes:
await this.synchronizeChildren(input.relations?.clients, this.clientSynchronizer, attributes);packages/server-core/src/app/modules/provisioning/synchronizer/robot/module.ts (2)
62-65: REPLACE branch mutates the caller'sinput.attributesobject.Line 63 assigns
input.attributes.id = attributes.id, which is a side-effect on the input parameter. Ifinputis shared or reused upstream (e.g., retries, logging, or the returned spread on line 200), this mutation leaks into the original object. Consider working on a copy instead:Suggested fix
case ProvisioningEntityStrategyType.REPLACE: - input.attributes.id = attributes.id; - attributes = await this.robotRepository.save(input.attributes); + attributes = await this.robotRepository.save( + this.robotRepository.merge(attributes, input.attributes), + ); break;This also aligns the REPLACE branch more closely with the MERGE branch pattern and avoids mutating
input.
30-30: Remove unusedclientRepositoryinjection or implement client-scoped permission resolution.The
clientRepositoryis wired up in the constructor but never used in thesynchronizemethod. While the comment on line 71 hints at client permissions, the implementation only handles global and realm permissions (lines 73–111). Either remove this unused dependency or add the planned client-scoped permission synchronization logic.packages/server-core/src/app/modules/provisioning/synchronizer/scope/module.ts (2)
29-32: Prefer nullish coalescing (??) and guard against missingname.Two minor observations on the lookup:
realm_id || IsNull()— using||will treat any falsy value (including'') as null.??is more precise for null/undefined.input.attributesis typedPartial<Scope>, sonamecould theoretically beundefined. TypeORM'sfindOneBysilently ignoresundefinedproperties, which would drop thenamefilter and potentially match the wrong record. If upstream validation guaranteesnameis always present, consider tightening the type to reflect that (e.g.,Required<Pick<Scope, 'name'>> & Partial<Scope>), or add a runtime guard here.Suggested diff
- let attributes = await this.repository.findOneBy({ - name: input.attributes.name, - realm_id: input.attributes.realm_id || IsNull(), - }); + if (!input.attributes.name) { + throw new Error('Scope provisioning requires a name attribute'); + } + + let attributes = await this.repository.findOneBy({ + name: input.attributes.name, + realm_id: input.attributes.realm_id ?? IsNull(), + });
33-52: CREATE_ONLY strategy falls through the switch silently — consider making it explicit.When
strategy.typeisCREATE_ONLYand the entity already exists, execution falls through theswitchwith no matchingcase, so the existingattributesare returned unchanged. This is correct behavior, but adding an explicit case (or adefaultwith a comment) would make the intent clearer to future readers.Also, line 46 mutates
input.attributes.idas a side effect on the caller's data. If the caller ever re-uses the input object, it would unexpectedly carry anid.Suggested diff
if (attributes) { switch (strategy.type) { case ProvisioningEntityStrategyType.MERGE: attributes = this.repository.merge( attributes, strategy.attributes ? pickRecord(input.attributes, strategy.attributes) : input.attributes, ); attributes = await this.repository.save(attributes); break; - case ProvisioningEntityStrategyType.REPLACE: - input.attributes.id = attributes.id; - attributes = await this.repository.save(input.attributes); + case ProvisioningEntityStrategyType.REPLACE: { + const replaced = { ...input.attributes, id: attributes.id }; + attributes = await this.repository.save(replaced); break; + } + default: + // CREATE_ONLY: entity already exists, keep as-is + break; }packages/server-core/src/app/modules/provisioning/synchronizer/user/module.ts (3)
166-183: N+1 queries: individualfindOneByper permission/role is inefficient.Each iteration issues a separate
findOneByquery. For users with many permissions, this generates a large number of round-trips. A single bulk query can replace the loop:Batch approach
if (permissions.length > 0) { + const existingUPs = await this.userPermissionRepository.findBy({ + user_id: attributes.id, + permission_id: In(permissions.map(p => p.id)), + }); + const existingPermIds = new Set(existingUPs.map(up => up.permission_id)); + for (let i = 0; i < permissions.length; i++) { const permission = permissions[i]; - - let userPermission = await this.userPermissionRepository.findOneBy({ - user_id: attributes.id, - permission_id: permission.id, - }); - - if (!userPermission) { - userPermission = this.userPermissionRepository.create({ + if (!existingPermIds.has(permission.id)) { + const userPermission = this.userPermissionRepository.create({ user_id: attributes.id, user_realm_id: attributes.realm_id, permission_id: permission.id, permission_realm_id: permission.realm_id, }); - await this.userPermissionRepository.save(userPermission); } } }Same optimization applies to the role creation loop at lines 260–278.
93-257: Consider extracting repeated scope-resolution logic into a shared helper.The three-scope (global / realm / client) resolution pattern is duplicated almost verbatim for both permissions (lines 93–163) and roles (lines 187–257). A helper such as
resolveEntitiesByScope(repo, relations, realmId, clientRepo)would cut ~130 lines of duplication and make future scope additions (e.g., organization-scoped) a one-line change.
95-110: Consider adding length guards for defensive code clarity, though TypeORM 0.3.28 currently handlesIn([])safely.The project uses TypeORM 0.3.28, which safely converts empty
In([])to an always-false condition (0=1/1=0), returning no rows. However, guarding empty arrays improves code readability and future-proofs against potential TypeORM version changes. The pattern occurs at six locations: lines 95 (globalPermissions), 115 (realmPermissions), 146 (clientPermissions), 189 (globalRoles), 209 (realmRoles), and 240 (clientRoles).Consider:
Proposed guard
if (input.relations && input.relations.globalPermissions) { + if (input.relations.globalPermissions.length > 0) { let entities : Permission[]; const hasWildcard = input.relations.globalPermissions.some((el) => el === '*'); // ... existing logic ... permissions.push(...entities); + } }
|
@coderabbitai review |
resolves #2801
Summary by CodeRabbit
Release Notes
New Features
Configuration Changes
clientSystemEnabled,clientSystemSecret,clientSystemSecretReset).Refactor