Skip to content

refactor: deduplicate provisioning synchronizers and improve module wiring - #2905

Merged
tada5hi merged 8 commits into
masterfrom
2843-provisioning
Mar 13, 2026
Merged

tada5hi merged 8 commits into
masterfrom
2843-provisioning

Conversation

@tada5hi

@tada5hi tada5hi commented Mar 13, 2026 •

Copy link
Copy Markdown
Collaborator

resolves #2843
resolves #2841

Summary by CodeRabbit

  • New Features

    • Added built-in policy protection preventing deletion and modification of system-managed policies.
    • Introduced ABSENT strategy for provisioning, enabling entity removal during provisioning operations.
    • Expanded provisioning capabilities with comprehensive documentation for declarative resource configuration.
  • Bug Fixes

    • Fixed query filtering to correctly handle null values and array conditions across repositories.
  • Documentation

    • Added provisioning system guide with schema reference and configuration examples.

@coderabbitai

coderabbitai Bot commented Mar 13, 2026 •

Copy link
Copy Markdown

Caution

Review failed

Pull request was closed or merged during review

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR implements a comprehensive declarative provisioning system for Authup, introducing entity synchronizers for Client, Role, Robot, User, Permission, Scope, and Realm entities, adding an "ABSENT" deletion strategy, and refactoring repositories with a translation layer for query conditions. Repository adapters across the system now support a findManyBy method with condition translation.

Changes

Cohort / File(s) Summary
Policy Module Guards
apps/server-core/src/adapters/http/controllers/entities/policy/module.ts
Added validation guards to prevent deletion and updates of built-in policies by raising BadRequestError when built_in = true.
Repository Query Translation Layer
apps/server-core/src/app/modules/database/repositories/helpers.ts
New translateWhereConditions helper converts plain objects to TypeORM-compatible filters: null values become IsNull(), arrays become In([...]), and other values pass through unchanged.
Repository Adapter Enhancements
apps/server-core/src/app/modules/database/repositories/{client,permission,role,scope,client-role,client-permission,client-scope,identity-provider,identity-provider-role-mapping,permission,policy,realm,robot,robot-role,robot-permission,role-attribute,role-permission,scope,user,user-attribute,user-permission,user-role}/repository.ts
Added findManyBy(where: Record<string, any>): Promise<T[]> method and updated findOneBy to apply translateWhereConditions transformation across 20+ repository adapters.
IEntityRepository Interface
apps/server-core/src/core/entities/types.ts
Added findManyBy(where: Record<string, any>): Promise<T[]> method signature to the IEntityRepository<T> interface.
Provisioning Core Infrastructure
apps/server-core/src/core/provisioning/{entity-resolver.ts,junction-synchronizer.ts,strategy/constants.ts,strategy/types.ts,strategy/validator.ts,types.ts}
Introduced ProvisioningEntityResolver for resolving entities by scope (global, realm, client); added ProvisioningJunctionSynchronizer for managing associations; added ABSENT strategy constant and type; updated strategy validator to accept 'absent' option.
Provisioning Entity Synchronizers (Core)
apps/server-core/src/core/provisioning/synchronizer/{client,permission,realm,role,robot,scope,user}/{module.ts,types.ts}
New and updated synchronizer implementations for Client, Role, Robot, User, Realm, Scope, Permission. Refactored from TypeORM Repository<T> to custom IEntityRepository interfaces. Implemented ABSENT strategy handling for deletion, MERGE/REPLACE logic, and junction-based relationship synchronization.
Provisioning Module Restructuring
apps/server-core/src/app/modules/provisioning/{index.ts,module.ts,sources/{composite,default,file}/module.ts}
Moved provisioning entities and types to core/provisioning; updated module.ts to wire repository adapters instead of raw repositories; removed synchronizer context types from app layer; updated import paths in source modules (composite, default, file) to reference core/provisioning.
Removed Synchronizer Context Types
apps/server-core/src/app/modules/provisioning/synchronizer/{robot,user}/types.ts
Deleted RobotProvisioningSynchronizerContext and UserProvisioningSynchronizerContext type definitions (migrated to core/provisioning).
Core Module Exports
apps/server-core/src/core/{index.ts,provisioning/index.ts}
Added provisioning/index.ts as centralized re-export hub for provisioning entities, strategies, synchronizers, and types; updated core/index.ts to export from provisioning module.
Documentation and Configuration
docs/src/guide/{deployment/provisioning.md,contributing/database-seeds.md}, .agents/architecture.md, docs/src/.vitepress/config.mjs, AGENTS.md
Added comprehensive provisioning documentation with schema reference, strategies, and examples; updated architecture guide; removed database seeds documentation; added provisioning sidebar navigation.

Sequence Diagram

sequenceDiagram
    participant Client as Provisioning Source
    participant Sync as Synchronizer (e.g., User)
    participant Resolver as ProvisioningEntityResolver
    participant Junction as ProvisioningJunctionSynchronizer
    participant Repo as IEntityRepository

    Client->>Sync: synchronize(input: ProvisioningEntity)
    Sync->>Sync: normalizeEntityProvisioningStrategy(strategy)
    Sync->>Repo: findOneBy({name, realm_id, client_id})
    Repo-->>Sync: existing entity or null
    
    alt ABSENT Strategy
        Sync->>Repo: remove(existing)
        Repo-->>Sync: deleted
    else MERGE/REPLACE Strategy
        Sync->>Repo: create(input.attributes)
        Repo-->>Sync: created entity
        Sync->>Repo: save(entity)
        Repo-->>Sync: persisted entity
    end
    
    Sync->>Resolver: resolveGlobal(names)
    Resolver->>Repo: findManyBy({name, realm_id: null, client_id: null})
    Repo-->>Resolver: entities
    Resolver-->>Sync: resolved entities
    
    Sync->>Junction: synchronize(owner, targets, targetKey, targetRealmKey)
    Junction->>Repo: findOneBy({[ownerKey], [targetKey]})
    Repo-->>Junction: existing or null
    
    alt Missing Association
        Junction->>Repo: create({owner_id, target_id, ...})
        Repo-->>Junction: junction entity
        Junction->>Repo: save(junction)
        Repo-->>Junction: persisted
    end
    
    Junction-->>Sync: void
    Sync-->>Client: input with persisted attributes
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • authup/authup#2880: Both PRs introduce and expand IEntityRepository interfaces and repository adapter patterns across the codebase, with overlapping changes to core/entities types and database repositories layer.
  • authup/authup#2836: Both PRs implement core provisioning infrastructure including entity types, validators, and synchronizer patterns, with shared modifications to provisioning-related modules and abstractions.
  • authup/authup#2858: Both PRs modify provisioning sources and the composite source implementation, including changes to provisioning load signatures and synchronization logic.

Poem

🐰 A rabbit hops through provisioning halls,
Where strategies declare what matters most—
ABSENT whispers deletion's call,
While MERGE and REPLACE hold the cost.
Junctions link entities in dance,
And resolvers turn names to chance! ✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning The PR introduces substantial out-of-scope changes unrelated to the linked issues, including policy built-in protection guards, refactored provisioning module wiring, documentation updates, and migration of repository types from TypeORM to custom interfaces, which exceed the deduplication and entity resolver scope. Consider splitting policy protection logic, repository interface changes, and extensive documentation updates into separate PRs to maintain focused scope aligned with the entity resolver and delete strategy objectives.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'refactor: deduplicate provisioning synchronizers and improve module wiring' accurately describes the primary change in the changeset—consolidating and refactoring provisioning synchronizers while improving their module dependencies and wiring.
Linked Issues check ✅ Passed The PR implements core requirements from both linked issues: Issue #2841 (Entity Resolver) is addressed via findManyBy methods across all repositories and the new ProvisioningEntityResolver class; Issue #2843 (Delete Provisioning Strategy) is addressed by adding ABSENT strategy with deletion logic across synchronizers.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 2843-provisioning
📝 Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (6)
apps/server-core/src/app/modules/database/repositories/user-role/repository.ts (1)

64-70: ⚠️ Potential issue | 🟡 Minor

Same concern: findOneByName appears incorrect for a junction table.

UserRole is a junction entity (user_id, role_id) without a name property. The { name } as any cast and the findOneByIdOrName that ignores the name suggest these methods don't apply to this entity type. Consider the same remediation as noted for RolePermissionRepositoryAdapter.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@apps/server-core/src/app/modules/database/repositories/user-role/repository.ts`
around lines 64 - 70, The methods findOneByName and findOneByIdOrName in
UserRole are incorrect because UserRole is a junction entity without a name;
remove or replace them: delete findOneByName (and the casted
repository.findOneBy({ name } as any)), and change findOneByIdOrName to either a
meaningful lookup (e.g., findOneByUserIdAndRoleId or a join-based lookup that
resolves a role name via the Role entity) or remove it if not needed; update any
callers accordingly and follow the same remediation pattern used for
RolePermissionRepositoryAdapter.
apps/server-core/src/app/modules/database/repositories/robot-permission/repository.ts (1)

68-74: ⚠️ Potential issue | 🟡 Minor

Same junction table concern: findOneByName doesn't apply.

RobotPermission is a junction entity without a name property. Consider addressing this across all junction table repositories together.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@apps/server-core/src/app/modules/database/repositories/robot-permission/repository.ts`
around lines 68 - 74, The method findOneByName wrongly assumes RobotPermission
has a name field; update repository methods so junction-entity logic is used:
remove or deprecate findOneByName and change findOneByIdOrName (and any callers)
to resolve by id or by joining the related Permission (or Robot/User) entity and
filtering on that entity's name; specifically adjust the implementations of
findOneByName, findOneByIdOrName, and any use of repository.findOneBy to instead
perform a proper join/query against the related entity (or return null/throw)
when looking up by name for the RobotPermission junction entity.
apps/server-core/src/app/modules/database/repositories/user-permission/repository.ts (1)

70-76: ⚠️ Potential issue | 🟡 Minor

Same junction table concern: findOneByName doesn't apply.

UserPermission is a junction entity without a name property. Same issue as noted in RolePermissionRepositoryAdapter and UserRoleRepositoryAdapter.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@apps/server-core/src/app/modules/database/repositories/user-permission/repository.ts`
around lines 70 - 76, The method findOneByName incorrectly assumes
UserPermission has a name; update it to join the related Permission entity and
filter by permission.name instead. Replace repository.findOneBy({ name }) in
findOneByName with a query using
repository.createQueryBuilder('up').innerJoin('up.permission','p').where('p.name
= :name',{ name }) and return the UserPermission result (or null), and ensure
findOneByIdOrName calls either findOneById(idOrName) or the updated
findOneByName when the input is not a UUID; reference the methods findOneByName,
findOneByIdOrName, findOneById, and the UserPermission relation 'permission'.
apps/server-core/src/app/modules/database/repositories/role-permission/repository.ts (1)

67-73: ⚠️ Potential issue | 🟠 Major

Junction table repositories implement findOneByName and findOneByIdOrName methods that don't function as intended.

RolePermission is a junction entity without a name property. Yet IRolePermissionRepository extends IEntityRepository which requires findOneByName(name: string) and findOneByIdOrName(idOrName: string) methods. The current implementation queries { name } as any (which always returns null) and ignores the name parameter in findOneByIdOrName.

This pattern is systemic across all junction table repositories (UserPermission, ClientPermission, RobotPermission, UserRole, RobotRole, ClientRole, etc.)—none have a name property, yet all implement these methods with the same workaround.

Consider:

  1. Overriding the interface for junction tables to exclude findOneByName and prevent the name parameter in findOneByIdOrName
  2. Explicitly throwing NotImplementedError in these methods for junction entities to prevent silent failures
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@apps/server-core/src/app/modules/database/repositories/role-permission/repository.ts`
around lines 67 - 73, The junction repository methods findOneByName and
findOneByIdOrName on RolePermission (and other junction entities like
UserPermission, ClientPermission, RobotPermission, UserRole, RobotRole,
ClientRole) are incorrect because the junction entities have no name property;
either modify the repository interface so junction repositories do not require
findOneByName/findOneByIdOrName (e.g., create a IJunctionRepository that does
not extend IEntityRepository's name-based methods and have
IRolePermissionRepository extend that), or change the implementations in
RolePermission repository (and the other junction repos) to explicitly throw a
NotImplementedError from findOneByName and from findOneByIdOrName (or accept
only the id path) to avoid silent null returns; update corresponding
interfaces/types (IRolePermissionRepository) to reflect the chosen approach and
ensure callers are adjusted to not rely on name-based lookups for junction
entities.
apps/server-core/src/core/provisioning/synchronizer/user/module.ts (1)

121-135: ⚠️ Potential issue | 🔴 Critical

Don't let realm-scoped user relations resolve against global grants.

Unlike RoleProvisioningSynchronizer, these branches still execute when attributes.realm_id is null. That makes realmPermissions / realmRoles query global records and can broaden a global user's access unexpectedly.

🔒 Suggested guard
-        if (input.relations && input.relations.realmPermissions) {
+        if (attributes.realm_id && input.relations && input.relations.realmPermissions) {
             let entities : Permission[];
@@
-        if (input.relations && input.relations.realmRoles) {
+        if (attributes.realm_id && input.relations && input.relations.realmRoles) {
             let entities : Role[];

Also applies to: 215-229

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/core/provisioning/synchronizer/user/module.ts` around
lines 121 - 135, The code resolves input.relations.realmPermissions (and
similarly realmRoles) even when attributes.realm_id is null, which causes
queries against global grants; update the branches that call
permissionRepository.findManyBy (and the analogous roleRepository calls) to
short-circuit or skip resolving realm-scoped relations when attributes.realm_id
is null by adding a guard checking attributes.realm_id !== null/undefined before
running the hasWildcard logic and repository queries so
realmPermissions/realmRoles are only looked up for non-null realm_id values.
apps/server-core/src/core/provisioning/synchronizer/robot/module.ts (1)

99-113: ⚠️ Potential issue | 🔴 Critical

Don't let realm-scoped robot relations fall back to global grants.

Unlike RoleProvisioningSynchronizer, these branches still run when attributes.realm_id is null. That turns realmPermissions / realmRoles into global lookups and can assign broader permissions or roles to a global robot than the provisioning input asked for.

🔒 Suggested guard
-        if (input.relations && input.relations.realmPermissions) {
+        if (attributes.realm_id && input.relations && input.relations.realmPermissions) {
             let entities : Permission[];
@@
-        if (input.relations && input.relations.realmRoles) {
+        if (attributes.realm_id && input.relations && input.relations.realmRoles) {
             let entities : Role[];

Also applies to: 163-177

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/core/provisioning/synchronizer/robot/module.ts` around
lines 99 - 113, The realm-scoped branches currently run even when
attributes.realm_id is null, causing realmPermissions/realmRoles to fall back to
global lookups; add a guard to require attributes.realm_id to be non-null before
executing the realm-scoped queries (i.e., wrap the existing checks for
input.relations.realmPermissions and input.relations.realmRoles with a condition
like "if (attributes.realm_id != null && input.relations?.realmPermissions)" and
similarly for realmRoles) so permissionRepository.findManyBy and
roleRepository.findManyBy are only called for actual realm-scoped robots and not
for global robots.
🧹 Nitpick comments (5)
apps/server-core/src/core/entities/types.ts (1)

29-31: Consider replacing any in repository where contracts.

Since this is the base entity repository interface, narrowing where to unknown prevents unsafe spread of any across all adapters.

♻️ Proposed refactor
-    findManyBy(where: Record<string, any>): Promise<T[]>;
+    findManyBy(where: Record<string, unknown>): Promise<T[]>;
 
-    findOneBy(where: Record<string, any>): Promise<T | null>;
+    findOneBy(where: Record<string, unknown>): Promise<T | null>;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/core/entities/types.ts` around lines 29 - 31, Change the
`where` parameter types on the base repository methods to avoid leaking `any`:
update the signatures of findManyBy and findOneBy in types.ts to use
Record<string, unknown> (or a generic constraint like Partial<Record<string,
unknown>>) instead of Record<string, any>; then update all
implementations/adapters that implement these interfaces (repositories, DAO
classes) to accept/handle the unknown-typed `where` (perform safe type-narrowing
or explicit casts where necessary) so the codebase no longer propagates `any`
from the core contract.
apps/server-core/src/app/modules/database/repositories/helpers.ts (1)

10-22: Harden the helper contract for shared usage.

This utility is now central; tightening input/output typing and allowing a default empty object will make call-sites safer and reduce any leakage.

♻️ Proposed refactor
 import { In, IsNull } from 'typeorm';
 
-export function translateWhereConditions(where: Record<string, any>): Record<string, any> {
-    const result: Record<string, any> = {};
+type WhereConditions = Record<string, unknown>;
+
+export function translateWhereConditions(where: WhereConditions = {}): WhereConditions {
+    const result: WhereConditions = {};
     Object.entries(where).forEach(([key, value]) => {
         if (value === null) {
             result[key] = IsNull();
         } else if (Array.isArray(value)) {
-            result[key] = In(value);
+            result[key] = In(value);
         } else {
             result[key] = value;
         }
     });
     return result;
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/app/modules/database/repositories/helpers.ts` around
lines 10 - 22, translateWhereConditions currently uses broad any types and
requires a caller-provided object; tighten the contract by changing the
parameter to a defaulted, stricter type (e.g., where: Record<string, unknown> =
{}) and narrow the return typing (e.g., Record<string, unknown> or
Record<string, FindOperator<unknown>> if using TypeORM FindOperator) so callers
don't leak any. Keep the existing null and array handling logic inside
translateWhereConditions, but update the function signature and the local result
typing to the stricter types and ensure the function safely handles an
omitted/undefined argument by using the default empty object.
apps/server-core/src/app/modules/database/repositories/user/repository.ts (1)

166-168: Consider extending findManyBy with EA for consistency with findMany and findOneById.

findMany (line 76) and all single-entity methods (findOneById, findOneByName, findOne) extend results with EA, but findManyBy returns raw results. While callers in the provisioning synchronizers currently use these results for matching only, this creates an inconsistent API contract that could lead to issues if the method is used differently in the future.

The suggested enhancement remains valid:

♻️ Suggested enhancement
 async findManyBy(where: Record<string, any>): Promise<User[]> {
-    return this.repository.findBy(translateWhereConditions(where));
+    const entities = await this.repository.findBy(translateWhereConditions(where));
+    await this.repository.extendManyWithEA(entities as UserEntity[]);
+    return entities;
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/app/modules/database/repositories/user/repository.ts`
around lines 166 - 168, findManyBy currently returns raw results from
this.repository.findBy(translateWhereConditions(where)) while findMany and
single-entity methods (findOneById, findOneByName, findOne) map results through
the EA-extension logic; update findManyBy to apply the same EA extension to each
returned User (i.e., call the same mapper/extension used by findMany and the
single-entity methods) before returning, keeping the
translateWhereConditions(where) and repository.findBy call but mapping the
result array through the EA extension function so the API contract is
consistent.
apps/server-core/src/app/modules/provisioning/sources/composite/module.ts (1)

26-26: Prefer forEach over map when return value is unused.

Using map() without utilizing its return value is misleading. Since you're only calling merge() for side effects, forEach() better expresses intent.

♻️ Suggested change
-        sourcesData.map((sourceData) => this.merge(output, sourceData));
+        sourcesData.forEach((sourceData) => this.merge(output, sourceData));
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/app/modules/provisioning/sources/composite/module.ts` at
line 26, The code uses sourcesData.map((sourceData) => this.merge(output,
sourceData)) but ignores map's return value; change to using forEach to express
the side-effect intent: replace the call to sourcesData.map with
sourcesData.forEach and keep the callback invoking this.merge(output,
sourceData) so that merge and output behavior is unchanged while removing the
misleading use of map.
apps/server-core/src/app/modules/provisioning/module.ts (1)

89-195: Reuse shared repository adapters instead of rebuilding them inline.

PermissionRepositoryAdapter, RoleRepositoryAdapter, and ClientRepositoryAdapter are constructed multiple times from the same resolved repositories. Hoisting them once would shorten this bootstrap code and reduce wiring drift when one constructor changes.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/app/modules/provisioning/module.ts` around lines 89 -
195, The provisioning module repeatedly constructs the same repository adapters
(e.g., PermissionRepositoryAdapter, RoleRepositoryAdapter,
ClientRepositoryAdapter) from identical resolved repositories; hoist these
adapters into local constants (created once using
container.resolve<Repository<...>>(...) and realmRepository or dataSource where
applicable) and reuse those constants when instantiating
PermissionProvisioningSynchronizer, RoleProvisioningSynchronizer,
ClientProvisioningSynchronizer, UserProvisioningSynchronizer,
RobotProvisioningSynchronizer, etc.; ensure you replace the inline new
PermissionRepositoryAdapter({ repository:
container.resolve<Repository<Permission>>(PermissionEntity), realmRepository })
(and the analogous Role/Client adapters) with the shared variables so wiring
changes only need a single update.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@provisioning-refactor-plan.md`:
- Around line 19-39: The markdown has fenced code blocks without language
identifiers in provisioning-refactor-plan.md (the blocks listing the tree
starting with "app/modules/provisioning/" and the subsequent block starting with
"core/provisioning/"); add a language tag (e.g., ```text) after the opening
triple backticks for those two blocks and any other similar fences (notably the
occurrences around lines 65-86) so markdownlint MD040 is satisfied, preserving
the exact block contents including paths like "app/modules/provisioning/" and
"core/provisioning/".

---

Outside diff comments:
In
`@apps/server-core/src/app/modules/database/repositories/robot-permission/repository.ts`:
- Around line 68-74: The method findOneByName wrongly assumes RobotPermission
has a name field; update repository methods so junction-entity logic is used:
remove or deprecate findOneByName and change findOneByIdOrName (and any callers)
to resolve by id or by joining the related Permission (or Robot/User) entity and
filtering on that entity's name; specifically adjust the implementations of
findOneByName, findOneByIdOrName, and any use of repository.findOneBy to instead
perform a proper join/query against the related entity (or return null/throw)
when looking up by name for the RobotPermission junction entity.

In
`@apps/server-core/src/app/modules/database/repositories/role-permission/repository.ts`:
- Around line 67-73: The junction repository methods findOneByName and
findOneByIdOrName on RolePermission (and other junction entities like
UserPermission, ClientPermission, RobotPermission, UserRole, RobotRole,
ClientRole) are incorrect because the junction entities have no name property;
either modify the repository interface so junction repositories do not require
findOneByName/findOneByIdOrName (e.g., create a IJunctionRepository that does
not extend IEntityRepository's name-based methods and have
IRolePermissionRepository extend that), or change the implementations in
RolePermission repository (and the other junction repos) to explicitly throw a
NotImplementedError from findOneByName and from findOneByIdOrName (or accept
only the id path) to avoid silent null returns; update corresponding
interfaces/types (IRolePermissionRepository) to reflect the chosen approach and
ensure callers are adjusted to not rely on name-based lookups for junction
entities.

In
`@apps/server-core/src/app/modules/database/repositories/user-permission/repository.ts`:
- Around line 70-76: The method findOneByName incorrectly assumes UserPermission
has a name; update it to join the related Permission entity and filter by
permission.name instead. Replace repository.findOneBy({ name }) in findOneByName
with a query using
repository.createQueryBuilder('up').innerJoin('up.permission','p').where('p.name
= :name',{ name }) and return the UserPermission result (or null), and ensure
findOneByIdOrName calls either findOneById(idOrName) or the updated
findOneByName when the input is not a UUID; reference the methods findOneByName,
findOneByIdOrName, findOneById, and the UserPermission relation 'permission'.

In
`@apps/server-core/src/app/modules/database/repositories/user-role/repository.ts`:
- Around line 64-70: The methods findOneByName and findOneByIdOrName in UserRole
are incorrect because UserRole is a junction entity without a name; remove or
replace them: delete findOneByName (and the casted repository.findOneBy({ name }
as any)), and change findOneByIdOrName to either a meaningful lookup (e.g.,
findOneByUserIdAndRoleId or a join-based lookup that resolves a role name via
the Role entity) or remove it if not needed; update any callers accordingly and
follow the same remediation pattern used for RolePermissionRepositoryAdapter.

In `@apps/server-core/src/core/provisioning/synchronizer/robot/module.ts`:
- Around line 99-113: The realm-scoped branches currently run even when
attributes.realm_id is null, causing realmPermissions/realmRoles to fall back to
global lookups; add a guard to require attributes.realm_id to be non-null before
executing the realm-scoped queries (i.e., wrap the existing checks for
input.relations.realmPermissions and input.relations.realmRoles with a condition
like "if (attributes.realm_id != null && input.relations?.realmPermissions)" and
similarly for realmRoles) so permissionRepository.findManyBy and
roleRepository.findManyBy are only called for actual realm-scoped robots and not
for global robots.

In `@apps/server-core/src/core/provisioning/synchronizer/user/module.ts`:
- Around line 121-135: The code resolves input.relations.realmPermissions (and
similarly realmRoles) even when attributes.realm_id is null, which causes
queries against global grants; update the branches that call
permissionRepository.findManyBy (and the analogous roleRepository calls) to
short-circuit or skip resolving realm-scoped relations when attributes.realm_id
is null by adding a guard checking attributes.realm_id !== null/undefined before
running the hasWildcard logic and repository queries so
realmPermissions/realmRoles are only looked up for non-null realm_id values.

---

Nitpick comments:
In `@apps/server-core/src/app/modules/database/repositories/helpers.ts`:
- Around line 10-22: translateWhereConditions currently uses broad any types and
requires a caller-provided object; tighten the contract by changing the
parameter to a defaulted, stricter type (e.g., where: Record<string, unknown> =
{}) and narrow the return typing (e.g., Record<string, unknown> or
Record<string, FindOperator<unknown>> if using TypeORM FindOperator) so callers
don't leak any. Keep the existing null and array handling logic inside
translateWhereConditions, but update the function signature and the local result
typing to the stricter types and ensure the function safely handles an
omitted/undefined argument by using the default empty object.

In `@apps/server-core/src/app/modules/database/repositories/user/repository.ts`:
- Around line 166-168: findManyBy currently returns raw results from
this.repository.findBy(translateWhereConditions(where)) while findMany and
single-entity methods (findOneById, findOneByName, findOne) map results through
the EA-extension logic; update findManyBy to apply the same EA extension to each
returned User (i.e., call the same mapper/extension used by findMany and the
single-entity methods) before returning, keeping the
translateWhereConditions(where) and repository.findBy call but mapping the
result array through the EA extension function so the API contract is
consistent.

In `@apps/server-core/src/app/modules/provisioning/module.ts`:
- Around line 89-195: The provisioning module repeatedly constructs the same
repository adapters (e.g., PermissionRepositoryAdapter, RoleRepositoryAdapter,
ClientRepositoryAdapter) from identical resolved repositories; hoist these
adapters into local constants (created once using
container.resolve<Repository<...>>(...) and realmRepository or dataSource where
applicable) and reuse those constants when instantiating
PermissionProvisioningSynchronizer, RoleProvisioningSynchronizer,
ClientProvisioningSynchronizer, UserProvisioningSynchronizer,
RobotProvisioningSynchronizer, etc.; ensure you replace the inline new
PermissionRepositoryAdapter({ repository:
container.resolve<Repository<Permission>>(PermissionEntity), realmRepository })
(and the analogous Role/Client adapters) with the shared variables so wiring
changes only need a single update.

In `@apps/server-core/src/app/modules/provisioning/sources/composite/module.ts`:
- Line 26: The code uses sourcesData.map((sourceData) => this.merge(output,
sourceData)) but ignores map's return value; change to using forEach to express
the side-effect intent: replace the call to sourcesData.map with
sourcesData.forEach and keep the callback invoking this.merge(output,
sourceData) so that merge and output behavior is unchanged while removing the
misleading use of map.

In `@apps/server-core/src/core/entities/types.ts`:
- Around line 29-31: Change the `where` parameter types on the base repository
methods to avoid leaking `any`: update the signatures of findManyBy and
findOneBy in types.ts to use Record<string, unknown> (or a generic constraint
like Partial<Record<string, unknown>>) instead of Record<string, any>; then
update all implementations/adapters that implement these interfaces
(repositories, DAO classes) to accept/handle the unknown-typed `where` (perform
safe type-narrowing or explicit casts where necessary) so the codebase no longer
propagates `any` from the core contract.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: a6622888-011c-4559-a9a8-cb39972123a7

📥 Commits

Reviewing files that changed from the base of the PR and between 7a9ef6a and 5cc050c.

📒 Files selected for processing (96)
  • apps/server-core/src/adapters/http/controllers/entities/policy/module.ts
  • apps/server-core/src/app/modules/database/repositories/client-permission/repository.ts
  • apps/server-core/src/app/modules/database/repositories/client-role/repository.ts
  • apps/server-core/src/app/modules/database/repositories/client-scope/repository.ts
  • apps/server-core/src/app/modules/database/repositories/client/repository.ts
  • apps/server-core/src/app/modules/database/repositories/helpers.ts
  • apps/server-core/src/app/modules/database/repositories/identity-provider-role-mapping/repository.ts
  • apps/server-core/src/app/modules/database/repositories/identity-provider/repository.ts
  • apps/server-core/src/app/modules/database/repositories/permission/repository.ts
  • apps/server-core/src/app/modules/database/repositories/policy/repository.ts
  • apps/server-core/src/app/modules/database/repositories/realm/repository.ts
  • apps/server-core/src/app/modules/database/repositories/robot-permission/repository.ts
  • apps/server-core/src/app/modules/database/repositories/robot-role/repository.ts
  • apps/server-core/src/app/modules/database/repositories/robot/repository.ts
  • apps/server-core/src/app/modules/database/repositories/role-attribute/repository.ts
  • apps/server-core/src/app/modules/database/repositories/role-permission/repository.ts
  • apps/server-core/src/app/modules/database/repositories/role/repository.ts
  • apps/server-core/src/app/modules/database/repositories/scope/repository.ts
  • apps/server-core/src/app/modules/database/repositories/user-attribute/repository.ts
  • apps/server-core/src/app/modules/database/repositories/user-permission/repository.ts
  • apps/server-core/src/app/modules/database/repositories/user-role/repository.ts
  • apps/server-core/src/app/modules/database/repositories/user/repository.ts
  • apps/server-core/src/app/modules/provisioning/index.ts
  • apps/server-core/src/app/modules/provisioning/module.ts
  • apps/server-core/src/app/modules/provisioning/sources/composite/module.ts
  • apps/server-core/src/app/modules/provisioning/sources/default/module.ts
  • apps/server-core/src/app/modules/provisioning/sources/file/module.ts
  • apps/server-core/src/app/modules/provisioning/synchronizer/robot/types.ts
  • apps/server-core/src/app/modules/provisioning/synchronizer/user/types.ts
  • apps/server-core/src/core/entities/types.ts
  • apps/server-core/src/core/index.ts
  • apps/server-core/src/core/provisioning/entities/client/index.ts
  • apps/server-core/src/core/provisioning/entities/client/relations-validator.ts
  • apps/server-core/src/core/provisioning/entities/client/types.ts
  • apps/server-core/src/core/provisioning/entities/client/validator.ts
  • apps/server-core/src/core/provisioning/entities/index.ts
  • apps/server-core/src/core/provisioning/entities/permission/index.ts
  • apps/server-core/src/core/provisioning/entities/permission/types.ts
  • apps/server-core/src/core/provisioning/entities/permission/validator.ts
  • apps/server-core/src/core/provisioning/entities/realm/index.ts
  • apps/server-core/src/core/provisioning/entities/realm/relations-validator.ts
  • apps/server-core/src/core/provisioning/entities/realm/types.ts
  • apps/server-core/src/core/provisioning/entities/realm/validator.ts
  • apps/server-core/src/core/provisioning/entities/robot/index.ts
  • apps/server-core/src/core/provisioning/entities/robot/relations-validator.ts
  • apps/server-core/src/core/provisioning/entities/robot/types.ts
  • apps/server-core/src/core/provisioning/entities/robot/validator.ts
  • apps/server-core/src/core/provisioning/entities/role/index.ts
  • apps/server-core/src/core/provisioning/entities/role/relations-validator.ts
  • apps/server-core/src/core/provisioning/entities/role/types.ts
  • apps/server-core/src/core/provisioning/entities/role/validator.ts
  • apps/server-core/src/core/provisioning/entities/root/index.ts
  • apps/server-core/src/core/provisioning/entities/root/types.ts
  • apps/server-core/src/core/provisioning/entities/root/validator.ts
  • apps/server-core/src/core/provisioning/entities/scope/index.ts
  • apps/server-core/src/core/provisioning/entities/scope/types.ts
  • apps/server-core/src/core/provisioning/entities/scope/validator.ts
  • apps/server-core/src/core/provisioning/entities/types.ts
  • apps/server-core/src/core/provisioning/entities/user/index.ts
  • apps/server-core/src/core/provisioning/entities/user/relations-validator.ts
  • apps/server-core/src/core/provisioning/entities/user/types.ts
  • apps/server-core/src/core/provisioning/entities/user/validator.ts
  • apps/server-core/src/core/provisioning/index.ts
  • apps/server-core/src/core/provisioning/strategy/constants.ts
  • apps/server-core/src/core/provisioning/strategy/index.ts
  • apps/server-core/src/core/provisioning/strategy/normalize.ts
  • apps/server-core/src/core/provisioning/strategy/types.ts
  • apps/server-core/src/core/provisioning/strategy/validator.ts
  • apps/server-core/src/core/provisioning/synchronizer/base.ts
  • apps/server-core/src/core/provisioning/synchronizer/client/index.ts
  • apps/server-core/src/core/provisioning/synchronizer/client/module.ts
  • apps/server-core/src/core/provisioning/synchronizer/client/types.ts
  • apps/server-core/src/core/provisioning/synchronizer/index.ts
  • apps/server-core/src/core/provisioning/synchronizer/permission/index.ts
  • apps/server-core/src/core/provisioning/synchronizer/permission/module.ts
  • apps/server-core/src/core/provisioning/synchronizer/permission/types.ts
  • apps/server-core/src/core/provisioning/synchronizer/realm/index.ts
  • apps/server-core/src/core/provisioning/synchronizer/realm/module.ts
  • apps/server-core/src/core/provisioning/synchronizer/realm/types.ts
  • apps/server-core/src/core/provisioning/synchronizer/robot/index.ts
  • apps/server-core/src/core/provisioning/synchronizer/robot/module.ts
  • apps/server-core/src/core/provisioning/synchronizer/robot/types.ts
  • apps/server-core/src/core/provisioning/synchronizer/role/index.ts
  • apps/server-core/src/core/provisioning/synchronizer/role/module.ts
  • apps/server-core/src/core/provisioning/synchronizer/role/types.ts
  • apps/server-core/src/core/provisioning/synchronizer/root/index.ts
  • apps/server-core/src/core/provisioning/synchronizer/root/module.ts
  • apps/server-core/src/core/provisioning/synchronizer/root/types.ts
  • apps/server-core/src/core/provisioning/synchronizer/scope/index.ts
  • apps/server-core/src/core/provisioning/synchronizer/scope/module.ts
  • apps/server-core/src/core/provisioning/synchronizer/scope/types.ts
  • apps/server-core/src/core/provisioning/synchronizer/user/index.ts
  • apps/server-core/src/core/provisioning/synchronizer/user/module.ts
  • apps/server-core/src/core/provisioning/synchronizer/user/types.ts
  • apps/server-core/src/core/provisioning/types.ts
  • provisioning-refactor-plan.md
💤 Files with no reviewable changes (2)
  • apps/server-core/src/app/modules/provisioning/synchronizer/user/types.ts
  • apps/server-core/src/app/modules/provisioning/synchronizer/robot/types.ts

Comment thread provisioning-refactor-plan.md Outdated
Comment on lines +19 to +39
```
app/modules/provisioning/
module.ts ← ProvisionerModule (orchestration + wiring)
types.ts ← IProvisioningSource, shared types
synchronizer/
base.ts ← IProvisioningSynchronizer, BaseProvisioningSynchronizer
permission/module.ts, types.ts
role/module.ts, types.ts
client/module.ts, types.ts
user/module.ts, types.ts
robot/module.ts, types.ts
realm/module.ts, types.ts
scope/module.ts, types.ts
root/module.ts, types.ts ← GraphProvisioningSynchronizer
entities/ ← provisioning entity types
strategy/ ← strategy types, normalize, validator
sources/
default/module.ts ← DefaultProvisioningSource
file/module.ts ← FileProvisioningSource
composite/module.ts ← CompositeProvisioningSource
```

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Add fence languages for markdownlint MD040 compliance.

Two fenced blocks are missing language identifiers; this is currently flagged by markdownlint.

🧩 Proposed fix
-```
+```text
 app/modules/provisioning/
   module.ts                         ← ProvisionerModule (orchestration + wiring)
   types.ts                          ← IProvisioningSource, shared types
@@
   sources/
     default/module.ts               ← DefaultProvisioningSource
     file/module.ts                  ← FileProvisioningSource
     composite/module.ts             ← CompositeProvisioningSource

@@
- +text
core/provisioning/ ← NEW: business logic
synchronizer/
base.ts ← IProvisioningSynchronizer, BaseProvisioningSynchronizer
@@
app/modules/provisioning/ ← orchestration only
module.ts ← ProvisionerModule wires adapters to core synchronizers
sources/ ← source implementations (default, file, composite)

Also applies to: 65-86

🧰 Tools
🪛 markdownlint-cli2 (0.21.0)

[warning] 19-19: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@provisioning-refactor-plan.md` around lines 19 - 39, The markdown has fenced
code blocks without language identifiers in provisioning-refactor-plan.md (the
blocks listing the tree starting with "app/modules/provisioning/" and the
subsequent block starting with "core/provisioning/"); add a language tag (e.g.,
```text) after the opening triple backticks for those two blocks and any other
similar fences (notably the occurrences around lines 65-86) so markdownlint
MD040 is satisfied, preserving the exact block contents including paths like
"app/modules/provisioning/" and "core/provisioning/".

@tada5hi tada5hi changed the title feat: split provisioning module in bootstraping and buisness logic refactor: deduplicate provisioning synchronizers and improve module wiring Mar 13, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (4)
apps/server-core/src/core/provisioning/strategy/validator.ts (1)

37-42: Type declaration mismatch with validated values.

The altContainer is typed as Container<ProvisioningEntityReplaceStrategy>, but it now validates 'replace', 'createOnly', and 'absent' types. This creates a type inconsistency since ProvisioningEntityReplaceStrategy only has type: 'replace'.

Consider using a union type that accurately represents all validated strategies:

Suggested fix
+import type { ProvisioningEntityMergeStrategy, ProvisioningEntityReplaceStrategy, ProvisioningEntityStrategy, ProvisioningEntityCreateOnlyStrategy, ProvisioningEntityAbsentStrategy } from './types.ts';
...
-        const altContainer = new Container<ProvisioningEntityReplaceStrategy>();
+        const altContainer = new Container<ProvisioningEntityReplaceStrategy | ProvisioningEntityCreateOnlyStrategy | ProvisioningEntityAbsentStrategy>();
         altContainer.mount('type', createValidator(
             z
                 .enum(['replace', 'createOnly', 'absent']),
         ));
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/core/provisioning/strategy/validator.ts` around lines 37
- 42, The altContainer is declared as
Container<ProvisioningEntityReplaceStrategy> but the validator
(z.enum(['replace','createOnly','absent'])) accepts three strategy types; update
the generic type to match the validated union (e.g.,
Container<ProvisioningEntityReplaceStrategy |
ProvisioningEntityCreateOnlyStrategy | ProvisioningEntityAbsentStrategy> or
declare a single union type like ProvisioningEntityStrategy =
ProvisioningEntityReplaceStrategy | ...), then use that union in the Container
generic where altContainer is created and ensure any downstream uses of
mount/altContainer align with the new union type.
apps/server-core/src/app/modules/provisioning/sources/composite/module.ts (1)

26-26: Use .forEach() instead of .map() when ignoring the return value.

The merge method is called for its side effects only; the mapped array is discarded. Using .forEach() clarifies intent and avoids allocating an unused array.

Suggested fix
-        sourcesData.map((sourceData) => this.merge(output, sourceData));
+        sourcesData.forEach((sourceData) => this.merge(output, sourceData));
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/app/modules/provisioning/sources/composite/module.ts` at
line 26, The code calls sourcesData.map(...) solely for side effects by invoking
this.merge(output, sourceData) and discards the returned array; change the call
to use sourcesData.forEach(sourceData => this.merge(output, sourceData)) so no
unused array is allocated and intent is clear—update the invocation that
currently uses .map(...) and keep the this.merge(...) call unchanged.
apps/server-core/src/core/provisioning/synchronizer/client/module.ts (1)

147-165: Direct mutation of input objects.

The map callbacks mutate child.attributes directly, which modifies the original input.relations.permissions and input.relations.roles arrays. If the input object is reused or referenced elsewhere, this could cause unexpected side effects.

Consider shallow-cloning before mutation
         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);
         }

Apply the same pattern to the roles block.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/core/provisioning/synchronizer/client/module.ts` around
lines 147 - 165, The code directly mutates input.relations children inside the
map callbacks, causing side effects; fix by shallow-cloning each child and its
attributes before adding client_id and client, e.g. construct a newChild with
{...child, attributes: {...child.attributes, client_id: attributes.id, client:
attributes}} and use those newChild objects when calling
permissionSynchronizer.synchronizeMany and roleSynchronizer.synchronizeMany so
the original input.relations.permissions and input.relations.roles are not
modified.
apps/server-core/src/core/provisioning/synchronizer/user/module.ts (1)

127-144: Resolve client names once and reuse the lookup for both relation passes.

Both blocks walk client-name keys and call clientRepository.findOneBy(...) one by one. Preloading the referenced clients once and reusing a lookup map would remove duplicated logic and cut a noticeable amount of query traffic here.

Also applies to: 168-185

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/core/provisioning/synchronizer/user/module.ts` around
lines 127 - 144, Both relation blocks repeatedly call clientRepository.findOneBy
for each client name; instead, preload all referenced clients once into a lookup
and reuse it in both passes. Collect the unique client names from
input.relations.clientPermissions (and the other relation block), query
clientRepository for all matching records by names + attributes.realm_id (e.g.,
a findBy or IN-style query), build a map keyed by client.name -> client entity,
then iterate the original keys and use map.get(name) to skip missing clients and
pass client.id into permissionResolver.resolveClient; update both places (the
block using clientRepository.findOneBy and the similar block at the second
occurrence) to use this shared lookup.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/server-core/src/core/provisioning/synchronizer/entity-resolver.ts`:
- Around line 18-36: The methods resolveGlobal, resolveRealm and resolveClient
can receive an empty names array which leads to repository.findManyBy({ name: []
}) and invalid SQL; update each method (resolveGlobal, resolveRealm,
resolveClient) to treat empty arrays the same as undefined by checking if
(!names || names.length === 0) and returning [] early, keep the existing
wildcard check (names.some(el => el === '*')) and then call
repository.findManyBy as before so you avoid passing an empty name array into
TypeORM's In([]).

In
`@apps/server-core/src/core/provisioning/synchronizer/junction-synchronizer.ts`:
- Around line 24-47: The synchronize method in junction-synchronizer.ts
currently only inserts missing junction rows and never removes stale ones;
update synchronize (and use this.ctx.repository) to first load all existing
junction rows for the given owner (query by [this.ctx.ownerKey]: owner.id),
build a set of desired target ids from the incoming targets array, diff the
existing rows to: (1) delete any existing rows whose [targetKey] is not in the
desired set (use repository.delete or repository.remove for those entities), and
(2) then insert only the missing target ids as it already does, making sure to
preserve realm fields ([this.ctx.ownerRealmKey] and [targetRealmKey]) when
creating new entities. Ensure the operations reference the same unique symbols:
synchronize, this.ctx.ownerKey, this.ctx.ownerRealmKey, targetKey,
targetRealmKey, and this.ctx.repository.

In `@apps/server-core/src/core/provisioning/synchronizer/user/module.ts`:
- Around line 97-103: The REPLACE branch for
ProvisioningEntityStrategyType.REPLACE currently sets input.attributes.email =
buildUserFakeEmail(...) whenever the incoming source omits email, which can
overwrite a real stored email; instead preserve the existing stored email if
present. Modify the logic in the REPLACE handler (around
ProvisioningEntityStrategyType.REPLACE) to check attributes.email (the current
stored email) before assigning a fake one: only call
buildUserFakeEmail(input.attributes.name) if neither input.attributes.email nor
attributes.email exist. Ensure you still set input.attributes.id = attributes.id
and then call
this.userRepository.save(this.userRepository.create(input.attributes)).

---

Nitpick comments:
In `@apps/server-core/src/app/modules/provisioning/sources/composite/module.ts`:
- Line 26: The code calls sourcesData.map(...) solely for side effects by
invoking this.merge(output, sourceData) and discards the returned array; change
the call to use sourcesData.forEach(sourceData => this.merge(output,
sourceData)) so no unused array is allocated and intent is clear—update the
invocation that currently uses .map(...) and keep the this.merge(...) call
unchanged.

In `@apps/server-core/src/core/provisioning/strategy/validator.ts`:
- Around line 37-42: The altContainer is declared as
Container<ProvisioningEntityReplaceStrategy> but the validator
(z.enum(['replace','createOnly','absent'])) accepts three strategy types; update
the generic type to match the validated union (e.g.,
Container<ProvisioningEntityReplaceStrategy |
ProvisioningEntityCreateOnlyStrategy | ProvisioningEntityAbsentStrategy> or
declare a single union type like ProvisioningEntityStrategy =
ProvisioningEntityReplaceStrategy | ...), then use that union in the Container
generic where altContainer is created and ensure any downstream uses of
mount/altContainer align with the new union type.

In `@apps/server-core/src/core/provisioning/synchronizer/client/module.ts`:
- Around line 147-165: The code directly mutates input.relations children inside
the map callbacks, causing side effects; fix by shallow-cloning each child and
its attributes before adding client_id and client, e.g. construct a newChild
with {...child, attributes: {...child.attributes, client_id: attributes.id,
client: attributes}} and use those newChild objects when calling
permissionSynchronizer.synchronizeMany and roleSynchronizer.synchronizeMany so
the original input.relations.permissions and input.relations.roles are not
modified.

In `@apps/server-core/src/core/provisioning/synchronizer/user/module.ts`:
- Around line 127-144: Both relation blocks repeatedly call
clientRepository.findOneBy for each client name; instead, preload all referenced
clients once into a lookup and reuse it in both passes. Collect the unique
client names from input.relations.clientPermissions (and the other relation
block), query clientRepository for all matching records by names +
attributes.realm_id (e.g., a findBy or IN-style query), build a map keyed by
client.name -> client entity, then iterate the original keys and use
map.get(name) to skip missing clients and pass client.id into
permissionResolver.resolveClient; update both places (the block using
clientRepository.findOneBy and the similar block at the second occurrence) to
use this shared lookup.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 8bdda12b-5682-4988-a9e5-558372c5fedc

📥 Commits

Reviewing files that changed from the base of the PR and between 5cc050c and e38f969.

📒 Files selected for processing (16)
  • apps/server-core/src/app/modules/provisioning/module.ts
  • apps/server-core/src/app/modules/provisioning/sources/composite/module.ts
  • apps/server-core/src/core/provisioning/strategy/constants.ts
  • apps/server-core/src/core/provisioning/strategy/types.ts
  • apps/server-core/src/core/provisioning/strategy/validator.ts
  • apps/server-core/src/core/provisioning/synchronizer/client/module.ts
  • apps/server-core/src/core/provisioning/synchronizer/entity-resolver.ts
  • apps/server-core/src/core/provisioning/synchronizer/index.ts
  • apps/server-core/src/core/provisioning/synchronizer/junction-synchronizer.ts
  • apps/server-core/src/core/provisioning/synchronizer/permission/module.ts
  • apps/server-core/src/core/provisioning/synchronizer/realm/module.ts
  • apps/server-core/src/core/provisioning/synchronizer/robot/module.ts
  • apps/server-core/src/core/provisioning/synchronizer/robot/types.ts
  • apps/server-core/src/core/provisioning/synchronizer/role/module.ts
  • apps/server-core/src/core/provisioning/synchronizer/scope/module.ts
  • apps/server-core/src/core/provisioning/synchronizer/user/module.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/server-core/src/core/provisioning/synchronizer/robot/types.ts

Comment on lines +24 to +47
async synchronize(
owner: { id: string, realm_id?: string | null },
targets: Array<{ id: string, realm_id?: string | null }>,
targetKey: string,
targetRealmKey: string,
): Promise<void> {
for (let i = 0; i < targets.length; i++) {
const target = targets[i];

const existing = await this.ctx.repository.findOneBy({
[this.ctx.ownerKey]: owner.id,
[targetKey]: target.id,
});

if (!existing) {
const entity = this.ctx.repository.create({
[this.ctx.ownerKey]: owner.id,
[this.ctx.ownerRealmKey]: owner.realm_id,
[targetKey]: target.id,
[targetRealmKey]: target.realm_id,
} as Partial<T>);

await this.ctx.repository.save(entity);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Prune stale junction rows instead of only inserting missing ones.

This helper never removes links when the desired targets set shrinks. After a provisioning change drops a role or permission, RoleProvisioningSynchronizer, UserProvisioningSynchronizer, and RobotProvisioningSynchronizer will leave the old junction row behind, so the effective access set drifts away from the source of truth. Load the existing rows for the owner, diff them against targets, remove extras, then insert the missing ones.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/core/provisioning/synchronizer/junction-synchronizer.ts`
around lines 24 - 47, The synchronize method in junction-synchronizer.ts
currently only inserts missing junction rows and never removes stale ones;
update synchronize (and use this.ctx.repository) to first load all existing
junction rows for the given owner (query by [this.ctx.ownerKey]: owner.id),
build a set of desired target ids from the incoming targets array, diff the
existing rows to: (1) delete any existing rows whose [targetKey] is not in the
desired set (use repository.delete or repository.remove for those entities), and
(2) then insert only the missing target ids as it already does, making sure to
preserve realm fields ([this.ctx.ownerRealmKey] and [targetRealmKey]) when
creating new entities. Ensure the operations reference the same unique symbols:
synchronize, this.ctx.ownerKey, this.ctx.ownerRealmKey, targetKey,
targetRealmKey, and this.ctx.repository.

@tada5hi

tada5hi commented Mar 13, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Mar 13, 2026

Copy link
Copy Markdown
✅ Actions performed

Review triggered.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
apps/server-core/src/core/provisioning/synchronizer/entity-resolver.ts (1)

18-76: Extract shared resolution flow to reduce triplicated logic.

resolveGlobal, resolveRealm, and resolveClient repeat the same control flow. A small helper would keep this easier to maintain.

♻️ Proposed refactor
 export class ProvisioningEntityResolver<T extends ObjectLiteral = ObjectLiteral> {
     protected repository: IEntityRepository<T>;
@@
+    protected resolveByScope(
+        names: string[] | undefined,
+        scope: Record<string, string | null>,
+    ) : Promise<T[]> | T[] {
+        if (!names || names.length === 0) {
+            return [];
+        }
+
+        const hasWildcard = names.some((el) => el === '*');
+        if (hasWildcard) {
+            return this.repository.findManyBy(scope);
+        }
+
+        return this.repository.findManyBy({
+            ...scope,
+            name: names,
+        });
+    }
+
     async resolveGlobal(names?: string[]): Promise<T[]> {
-        if (!names || names.length === 0) {
-            return [];
-        }
-
-        const hasWildcard = names.some((el) => el === '*');
-        if (hasWildcard) {
-            return this.repository.findManyBy({
-                realm_id: null,
-                client_id: null,
-            });
-        }
-
-        return this.repository.findManyBy({
-            name: names,
-            realm_id: null,
-            client_id: null,
-        });
+        return this.resolveByScope(names, {
+            realm_id: null,
+            client_id: null,
+        });
     }
@@
     async resolveRealm(names: string[] | undefined, realmId: string): Promise<T[]> {
-        if (!names || names.length === 0) {
-            return [];
-        }
-
-        const hasWildcard = names.some((el) => el === '*');
-        if (hasWildcard) {
-            return this.repository.findManyBy({
-                realm_id: realmId,
-                client_id: null,
-            });
-        }
-
-        return this.repository.findManyBy({
-            name: names,
-            realm_id: realmId,
-            client_id: null,
-        });
+        return this.resolveByScope(names, {
+            realm_id: realmId,
+            client_id: null,
+        });
     }
@@
     async resolveClient(names: string[] | undefined, realmId: string, clientId: string): Promise<T[]> {
-        if (!names || names.length === 0) {
-            return [];
-        }
-
-        const hasWildcard = names.some((el) => el === '*');
-        if (hasWildcard) {
-            return this.repository.findManyBy({
-                realm_id: realmId,
-                client_id: clientId,
-            });
-        }
-
-        return this.repository.findManyBy({
-            name: names,
-            realm_id: realmId,
-            client_id: clientId,
-        });
+        return this.resolveByScope(names, {
+            realm_id: realmId,
+            client_id: clientId,
+        });
     }
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/core/provisioning/synchronizer/entity-resolver.ts`
around lines 18 - 76, The three methods resolveGlobal, resolveRealm, and
resolveClient duplicate the same control flow (empty-name guard, wildcard check,
then repository.findManyBy with differing realm_id/client_id); extract a small
helper (e.g., resolveByScope or buildAndResolve) that accepts (names?: string[],
realmId: string | null, clientId: string | null) and encapsulates the
empty-array return, wildcard detection, and the call to
this.repository.findManyBy with the constructed { name, realm_id, client_id }
filter; then simplify resolveGlobal/resolveRealm/resolveClient to call that
helper with appropriate null or provided realmId/clientId values, leaving
repository.findManyBy as the sole DB call location.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@apps/server-core/src/core/provisioning/synchronizer/entity-resolver.ts`:
- Around line 18-76: The three methods resolveGlobal, resolveRealm, and
resolveClient duplicate the same control flow (empty-name guard, wildcard check,
then repository.findManyBy with differing realm_id/client_id); extract a small
helper (e.g., resolveByScope or buildAndResolve) that accepts (names?: string[],
realmId: string | null, clientId: string | null) and encapsulates the
empty-array return, wildcard detection, and the call to
this.repository.findManyBy with the constructed { name, realm_id, client_id }
filter; then simplify resolveGlobal/resolveRealm/resolveClient to call that
helper with appropriate null or provided realmId/clientId values, leaving
repository.findManyBy as the sole DB call location.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: b8926294-82b1-42e5-b179-cf1f084642e9

📥 Commits

Reviewing files that changed from the base of the PR and between e38f969 and b3b9faa.

📒 Files selected for processing (2)
  • apps/server-core/src/core/provisioning/synchronizer/entity-resolver.ts
  • apps/server-core/src/core/provisioning/synchronizer/user/module.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/server-core/src/core/provisioning/synchronizer/user/module.ts

@tada5hi

tada5hi commented Mar 13, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@tada5hi tada5hi closed this Mar 13, 2026
@tada5hi tada5hi reopened this Mar 13, 2026
@tada5hi

tada5hi commented Mar 13, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Mar 13, 2026

Copy link
Copy Markdown
✅ Actions performed

Review triggered.

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

1 similar comment
@coderabbitai

coderabbitai Bot commented Mar 13, 2026

Copy link
Copy Markdown
✅ Actions performed

Review triggered.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
.agents/architecture.md (1)

221-224: Consider adding context for synchronizer class names.

The section references GraphProvisioningSynchronizer and RealmProvisioningSynchronizer without introducing them. Readers may find it helpful to know these are orchestrator classes (or where they're defined in the file structure).

📝 Optional documentation enhancement

Consider adding a brief introduction before listing the order:

 ### Synchronization Order
 
+The system uses two orchestrator classes to coordinate synchronization:
+
 `GraphProvisioningSynchronizer` processes: permissions → roles → scopes → realms.
 `RealmProvisioningSynchronizer` processes per realm: clients → permissions → roles → users → robots → scopes.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In @.agents/architecture.md around lines 221 - 224, Add a short introductory
sentence before the "Synchronization Order" list that identifies
GraphProvisioningSynchronizer and RealmProvisioningSynchronizer as orchestrator
classes responsible for coordinating provisioning flows (e.g., permissions,
roles, scopes, realms and per-realm clients, users, robots, etc.), and note that
these class definitions live in the codebase (referenced by their class names
GraphProvisioningSynchronizer and RealmProvisioningSynchronizer) so readers know
where to look for implementation details.
docs/src/guide/deployment/provisioning.md (1)

41-54: Add a short warning that example secrets are placeholders.

The sample uses literal credentials (changeme, my-secret, bot-secret). A one-line caution helps prevent unsafe copy/paste into production.

📝 Suggested addition
 ## File-Based Provisioning
 
 Place one or more provisioning files in a directory and point the server to it.
 Supported formats: `.json`, `.yaml`, `.yml`, `.ts`, `.mts`, `.mjs`, `.js`.
+
+> ⚠️ Secrets/passwords shown below are examples only. Use secure values from your secret manager in real deployments.

Also applies to: 88-88

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/src/guide/deployment/provisioning.md` around lines 41 - 54, Add a
one-line warning above the example block stating that the shown credentials are
placeholders and must be replaced with secure secrets before use; specifically
call out the example attributes/passwords (e.g., attributes: { name: 'alice',
password: 'changeme' }, client secret 'my-secret', robot secret 'bot-secret') so
readers know not to copy them into production, and add the same warning near the
other identical example instance.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@docs/src/guide/deployment/provisioning.md`:
- Around line 294-297: The documentation lists the global sync order
incorrectly; update the provisioning doc list so the global synchronization
order matches the implementation in the synchronizer root module
(apps/server-core/src/core/provisioning/synchronizer/root/module.ts) which
processes permissions → roles → scopes → realms — change the numbered list to:
1. Permissions (global) 2. Roles (global, with permission assignments) 3. Scopes
(global) 4. Realms, then for each realm.

---

Nitpick comments:
In @.agents/architecture.md:
- Around line 221-224: Add a short introductory sentence before the
"Synchronization Order" list that identifies GraphProvisioningSynchronizer and
RealmProvisioningSynchronizer as orchestrator classes responsible for
coordinating provisioning flows (e.g., permissions, roles, scopes, realms and
per-realm clients, users, robots, etc.), and note that these class definitions
live in the codebase (referenced by their class names
GraphProvisioningSynchronizer and RealmProvisioningSynchronizer) so readers know
where to look for implementation details.

In `@docs/src/guide/deployment/provisioning.md`:
- Around line 41-54: Add a one-line warning above the example block stating that
the shown credentials are placeholders and must be replaced with secure secrets
before use; specifically call out the example attributes/passwords (e.g.,
attributes: { name: 'alice', password: 'changeme' }, client secret 'my-secret',
robot secret 'bot-secret') so readers know not to copy them into production, and
add the same warning near the other identical example instance.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 7f772514-45d8-4703-954f-9238cf12ef74

📥 Commits

Reviewing files that changed from the base of the PR and between b3b9faa and 91a883d.

📒 Files selected for processing (5)
  • .agents/architecture.md
  • AGENTS.md
  • docs/src/.vitepress/config.mjs
  • docs/src/guide/contributing/database-seeds.md
  • docs/src/guide/deployment/provisioning.md
💤 Files with no reviewable changes (1)
  • docs/src/guide/contributing/database-seeds.md
✅ Files skipped from review due to trivial changes (1)
  • AGENTS.md

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature: Default Provisioning Source Feature(server-core): Entity Resolver

1 participant