Skip to content

feat: policy-based realm scoping and global entity support - #2928

Merged
tada5hi merged 25 commits into
masterfrom
2926-realm-scoping
Mar 24, 2026
Merged

tada5hi merged 25 commits into
masterfrom
2926-realm-scoping

Conversation

@tada5hi

@tada5hi tada5hi commented Mar 21, 2026 •

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • New Features

    • Permissions support multiple attached policies with per-permission decision strategy.
    • Permission Policies management API and UI; new “Policies” tab on permission pages and assignment controls.
  • Improvements

    • Added realm-scoped realm_admin role and system policies to better constrain admin scope (realm-bound / realm-or-global).
    • File-based provisioning from server writable directory; role provisioning supports exclusions and per-assignment policy selection.
  • Changes

    • Permission API/SDK/docs renamed from “Checker” to “Evaluator” and adapted accordingly.

@coderabbitai

coderabbitai Bot commented Mar 21, 2026 •

Copy link
Copy Markdown

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

Refactors permissions to an n:m permission–policy model (PermissionPolicy / PermissionBinding), renames PermissionChecker→PermissionEvaluator, migrates APIs/fields to snake_case, adds IdentityPermissionProvider and PermissionDatabaseProvider, introduces permission-policy controllers/UI/APIs, and updates repositories, services, tests, and docs.

Changes

Cohort / File(s) Summary
Domain model & DB entities
apps/server-core/src/adapters/database/domains/permission/entity.ts, apps/server-core/src/adapters/database/domains/permission-policy/entity.ts, packages/core-kit/src/domains/permission/entity.ts, packages/core-kit/src/domains/permission-policy/*, apps/server-core/src/adapters/database/domains/index.ts
Add PermissionPolicy entity/type; remove permission->policy single FK; add Permission.decision_strategy; re-export permission-policy domain.
Permission provider & DB lookup
apps/server-core/src/security/permission/provider/db.ts, apps/server-core/src/app/modules/database/repositories/permission-provider/module.ts
New PermissionDatabaseProvider and provider findOne returning PermissionBinding with policies[]; use snake_case criteria (client_id/realm_id); load junction rows and descendant policy trees.
Permission repository adapters
apps/server-core/src/app/modules/database/repositories/permission-policy/repository.ts, .../index.ts
Add PermissionPolicyRepositoryAdapter (CRUD, findMany, validateJoinColumns) and index export.
Binding types & helpers
packages/access/src/permission/types.ts, .../helpers/key.ts, .../helpers/equal.ts, .../helpers/merge.ts
Replace PermissionItem→PermissionBinding (nested permission + policies[]); add buildPermissionBindingKey; update equality and merge logic to operate on bindings and composite policies.
Evaluator API & in-memory provider
packages/access/src/permission/checker/module.ts, .../types.ts, packages/access/src/permission/repository/memory.ts
Rename PermissionChecker→PermissionEvaluator, IPermissionRepository→IPermissionProvider; rename methods (check→evaluate, preCheck→preEvaluate); memory provider now handles PermissionBinding and snake_case options.
Policy built-ins and validators
packages/access/src/policy/built-in/...
Migrate built-in policy config keys to snake_case (decision_strategy, attribute_name, day_of_week, etc.), add REALM_BOUND/REALM_OR_GLOBAL constants, and update validators/evaluators to use new keys.
Identity permission provider & types
apps/server-core/src/core/identity/permission/module.ts, .../types.ts, .../index.ts
Add IdentityPermissionProvider and interfaces: getFor, isSuperset, resolveJunctionPolicy; provider composes/merges bindings and enforces policy-aware superset rules.
Policy engine & evaluator integration
apps/server-core/src/core/security/policy/engine.ts, .../evaluator.ts, .../index.ts
PolicyEngine now requires IIdentityPermissionProvider; PermissionBindingPolicyEvaluator refactored to use provider and operate on PermissionBinding/policies arrays.
Bound-permission repositories
apps/server-core/src/adapters/database/domains/{client,user,robot,role}/repository.ts, apps/server-core/src/adapters/database/domains/policy/repository.ts
getBoundPermissions now returns PermissionBinding[], attaches policy descendant trees via findDescendantsTreeById and private loadPolicyTrees.
Services & business logic
apps/server-core/src/core/entities/permission/service.ts, many apps/server-core/src/core/entities/* files
Switch services to use actor.permissionEvaluator.*; remove single-default-policy backfill; add post-create junction assignment and admin-role assignment flows; adjust realm defaulting behavior.
Provisioning & synchronizers
apps/server-core/src/app/modules/provisioning/*, apps/server-core/src/core/provisioning/synchronizer/*
Stop injecting default policy_id on create; add file-based provisioning source; junction synchronizer accepts extraAttributes to pass policy_id into created junction rows; role provisioning supports globalPermissionsExclude and globalPermissionsPolicyName/overrides.
Controllers, HTTP wiring & middleware
apps/server-core/src/adapters/http/controllers/**/permission*, .../permission-policy/*, apps/server-core/src/adapters/http/request/permission/*, .../middleware/*
Add PermissionPolicyController endpoints and client UI wiring; replace IdentityPermissionService usages with IIdentityPermissionProvider; introduce RequestPermissionEvaluator, set/get helpers, and initialize middleware with PermissionDatabaseProvider + identityPermissionProvider.
Client UI & HTTP APIs
packages/client-web-kit/src/components/entities/permission-policy/*, apps/client-web/pages/permissions/[id]/policies.vue, packages/core-http-kit/src/domains/entities/permission-policy/*, packages/core-http-kit/src/client/module.ts
Add permission-policy UI components and page; add PermissionPolicyAPI and client permissionPolicy property; client store uses PermissionMemoryProvider and binding-shaped cache.
Tests & docs
packages/access/test/*, apps/server-core/test/*, docs/src/*
Update unit tests to use PermissionEvaluator and PermissionBinding shapes; add merge/escalation tests; update docs for junction model, snake_case keys, new system policies, and provisioning guidance.
Barrels & exports
multiple index.ts files across apps/packages
Add/adjust re-exports for permission-policy and identity-permission, remove or reshape old security/policy barrels to reflect new modules and exports.

Sequence Diagram(s)

sequenceDiagram
    participant Client as HTTP Client
    participant Controller as PermissionController
    participant Service as PermissionService
    participant Evaluator as PermissionEvaluator
    participant Provider as PermissionDatabaseProvider
    participant PolicyEngine as PolicyEngine

    Client->>Controller: POST /permission (actor, data)
    Controller->>Service: create(data, actor)
    Service->>Evaluator: preEvaluate({ name, input })
    Evaluator->>Provider: findOne({ name, client_id?, realm_id? })
    Provider->>PolicyEngine: return PermissionBinding (permission + policies[])
    Evaluator->>PolicyEngine: evaluate(binding.policies, binding.permission.decision_strategy)
    PolicyEngine-->>Evaluator: allow/deny
    Evaluator-->>Service: result (allow or throw)
    alt allowed
        Service->>Service: persist and assign roles/junctions
        Controller-->>Client: 201 Created
    else denied
        Controller-->>Client: 403 Forbidden
    end
Loading
sequenceDiagram
    participant RoleSync as RoleProvisioningSynchronizer
    participant PolicyRepo as PolicyRepository
    participant JunctionSync as ProvisioningJunctionSynchronizer
    participant DB as Database

    RoleSync->>RoleSync: resolve globalPermissions (wildcard)
    RoleSync->>RoleSync: apply globalPermissionsExclude
    alt globalPermissionsPolicyName provided
        RoleSync->>PolicyRepo: findOneByName(policyName)
        PolicyRepo-->>RoleSync: policy
        RoleSync->>JunctionSync: synchronize(junction, extraAttributes={policy_id})
    else
        RoleSync->>JunctionSync: synchronize(junction)
    end
    JunctionSync->>DB: create/update junction rows (including extraAttributes)
    JunctionSync-->>RoleSync: done
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related PRs

Poem

🐇 I hopped through code where junctions grow,

Policies braided in a tidy row.
Evaluator hums as bindings unite,
Realm-bound guards keep privileges right.
A rabbit cheers — permissions take flight!

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch 2926-realm-scoping

@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: 4

Caution

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

⚠️ Outside diff range comments (1)
apps/server-core/src/adapters/database/domains/permission/subscriber.ts (1)

94-104: ⚠️ Potential issue | 🟠 Major

Use the same Redis key wrapper in afterRemove as in afterUpdate.

afterRemove currently removes a raw buildPermissionItemKey(...) string, while the update path removes buildRedisKeyPath({ prefix, key: buildPermissionItemKey(...) }). This mismatch can miss cache invalidation for deleted permissions.

Proposed fix
         if (event.connection.queryResultCache) {
             await event.connection.queryResultCache.remove([
                 buildRedisKeyPath({
                     prefix: CachePrefix.PERMISSION,
                     key: event.entity.id,
                 }),
-                buildPermissionItemKey({
-                    name: event.entity.name,
-                    client_id: event.entity.client_id,
-                    realm_id: event.entity.realm_id,
-                }),
+                buildRedisKeyPath({
+                    prefix: CachePrefix.PERMISSION,
+                    key: buildPermissionItemKey({
+                        name: event.entity.name,
+                        client_id: event.entity.client_id,
+                        realm_id: event.entity.realm_id,
+                    }),
+                }),
             ]);
         }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/adapters/database/domains/permission/subscriber.ts`
around lines 94 - 104, afterRemove is removing the raw
buildPermissionItemKey(...) string while afterUpdate removes the wrapped key via
buildRedisKeyPath({ prefix: CachePrefix.PERMISSION, key: ... }), causing
inconsistent cache invalidation; update afterRemove (in subscriber.ts) to call
buildRedisKeyPath with CachePrefix.PERMISSION and the
buildPermissionItemKey(...) result (same wrapper used in afterUpdate) when
calling event.connection.queryResultCache.remove so both delete paths target the
identical Redis key format.
🧹 Nitpick comments (1)
packages/access/src/policy/built-in/time/evaluator.ts (1)

91-100: Property access correctly updated to snake_case.

The evaluator correctly uses policy.day_of_week matching the updated TimePolicy interface.

However, note a pre-existing issue: the truthy guard policy.day_of_week on line 93 will be falsy when day_of_week is 0 (Sunday), causing Sunday restrictions to be skipped. Consider using an explicit check like policy.day_of_week !== undefined && policy.day_of_week !== null if Sunday enforcement is needed.

♻️ Optional fix for Sunday handling
         if (
             isIntervalForDayOfWeek(policy.interval) &&
-            policy.day_of_week
+            policy.day_of_week != null
         ) {

Apply the same pattern to day_of_month and day_of_year if 0 is a valid value for those fields.

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

In `@packages/access/src/policy/built-in/time/evaluator.ts` around lines 91 - 100,
The guard `policy.day_of_week` is using a truthy check which fails for valid
value 0 (Sunday); change the condition in the evaluator (around the block
referencing isIntervalForDayOfWeek and policy.day_of_week) to an explicit
presence check like `policy.day_of_week !== undefined && policy.day_of_week !==
null` so Sunday (0) is handled correctly; apply the same explicit null/undefined
pattern for other numeric date fields checked similarly (e.g.,
policy.day_of_month, policy.day_of_year) to avoid skipping valid zero values.
🤖 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/security/policy/variants/permission-binding/evaluator.ts`:
- Around line 109-115: The mapper building items for mergePermissionItems is
setting policyId instead of the expected PermissionItem.policy field, so merged
permissions lose their policy linkage; update the identityPermissions.map to set
policy: raw.policy (not policyId) so mergePermissionItems receives the correct
property and policy constraints are preserved when merging; check the mapping
around identityPermissions and mergePermissionItems to ensure the object uses
name, realm_id, client_id, and policy.

In `@packages/access/src/permission/checker/module.ts`:
- Around line 48-54: The assignments for nullable scope filters (client_id and
realm_id) in module.ts use truthy checks which drop explicit nulls; update the
checks to test for undefined instead (e.g., if (options.client_id !== undefined)
this.client_id = options.client_id) so that null is preserved as a deliberate
value; apply the same change for realm_id and for the other occurrence later in
the file (the second block around lines 75-81 that sets client_id/realm_id) and
any similar assignments in the PermissionChecker/module constructor or methods
to ensure null scoping is not lost.

In `@packages/access/src/policy/built-in/time/types.ts`:
- Around line 30-40: The type change introduced snake_case fields day_of_week,
day_of_month, day_of_year but callers still use camelCase
dayOfWeek/dayOfMonth/dayOfYear, so update the form bindings/validation to accept
or map the camelCase names to the new snake_case properties; find places that
construct/validate time policies (e.g., form handlers, validators or mappers
like buildTimePolicyFromForm / validateTimePolicy / parseTimePolicy or any use
sites that reference dayOfWeek/dayOfMonth/dayOfYear) and either convert incoming
camelCase keys to snake_case or accept both keys, and update tests to cover both
input shapes.

In
`@packages/client-web-kit/src/components/entities/policy/realm-match/ARealmMatchPolicyForm.vue`:
- Around line 44-49: The form assignment logic leaves stale values when a new
input lacks attribute_name; update the block that destructures attribute_name
from input (and calls assignFormProperties) to explicitly reset
form.attribute_name when attribute_name is missing (e.g., set
form.attribute_name = [] if attribute_name is undefined/null) and continue to
convert a provided string to an array when present; adjust the code around
assignFormProperties, input, and form.attribute_name accordingly.

---

Outside diff comments:
In `@apps/server-core/src/adapters/database/domains/permission/subscriber.ts`:
- Around line 94-104: afterRemove is removing the raw
buildPermissionItemKey(...) string while afterUpdate removes the wrapped key via
buildRedisKeyPath({ prefix: CachePrefix.PERMISSION, key: ... }), causing
inconsistent cache invalidation; update afterRemove (in subscriber.ts) to call
buildRedisKeyPath with CachePrefix.PERMISSION and the
buildPermissionItemKey(...) result (same wrapper used in afterUpdate) when
calling event.connection.queryResultCache.remove so both delete paths target the
identical Redis key format.

---

Nitpick comments:
In `@packages/access/src/policy/built-in/time/evaluator.ts`:
- Around line 91-100: The guard `policy.day_of_week` is using a truthy check
which fails for valid value 0 (Sunday); change the condition in the evaluator
(around the block referencing isIntervalForDayOfWeek and policy.day_of_week) to
an explicit presence check like `policy.day_of_week !== undefined &&
policy.day_of_week !== null` so Sunday (0) is handled correctly; apply the same
explicit null/undefined pattern for other numeric date fields checked similarly
(e.g., policy.day_of_month, policy.day_of_year) to avoid skipping valid zero
values.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: e1909987-e838-4483-9cf6-dba33efcf0cc

📥 Commits

Reviewing files that changed from the base of the PR and between 6b83753 and b35173f.

📒 Files selected for processing (26)
  • apps/server-core/src/adapters/database/domains/permission/subscriber.ts
  • apps/server-core/src/app/modules/provisioning/sources/default/module.ts
  • apps/server-core/src/security/permission/provider/db.ts
  • apps/server-core/src/security/policy/variants/permission-binding/evaluator.ts
  • apps/server-core/src/services/identity-permission/module.ts
  • apps/server-core/test/unit/modules/provisioning.spec.ts
  • packages/access/src/permission/checker/module.ts
  • packages/access/src/permission/checker/types.ts
  • packages/access/src/permission/helpers/equal.ts
  • packages/access/src/permission/helpers/key.ts
  • packages/access/src/permission/helpers/merge.ts
  • packages/access/src/permission/repository/types.ts
  • packages/access/src/permission/types.ts
  • packages/access/src/policy/built-in/composite/evaluator.ts
  • packages/access/src/policy/built-in/composite/types.ts
  • packages/access/src/policy/built-in/composite/validator.ts
  • packages/access/src/policy/built-in/realm-match/evaluator.ts
  • packages/access/src/policy/built-in/realm-match/types.ts
  • packages/access/src/policy/built-in/realm-match/validator.ts
  • packages/access/src/policy/built-in/time/evaluator.ts
  • packages/access/src/policy/built-in/time/types.ts
  • packages/access/src/policy/built-in/time/validator.ts
  • packages/access/test/unit/policy/engine.spec.ts
  • packages/access/test/unit/policy/realm-match.spec.ts
  • packages/access/test/unit/policy/time.spec.ts
  • packages/client-web-kit/src/components/entities/policy/realm-match/ARealmMatchPolicyForm.vue

@tada5hi tada5hi changed the title feat: realm socping feat: realm scoping & policy-permission restructuring Mar 21, 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: 2

🧹 Nitpick comments (3)
packages/core-kit/src/domains/permission/entity.ts (1)

37-37: Consider using a stricter type for decision_strategy.

The validator enforces 'affirmative' | 'unanimous' | 'consensus' but the entity type uses string | null. Using a literal union type would provide compile-time safety and better IDE support.

♻️ Proposed type refinement
-    decision_strategy: string | null;
+    decision_strategy: 'affirmative' | 'unanimous' | 'consensus' | null;

Alternatively, extract to a shared type/enum if used elsewhere.

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

In `@packages/core-kit/src/domains/permission/entity.ts` at line 37, The
decision_strategy field currently typed as string | null should be narrowed to
the literal union used by the validator (e.g., 'affirmative' | 'unanimous' |
'consensus' | null) to get compile-time safety; update the decision_strategy
property in the Permission entity (decision_strategy) accordingly, or extract a
shared union/enum type (e.g., PermissionDecisionStrategy) and use that both in
the entity and any validators that reference those same values.
apps/server-core/src/app/modules/http/modules/controller.ts (1)

513-530: Consider removing unnecessary async keyword.

The createPermissionController method is marked async but no longer contains any await expressions after removing the default policy lookup. This could be simplified to a synchronous method.

♻️ Proposed fix
-    async createPermissionController(container: IDIContainer) {
+    createPermissionController(container: IDIContainer) {

Also update the call site at line 167:

-        const permissionController = await this.createPermissionController(container);
+        const permissionController = this.createPermissionController(container);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/app/modules/http/modules/controller.ts` around lines 513
- 530, The createPermissionController function is declared async but contains no
awaits; remove the async modifier from createPermissionController (the factory
that constructs PermissionRepositoryAdapter, RealmRepositoryAdapter,
PermissionService and returns new PermissionController) and update any call
sites that currently await it to call it synchronously (remove the await where
createPermissionController(...) is invoked) so callers no longer expect a
Promise.
apps/server-core/src/core/entities/permission-policy/service.ts (1)

62-81: Consider handling duplicate permission-policy constraint violations.

The create method validates join columns but doesn't check for existing permission-policy pairs before insertion. If a duplicate is inserted, the database will throw a constraint violation due to the composite unique index. Consider catching this and converting to a user-friendly ConflictError or DatabaseConflictError.

♻️ Proposed improvement
+import { DatabaseConflictError } from '../../../adapters/database/index.ts';
+
 async create(
     data: Record<string, any>,
     actor: ActorContext,
 ): Promise<PermissionPolicy> {
     await actor.permissionChecker.preCheck({ name: PermissionName.PERMISSION_UPDATE });

     await this.repository.validateJoinColumns(data);

+    // Check for existing link
+    const existing = await this.repository.findOneBy({
+        permission_id: data.permission_id,
+        policy_id: data.policy_id,
+    });
+    if (existing) {
+        throw new DatabaseConflictError();
+    }

     await actor.permissionChecker.check({
         name: PermissionName.PERMISSION_UPDATE,
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/core/entities/permission-policy/service.ts` around lines
62 - 81, The create method in PermissionPolicy service should guard against
inserting duplicate permission-policy pairs: either first query for an existing
PermissionPolicy using the same join keys (use repository.findOne/findOneBy with
the join column values validated by repository.validateJoinColumns) and throw a
ConflictError/DatabaseConflictError if found, or wrap the repository.save(...)
call in a try/catch and map database unique-constraint errors (e.g., Postgres
23505 or driver-specific duplicate-key code) to a user-friendly ConflictError;
update the create(...) flow (the create method, repository.validateJoinColumns,
and repository.save usage) to implement one of these fixes and return/throw the
standardized conflict error when a composite unique index violation for
PermissionPolicy occurs.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In
`@apps/server-core/src/app/modules/database/repositories/permission-policy/repository.ts`:
- Around line 67-73: The methods findOneByName and findOneByIdOrName on the
PermissionPolicy repository are incorrect because PermissionPolicyEntity has no
"name" field; update them to either implement a meaningful lookup (e.g.,
implement findOneByName to join PermissionPolicyEntity -> PermissionEntity
and/or PolicyEntity and search by permission name and/or policy name using the
relation fields), or if name-based lookup is not applicable, change
findOneByName to throw a clear "not supported" error and make findOneByIdOrName
call findOneById or throw likewise; modify the repository methods findOneByName
and findOneByIdOrName (and, if needed, update the IPermissionPolicyRepository
signature) to reflect the chosen approach.

In `@packages/core-kit/src/domains/permission-policy/entity.ts`:
- Around line 1-3: Add the project's standard copyright header to the top of
this file (packages/core-kit/src/domains/permission-policy/entity.ts) so it
matches other source files; open the file containing the imports (the existing
lines importing Permission and Policy) and insert the same multi-line header
comment used across the codebase immediately above those imports, preserving
formatting and license text exactly as in other files.

---

Nitpick comments:
In `@apps/server-core/src/app/modules/http/modules/controller.ts`:
- Around line 513-530: The createPermissionController function is declared async
but contains no awaits; remove the async modifier from
createPermissionController (the factory that constructs
PermissionRepositoryAdapter, RealmRepositoryAdapter, PermissionService and
returns new PermissionController) and update any call sites that currently await
it to call it synchronously (remove the await where
createPermissionController(...) is invoked) so callers no longer expect a
Promise.

In `@apps/server-core/src/core/entities/permission-policy/service.ts`:
- Around line 62-81: The create method in PermissionPolicy service should guard
against inserting duplicate permission-policy pairs: either first query for an
existing PermissionPolicy using the same join keys (use
repository.findOne/findOneBy with the join column values validated by
repository.validateJoinColumns) and throw a ConflictError/DatabaseConflictError
if found, or wrap the repository.save(...) call in a try/catch and map database
unique-constraint errors (e.g., Postgres 23505 or driver-specific duplicate-key
code) to a user-friendly ConflictError; update the create(...) flow (the create
method, repository.validateJoinColumns, and repository.save usage) to implement
one of these fixes and return/throw the standardized conflict error when a
composite unique index violation for PermissionPolicy occurs.

In `@packages/core-kit/src/domains/permission/entity.ts`:
- Line 37: The decision_strategy field currently typed as string | null should
be narrowed to the literal union used by the validator (e.g., 'affirmative' |
'unanimous' | 'consensus' | null) to get compile-time safety; update the
decision_strategy property in the Permission entity (decision_strategy)
accordingly, or extract a shared union/enum type (e.g.,
PermissionDecisionStrategy) and use that both in the entity and any validators
that reference those same values.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: d4391a97-cb47-405d-9140-4620c9876f91

📥 Commits

Reviewing files that changed from the base of the PR and between b35173f and 53cff4c.

📒 Files selected for processing (34)
  • apps/server-core/src/adapters/database/data-source/options/module.ts
  • apps/server-core/src/adapters/database/domains/index.ts
  • apps/server-core/src/adapters/database/domains/permission-policy/entity.ts
  • apps/server-core/src/adapters/database/domains/permission-policy/index.ts
  • apps/server-core/src/adapters/database/domains/permission/entity.ts
  • apps/server-core/src/adapters/database/domains/permission/subscriber.ts
  • apps/server-core/src/adapters/http/controllers/entities/index.ts
  • apps/server-core/src/adapters/http/controllers/entities/permission-policy/index.ts
  • apps/server-core/src/adapters/http/controllers/entities/permission-policy/module.ts
  • apps/server-core/src/app/modules/database/repositories/index.ts
  • apps/server-core/src/app/modules/database/repositories/permission-policy/index.ts
  • apps/server-core/src/app/modules/database/repositories/permission-policy/repository.ts
  • apps/server-core/src/app/modules/database/repositories/permission/repository.ts
  • apps/server-core/src/app/modules/http/modules/controller.ts
  • apps/server-core/src/app/modules/provisioning/module.ts
  • apps/server-core/src/core/entities/index.ts
  • apps/server-core/src/core/entities/permission-policy/index.ts
  • apps/server-core/src/core/entities/permission-policy/service.ts
  • apps/server-core/src/core/entities/permission-policy/types.ts
  • apps/server-core/src/core/entities/permission/service.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/security/permission/provider/db.ts
  • apps/server-core/src/security/policy/variants/permission-binding/evaluator.ts
  • apps/server-core/src/services/identity-permission/module.ts
  • packages/access/src/permission/checker/module.ts
  • packages/access/src/permission/types.ts
  • packages/access/test/unit/permission/checker.spec.ts
  • packages/core-kit/src/domains/contstants.ts
  • packages/core-kit/src/domains/index.ts
  • packages/core-kit/src/domains/permission-policy/entity.ts
  • packages/core-kit/src/domains/permission-policy/index.ts
  • packages/core-kit/src/domains/permission/entity.ts
  • packages/core-kit/src/domains/permission/validator.ts
💤 Files with no reviewable changes (3)
  • apps/server-core/src/core/provisioning/synchronizer/permission/types.ts
  • apps/server-core/src/core/provisioning/synchronizer/permission/module.ts
  • apps/server-core/src/core/entities/permission/service.ts
✅ Files skipped from review due to trivial changes (10)
  • apps/server-core/src/adapters/http/controllers/entities/index.ts
  • apps/server-core/src/app/modules/database/repositories/index.ts
  • apps/server-core/src/adapters/database/domains/index.ts
  • apps/server-core/src/app/modules/database/repositories/permission-policy/index.ts
  • packages/core-kit/src/domains/index.ts
  • packages/core-kit/src/domains/contstants.ts
  • apps/server-core/src/adapters/database/domains/permission-policy/index.ts
  • apps/server-core/src/core/entities/index.ts
  • apps/server-core/src/core/entities/permission-policy/index.ts
  • packages/core-kit/src/domains/permission-policy/index.ts
🚧 Files skipped from review as they are similar to previous changes (5)
  • apps/server-core/src/adapters/database/domains/permission/subscriber.ts
  • apps/server-core/src/security/policy/variants/permission-binding/evaluator.ts
  • apps/server-core/src/services/identity-permission/module.ts
  • packages/access/src/permission/types.ts
  • apps/server-core/src/security/permission/provider/db.ts

@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

Caution

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

⚠️ Outside diff range comments (2)
packages/access/src/permission/checker/module.ts (1)

135-143: ⚠️ Potential issue | 🔴 Critical

Reject missing policy collections instead of authorizing them.

entity.policies ?? [] conflates “policies were not loaded” with “this permission has no policies”. Because the next branch authorizes an empty set, any repository/serializer miss here becomes a fail-open permission check.

🔒 Suggested hardening
-            const policies = entity.policies ?? [];
-            if (policies.length === 0) {
+            if (typeof entity.policies === 'undefined') {
+                issues.push(defineIssueItem({
+                    code: ErrorCode.PERMISSION_EVALUATION_FAILED,
+                    message: `The ${entity.name} permission policies were not loaded`,
+                    path: [entity.name, 'policies'],
+                }));
+
+                if (decision_strategy === DecisionStrategy.UNANIMOUS) {
+                    const error = PermissionError.evaluationFailed(entity.name);
+                    error.addIssues(issues);
+                    throw error;
+                }
+
+                continue;
+            }
+
+            const policies = entity.policies;
+            if (policies.length === 0) {
                 if (decision_strategy === DecisionStrategy.AFFIRMATIVE) {
                     return;
                 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/access/src/permission/checker/module.ts` around lines 135 - 143, The
code currently uses entity.policies ?? [] which hides “policies not loaded” as
an empty set and allows AFFIRMATIVE decision_strategy to authorize missing data;
change the logic to distinguish undefined from an intentionally empty array:
check if entity.policies === undefined (or null) first and treat that as a
missing-policy failure (increment count/continue or reject) rather than
autorizing, and only apply the existing empty-array handling when
entity.policies is an actual array (i.e. use entity.policies === undefined vs
Array.isArray(entity.policies) and keep the DecisionStrategy.AFFIRMATIVE
behavior only for a real empty array).
apps/server-core/src/core/provisioning/synchronizer/junction-synchronizer.ts (1)

33-47: ⚠️ Potential issue | 🟠 Major

Update existing junction rows when extraAttributes change.

This stopped being convergent once policy_id moved onto the junction. If the row already exists, reruns never backfill or change the new attributes, so old assignments stay stale.

🔧 Suggested fix
             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,
-                    ...(extraAttributes || {}),
-                } as Partial<T>);
-
-                await this.ctx.repository.save(entity);
-            }
+            if (existing) {
+                if (extraAttributes) {
+                    const entity = this.ctx.repository.merge(
+                        existing,
+                        extraAttributes as Partial<T>,
+                    );
+                    await this.ctx.repository.save(entity);
+                }
+                continue;
+            }
+
+            const entity = this.ctx.repository.create({
+                [this.ctx.ownerKey]: owner.id,
+                [this.ctx.ownerRealmKey]: owner.realm_id,
+                [targetKey]: target.id,
+                [targetRealmKey]: target.realm_id,
+                ...(extraAttributes ?? {}),
+            } as Partial<T>);
+
+            await this.ctx.repository.save(entity);
🤖 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 33 - 47, The existing logic creates a junction row but never
updates it when extraAttributes change; modify the branch where `existing` is
truthy to merge and persist attribute changes: load `existing` (the found
entity), compute the new attribute set from `...(extraAttributes || {})` and the
relevant realm/id keys (`this.ctx.ownerKey`, `this.ctx.ownerRealmKey`,
`targetKey`, `targetRealmKey`), compare or assign these updated fields onto
`existing`, and call `this.ctx.repository.save(existing)` so attribute changes
(e.g., `policy_id`) are applied on re-runs instead of left stale.
🧹 Nitpick comments (2)
apps/server-core/src/core/provisioning/entities/role/types.ts (1)

16-24: JSDoc comment is misleading - refers to ID but field holds a name.

The comment says "Policy ID to set" but the field is globalPermissionsPolicyName which holds a policy name that gets resolved to an ID by the synchronizer. Consider updating the documentation to reflect this:

📝 Suggested documentation fix
     /**
-     * Policy ID to set on each role-permission junction entry.
+     * Policy name to resolve and attach to each role-permission junction entry.
      */
     globalPermissionsPolicyName?: string,
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/core/provisioning/entities/role/types.ts` around lines
16 - 24, The JSDoc for the field globalPermissionsPolicyName is misleading (it
says "Policy ID to set") — update the comment above the
globalPermissionsPolicyName property in types.ts to state that this field
contains a policy name (not an ID) and that the synchronizer will resolve this
name to an ID; keep the existing wording for globalPermissionsExclude untouched
but ensure the new comment clearly explains the name→ID resolution performed
elsewhere (synchronizer) so callers know to supply a name.
apps/server-core/test/unit/core/entities/permission/service.spec.ts (1)

119-126: This test still asserts the legacy policy_id shape.

After moving policy binding to a junction, expect(result.policy_id).toBeUndefined() does not really lock down the new contract. It passes both when the field is gone and when legacy policy handling still leaks in elsewhere. I’d rather cover rejected/ignored legacy policy_id input here, or move the assertion to the new permission-policy junction tests.

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

In `@apps/server-core/test/unit/core/entities/permission/service.spec.ts` around
lines 119 - 126, The test currently only checks that result.policy_id is
undefined which doesn't verify legacy input is ignored; update the test around
service.create to pass a legacy policy_id (e.g., call service.create({ name:
'no-policy-perm', policy_id: 'some-id' }, createAllowAllActor())) and assert
that the returned result.policy_id is undefined (or not present) and that no
permission-policy junction was created for this permission (or move this
assertion into the permission-policy junction tests). Target the service.create
call and the result.policy_id check so the spec proves legacy policy_id input is
rejected/ignored rather than accidentally accepted elsewhere.
🤖 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/role/module.ts`:
- Around line 85-95: The current code concatenates global and realm permission
lists before applying global-only filters, so globalPermissionsExclude and
globalPermissionsPolicyName can wrongly remove or mutate realm permissions;
instead, resolve globals via this.permissionResolver.resolveGlobal(...) into a
separate array, apply input.relations.globalPermissionsExclude (using a Set) and
apply input.relations.globalPermissionsPolicyName (set policy_id) only to that
globals array, resolve realm permissions via
this.permissionResolver.resolveRealm(...) separately and leave them unchanged,
then concatenate the two lists into permissions; apply the same separation/fix
to the other block that handles globalPermissionsPolicyName elsewhere in this
module.
- Around line 100-105: If input.relations.globalPermissionsPolicyName is
provided, ensure the provisioner fails fast instead of silently creating
role-permission rows without a policy_id: validate that this.policyRepository
exists and that
this.policyRepository.findOneByName(input.relations.globalPermissionsPolicyName)
returns a policy; if either check fails, throw a descriptive error (e.g.,
mentioning globalPermissionsPolicyName) so provisioning stops rather than
proceeding with missing extraAttributes; update the logic around extraAttributes
assignment (the block using policyRepository, globalPermissionsPolicyName,
policy, and policy.id) to enforce these validations.

In
`@packages/client-web-kit/src/components/entities/policy/time/ATimePolicyForm.vue`:
- Line 203: The day-of-week input placeholder currently shows "0-7" but the
validation for the field (see the validator referenced at line ~55 in
ATimePolicyForm.vue) enforces a max of 6; update the placeholder on the
day-of-week input in ATimePolicyForm.vue from "0-7" to "0-6" so the UI matches
the validation logic and avoids misleading users.

---

Outside diff comments:
In
`@apps/server-core/src/core/provisioning/synchronizer/junction-synchronizer.ts`:
- Around line 33-47: The existing logic creates a junction row but never updates
it when extraAttributes change; modify the branch where `existing` is truthy to
merge and persist attribute changes: load `existing` (the found entity), compute
the new attribute set from `...(extraAttributes || {})` and the relevant
realm/id keys (`this.ctx.ownerKey`, `this.ctx.ownerRealmKey`, `targetKey`,
`targetRealmKey`), compare or assign these updated fields onto `existing`, and
call `this.ctx.repository.save(existing)` so attribute changes (e.g.,
`policy_id`) are applied on re-runs instead of left stale.

In `@packages/access/src/permission/checker/module.ts`:
- Around line 135-143: The code currently uses entity.policies ?? [] which hides
“policies not loaded” as an empty set and allows AFFIRMATIVE decision_strategy
to authorize missing data; change the logic to distinguish undefined from an
intentionally empty array: check if entity.policies === undefined (or null)
first and treat that as a missing-policy failure (increment count/continue or
reject) rather than autorizing, and only apply the existing empty-array handling
when entity.policies is an actual array (i.e. use entity.policies === undefined
vs Array.isArray(entity.policies) and keep the DecisionStrategy.AFFIRMATIVE
behavior only for a real empty array).

---

Nitpick comments:
In `@apps/server-core/src/core/provisioning/entities/role/types.ts`:
- Around line 16-24: The JSDoc for the field globalPermissionsPolicyName is
misleading (it says "Policy ID to set") — update the comment above the
globalPermissionsPolicyName property in types.ts to state that this field
contains a policy name (not an ID) and that the synchronizer will resolve this
name to an ID; keep the existing wording for globalPermissionsExclude untouched
but ensure the new comment clearly explains the name→ID resolution performed
elsewhere (synchronizer) so callers know to supply a name.

In `@apps/server-core/test/unit/core/entities/permission/service.spec.ts`:
- Around line 119-126: The test currently only checks that result.policy_id is
undefined which doesn't verify legacy input is ignored; update the test around
service.create to pass a legacy policy_id (e.g., call service.create({ name:
'no-policy-perm', policy_id: 'some-id' }, createAllowAllActor())) and assert
that the returned result.policy_id is undefined (or not present) and that no
permission-policy junction was created for this permission (or move this
assertion into the permission-policy junction tests). Target the service.create
call and the result.policy_id check so the spec proves legacy policy_id input is
rejected/ignored rather than accidentally accepted elsewhere.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: a1926610-f524-4efe-ac57-37bcd4419139

📥 Commits

Reviewing files that changed from the base of the PR and between 53cff4c and cbf1bc5.

📒 Files selected for processing (19)
  • apps/server-core/src/app/modules/provisioning/module.ts
  • apps/server-core/src/app/modules/provisioning/sources/default/module.ts
  • apps/server-core/src/core/entities/permission/service.ts
  • apps/server-core/src/core/entities/policy/service.ts
  • apps/server-core/src/core/entities/role/service.ts
  • apps/server-core/src/core/entities/scope/service.ts
  • apps/server-core/src/core/entities/service.ts
  • apps/server-core/src/core/provisioning/entities/role/types.ts
  • apps/server-core/src/core/provisioning/synchronizer/junction-synchronizer.ts
  • apps/server-core/src/core/provisioning/synchronizer/role/module.ts
  • apps/server-core/src/core/provisioning/synchronizer/role/types.ts
  • apps/server-core/test/unit/core/entities/permission/service.spec.ts
  • apps/server-core/test/unit/core/entities/role/service.spec.ts
  • apps/server-core/test/unit/core/entities/scope/service.spec.ts
  • packages/access/src/permission/checker/module.ts
  • packages/access/src/policy/built-in/constants.ts
  • packages/client-web-kit/src/components/entities/policy/realm-match/ARealmMatchPolicyForm.vue
  • packages/client-web-kit/src/components/entities/policy/time/ATimePolicyForm.vue
  • packages/core-kit/src/domains/role/constants.ts
✅ Files skipped from review due to trivial changes (3)
  • packages/access/src/policy/built-in/constants.ts
  • packages/core-kit/src/domains/role/constants.ts
  • apps/server-core/src/core/entities/service.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/client-web-kit/src/components/entities/policy/realm-match/ARealmMatchPolicyForm.vue
  • apps/server-core/src/app/modules/provisioning/sources/default/module.ts

@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 (1)
apps/server-core/src/app/modules/database/repositories/permission-policy/repository.ts (1)

95-97: Consider removing the as any cast if possible.

The cast suggests a type mismatch between the PermissionPolicy interface and what TypeORM's remove expects. If PermissionPolicy is a plain type while the repository works with PermissionPolicyEntity class instances, consider typing the repository as Repository<PermissionPolicyEntity> internally, or documenting why the cast is necessary.

🤖 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/permission-policy/repository.ts`
around lines 95 - 97, The cast "as any" in remove(entity: PermissionPolicy)
hides a type mismatch—update the repository usage so it accepts the correct
entity type: change the injected repository type to
Repository<PermissionPolicyEntity> (or convert/map the PermissionPolicy DTO to a
PermissionPolicyEntity instance) and call this.repository.remove(...) with a
properly typed PermissionPolicyEntity; alternatively, if you only have an id,
use this.repository.delete(id). Ensure references to PermissionPolicyEntity and
the remove method are updated so the cast is no longer necessary.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In
`@apps/server-core/src/app/modules/database/repositories/permission-policy/repository.ts`:
- Around line 67-69: Update the findOneByName implementation to match the
IEntityRepository contract by adding the missing parameters (name: string,
realm?: string) to the method signature in the PermissionPolicy repository;
change async findOneByName(): Promise<PermissionPolicy | null> to async
findOneByName(name: string, realm?: string): Promise<PermissionPolicy | null>,
and implement the body to use those parameters to query the underlying data
store (e.g., delegate to the ORM/repository query using name and optional realm)
so the method satisfies
IPermissionPolicyRepository/IEntityRepository<PermissionPolicy> and TypeScript
compilation.

---

Nitpick comments:
In
`@apps/server-core/src/app/modules/database/repositories/permission-policy/repository.ts`:
- Around line 95-97: The cast "as any" in remove(entity: PermissionPolicy) hides
a type mismatch—update the repository usage so it accepts the correct entity
type: change the injected repository type to Repository<PermissionPolicyEntity>
(or convert/map the PermissionPolicy DTO to a PermissionPolicyEntity instance)
and call this.repository.remove(...) with a properly typed
PermissionPolicyEntity; alternatively, if you only have an id, use
this.repository.delete(id). Ensure references to PermissionPolicyEntity and the
remove method are updated so the cast is no longer necessary.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 03904652-62dd-44fa-85ba-7a36a4bc6b21

📥 Commits

Reviewing files that changed from the base of the PR and between cbf1bc5 and 2d0efc3.

📒 Files selected for processing (2)
  • apps/server-core/src/app/modules/database/repositories/permission-policy/repository.ts
  • packages/core-kit/src/domains/permission-policy/entity.ts
✅ Files skipped from review due to trivial changes (1)
  • packages/core-kit/src/domains/permission-policy/entity.ts

Comment on lines +67 to +69
async findOneByName(): Promise<PermissionPolicy | null> {
return null;
}

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify the interface signature for findOneByName
ast-grep --pattern 'interface IPermissionPolicyRepository {
  $$$
  findOneByName($$$)$$$
  $$$
}'

# Also check if there's a base repository interface
rg -n 'findOneByName.*:.*string' --type ts -C2

Repository: authup/authup

Length of output: 14885


🏁 Script executed:

#!/bin/bash
# Check the PermissionPolicy repository to see what interface it implements
cat -n apps/server-core/src/app/modules/database/repositories/permission-policy/repository.ts | head -30

# Also search for IPermissionPolicyRepository interface
rg -n 'interface.*PermissionPolicyRepository' --type ts -A 10

Repository: authup/authup

Length of output: 2648


Add the name parameter to match the IEntityRepository interface contract.

The method signature violates the interface requirement. IPermissionPolicyRepository extends IEntityRepository<PermissionPolicy>, which declares findOneByName(name: string, realm?: string). The current implementation omits the required parameters, causing a TypeScript compilation error.

♻️ Suggested fix
-    async findOneByName(): Promise<PermissionPolicy | null> {
+    async findOneByName(_name: string, _realm?: string): Promise<PermissionPolicy | null> {
         return null;
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async findOneByName(): Promise<PermissionPolicy | null> {
return null;
}
async findOneByName(_name: string, _realm?: string): Promise<PermissionPolicy | null> {
return null;
}
🤖 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/permission-policy/repository.ts`
around lines 67 - 69, Update the findOneByName implementation to match the
IEntityRepository contract by adding the missing parameters (name: string,
realm?: string) to the method signature in the PermissionPolicy repository;
change async findOneByName(): Promise<PermissionPolicy | null> to async
findOneByName(name: string, realm?: string): Promise<PermissionPolicy | null>,
and implement the body to use those parameters to query the underlying data
store (e.g., delegate to the ORM/repository query using name and optional realm)
so the method satisfies
IPermissionPolicyRepository/IEntityRepository<PermissionPolicy> and TypeScript
compilation.

@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: 8

Caution

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

⚠️ Outside diff range comments (2)
apps/server-core/src/adapters/http/controllers/entities/policy/module.ts (1)

117-125: ⚠️ Potential issue | 🟠 Major

Don't honor caller-supplied identities on this check endpoint.

Lines 117-122 still let the request body override BuiltInPolicyType.IDENTITY, and Line 124 now backs evaluation with live permission resolution. Because this route only uses ForceLoggedInMiddleware, any authenticated caller can probe permission-binding policies against other identities. Either always replace the identity with useRequestIdentity(req) here, or gate custom identities behind an explicit admin/policy-read check.

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

In `@apps/server-core/src/adapters/http/controllers/entities/policy/module.ts`
around lines 117 - 125, The endpoint currently allows caller-supplied
BuiltInPolicyType.IDENTITY to override the identity used for evaluation; always
replace that value with the caller's identity instead of honoring the request
body. Concretely, remove the conditional that checks
data[BuiltInPolicyType.IDENTITY] and unconditionally set
data[BuiltInPolicyType.IDENTITY] = useRequestIdentity(req) before instantiating
PolicyEngine (reference BuiltInPolicyType.IDENTITY, useRequestIdentity,
PolicyEngine), so evaluations always run as the authenticated caller. If you
prefer the alternative, gate honoring custom identities behind an explicit
admin/policy-read permission check instead.
apps/server-core/src/adapters/http/controllers/entities/identity-provide-role/module.ts (1)

213-217: ⚠️ Potential issue | 🔴 Critical

Add a null guard before accessing data.role.client_id on line 216.

The validateJoinColumns() method only validates that foreign key IDs exist; it does not guarantee that related objects like data.role are hydrated. Line 216 accesses data.role.client_id without checking if data.role exists, creating a potential null-pointer dereference.

The user-role controller (line 63–73) demonstrates the correct pattern: it wraps the isSuperset() call inside an if (data.role) guard. Apply the same defensive check here:

if (data.role) {
    const identity = useRequestIdentityOrFail(req);
    const hasPermissions = await this.identityPermissionProvider.isSuperset(identity, {
        type: 'role',
        id: data.role_id,
        clientId: data.role.client_id,
    });
    if (!hasPermissions) {
        throw new ForbiddenError('You don\'t own the required permissions.');
    }
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@apps/server-core/src/adapters/http/controllers/entities/identity-provide-role/module.ts`
around lines 213 - 217, Wrap the call to identityPermissionProvider.isSuperset
in a null guard checking data.role to avoid a potential null dereference: when
data.role exists, call useRequestIdentityOrFail(req) to get identity, call
this.identityPermissionProvider.isSuperset(identity, { type: 'role', id:
data.role_id, clientId: data.role.client_id }) and if it returns false throw the
same ForbiddenError('You don\'t own the required permissions.'). This mirrors
the pattern used in the user-role controller and prevents accessing
data.role.client_id when data.role is undefined.
🧹 Nitpick comments (10)
packages/access/test/unit/permission/escalation.spec.ts (1)

16-36: Consider extracting isSupersetPolicyAware to production code.

The isSupersetPolicyAware function implements useful escalation prevention logic that validates whether a parent's permissions are a superset of a child's (considering policy restrictions). If this pattern is used elsewhere in the codebase, consider promoting it to the src module for reuse rather than keeping it as a test-local utility.

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

In `@packages/access/test/unit/permission/escalation.spec.ts` around lines 16 -
36, The isSupersetPolicyAware helper in the test should be promoted to
production code for reuse: create and export a function named
isSupersetPolicyAware in the package's src (using the same signature and relying
on mergePermissionItems, PermissionItem type, and isPermissionItemEqual), update
the test to import isSupersetPolicyAware from that module instead of defining it
inline, and ensure the new exported function is covered by unit tests and
properly typed and exported from the package's index (or appropriate entry) so
other modules can reuse it.
docs/src/guide/user/permissions-and-policies.md (1)

110-112: Minor wording improvement.

The phrase "adds an additional restriction" is redundant. Consider simplifying:

📝 Suggested wording fix
 Permission assignments (role-permission, user-permission) can carry their own policy via the junction table.
-This **junction policy** adds an additional restriction on top of the permission's own policies.
+This **junction policy** adds a restriction on top of the permission's own policies.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/src/guide/user/permissions-and-policies.md` around lines 110 - 112,
Simplify the redundant phrasing in the second sentence: change "This junction
policy adds an additional restriction on top of the permission's own policies."
to a concise variant such as "This junction policy adds a restriction on top of
the permission's own policies." or "This junction policy imposes an extra
restriction on the permission's policies." Update the sentence in the
Permissions and Policies section so it reads more concisely while preserving
meaning.
apps/server-core/src/app/modules/http/modules/middleware.ts (1)

145-150: Move IdentityPermissionProvider composition into DI.

This method now owns the DataSource -> repository -> provider wiring while the rest of the authorization collaborators come from IDIContainer. Resolving a ready-made provider from the container would keep one composition path and avoid bypassing future repository wrappers or decorators here.

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

In `@apps/server-core/src/app/modules/http/modules/middleware.ts` around lines 145
- 150, The middleware is directly instantiating IdentityPermissionProvider and
its repositories (ClientRepository, UserRepository, RobotRepository,
RoleRepository) instead of resolving a composed provider from the DI container;
register a ready-made IdentityPermissionProvider (or a factory that composes
those repository implementations) in your IDIContainer and replace the new
IdentityPermissionProvider(...) usage in middleware.ts with a
container.resolve/get call so the middleware receives the provider from DI and
respects any repository wrappers/decorators already configured in the container.
apps/server-core/src/security/policy/variants/permission-binding/evaluator.ts (1)

108-115: Consider adding proper typing for policy field access.

The (raw as any).policy cast works but obscures the actual type. The Permission type from @authup/core-kit may not include the policy field in its base definition since it comes from junction tables. This is functionally correct but could benefit from a more explicit type.

♻️ Optional: Define an extended type for permission with policy
+type PermissionWithPolicy = Permission & { policy?: PolicyWithType };
+
 const permissionsMerged = mergePermissionItems(
-    identityPermissions.map((raw) => ({
+    identityPermissions.map((raw: PermissionWithPolicy) => ({
         name: raw.name,
         realm_id: raw.realm_id,
         client_id: raw.client_id,
-        policy: (raw as any).policy || undefined,
+        policy: raw.policy || undefined,
     })),
 );
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@apps/server-core/src/security/policy/variants/permission-binding/evaluator.ts`
around lines 108 - 115, The code uses a loose cast (raw as any).policy when
mapping identityPermissions before calling mergePermissionItems; define an
explicit extended type (e.g., PermissionWithPolicy) that extends the existing
Permission type to include an optional policy field, update the
identityPermissions typing (or narrow each item) to that extended type, and
replace (raw as any).policy with raw.policy so the policy access is strongly
typed in the mapping used by mergePermissionItems.
apps/server-core/src/core/identity/permission/module.ts (1)

147-154: Consider defining a typed interface for Permission with policy.

The (input as any).policy pattern appears in multiple places (here and in the evaluator). A shared type extension would improve type safety across the codebase.

♻️ Optional: Create shared type

Add to types.ts:

export type PermissionWithPolicy = Permission & { 
    policy?: PolicyWithType 
};

Then use in toPermissionItem:

-private toPermissionItem(input: Permission) : PermissionItem {
+private toPermissionItem(input: PermissionWithPolicy) : PermissionItem {
     return {
         name: input.name,
         client_id: input.client_id,
         realm_id: input.realm_id,
-        policy: (input as any).policy || undefined,
+        policy: input.policy,
     };
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/core/identity/permission/module.ts` around lines 147 -
154, Create a shared typed extension for Permission (e.g., export type
PermissionWithPolicy = Permission & { policy?: PolicyWithType } in types.ts),
import and use that type in places that currently use (input as any). Replace
the cast in toPermissionItem so its signature becomes toPermissionItem(input:
PermissionWithPolicy): PermissionItem and access input.policy directly, and
update the evaluator function(s) that read policy to accept/annotate
PermissionWithPolicy as well; ensure PolicyWithType is defined or imported and
update any imports/usages accordingly to remove the unsafe any cast.
packages/client-web-kit/src/components/entities/permission-policy/APermissionPolicyAssignment.ts (1)

23-42: Async setup blocks initial render until manager.resolve() completes.

Using async setup with await manager.resolve() will suspend the component until the query resolves. This is intentional here (determining initial toggle state), but consider whether a loading state or Suspense boundary is provided by the parent. If not, users may experience UI stalls on slow networks.

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

In
`@packages/client-web-kit/src/components/entities/permission-policy/APermissionPolicyAssignment.ts`
around lines 23 - 42, The current async setup block (async setup) awaits
manager.resolve(), which blocks initial render; change to non-blocking
initialization by removing async/await and calling manager.resolve() without
awaiting (e.g. manager.resolve(...).then(...).catch(...)) or run the resolve
inside onMounted so the component renders immediately; also add a local loading
state (ref like isLoading) or ensure a Suspense/fallback is provided by the
parent and update that state when manager.resolve() completes; locate code
around defineEntityManager, manager.resolve, and
props.permissionId/props.policyId to implement the non-blocking call and
loading-state update.
apps/server-core/src/adapters/http/request/helpers/actor.ts (1)

32-39: Consolidate the (b as any).policy pattern.

This is the third occurrence of the (b as any).policy || undefined cast pattern (also in evaluator.ts and module.ts). Consider extracting a shared helper or type to reduce duplication and improve maintainability.

♻️ Optional: Extract helper function
// In a shared utilities file
export function toPermissionItemFromBinding(binding: Permission): PermissionItem {
    return {
        name: binding.name,
        client_id: binding.client_id,
        realm_id: binding.realm_id,
        policy: (binding as any).policy || undefined,
    };
}

Then use across all three files:

 const merged = mergePermissionItems(
-    matching.map((b) => ({
-        name: b.name,
-        client_id: b.client_id,
-        realm_id: b.realm_id,
-        policy: (b as any).policy || undefined,
-    })),
+    matching.map(toPermissionItemFromBinding),
 );
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/adapters/http/request/helpers/actor.ts` around lines 32
- 39, Extract a small shared helper that converts a Permission binding to a
PermissionItem to remove repeated casts; implement something like
toPermissionItemFromBinding(binding: Permission): PermissionItem that returns {
name: binding.name, client_id: binding.client_id, realm_id: binding.realm_id,
policy: (binding as any).policy || undefined } and replace the inline mapping in
mergePermissionItems calls (e.g., the mapping in actor.ts) and the similar
occurrences in evaluator.ts and module.ts to call
toPermissionItemFromBinding(binding) instead.
packages/core-http-kit/src/domains/entities/permission-policy/module.ts (2)

20-24: Consider adding the optional record parameter to match the interface.

The EntityAPISlim interface defines getOne(id: DomainEntityID<T>, record?: BuildInput<T>), but this implementation omits the optional record parameter. While TypeScript allows this, adding the parameter would allow callers to pass query options (e.g., for field selection or relations).

♻️ Proposed fix
-    async getOne(id: PermissionPolicy['id']) : Promise<EntityRecordResponse<PermissionPolicy>> {
-        const response = await this.client.get(`permission-policies/${id}`);
+    async getOne(id: PermissionPolicy['id'], data?: BuildInput<PermissionPolicy>) : Promise<EntityRecordResponse<PermissionPolicy>> {
+        const response = await this.client.get(`permission-policies/${id}${buildQuery(data)}`);

         return response.data;
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core-http-kit/src/domains/entities/permission-policy/module.ts`
around lines 20 - 24, The getOne implementation for PermissionPolicy should add
the optional record parameter to match EntityAPISlim: change the signature of
getOne to include record?: BuildInput<PermissionPolicy> (keeping id:
PermissionPolicy['id']) and forward that record when making the HTTP request
(e.g., include it as query/body/options to this.client.get) so callers can pass
selection/relations; update the function name getOne and its call to
this.client.get(`permission-policies/${id}`, ...) to include the record
payload/params and keep return response.data.

32-36: Consider using a stricter type for required fields in create.

Partial<PermissionPolicy> allows calling create({}) with no compile-time error, even though the server requires permission_id and policy_id. Consider using a type that enforces these required fields.

♻️ Proposed fix
-    async create(data: Partial<PermissionPolicy>) : Promise<EntityRecordResponse<PermissionPolicy>> {
+    async create(data: Pick<PermissionPolicy, 'permission_id' | 'policy_id'>) : Promise<EntityRecordResponse<PermissionPolicy>> {
         const response = await this.client.post('permission-policies', data);

         return response.data;
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core-http-kit/src/domains/entities/permission-policy/module.ts`
around lines 32 - 36, The create method currently accepts
Partial<PermissionPolicy>, allowing empty objects; tighten the parameter type so
permission_id and policy_id are required. Replace the signature async
create(data: Partial<PermissionPolicy>) with one using a stricter type (e.g.
type CreatePermissionPolicy = Pick<PermissionPolicy, 'permission_id' |
'policy_id'> & Partial<Omit<PermissionPolicy, 'permission_id' | 'policy_id'>>
and then async create(data: CreatePermissionPolicy)), update any callers if
needed, and keep the implementation using
this.client.post('permission-policies', data) and returning response.data
unchanged.
apps/server-core/src/app/modules/http/modules/controller.ts (1)

251-259: Consider caching the IdentityPermissionProvider instance.

createIdentityPermissionProvider is called ~11 times during mount(), creating 44 repository instances (4 per call). Since repositories are stateless wrappers around the DataSource, consider caching the provider to reduce object allocation.

♻️ Proposed approach
 export class HTTPControllerModule {
+    private identityPermissionProvider?: IdentityPermissionProvider;
+
     async mount(router: Router, container: IDIContainer): Promise<void> {
+        // Clear any cached instance for fresh mount
+        this.identityPermissionProvider = undefined;
         const realmController = this.createRealmController(container);
         // ...
     }

     createIdentityPermissionProvider(container: IDIContainer) {
+        if (this.identityPermissionProvider) {
+            return this.identityPermissionProvider;
+        }
         const dataSource = container.resolve<DataSource>(DatabaseInjectionKey.DataSource);
-        return new IdentityPermissionProvider({
+        this.identityPermissionProvider = new IdentityPermissionProvider({
             clientRepository: new ClientRepository(dataSource),
             userRepository: new UserRepository(dataSource),
             robotRepository: new RobotRepository(dataSource),
             roleRepository: new RoleRepository(dataSource),
         });
+        return this.identityPermissionProvider;
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/app/modules/http/modules/controller.ts` around lines 251
- 259, createIdentityPermissionProvider is being called repeatedly and allocates
new repository instances each time; change it to return a cached
IdentityPermissionProvider instance instead of rebuilding it on every call.
Implement a simple cache (e.g., a private module-level or class-level variable)
and on first call construct new IdentityPermissionProvider with new
ClientRepository/UserRepository/RobotRepository/RoleRepository(dataSource) and
store it; subsequent calls should return the stored instance. Keep references to
the unique symbols IdentityPermissionProvider, createIdentityPermissionProvider,
ClientRepository, UserRepository, RobotRepository, RoleRepository and ensure the
DataSource is still resolved from
container.resolve<DataSource>(DatabaseInjectionKey.DataSource) when building the
cached 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 @.agents/architecture.md:
- Around line 171-185: The parameter name in buildActorContext is inconsistent
with the implementation; rename the optional parameter from
identityPermissionService to identityPermissionProvider and update its type to
IIdentityPermissionProvider (and any related wiring) so the function signature,
docs, and usages (e.g., where controllers pass the provider) all match; also
ensure resolveJunctionPolicy logic still references the correct provider symbol
after the rename.

In `@apps/server-core/src/app/modules/provisioning/module.ts`:
- Around line 249-260: The findOneBy→save sequence for creating default-policy
junctions is a TOCTOU and can race across instances; replace the per-permission
read-then-insert with a single DB-side upsert/ignore using the junctionRepo
insert/upsert facility (e.g., QueryBuilder insert ... on conflict do nothing or
repository.upsert) to insert the row with
permission_id/permission_realm_id/policy_id/policy_realm_id in one statement for
each permission (referencing junctionRepo, findOneBy, save, create, permission,
defaultPolicy, policy_id and permission_id) so the database atomically ignores
existing rows and prevents duplicate inserts without the extra read.
- Around line 247-260: Currently the loop checks only for an existing junction
with policy_id === defaultPolicy.id, causing defaultPolicy to be added even when
a permission already has other policy rows; change the logic to first check
whether any junction exists for the permission (e.g., use
junctionRepo.findOneBy({ permission_id: permission.id }) or junctionRepo.count({
permission_id: permission.id })) and only insert the defaultPolicy row when that
check returns none/zero. Update the block around permissionRepo, junctionRepo,
permission.id and defaultPolicy.id so you create/save the default junction only
when the permission has no policy rows at all.
- Around line 101-104: The code currently uses fs.existsSync(provisioningDir)
which returns true for files too; change the check to ensure provisioningDir is
a directory (e.g., use fs.statSync or fs.lstatSync and call .isDirectory(), or
use fs.promises.stat(...).then(s => s.isDirectory())) before pushing new
FileProvisioningSource({ cwd: provisioningDir }). Update the conditional around
provisioningDir (the variable and the block that constructs
FileProvisioningSource) to perform the isDirectory() check so an actual file
will not be passed as cwd.

In `@apps/server-core/src/core/entities/client-permission/service.ts`:
- Around line 82-89: The call to actor.resolveJunctionPolicy currently passes
only data.permission.name, which can return the wrong policy when the actor
holds the same permission across multiple realms; change the call site in the
client-permission creation logic to pass the realm context
(data.permission_realm_id and data.client_realm_id) or the full binding payload
(e.g., the data object) and update the resolveJunctionPolicy signature
accordingly so it can deterministically select the correct junction policy;
ensure you update any implementations and types that implement
actor.resolveJunctionPolicy to accept and use the new realm parameters and
preserve backward compatibility if needed.

In `@apps/server-core/src/core/entities/role-permission/service.ts`:
- Around line 84-91: The junction policy lookup currently calls
actor.resolveJunctionPolicy(data.permission.name) and can pick the wrong realm
when the actor owns the permission in multiple realms; change the call to
include the relevant realm ids (data.permission_realm_id and data.role_realm_id)
so the resolver can disambiguate and return the correct policy, then assign
data.policy_id from that result as before; update the invocation of
actor.resolveJunctionPolicy and any signature usage to accept (permissionName,
permissionRealmId, roleRealmId).

In `@apps/server-core/src/core/entities/user-permission/service.ts`:
- Around line 84-91: The lookup for the inherited policy uses only
data.permission.name and may pick the wrong realm; update the branch in the
user-permission creation flow so the call to actor.resolveJunctionPolicy
includes the realm ids (e.g., pass data.permission_realm_id and
data.user_realm_id along with data.permission.name) so the resolved
junctionPolicy is scoped correctly before assigning data.policy_id; ensure you
handle undefined realm ids the same way other callers expect.

In
`@packages/client-web-kit/src/components/entities/permission-policy/APermissionPolicyAssignment.ts`:
- Around line 17-21: The component APermissionPolicyAssignment declares props
permissionId and policyId but doesn't mark them required, so update the props
definition in APermissionPolicyAssignment to set required: true for both
permissionId and policyId (keep the String type) so Vue will warn if they are
omitted and downstream socket/filter/query/create logic always receives these
values.

---

Outside diff comments:
In
`@apps/server-core/src/adapters/http/controllers/entities/identity-provide-role/module.ts`:
- Around line 213-217: Wrap the call to identityPermissionProvider.isSuperset in
a null guard checking data.role to avoid a potential null dereference: when
data.role exists, call useRequestIdentityOrFail(req) to get identity, call
this.identityPermissionProvider.isSuperset(identity, { type: 'role', id:
data.role_id, clientId: data.role.client_id }) and if it returns false throw the
same ForbiddenError('You don\'t own the required permissions.'). This mirrors
the pattern used in the user-role controller and prevents accessing
data.role.client_id when data.role is undefined.

In `@apps/server-core/src/adapters/http/controllers/entities/policy/module.ts`:
- Around line 117-125: The endpoint currently allows caller-supplied
BuiltInPolicyType.IDENTITY to override the identity used for evaluation; always
replace that value with the caller's identity instead of honoring the request
body. Concretely, remove the conditional that checks
data[BuiltInPolicyType.IDENTITY] and unconditionally set
data[BuiltInPolicyType.IDENTITY] = useRequestIdentity(req) before instantiating
PolicyEngine (reference BuiltInPolicyType.IDENTITY, useRequestIdentity,
PolicyEngine), so evaluations always run as the authenticated caller. If you
prefer the alternative, gate honoring custom identities behind an explicit
admin/policy-read permission check instead.

---

Nitpick comments:
In `@apps/server-core/src/adapters/http/request/helpers/actor.ts`:
- Around line 32-39: Extract a small shared helper that converts a Permission
binding to a PermissionItem to remove repeated casts; implement something like
toPermissionItemFromBinding(binding: Permission): PermissionItem that returns {
name: binding.name, client_id: binding.client_id, realm_id: binding.realm_id,
policy: (binding as any).policy || undefined } and replace the inline mapping in
mergePermissionItems calls (e.g., the mapping in actor.ts) and the similar
occurrences in evaluator.ts and module.ts to call
toPermissionItemFromBinding(binding) instead.

In `@apps/server-core/src/app/modules/http/modules/controller.ts`:
- Around line 251-259: createIdentityPermissionProvider is being called
repeatedly and allocates new repository instances each time; change it to return
a cached IdentityPermissionProvider instance instead of rebuilding it on every
call. Implement a simple cache (e.g., a private module-level or class-level
variable) and on first call construct new IdentityPermissionProvider with new
ClientRepository/UserRepository/RobotRepository/RoleRepository(dataSource) and
store it; subsequent calls should return the stored instance. Keep references to
the unique symbols IdentityPermissionProvider, createIdentityPermissionProvider,
ClientRepository, UserRepository, RobotRepository, RoleRepository and ensure the
DataSource is still resolved from
container.resolve<DataSource>(DatabaseInjectionKey.DataSource) when building the
cached instance.

In `@apps/server-core/src/app/modules/http/modules/middleware.ts`:
- Around line 145-150: The middleware is directly instantiating
IdentityPermissionProvider and its repositories (ClientRepository,
UserRepository, RobotRepository, RoleRepository) instead of resolving a composed
provider from the DI container; register a ready-made IdentityPermissionProvider
(or a factory that composes those repository implementations) in your
IDIContainer and replace the new IdentityPermissionProvider(...) usage in
middleware.ts with a container.resolve/get call so the middleware receives the
provider from DI and respects any repository wrappers/decorators already
configured in the container.

In `@apps/server-core/src/core/identity/permission/module.ts`:
- Around line 147-154: Create a shared typed extension for Permission (e.g.,
export type PermissionWithPolicy = Permission & { policy?: PolicyWithType } in
types.ts), import and use that type in places that currently use (input as any).
Replace the cast in toPermissionItem so its signature becomes
toPermissionItem(input: PermissionWithPolicy): PermissionItem and access
input.policy directly, and update the evaluator function(s) that read policy to
accept/annotate PermissionWithPolicy as well; ensure PolicyWithType is defined
or imported and update any imports/usages accordingly to remove the unsafe any
cast.

In
`@apps/server-core/src/security/policy/variants/permission-binding/evaluator.ts`:
- Around line 108-115: The code uses a loose cast (raw as any).policy when
mapping identityPermissions before calling mergePermissionItems; define an
explicit extended type (e.g., PermissionWithPolicy) that extends the existing
Permission type to include an optional policy field, update the
identityPermissions typing (or narrow each item) to that extended type, and
replace (raw as any).policy with raw.policy so the policy access is strongly
typed in the mapping used by mergePermissionItems.

In `@docs/src/guide/user/permissions-and-policies.md`:
- Around line 110-112: Simplify the redundant phrasing in the second sentence:
change "This junction policy adds an additional restriction on top of the
permission's own policies." to a concise variant such as "This junction policy
adds a restriction on top of the permission's own policies." or "This junction
policy imposes an extra restriction on the permission's policies." Update the
sentence in the Permissions and Policies section so it reads more concisely
while preserving meaning.

In `@packages/access/test/unit/permission/escalation.spec.ts`:
- Around line 16-36: The isSupersetPolicyAware helper in the test should be
promoted to production code for reuse: create and export a function named
isSupersetPolicyAware in the package's src (using the same signature and relying
on mergePermissionItems, PermissionItem type, and isPermissionItemEqual), update
the test to import isSupersetPolicyAware from that module instead of defining it
inline, and ensure the new exported function is covered by unit tests and
properly typed and exported from the package's index (or appropriate entry) so
other modules can reuse it.

In
`@packages/client-web-kit/src/components/entities/permission-policy/APermissionPolicyAssignment.ts`:
- Around line 23-42: The current async setup block (async setup) awaits
manager.resolve(), which blocks initial render; change to non-blocking
initialization by removing async/await and calling manager.resolve() without
awaiting (e.g. manager.resolve(...).then(...).catch(...)) or run the resolve
inside onMounted so the component renders immediately; also add a local loading
state (ref like isLoading) or ensure a Suspense/fallback is provided by the
parent and update that state when manager.resolve() completes; locate code
around defineEntityManager, manager.resolve, and
props.permissionId/props.policyId to implement the non-blocking call and
loading-state update.

In `@packages/core-http-kit/src/domains/entities/permission-policy/module.ts`:
- Around line 20-24: The getOne implementation for PermissionPolicy should add
the optional record parameter to match EntityAPISlim: change the signature of
getOne to include record?: BuildInput<PermissionPolicy> (keeping id:
PermissionPolicy['id']) and forward that record when making the HTTP request
(e.g., include it as query/body/options to this.client.get) so callers can pass
selection/relations; update the function name getOne and its call to
this.client.get(`permission-policies/${id}`, ...) to include the record
payload/params and keep return response.data.
- Around line 32-36: The create method currently accepts
Partial<PermissionPolicy>, allowing empty objects; tighten the parameter type so
permission_id and policy_id are required. Replace the signature async
create(data: Partial<PermissionPolicy>) with one using a stricter type (e.g.
type CreatePermissionPolicy = Pick<PermissionPolicy, 'permission_id' |
'policy_id'> & Partial<Omit<PermissionPolicy, 'permission_id' | 'policy_id'>>
and then async create(data: CreatePermissionPolicy)), update any callers if
needed, and keep the implementation using
this.client.post('permission-policies', data) and returning response.data
unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: bc8811e8-d32a-492c-83c0-c603d36d41a4

📥 Commits

Reviewing files that changed from the base of the PR and between 2d0efc3 and 21a6dda.

📒 Files selected for processing (50)
  • .agents/architecture.md
  • apps/client-web/pages/permissions/[id].vue
  • apps/client-web/pages/permissions/[id]/policies.vue
  • apps/server-core/src/adapters/database/domains/permission-policy/entity.ts
  • apps/server-core/src/adapters/http/controllers/entities/client-permission/module.ts
  • apps/server-core/src/adapters/http/controllers/entities/client-role/module.ts
  • apps/server-core/src/adapters/http/controllers/entities/identity-provide-role/module.ts
  • apps/server-core/src/adapters/http/controllers/entities/permission/module.ts
  • apps/server-core/src/adapters/http/controllers/entities/policy/module.ts
  • apps/server-core/src/adapters/http/controllers/entities/robot-permission/module.ts
  • apps/server-core/src/adapters/http/controllers/entities/robot-role/module.ts
  • apps/server-core/src/adapters/http/controllers/entities/role-permission/module.ts
  • apps/server-core/src/adapters/http/controllers/entities/user-permission/module.ts
  • apps/server-core/src/adapters/http/controllers/entities/user-role/module.ts
  • apps/server-core/src/adapters/http/controllers/workflows/token/module.ts
  • apps/server-core/src/adapters/http/controllers/workflows/token/types.ts
  • apps/server-core/src/adapters/http/middleware/built-in/authorization/module.ts
  • apps/server-core/src/adapters/http/middleware/built-in/authorization/types.ts
  • apps/server-core/src/adapters/http/request/helpers/actor.ts
  • apps/server-core/src/app/modules/config/types.ts
  • apps/server-core/src/app/modules/http/modules/controller.ts
  • apps/server-core/src/app/modules/http/modules/middleware.ts
  • apps/server-core/src/app/modules/provisioning/module.ts
  • apps/server-core/src/core/entities/actor/types.ts
  • apps/server-core/src/core/entities/client-permission/service.ts
  • apps/server-core/src/core/entities/permission-policy/service.ts
  • apps/server-core/src/core/entities/robot-permission/service.ts
  • apps/server-core/src/core/entities/role-permission/service.ts
  • apps/server-core/src/core/entities/user-permission/service.ts
  • apps/server-core/src/core/identity/index.ts
  • apps/server-core/src/core/identity/permission/index.ts
  • apps/server-core/src/core/identity/permission/module.ts
  • apps/server-core/src/core/identity/permission/types.ts
  • apps/server-core/src/security/policy/engine/module.ts
  • apps/server-core/src/security/policy/variants/permission-binding/evaluator.ts
  • apps/server-core/src/services/index.ts
  • docs/src/guide/deployment/provisioning.md
  • docs/src/guide/user/permissions-and-policies.md
  • packages/access/src/permission/helpers/merge.ts
  • packages/access/test/unit/permission/escalation.spec.ts
  • packages/access/test/unit/permission/merge.spec.ts
  • packages/client-web-kit/src/components/entities/index.ts
  • packages/client-web-kit/src/components/entities/permission-policy/APermissionPolicyAssignment.ts
  • packages/client-web-kit/src/components/entities/permission-policy/APermissionPolicyAssignments.ts
  • packages/client-web-kit/src/components/entities/permission-policy/index.ts
  • packages/core-http-kit/src/client/module.ts
  • packages/core-http-kit/src/domains/entities/index.ts
  • packages/core-http-kit/src/domains/entities/permission-policy/index.ts
  • packages/core-http-kit/src/domains/entities/permission-policy/module.ts
  • packages/core-kit/src/domains/permission-policy/entity.ts
💤 Files with no reviewable changes (1)
  • apps/server-core/src/services/index.ts
✅ Files skipped from review due to trivial changes (9)
  • apps/client-web/pages/permissions/[id].vue
  • apps/server-core/src/core/identity/permission/index.ts
  • packages/client-web-kit/src/components/entities/index.ts
  • apps/server-core/src/app/modules/config/types.ts
  • apps/server-core/src/core/identity/index.ts
  • packages/core-http-kit/src/domains/entities/index.ts
  • apps/server-core/src/core/entities/actor/types.ts
  • docs/src/guide/deployment/provisioning.md
  • packages/core-kit/src/domains/permission-policy/entity.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/access/src/permission/helpers/merge.ts
  • apps/server-core/src/adapters/database/domains/permission-policy/entity.ts

Comment thread .agents/architecture.md Resolved
Comment on lines +101 to +104
const provisioningDir = path.join(config.writableDirectoryPath, 'provisioning');
if (fs.existsSync(provisioningDir)) {
sources.push(new FileProvisioningSource({ cwd: provisioningDir }));
}

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

❓ Verification inconclusive

Script executed:

cat -n apps/server-core/src/app/modules/provisioning/module.ts | sed -n '95,115p'

Repository: authup/authup


Repository: authup/authup
Exit code: 0

stdout:

    95	    }
    96	
    97	    async start(container: IDIContainer): Promise<void> {
    98	        const sources = [...this.sources];
    99	
   100	        const config = container.resolve<Config>(ConfigInjectionKey);
   101	        const provisioningDir = path.join(config.writableDirectoryPath, 'provisioning');
   102	        if (fs.existsSync(provisioningDir)) {
   103	            sources.push(new FileProvisioningSource({ cwd: provisioningDir }));
   104	        }
   105	
   106	        const composite = new CompositeProvisioningSource(sources);
   107	        const data = await composite.load(container);
   108	
   109	        const dataSource = container.resolve<DataSource>(DatabaseInjectionKey.DataSource);
   110	        const realmRepository = container.resolve<Repository<Realm>>(RealmEntity);
   111	
   112	        const permissionRepository = new PermissionRepositoryAdapter({
   113	            repository: container.resolve<Repository<PermissionEntity>>(PermissionEntity),
   114	            realmRepository,
   115	        });

Script executed:

find . -type f -name "*.ts" | xargs grep -l "class FileProvisioningSource" | head -5

Repository: authup/authup


Repository: authup/authup
Exit code: 0

stdout:

./apps/server-core/src/app/modules/provisioning/sources/file/module.ts

Script executed:

rg "class FileProvisioningSource" -A 20

Repository: authup/authup


Repository: authup/authup
Exit code: 0

stdout:

apps/server-core/src/app/modules/provisioning/sources/file/module.ts:export class FileProvisioningSource implements IProvisioningSource {
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-    protected options: FileEntitySchemaImporterOptions;
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-    protected rootValidator: RootProvisioningValidator;
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-    constructor(options: FileEntitySchemaImporterOptions) {
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-        this.options = options;
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-        this.rootValidator = new RootProvisioningValidator();
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-    }
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-    async load(): Promise<RootProvisioningEntity> {
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-        const cwd = path.isAbsolute(this.options.cwd) ?
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-            this.options.cwd :
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-            path.join(process.cwd(), this.options.cwd);
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-        const locations = await locateMany('*.{json,yaml,yml,ts,mts,mjs,js}', {
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-            path: cwd,
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-        });
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-        const compositeSource = new CompositeProvisioningSource([]);

Script executed:

rg "function locateMany|const locateMany|export.*locateMany" -A 10 | head -40

Repository: authup/authup


Repository: authup/authup
Exit code: 0


Script executed:

find . -type f -name "*.ts" -path "*/provisioning/*" | xargs grep -l "locateMany" | head -3

Repository: authup/authup


Repository: authup/authup
Exit code: 0

stdout:

./apps/server-core/src/app/modules/provisioning/sources/file/module.ts

Script executed:

rg "locateMany" apps/server-core/src/app/modules/provisioning/sources/file/module.ts -B 5 -A 15

Repository: authup/authup


Repository: authup/authup
Exit code: 0

stdout:

 *  Author Peter Placzek (tada5hi)
 *  For the full copyright and license information,
 *  view the LICENSE file that was distributed with this source code.
 */

import { load, locateMany } from 'locter';
import path from 'node:path';
import type { RootProvisioningEntity } from '../../../../../core/provisioning/entities/index.ts';
import { RootProvisioningValidator } from '../../../../../core/provisioning/entities/index.ts';
import type { IProvisioningSource } from '../../../../../core/provisioning/types.ts';
import { CompositeProvisioningSource } from '../composite/index.ts';
import type { FileEntitySchemaImporterOptions } from './types.ts';

export class FileProvisioningSource implements IProvisioningSource {
    protected options: FileEntitySchemaImporterOptions;

    protected rootValidator: RootProvisioningValidator;

    constructor(options: FileEntitySchemaImporterOptions) {
        this.options = options;

--
    async load(): Promise<RootProvisioningEntity> {
        const cwd = path.isAbsolute(this.options.cwd) ?
            this.options.cwd :
            path.join(process.cwd(), this.options.cwd);

        const locations = await locateMany('*.{json,yaml,yml,ts,mts,mjs,js}', {
            path: cwd,
        });

        const compositeSource = new CompositeProvisioningSource([]);

        const output : RootProvisioningEntity = {};
        for (const location of locations) {

            const raw = await load(location);
            const data = await this.rootValidator.run(raw.default);

            compositeSource.merge(output, data);
        }

        return output;

Script executed:

web_search
locter npm package locateMany behavior when path is not a directory

Repository: authup/authup


Repository: authup/authup
Exit code: 127

stderr:

/bin/bash: line 1: web_search: command not found
/bin/bash: line 2: locter: command not found

Script executed:

rg "FileProvisioningSource|locateMany" apps/server-core/src/app/modules/provisioning/module.ts -B 3 -A 5

Repository: authup/authup


Repository: authup/authup
Exit code: 0

stdout:

import path from 'node:path';
import type { Config } from '../config/index.ts';
import { ConfigInjectionKey } from '../config/index.ts';
import { CompositeProvisioningSource, FileProvisioningSource } from './sources/index.ts';

export class ProvisionerModule implements Module {
    readonly name: string;

    readonly dependsOn: string[];
--
        const config = container.resolve<Config>(ConfigInjectionKey);
        const provisioningDir = path.join(config.writableDirectoryPath, 'provisioning');
        if (fs.existsSync(provisioningDir)) {
            sources.push(new FileProvisioningSource({ cwd: provisioningDir }));
        }

        const composite = new CompositeProvisioningSource(sources);
        const data = await composite.load(container);


Script executed:

cat -n apps/server-core/src/app/modules/provisioning/module.ts | sed -n '106,130p'

Repository: authup/authup


Repository: authup/authup
Exit code: 0

stdout:

   106	        const composite = new CompositeProvisioningSource(sources);
   107	        const data = await composite.load(container);
   108	
   109	        const dataSource = container.resolve<DataSource>(DatabaseInjectionKey.DataSource);
   110	        const realmRepository = container.resolve<Repository<Realm>>(RealmEntity);
   111	
   112	        const permissionRepository = new PermissionRepositoryAdapter({
   113	            repository: container.resolve<Repository<PermissionEntity>>(PermissionEntity),
   114	            realmRepository,
   115	        });
   116	
   117	        const policyRepository = new PolicyRepositoryAdapter({
   118	            repository: new PolicyRepository(dataSource),
   119	            realmRepository,
   120	        });
   121	
   122	        // ---------------------------------------------------------------
   123	        // Synchronize all entities (policies → permissions → roles → ...)
   124	        // ---------------------------------------------------------------
   125	
   126	        const policySynchronizer = new PolicyProvisioningSynchronizer({
   127	            repository: policyRepository,
   128	            permissionRepository,
   129	        });
   130	

Script executed:

web_search

Repository: authup/authup


Repository: authup/authup
Exit code: 127

stderr:

/bin/bash: line 1: web_search: command not found

Script executed:

rg "locter" -B 2 -A 2 apps/server-core/package.json

Repository: authup/authup


Repository: authup/authup
Exit code: 0

stdout:

        "hapic": "^2.5.1",
        "ldapjs": "^3.0.7",
        "locter": "^2.2.1",
        "morgan": "^1.10.1",
        "mysql2": "^3.20.0",

Script executed:

cat -n apps/server-core/src/app/modules/provisioning/sources/file/module.ts | sed -n '20,50p'

Repository: authup/authup


Repository: authup/authup
Exit code: 0

stdout:

    20	
    21	    constructor(options: FileEntitySchemaImporterOptions) {
    22	        this.options = options;
    23	
    24	        this.rootValidator = new RootProvisioningValidator();
    25	    }
    26	
    27	    async load(): Promise<RootProvisioningEntity> {
    28	        const cwd = path.isAbsolute(this.options.cwd) ?
    29	            this.options.cwd :
    30	            path.join(process.cwd(), this.options.cwd);
    31	
    32	        const locations = await locateMany('*.{json,yaml,yml,ts,mts,mjs,js}', {
    33	            path: cwd,
    34	        });
    35	
    36	        const compositeSource = new CompositeProvisioningSource([]);
    37	
    38	        const output : RootProvisioningEntity = {};
    39	        for (const location of locations) {
    40	
    41	            const raw = await load(location);
    42	            const data = await this.rootValidator.run(raw.default);
    43	
    44	            compositeSource.merge(output, data);
    45	        }
    46	
    47	        return output;
    48	    }
    49	}

Script executed:

rg "fs\.isDirectory|isDirectory|stat|lstat" apps/server-core/src/app/modules/provisioning/ -B 2 -A 2

Repository: authup/authup


Repository: authup/authup
Exit code: 1


Script executed:

find . -type f -name "*.ts" -path "*test*" -o -name "*.spec.ts" | xargs grep -l "FileProvisioningSource" 2>/dev/null | head -3

Repository: authup/authup


Repository: authup/authup
Exit code: 0

stdout:

./apps/server-core/test/unit/modules/provisioning.spec.ts

Script executed:

rg "locateMany" --type ts -B 3 -A 3 | head -50

Repository: authup/authup


Repository: authup/authup
Exit code: 0

stdout:

apps/server-core/src/app/modules/provisioning/sources/file/module.ts- *  view the LICENSE file that was distributed with this source code.
apps/server-core/src/app/modules/provisioning/sources/file/module.ts- */
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-
apps/server-core/src/app/modules/provisioning/sources/file/module.ts:import { load, locateMany } from 'locter';
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-import path from 'node:path';
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-import type { RootProvisioningEntity } from '../../../../../core/provisioning/entities/index.ts';
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-import { RootProvisioningValidator } from '../../../../../core/provisioning/entities/index.ts';
--
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-            this.options.cwd :
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-            path.join(process.cwd(), this.options.cwd);
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-
apps/server-core/src/app/modules/provisioning/sources/file/module.ts:        const locations = await locateMany('*.{json,yaml,yml,ts,mts,mjs,js}', {
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-            path: cwd,
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-        });
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-

Script executed:

python3 << 'EOF'
# Check locter npm package info
import subprocess
import json

result = subprocess.run(['npm', 'view', '[email protected]', 'repository', '--json'], 
                       capture_output=True, text=True)
if result.returncode == 0:
    print(result.stdout)
else:
    print("Could not fetch from npm, checking local behavior")
EOF

Repository: authup/authup


Repository: authup/authup
Exit code: 0

stdout:

{
  "type": "git",
  "url": "https://github.com/tada5hi/locter.git"
}


Script executed:

cat -n ./apps/server-core/test/unit/modules/provisioning.spec.ts | head -100

Repository: authup/authup


Repository: authup/authup
Exit code: 0

stdout:

     1	/*
     2	 * Copyright (c) 2026.
     3	 * Author Peter Placzek (tada5hi)
     4	 * For the full copyright and license information,
     5	 * view the LICENSE file that was distributed with this source code.
     6	 */
     7	
     8	import { BuiltInPolicyType, DecisionStrategy, SystemPolicyName } from '@authup/access';
     9	import type { Permission, Realm, Role } from '@authup/core-kit';
    10	import type { DataSource, Repository } from 'typeorm';
    11	import {
    12	    afterAll,
    13	    beforeAll, describe, expect, it,
    14	} from 'vitest';
    15	import {
    16	    CacheModule, ConfigModule,
    17	    DefaultProvisioningSource,
    18	    FileProvisioningSource,
    19	    LoggerModule,
    20	    PermissionEntity,
    21	    ProvisionerModule,
    22	    RealmEntity, RoleEntity,
    23	} from '../../../src/index.ts';
    24	import type { IDIContainer } from '../../../src/core/index.ts';
    25	import {
    26	    DependencyContainer,
    27	    PermissionProvisioningSynchronizer,
    28	    PolicyProvisioningSynchronizer,
    29	} from '../../../src/core/index.ts';
    30	import type { PolicyProvisioningEntity } from '../../../src/core/provisioning/entities/policy/index.ts';
    31	import {
    32	    PolicyRepository,
    33	} from '../../../src/adapters/database/domains/index.ts';
    34	import {
    35	    PermissionRepositoryAdapter,
    36	    PolicyRepositoryAdapter,
    37	} from '../../../src/app/modules/database/repositories/index.ts';
    38	import { DatabaseInjectionKey } from '../../../src/app/modules/database/index.ts';
    39	import { createTestDatabaseModuleForSuite } from '../../app/index.ts';
    40	
    41	describe('app/modules/provisioning', () => {
    42	    let di: IDIContainer;
    43	    let dataSource: DataSource;
    44	    let policyRepositoryAdapter: PolicyRepositoryAdapter;
    45	    let permissionRepositoryAdapter: PermissionRepositoryAdapter;
    46	
    47	    const config = new ConfigModule();
    48	    const logger = new LoggerModule();
    49	    const cache = new CacheModule();
    50	    const database = createTestDatabaseModuleForSuite();
    51	
    52	    beforeAll(async () => {
    53	        di = new DependencyContainer();
    54	
    55	        await config.start(di);
    56	        await logger.start(di);
    57	        await cache.start(di);
    58	        await database.start(di);
    59	
    60	        dataSource = di.resolve<DataSource>(DatabaseInjectionKey.DataSource);
    61	        const realmRepository = di.resolve<Repository<Realm>>(RealmEntity);
    62	
    63	        policyRepositoryAdapter = new PolicyRepositoryAdapter({
    64	            repository: new PolicyRepository(dataSource),
    65	            realmRepository,
    66	        });
    67	
    68	        permissionRepositoryAdapter = new PermissionRepositoryAdapter({
    69	            repository: di.resolve<Repository<Permission>>(PermissionEntity),
    70	            realmRepository,
    71	        });
    72	    });
    73	
    74	    afterAll(async () => {
    75	        await database.stop(di);
    76	    });
    77	
    78	    // ---------------------------------------------------------------
    79	    // File provisioning source
    80	    // ---------------------------------------------------------------
    81	
    82	    it('should load provisioning data', async () => {
    83	        const source = new FileProvisioningSource({ cwd: 'test/data/sources' });
    84	        const output = await source.load();
    85	
    86	        expect(output.roles).toHaveLength(2);
    87	        expect(output.permissions).toHaveLength(1);
    88	        expect(output.scopes).toHaveLength(1);
    89	        expect(output.realms).toHaveLength(1);
    90	
    91	        const [realm] = output.realms!;
    92	
    93	        expect(realm.relations).toBeDefined();
    94	        expect(realm.relations?.roles).toHaveLength(2);
    95	        expect(realm.relations?.permissions).toHaveLength(1);
    96	        expect(realm.relations?.users).toHaveLength(1);
    97	        expect(realm.relations?.clients).toHaveLength(1);
    98	    });
    99	
   100	    it('should synchronize provisioning data', async () => {

Script executed:

rg "FileProvisioningSource|provisioningDir" ./apps/server-core/test/unit/modules/provisioning.spec.ts -B 5 -A 10

Repository: authup/authup


Repository: authup/authup
Exit code: 0

stdout:

    beforeAll, describe, expect, it,
} from 'vitest';
import {
    CacheModule, ConfigModule,
    DefaultProvisioningSource,
    FileProvisioningSource,
    LoggerModule,
    PermissionEntity,
    ProvisionerModule,
    RealmEntity, RoleEntity,
} from '../../../src/index.ts';
import type { IDIContainer } from '../../../src/core/index.ts';
import {
    DependencyContainer,
    PermissionProvisioningSynchronizer,
    PolicyProvisioningSynchronizer,
--
    // ---------------------------------------------------------------
    // File provisioning source
    // ---------------------------------------------------------------

    it('should load provisioning data', async () => {
        const source = new FileProvisioningSource({ cwd: 'test/data/sources' });
        const output = await source.load();

        expect(output.roles).toHaveLength(2);
        expect(output.permissions).toHaveLength(1);
        expect(output.scopes).toHaveLength(1);
        expect(output.realms).toHaveLength(1);

        const [realm] = output.realms!;

        expect(realm.relations).toBeDefined();
--
        expect(realm.relations?.clients).toHaveLength(1);
    });

    it('should synchronize provisioning data', async () => {
        const provisioning = new ProvisionerModule([
            new FileProvisioningSource({ cwd: 'test/data/sources' }),
        ]);
        await provisioning.start(di);

        const realmRepository = di.resolve<Repository<Realm>>(RealmEntity);
        const roleRepository = di.resolve<Repository<Role>>(RoleEntity);

        const realm = await realmRepository.findOneBy({ name: 'foo' });
        expect(realm).toBeDefined();

        const roles = await roleRepository.findBy({ name: 'foo' });

Script executed:

find . -type f -name "*.ts" | xargs grep -l "FileEntitySchemaImporterOptions" | head -3

Repository: authup/authup


Repository: authup/authup
Exit code: 0

stdout:

./apps/server-core/src/app/modules/provisioning/sources/file/module.ts
./apps/server-core/src/app/modules/provisioning/sources/file/types.ts

Script executed:

rg "FileEntitySchemaImporterOptions" -A 5 | head -30

Repository: authup/authup


Repository: authup/authup
Exit code: 0

stdout:

apps/server-core/src/app/modules/provisioning/sources/file/types.ts:export type FileEntitySchemaImporterOptions = {
apps/server-core/src/app/modules/provisioning/sources/file/types.ts-    cwd: string
apps/server-core/src/app/modules/provisioning/sources/file/types.ts-};
--
apps/server-core/src/app/modules/provisioning/sources/file/module.ts:import type { FileEntitySchemaImporterOptions } from './types.ts';
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-export class FileProvisioningSource implements IProvisioningSource {
apps/server-core/src/app/modules/provisioning/sources/file/module.ts:    protected options: FileEntitySchemaImporterOptions;
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-    protected rootValidator: RootProvisioningValidator;
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-
apps/server-core/src/app/modules/provisioning/sources/file/module.ts:    constructor(options: FileEntitySchemaImporterOptions) {
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-        this.options = options;
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-        this.rootValidator = new RootProvisioningValidator();
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-    }
apps/server-core/src/app/modules/provisioning/sources/file/module.ts-

Script executed:

cat -n ./apps/server-core/src/app/modules/provisioning/sources/file/types.ts

Repository: authup/authup


Repository: authup/authup
Exit code: 0

stdout:

     1	/*
     2	 * Copyright (c) 2026.
     3	 *  Author Peter Placzek (tada5hi)
     4	 *  For the full copyright and license information,
     5	 *  view the LICENSE file that was distributed with this source code.
     6	 */
     7	
     8	export type FileEntitySchemaImporterOptions = {
     9	    cwd: string
    10	};

Script executed:

rg "const data = await composite.load" apps/server-core/src/app/modules/provisioning/module.ts -B 2 -A 8

Repository: authup/authup


Repository: authup/authup
Exit code: 0

stdout:


        const composite = new CompositeProvisioningSource(sources);
        const data = await composite.load(container);

        const dataSource = container.resolve<DataSource>(DatabaseInjectionKey.DataSource);
        const realmRepository = container.resolve<Repository<Realm>>(RealmEntity);

        const permissionRepository = new PermissionRepositoryAdapter({
            repository: container.resolve<Repository<PermissionEntity>>(PermissionEntity),
            realmRepository,
        });

Script executed:

cat -n apps/server-core/src/app/modules/provisioning/module.ts | sed -n '97,145p'

Repository: authup/authup


Repository: authup/authup
Exit code: 0

stdout:

    97	    async start(container: IDIContainer): Promise<void> {
    98	        const sources = [...this.sources];
    99	
   100	        const config = container.resolve<Config>(ConfigInjectionKey);
   101	        const provisioningDir = path.join(config.writableDirectoryPath, 'provisioning');
   102	        if (fs.existsSync(provisioningDir)) {
   103	            sources.push(new FileProvisioningSource({ cwd: provisioningDir }));
   104	        }
   105	
   106	        const composite = new CompositeProvisioningSource(sources);
   107	        const data = await composite.load(container);
   108	
   109	        const dataSource = container.resolve<DataSource>(DatabaseInjectionKey.DataSource);
   110	        const realmRepository = container.resolve<Repository<Realm>>(RealmEntity);
   111	
   112	        const permissionRepository = new PermissionRepositoryAdapter({
   113	            repository: container.resolve<Repository<PermissionEntity>>(PermissionEntity),
   114	            realmRepository,
   115	        });
   116	
   117	        const policyRepository = new PolicyRepositoryAdapter({
   118	            repository: new PolicyRepository(dataSource),
   119	            realmRepository,
   120	        });
   121	
   122	        // ---------------------------------------------------------------
   123	        // Synchronize all entities (policies → permissions → roles → ...)
   124	        // ---------------------------------------------------------------
   125	
   126	        const policySynchronizer = new PolicyProvisioningSynchronizer({
   127	            repository: policyRepository,
   128	            permissionRepository,
   129	        });
   130	
   131	        const roleRepository = new RoleRepositoryAdapter({
   132	            repository: container.resolve<Repository<Role>>(RoleEntity),
   133	            realmRepository,
   134	        });
   135	        const clientRepository = new ClientRepositoryAdapter({
   136	            repository: container.resolve<Repository<Client>>(ClientEntity),
   137	            realmRepository,
   138	        });
   139	
   140	        const permissionSynchronizer = new PermissionProvisioningSynchronizer({
   141	            repository: permissionRepository,
   142	        });
   143	
   144	        const roleSynchronizer = new RoleProvisioningSynchronizer({
   145	            repository: roleRepository,

Use fs.isDirectory() or stat().isDirectory() instead of fs.existsSync() to validate the provisioning path.

fs.existsSync() returns true for regular files as well as directories. If <writableDirectoryPath>/provisioning is a file rather than a directory, FileProvisioningSource will be initialized with an invalid cwd and fail when locateMany() attempts to search for provisioning files.

🤖 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 101 -
104, The code currently uses fs.existsSync(provisioningDir) which returns true
for files too; change the check to ensure provisioningDir is a directory (e.g.,
use fs.statSync or fs.lstatSync and call .isDirectory(), or use
fs.promises.stat(...).then(s => s.isDirectory())) before pushing new
FileProvisioningSource({ cwd: provisioningDir }). Update the conditional around
provisioningDir (the variable and the block that constructs
FileProvisioningSource) to perform the isDirectory() check so an actual file
will not be passed as cwd.

Comment on lines +249 to +260
const existing = await junctionRepo.findOneBy({
permission_id: permission.id,
policy_id: defaultPolicy.id,
});

if (!existing) {
await junctionRepo.save(junctionRepo.create({
permission_id: permission.id,
permission_realm_id: permission.realm_id,
policy_id: defaultPolicy.id,
policy_realm_id: defaultPolicy.realm_id,
}));

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

Make the default-policy backfill atomic.

The findOneBy() → save() sequence is a TOCTOU race and also does one read plus one write per permission on every startup. If two instances provision in parallel, both can observe “missing” and then race on the insert. Prefer a single DB-side insert/upsert/ignore for the missing associations.

🤖 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 249 -
260, The findOneBy→save sequence for creating default-policy junctions is a
TOCTOU and can race across instances; replace the per-permission
read-then-insert with a single DB-side upsert/ignore using the junctionRepo
insert/upsert facility (e.g., QueryBuilder insert ... on conflict do nothing or
repository.upsert) to insert the row with
permission_id/permission_realm_id/policy_id/policy_realm_id in one statement for
each permission (referencing junctionRepo, findOneBy, save, create, permission,
defaultPolicy, policy_id and permission_id) so the database atomically ignores
existing rows and prevents duplicate inserts without the extra read.

@tada5hi

tada5hi commented Mar 22, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Mar 22, 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: 4

Caution

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

⚠️ Outside diff range comments (1)
apps/server-core/src/adapters/http/controllers/entities/identity-provide-role/module.ts (1)

212-220: ⚠️ Potential issue | 🟠 Major

Guard data.role before reading client_id.

Lines 193-195 already treat data.role as optional, but Line 216 dereferences it unconditionally. If the request only carries role_id, or validateJoinColumns() does not hydrate the relation, this path becomes a 500 instead of a controlled error.

🛡️ Suggested fix
         const identity = useRequestIdentityOrFail(req);
+        if (!data.role) {
+            throw new BadRequestError('Role relation could not be resolved.');
+        }
         const hasPermissions = await this.identityPermissionProvider.isSuperset(identity, {
             type: 'role',
             id: data.role_id,
             clientId: data.role.client_id,
         });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@apps/server-core/src/adapters/http/controllers/entities/identity-provide-role/module.ts`
around lines 212 - 220, The code dereferences data.role.client_id without
guarding data.role, which can cause a 500 when only data.role_id is provided; in
the block around useRequestIdentityOrFail and
this.identityPermissionProvider.isSuperset, first validate that data.role exists
(or extract clientId via a safe fallback) before calling isSuperset — e.g.,
check data.role and throw a controlled BadRequestError or ForbiddenError if
missing, or pass clientId = data.role?.client_id ?? /* fallback or error */ so
identityPermissionProvider.isSuperset is never invoked with an undefined
clientId; update the conditional that currently throws ForbiddenError to handle
the missing data.role case explicitly and reference data.role_id,
data.role.client_id, useRequestIdentityOrFail,
identityPermissionProvider.isSuperset, and ForbiddenError when making the
change.
♻️ Duplicate comments (2)
.agents/architecture.md (1)

171-174: ⚠️ Potential issue | 🟡 Minor

Update ActorContext builder docs to the provider naming/type used in code.

The snippet/docs still use identityPermissionService + IdentityPermissionService, which is out of sync with the provider-based wiring and can mislead maintainers.

📝 Suggested doc fix
 export function buildActorContext(
     req: Request,
-    identityPermissionService?: IdentityPermissionService,
+    identityPermissionProvider?: IIdentityPermissionProvider,
 ): ActorContext {
@@
-The `identityPermissionService` parameter is optional — only junction controllers that create permission bindings pass it.
+The `identityPermissionProvider` parameter is optional — only junction controllers that create permission bindings pass it.

As per coding guidelines, ".agents/**/*: Keep .agents directory files updated as the project evolves, including architectural changes, new patterns, and important conventions".

Also applies to: 185-185

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

In @.agents/architecture.md around lines 171 - 174, Update the ActorContext
builder docs to match the provider-based wiring used in code: replace references
to the parameter and type name `identityPermissionService` /
`IdentityPermissionService` with the provider naming/type used in the codebase
(e.g., `identityPermissionProvider` or the appropriate `Provider<...>` type),
and update the example signature for buildActorContext accordingly; ensure the
same change is applied to the other occurrence noted (around the second snippet)
so documentation and code use the same provider identifier and type.
apps/server-core/src/core/entities/role-permission/service.ts (1)

84-90: ⚠️ Potential issue | 🟠 Major

Pass realm scope into junction-policy resolution.

This still resolves by permission name only, which can attach the wrong inherited policy when the actor has the same permission across realms. Use the already-derived realm ids to disambiguate.

🔧 Suggested change
-            const junctionPolicy = await actor.resolveJunctionPolicy(data.permission.name);
+            const junctionPolicy = await actor.resolveJunctionPolicy(
+                data.permission.name,
+                data.permission_realm_id,
+                data.role_realm_id,
+            );
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/core/entities/role-permission/service.ts` around lines
84 - 90, The call to actor.resolveJunctionPolicy(data.permission.name) only uses
permission name and can pick the wrong policy when the same permission exists in
multiple realms; change the call to pass the derived realm ids so resolution is
scoped (e.g., actor.resolveJunctionPolicy(data.permission.name, realmIds) or
actor.resolveJunctionPolicy(data.permission.name, data.realm_ids)). Update the
resolveJunctionPolicy signature/implementation to accept and use the realm ids
parameter for disambiguation (ensure RolePermission service uses the
already-derived realm ids variable when invoking resolveJunctionPolicy).
🧹 Nitpick comments (3)
packages/access/test/unit/permission/escalation.spec.ts (1)

30-32: Consider adding a test case for different policies on both parent and child.

The current logic only checks for policy presence (parentItem.policy && !childItem.policy), meaning when both parent and child have policies but they differ, the assignment is allowed. This may be intentional, but there's no explicit test covering this scenario.

If different policies should be handled differently (e.g., requiring compatible or identical policies), the logic would need adjustment. If the current behavior is intentional, adding an explicit test case would document this design decision.

📝 Suggested additional test case
it('should allow: restricted actor assigning differently restricted role', () => {
    const parent: PermissionItem[] = [
        { name: 'user_read', policy: { type: BuiltInPolicyType.ATTRIBUTES, id: 'policy-a' } },
    ];
    const child: PermissionItem[] = [
        { name: 'user_read', policy: { type: BuiltInPolicyType.IDENTITY, id: 'policy-b' } },
    ];

    expect(isSupersetPolicyAware(parent, child)).toBe(true); // or false, depending on requirements
});
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/access/test/unit/permission/escalation.spec.ts` around lines 30 -
32, The test suite is missing a case where both parent and child PermissionItem
have policies but differ; add a unit test in escalation.spec.ts that calls
isSupersetPolicyAware with parent and child entries having different policy.type
and/or policy.id (use PermissionItem and BuiltInPolicyType to construct them)
and assert the intended outcome (true if differing policies are allowed, or
false if they must match). If the intended behavior is to reject differing
policies, update isSupersetPolicyAware to compare policy.type and policy.id for
equality (or the required compatibility rule) and add the corresponding test; if
the intended behavior is to allow them, add the explicit test to document that
decision.
apps/server-core/src/app/modules/database/repositories/permission-provider/module.ts (1)

75-83: Parallelize descendant-tree resolution.

This loop awaits each findDescendantsTree() call in series, so a permission with several policies pays the full sum of those latencies on the authorization path. Collect the lookups and await them together instead.

♻️ Suggested refactor
-            const policies : PolicyWithType[] = [];
-            for (const junction of junctions) {
-                if (junction.policy) {
-                    const tree = await this.policyRepository.findDescendantsTree(junction.policy);
-                    if (tree) {
-                        policies.push(tree);
-                    }
-                }
-            }
+            const policyTrees = await Promise.all(
+                junctions
+                    .filter((junction) => junction.policy)
+                    .map((junction) => this.policyRepository.findDescendantsTree(junction.policy!)),
+            );
+
+            const policies : PolicyWithType[] = policyTrees.filter(
+                (tree): tree is PolicyWithType => !!tree,
+            );
🤖 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/permission-provider/module.ts`
around lines 75 - 83, The loop that builds policies does sequential awaits,
causing unnecessary latency; instead collect promises from
this.policyRepository.findDescendantsTree for each junction that has a policy
(referencing junctions, policyRepository.findDescendantsTree, and the policies:
PolicyWithType[]), run them in parallel with Promise.all, then filter out
null/undefined results and push the trees into policies (or replace policies
with the resolved array). Ensure you preserve the original type
(PolicyWithType[]) and null-check/filter the results before using them.
apps/server-core/src/app/modules/http/modules/controller.ts (1)

252-260: Consider caching IdentityPermissionProvider instance.

createIdentityPermissionProvider is called 11 times throughout this module, creating 11 separate instances each with their own repository objects. If the provider is stateless, a single shared instance would reduce memory allocation.

♻️ Proposed refactor to cache the provider
+    private identityPermissionProviderInstance: IdentityPermissionProvider | null = null;
+
     createIdentityPermissionProvider(container: IDIContainer) {
+        if (this.identityPermissionProviderInstance) {
+            return this.identityPermissionProviderInstance;
+        }
+
         const dataSource = container.resolve<DataSource>(DatabaseInjectionKey.DataSource);
-        return new IdentityPermissionProvider({
+        this.identityPermissionProviderInstance = new IdentityPermissionProvider({
             clientRepository: new ClientRepository(dataSource),
             userRepository: new UserRepository(dataSource),
             robotRepository: new RobotRepository(dataSource),
             roleRepository: new RoleRepository(dataSource),
         });
+        return this.identityPermissionProviderInstance;
     }

Alternatively, register IdentityPermissionProvider in the DI container during application bootstrap.

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

In `@apps/server-core/src/app/modules/http/modules/controller.ts` around lines 252
- 260, createIdentityPermissionProvider currently instantiates a new
IdentityPermissionProvider (and new ClientRepository, UserRepository,
RobotRepository, RoleRepository) each time it's called; change it to return a
cached/shared instance instead (or register IdentityPermissionProvider once in
the DI container at bootstrap) so repeated calls reuse the same
IdentityPermissionProvider and its repositories; locate the factory function
createIdentityPermissionProvider and ensure it stores/returns a single
module-level or container-scoped instance of IdentityPermissionProvider
(constructed with the same repositories) rather than creating new instances on
every invocation.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In @.agents/architecture.md:
- Around line 504-513: The fenced code block starting with ``` and containing
"Layer 1: Permission-level policies (from auth_permission_policies)" is missing
a language tag, triggering markdownlint MD040; update the opening fence to
include a language identifier (e.g., ```text or ```md) so the block reads like
```text and leave the block content unchanged—look for the block that contains
"Layer 1: Permission-level policies" and "Layer 2: Junction-level policy" and
add the language tag to its opening fence.

In `@apps/server-core/src/core/identity/permission/module.ts`:
- Around line 38-55: The isSuperset() logic reduces policy metadata to a boolean
by using toPermissionItem() and then only checking parentItem.policy vs
childItem.policy; update it to preserve and compare the full policy payload
(policies array and decision_strategy) instead of collapsing to a single flag:
modify toPermissionItem() (or the mapping before mergePermissionItems) to carry
through policies and decision_strategy, and change the superset check in
isSuperset() to validate that parentItem.policies and
parentItem.decision_strategy actually cover/permit the childItem.policies and
childItem.decision_strategy (or call/extend
isPermissionItemEqual/mergePermissionItems to include those fields) so a parent
constrained by policy A cannot satisfy a child constrained by policy B. Ensure
the same fix is applied to the other occurrence at the later block (lines
147-153).

In `@apps/server-core/src/core/security/policy/evaluator.ts`:
- Around line 108-115: The code uses an unsafe assertion `(raw as any).policy`
when building items for mergePermissionItems from identityPermissions; fix by
adding an optional policy field to the Permission type (e.g., declare policy?:
PolicyWithType | null on Permission in the Permission entity) so the cast is
unnecessary, then remove the `(raw as any).policy` assertion in evaluator.ts;
alternatively, if the runtime field is intentional and cannot be typed, add an
inline comment next to the map explaining why policy may exist at runtime and
keep a narrower type (but prefer updating the Permission interface and
referencing PolicyWithType so mergePermissionItems consumes a properly typed
policy).

In `@docs/src/guide/user/permissions-and-policies.md`:
- Around line 105-106: Update the wording that currently limits "junction
policy" to role/user assignments so it explicitly covers machine identities:
change the phrasing in the two list items that mention "role or user assignment
that carries a junction policy" to say "role, user, client, or robot (machine
identity) assignment that carries a junction policy" and add a short example
sentence clarifying that client/robot permission bindings are evaluated the same
way; ensure both occurrences (the two spots flagged) are updated and that
examples/reference to "junction policy" include machine-identity bindings.

---

Outside diff comments:
In
`@apps/server-core/src/adapters/http/controllers/entities/identity-provide-role/module.ts`:
- Around line 212-220: The code dereferences data.role.client_id without
guarding data.role, which can cause a 500 when only data.role_id is provided; in
the block around useRequestIdentityOrFail and
this.identityPermissionProvider.isSuperset, first validate that data.role exists
(or extract clientId via a safe fallback) before calling isSuperset — e.g.,
check data.role and throw a controlled BadRequestError or ForbiddenError if
missing, or pass clientId = data.role?.client_id ?? /* fallback or error */ so
identityPermissionProvider.isSuperset is never invoked with an undefined
clientId; update the conditional that currently throws ForbiddenError to handle
the missing data.role case explicitly and reference data.role_id,
data.role.client_id, useRequestIdentityOrFail,
identityPermissionProvider.isSuperset, and ForbiddenError when making the
change.

---

Duplicate comments:
In @.agents/architecture.md:
- Around line 171-174: Update the ActorContext builder docs to match the
provider-based wiring used in code: replace references to the parameter and type
name `identityPermissionService` / `IdentityPermissionService` with the provider
naming/type used in the codebase (e.g., `identityPermissionProvider` or the
appropriate `Provider<...>` type), and update the example signature for
buildActorContext accordingly; ensure the same change is applied to the other
occurrence noted (around the second snippet) so documentation and code use the
same provider identifier and type.

In `@apps/server-core/src/core/entities/role-permission/service.ts`:
- Around line 84-90: The call to
actor.resolveJunctionPolicy(data.permission.name) only uses permission name and
can pick the wrong policy when the same permission exists in multiple realms;
change the call to pass the derived realm ids so resolution is scoped (e.g.,
actor.resolveJunctionPolicy(data.permission.name, realmIds) or
actor.resolveJunctionPolicy(data.permission.name, data.realm_ids)). Update the
resolveJunctionPolicy signature/implementation to accept and use the realm ids
parameter for disambiguation (ensure RolePermission service uses the
already-derived realm ids variable when invoking resolveJunctionPolicy).

---

Nitpick comments:
In
`@apps/server-core/src/app/modules/database/repositories/permission-provider/module.ts`:
- Around line 75-83: The loop that builds policies does sequential awaits,
causing unnecessary latency; instead collect promises from
this.policyRepository.findDescendantsTree for each junction that has a policy
(referencing junctions, policyRepository.findDescendantsTree, and the policies:
PolicyWithType[]), run them in parallel with Promise.all, then filter out
null/undefined results and push the trees into policies (or replace policies
with the resolved array). Ensure you preserve the original type
(PolicyWithType[]) and null-check/filter the results before using them.

In `@apps/server-core/src/app/modules/http/modules/controller.ts`:
- Around line 252-260: createIdentityPermissionProvider currently instantiates a
new IdentityPermissionProvider (and new ClientRepository, UserRepository,
RobotRepository, RoleRepository) each time it's called; change it to return a
cached/shared instance instead (or register IdentityPermissionProvider once in
the DI container at bootstrap) so repeated calls reuse the same
IdentityPermissionProvider and its repositories; locate the factory function
createIdentityPermissionProvider and ensure it stores/returns a single
module-level or container-scoped instance of IdentityPermissionProvider
(constructed with the same repositories) rather than creating new instances on
every invocation.

In `@packages/access/test/unit/permission/escalation.spec.ts`:
- Around line 30-32: The test suite is missing a case where both parent and
child PermissionItem have policies but differ; add a unit test in
escalation.spec.ts that calls isSupersetPolicyAware with parent and child
entries having different policy.type and/or policy.id (use PermissionItem and
BuiltInPolicyType to construct them) and assert the intended outcome (true if
differing policies are allowed, or false if they must match). If the intended
behavior is to reject differing policies, update isSupersetPolicyAware to
compare policy.type and policy.id for equality (or the required compatibility
rule) and add the corresponding test; if the intended behavior is to allow them,
add the explicit test to document that decision.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 92545f82-f120-43fc-b7b6-3f954db56d92

📥 Commits

Reviewing files that changed from the base of the PR and between 2d0efc3 and 71a9596.

📒 Files selected for processing (59)
  • .agents/architecture.md
  • apps/client-web/pages/permissions/[id].vue
  • apps/client-web/pages/permissions/[id]/policies.vue
  • apps/server-core/src/adapters/database/domains/permission-policy/entity.ts
  • apps/server-core/src/adapters/http/controllers/entities/client-permission/module.ts
  • apps/server-core/src/adapters/http/controllers/entities/client-role/module.ts
  • apps/server-core/src/adapters/http/controllers/entities/identity-provide-role/module.ts
  • apps/server-core/src/adapters/http/controllers/entities/permission/module.ts
  • apps/server-core/src/adapters/http/controllers/entities/policy/module.ts
  • apps/server-core/src/adapters/http/controllers/entities/robot-permission/module.ts
  • apps/server-core/src/adapters/http/controllers/entities/robot-role/module.ts
  • apps/server-core/src/adapters/http/controllers/entities/role-permission/module.ts
  • apps/server-core/src/adapters/http/controllers/entities/user-permission/module.ts
  • apps/server-core/src/adapters/http/controllers/entities/user-role/module.ts
  • apps/server-core/src/adapters/http/controllers/workflows/token/module.ts
  • apps/server-core/src/adapters/http/controllers/workflows/token/types.ts
  • apps/server-core/src/adapters/http/middleware/built-in/authorization/module.ts
  • apps/server-core/src/adapters/http/middleware/built-in/authorization/types.ts
  • apps/server-core/src/adapters/http/request/helpers/actor.ts
  • apps/server-core/src/app/modules/config/types.ts
  • apps/server-core/src/app/modules/database/repositories/index.ts
  • apps/server-core/src/app/modules/database/repositories/permission-provider/index.ts
  • apps/server-core/src/app/modules/database/repositories/permission-provider/module.ts
  • apps/server-core/src/app/modules/http/modules/controller.ts
  • apps/server-core/src/app/modules/http/modules/middleware.ts
  • apps/server-core/src/app/modules/provisioning/module.ts
  • apps/server-core/src/core/entities/actor/types.ts
  • apps/server-core/src/core/entities/client-permission/service.ts
  • apps/server-core/src/core/entities/permission-policy/service.ts
  • apps/server-core/src/core/entities/robot-permission/service.ts
  • apps/server-core/src/core/entities/role-permission/service.ts
  • apps/server-core/src/core/entities/user-permission/service.ts
  • apps/server-core/src/core/identity/index.ts
  • apps/server-core/src/core/identity/permission/index.ts
  • apps/server-core/src/core/identity/permission/module.ts
  • apps/server-core/src/core/identity/permission/types.ts
  • apps/server-core/src/core/index.ts
  • apps/server-core/src/core/security/index.ts
  • apps/server-core/src/core/security/policy/engine.ts
  • apps/server-core/src/core/security/policy/evaluator.ts
  • apps/server-core/src/core/security/policy/index.ts
  • apps/server-core/src/index.ts
  • apps/server-core/src/security/policy/constants.ts
  • apps/server-core/src/security/policy/index.ts
  • apps/server-core/src/services/index.ts
  • docs/src/guide/deployment/provisioning.md
  • docs/src/guide/user/permissions-and-policies.md
  • packages/access/src/permission/helpers/merge.ts
  • packages/access/test/unit/permission/escalation.spec.ts
  • packages/access/test/unit/permission/merge.spec.ts
  • packages/client-web-kit/src/components/entities/index.ts
  • packages/client-web-kit/src/components/entities/permission-policy/APermissionPolicyAssignment.ts
  • packages/client-web-kit/src/components/entities/permission-policy/APermissionPolicyAssignments.ts
  • packages/client-web-kit/src/components/entities/permission-policy/index.ts
  • packages/core-http-kit/src/client/module.ts
  • packages/core-http-kit/src/domains/entities/index.ts
  • packages/core-http-kit/src/domains/entities/permission-policy/index.ts
  • packages/core-http-kit/src/domains/entities/permission-policy/module.ts
  • packages/core-kit/src/domains/permission-policy/entity.ts
💤 Files with no reviewable changes (5)
  • apps/server-core/src/core/security/index.ts
  • apps/server-core/src/services/index.ts
  • apps/server-core/src/index.ts
  • apps/server-core/src/security/policy/index.ts
  • apps/server-core/src/security/policy/constants.ts
✅ Files skipped from review due to trivial changes (22)
  • apps/server-core/src/core/index.ts
  • apps/server-core/src/adapters/http/middleware/built-in/authorization/module.ts
  • apps/server-core/src/core/identity/index.ts
  • apps/server-core/src/app/modules/config/types.ts
  • apps/client-web/pages/permissions/[id].vue
  • apps/server-core/src/core/entities/robot-permission/service.ts
  • packages/client-web-kit/src/components/entities/index.ts
  • apps/server-core/src/core/entities/actor/types.ts
  • apps/server-core/src/adapters/http/middleware/built-in/authorization/types.ts
  • apps/server-core/src/core/identity/permission/index.ts
  • packages/core-http-kit/src/domains/entities/index.ts
  • packages/client-web-kit/src/components/entities/permission-policy/index.ts
  • apps/server-core/src/core/entities/client-permission/service.ts
  • apps/client-web/pages/permissions/[id]/policies.vue
  • packages/client-web-kit/src/components/entities/permission-policy/APermissionPolicyAssignment.ts
  • docs/src/guide/deployment/provisioning.md
  • packages/client-web-kit/src/components/entities/permission-policy/APermissionPolicyAssignments.ts
  • packages/access/test/unit/permission/merge.spec.ts
  • packages/core-kit/src/domains/permission-policy/entity.ts
  • packages/core-http-kit/src/domains/entities/permission-policy/module.ts
  • apps/server-core/src/core/entities/permission-policy/service.ts
  • apps/server-core/src/core/identity/permission/types.ts
🚧 Files skipped from review as they are similar to previous changes (12)
  • packages/core-http-kit/src/domains/entities/permission-policy/index.ts
  • apps/server-core/src/core/entities/user-permission/service.ts
  • apps/server-core/src/adapters/http/controllers/entities/client-permission/module.ts
  • apps/server-core/src/adapters/http/controllers/workflows/token/module.ts
  • apps/server-core/src/app/modules/provisioning/module.ts
  • apps/server-core/src/adapters/http/controllers/entities/client-role/module.ts
  • apps/server-core/src/adapters/http/controllers/entities/user-permission/module.ts
  • apps/server-core/src/adapters/http/controllers/entities/role-permission/module.ts
  • apps/server-core/src/adapters/database/domains/permission-policy/entity.ts
  • apps/server-core/src/app/modules/http/modules/middleware.ts
  • apps/server-core/src/adapters/http/request/helpers/actor.ts
  • packages/access/src/permission/helpers/merge.ts

Comment thread .agents/architecture.md Resolved
@tada5hi

tada5hi commented Mar 23, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Mar 23, 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.

♻️ Duplicate comments (2)
docs/src/guide/user/permissions-and-policies.md (2)

105-105: ⚠️ Potential issue | 🟡 Minor

Expand junction-policy scope to include all identity types.

The documentation still describes junction policies as "role or user assignment" specific, but the system also supports client and robot permission bindings. The resolveJunctionPolicy hook in the actor context works with all identity types.

Please update the wording to: "role, user, client, or robot assignment that carries a junction policy"

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

In `@docs/src/guide/user/permissions-and-policies.md` at line 105, Update the
sentence to expand junction-policy scope to all identity types by changing "role
or user assignment" to "role, user, client, or robot assignment that carries a
**junction policy**"; mention the resolveJunctionPolicy hook in the actor
context if helpful (e.g., "The resolveJunctionPolicy hook in the actor context
works with all identity types") to align docs with implementation.

121-121: ⚠️ Potential issue | 🟡 Minor

Include all identity types in junction policy documentation.

Similar to line 105, this line should explicitly mention all identity types that support junction policies: "Permission assignments (role-permission, user-permission, client-permission, robot-permission) can carry their own policy via the junction table."

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

In `@docs/src/guide/user/permissions-and-policies.md` at line 121, Update the
sentence that currently reads "Permission assignments (role-permission,
user-permission) can carry their own policy via the junction table." to
explicitly list all identity types that support junction policies by changing it
to mention "role-permission, user-permission, client-permission,
robot-permission" so it matches the wording used at line 105 and clearly
documents that client and robot identity types also support junction policies.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@docs/src/guide/user/permissions-and-policies.md`:
- Line 105: Update the sentence to expand junction-policy scope to all identity
types by changing "role or user assignment" to "role, user, client, or robot
assignment that carries a **junction policy**"; mention the
resolveJunctionPolicy hook in the actor context if helpful (e.g., "The
resolveJunctionPolicy hook in the actor context works with all identity types")
to align docs with implementation.
- Line 121: Update the sentence that currently reads "Permission assignments
(role-permission, user-permission) can carry their own policy via the junction
table." to explicitly list all identity types that support junction policies by
changing it to mention "role-permission, user-permission, client-permission,
robot-permission" so it matches the wording used at line 105 and clearly
documents that client and robot identity types also support junction policies.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 1d5ec026-e835-4537-9c9e-4ffd0d593c22

📥 Commits

Reviewing files that changed from the base of the PR and between 71a9596 and dbbb7ad.

📒 Files selected for processing (2)
  • docs/src/guide/deployment/provisioning.md
  • docs/src/guide/user/permissions-and-policies.md
✅ Files skipped from review due to trivial changes (1)
  • docs/src/guide/deployment/provisioning.md

@tada5hi

tada5hi commented Mar 23, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai resume

@coderabbitai

coderabbitai Bot commented Mar 23, 2026

Copy link
Copy Markdown
✅ Actions performed

Reviews resumed.

@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: 8

Caution

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

⚠️ Outside diff range comments (4)
apps/server-core/src/adapters/http/controllers/entities/identity-provider/module.ts (1)

93-111: ⚠️ Potential issue | 🔴 Critical

Fail-open authorization in read endpoints leaks protected data.

At Line 93 and Line 138, permission errors are caught and ignored, but responses are still sent. This bypasses IDENTITY_PROVIDER_READ enforcement for both list and single-item reads.

🔒 Suggested fail-closed fix
-        try {
-            const permissionEvaluator = useRequestPermissionEvaluator(req);
-            await permissionEvaluator.preEvaluate({ name: PermissionName.IDENTITY_PROVIDER_READ });
-
-            for (const datum of data) {
-                try {
-                    await permissionEvaluator.evaluate({
-                        name: PermissionName.IDENTITY_PROVIDER_READ,
-                        input: new PolicyData({
-                            [BuiltInPolicyType.ATTRIBUTES]: datum,
-                        }),
-                    });
-                } catch {
-                    // do nothing
-                }
-            }
-        } catch {
-            // do nothing
-        }
+        const permissionEvaluator = useRequestPermissionEvaluator(req);
+        await permissionEvaluator.preEvaluate({ name: PermissionName.IDENTITY_PROVIDER_READ });
+
+        const filtered : IdentityProvider[] = [];
+        for (const datum of data) {
+            try {
+                await permissionEvaluator.evaluate({
+                    name: PermissionName.IDENTITY_PROVIDER_READ,
+                    input: new PolicyData({
+                        [BuiltInPolicyType.ATTRIBUTES]: datum,
+                    }),
+                });
+                filtered.push(datum);
+            } catch {
+                // filtered out
+            }
+        }
 
         return send(res, {
-            data,
-            meta,
+            data: filtered,
+            meta: { ...meta, total: filtered.length },
         });
-        try {
-            const permissionEvaluator = useRequestPermissionEvaluator(req);
-            await permissionEvaluator.evaluate({
-                name: PermissionName.IDENTITY_PROVIDER_READ,
-                input: new PolicyData({
-                    [BuiltInPolicyType.ATTRIBUTES]: entity,
-                }),
-            });
-        } catch {
-            // do nothing
-        }
+        const permissionEvaluator = useRequestPermissionEvaluator(req);
+        await permissionEvaluator.evaluate({
+            name: PermissionName.IDENTITY_PROVIDER_READ,
+            input: new PolicyData({
+                [BuiltInPolicyType.ATTRIBUTES]: entity,
+            }),
+        });

Also applies to: 138-148

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

In
`@apps/server-core/src/adapters/http/controllers/entities/identity-provider/module.ts`
around lines 93 - 111, The current try/catch around
useRequestPermissionEvaluator/preEvaluate and per-item
permissionEvaluator.evaluate swallows authorization errors and returns data
(fail-open); change to fail-closed by propagating or handling failures: if
permissionEvaluator.preEvaluate throws, short-circuit and respond with a
403/authorization error for the whole request; for the per-item evaluate loop
(using PermissionName.IDENTITY_PROVIDER_READ, PolicyData,
BuiltInPolicyType.ATTRIBUTES), treat any evaluate rejection as “deny” and
exclude that datum from the response (or if this is single-item read, return
403), and remove the empty catch blocks so failures are handled explicitly and
logged via the request/response error path.
apps/server-core/src/core/entities/role/service.ts (1)

47-55: ⚠️ Potential issue | 🟠 Major

Don't satisfy reads with preEvaluateOneOf() alone.

These read paths now accept ROLE_UPDATE / ROLE_DELETE via a pre-check before any role data is loaded, but they never perform an entity-aware evaluate* afterward. That means attribute-scoped write permissions can still unlock broad role reads because no PolicyData is ever checked on getMany() / getOne(). Either gate reads on ROLE_READ only, or add post-fetch evaluateOneOf() filtering/validation when relying on write permissions to imply read access.

Also applies to: 62-75

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

In `@apps/server-core/src/core/entities/role/service.ts` around lines 47 - 55, The
current preEvaluateOneOf call (actor.permissionEvaluator.preEvaluateOneOf)
allows ROLE_UPDATE/ROLE_DELETE to satisfy read paths but never performs an
entity-aware check afterwards, so attribute-scoped write permissions can leak
reads; fix by either restricting the pre-check to PermissionName.ROLE_READ only
when calling repository.findMany/getOne, or (if you want
write-permissions-to-imply-read) fetch the entities via
repository.findMany/findOne and then run actor.permissionEvaluator.evaluateOneOf
(or evaluate* equivalent) against each returned entity/PolicyData to
filter/validate results before returning them; update both the code around the
preEvaluateOneOf call and the corresponding getMany/getOne paths to apply the
chosen approach consistently.
apps/server-core/src/adapters/http/controllers/entities/user-attribute/utils/authorization.ts (1)

36-40: ⚠️ Potential issue | 🟡 Minor

Dead code: !isMe check is unreachable in this catch block.

This catch block only handles exceptions thrown when isMe is true (line 26 condition). Therefore, !isMe on line 37 is always false, making the return false on line 38 unreachable.

If isMe is true and USER_SELF_MANAGE fails, execution falls through to line 55 and returns true—which may not be intended behavior.

Suggested fix if self-manage failure should deny access
     try {
         if (isMe) {
             await permissionEvaluator.evaluate({
                 name: PermissionName.USER_SELF_MANAGE,
                 input: new PolicyData({
                     [BuiltInPolicyType.ATTRIBUTES]: entity,
                 }),
             });

             return true;
         }
     } catch {
-        if (!isMe) {
-            return false;
-        }
+        return false;
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@apps/server-core/src/adapters/http/controllers/entities/user-attribute/utils/authorization.ts`
around lines 36 - 40, The catch block currently contains an unreachable check
"!isMe"; remove that check and make the catch explicitly deny access when
self-management authorization fails: inside the catch for the self-manage branch
(the code that checks isMe and calls USER_SELF_MANAGE), return false directly
(or rethrow if you prefer a failure to bubble), so that a failed
USER_SELF_MANAGE check for the case where isMe is true will result in denial;
update the catch in authorization.ts where isMe and USER_SELF_MANAGE are handled
accordingly.
apps/server-core/test/unit/core/helpers/mock-actor.ts (1)

41-52: ⚠️ Potential issue | 🟡 Minor

Populate identity.data.id in the realm actor fixtures.

The new junction-policy flow reads actor.identity.data.id, but both helpers still cast a partial User without that field. Any unit test that reaches resolveJunctionPolicy() through these fixtures will pass undefined as the actor id and fail for the wrong reason.

Also applies to: 55-66

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

In `@apps/server-core/test/unit/core/helpers/mock-actor.ts` around lines 41 - 52,
The realm actor fixtures (createMasterRealmActor and the similar helper at lines
55-66) leave identity.data.id undefined which breaks junction-policy resolution;
update createMasterRealmActor (and the other helper) to set identity.data.id to
the actor UUID (use the same local id variable) so actor.identity.data.id is
populated, keeping REALM_MASTER_NAME and existing structure and still returning
an ActorContext with permissionEvaluator from createMockPermissionEvaluator();
ensure the identity.type remains IdentityType.USER and identity.data includes
realm_id, id, and realm fields so resolveJunctionPolicy() receives a valid actor
id.
♻️ Duplicate comments (3)
apps/server-core/src/core/provisioning/synchronizer/role/module.ts (2)

96-119: ⚠️ Potential issue | 🟠 Major

Keep globalPermissionsPolicyName off realm permission bindings.

extraAttributes is computed once and then applied to the combined permissions array, so every realm permission in this batch inherits the global policy_id too. Scope the policy-bearing sync to globalPermissions only, and write realmPermissions without extraAttributes.

🤖 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/role/module.ts` around
lines 96 - 119, The code computes extraAttributes once and applies it to the
combined permissions array, causing realmPermissions to incorrectly inherit the
global policy; change the logic to sync globalPermissions and realmPermissions
separately: compute extraAttributes using
input.relations.globalPermissionsPolicyName and policyRepository as currently
done, then call this.permissionJunction.synchronize(attributes,
globalPermissions, 'permission_id', 'permission_realm_id', extraAttributes) only
for globalPermissions (if non-empty), and call
this.permissionJunction.synchronize(attributes, realmPermissions,
'permission_id', 'permission_realm_id') for realmPermissions without
extraAttributes (if non-empty); keep existing error handling when policy is not
found and reuse attributes, permissionJunction.synchronize, globalPermissions,
realmPermissions, input.relations.globalPermissionsPolicyName and
policyRepository to locate the changes.

104-112: ⚠️ Potential issue | 🔴 Critical

Fail fast when globalPermissionsPolicyName is set but no policy repository is available.

If ctx.policyRepository is undefined, the guard on Line 104 skips the lookup and still syncs the permissions without policy_id. That silently widens access compared to the provisioning config.

🔒 Suggested fix
-            if (input.relations.globalPermissionsPolicyName && this.policyRepository) {
+            if (input.relations.globalPermissionsPolicyName) {
+                if (!this.policyRepository) {
+                    throw new Error(
+                        'Provisioning: `globalPermissionsPolicyName` requires `policyRepository`.',
+                    );
+                }
+
                 const policy = await this.policyRepository.findOneByName(input.relations.globalPermissionsPolicyName);
                 if (!policy) {
                     throw new Error(
                         `Provisioning: policy '${input.relations.globalPermissionsPolicyName}' not found for role '${attributes.name}'.`,
                     );
                 }
                 extraAttributes = { policy_id: policy.id };
             }
🤖 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/role/module.ts` around
lines 104 - 112, If input.relations.globalPermissionsPolicyName is provided but
this.policyRepository is undefined, fail fast instead of silently continuing:
add a guard that throws a descriptive error when
input.relations.globalPermissionsPolicyName && !this.policyRepository
(mentioning the missing policy repository and the role name/attributes.name),
otherwise keep the existing lookup using this.policyRepository.findOneByName and
set extraAttributes = { policy_id: policy.id } as before; update the block that
currently checks input.relations.globalPermissionsPolicyName and
this.policyRepository to enforce this behavior.
apps/server-core/src/core/entities/role-permission/service.ts (1)

89-105: ⚠️ Potential issue | 🔴 Critical

Don't let callers bypass or mis-scope inherited role policies.

This branch still lets policy_id: null skip inherited scoping, and the resolver still only sees the permission tuple instead of data.role_realm_id. That means a scoped actor can persist an unscoped binding or copy the wrong inherited policy when the same permission exists in multiple role realms.

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

In `@apps/server-core/src/core/entities/role-permission/service.ts` around lines
89 - 105, The current branch lets callers bypass inherited scoping because it
only checks for typeof data.policy_id === 'undefined' (so policy_id: null slips
through) and the resolveJunctionPolicy call only receives the permission tuple
(so it can pick the wrong inherited policy when permissions exist in multiple
role realms). Change the guard to treat nullish policy_id (e.g., data.policy_id
== null) and call this.identityPermissionProvider.resolveJunctionPolicy with the
role realm included (pass data.role_realm_id along with name/realm_id/client_id)
so inherited policy resolution is scoped to data.role_realm_id; then assign
data.policy_id = junctionPolicy.id when found.
🧹 Nitpick comments (23)
packages/client-web-kit/src/core/store/create.ts (1)

157-161: Minor naming inconsistency: permissionRepository holds a Provider.

The variable permissionRepository is assigned a PermissionMemoryProvider instance. For consistency with the class rename, consider renaming the variable to permissionProvider.

✏️ Rename for consistency
-    const permissionRepository = new PermissionMemoryProvider();
+    const permissionProvider = new PermissionMemoryProvider();
     const permissionEvaluator = new PermissionEvaluator({
-        repository: permissionRepository,
+        repository: permissionProvider,
         policyEngine: new PolicyEngine(),
     });

And update the cleanup call:

-        permissionRepository.setMany([]);
+        permissionProvider.setMany([]);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/client-web-kit/src/core/store/create.ts` around lines 157 - 161, The
variable permissionRepository is misnamed because it holds a
PermissionMemoryProvider instance; rename permissionRepository to
permissionProvider wherever it's declared and used (including where passed into
new PermissionEvaluator and any cleanup calls), and update the corresponding
cleanup invocation that references the old name so all references use
permissionProvider consistently with the PermissionMemoryProvider class.
apps/server-core/src/adapters/database/domains/user/repository.ts (1)

122-138: Duplicate implementation of loadPolicyTrees.

This helper method is identical to the one in ClientRepository (and likely RobotRepository and RoleRepository based on the similar patterns). Consider extracting this into a shared utility or base class to reduce code duplication.

Additionally, the same N+1 query pattern concern applies here—consider parallel loading with Promise.all.

♻️ Extract shared helper

Consider creating a shared utility function:

// In a shared module, e.g., ../policy/helpers.ts
export async function loadPolicyTrees(
    manager: EntityManager,
    policyIds: string[]
): Promise<Record<string, PolicyWithType>> {
    if (policyIds.length === 0) {
        return {};
    }

    const policyRepository = new PolicyRepository(manager);
    const trees = await Promise.all(
        policyIds.map(async (id) => {
            const tree = await policyRepository.findDescendantsTreeById(id);
            return { id, tree };
        })
    );

    const result: Record<string, PolicyWithType> = {};
    for (const { id, tree } of trees) {
        if (tree) {
            result[id] = tree;
        }
    }
    return result;
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/adapters/database/domains/user/repository.ts` around
lines 122 - 138, The private method loadPolicyTrees duplicates logic across
repositories and does sequential DB calls; extract it into a shared helper
(e.g., a module function or a base repository method) that accepts the
EntityManager (or this.manager) and policyIds, then call
PolicyRepository.findDescendantsTreeById in parallel using Promise.all to
assemble and return a Record<string, PolicyWithType>; update UserRepository (and
ClientRepository/RobotRepository/RoleRepository) to call the new shared
loadPolicyTrees(manager, policyIds) instead of the in-class implementation.
packages/access/src/permission/types.ts (1)

10-18: Consider using a stricter type for decision_strategy.

The decision_strategy field is typed as string | null, but based on the usage in merge.ts (where it's cast to `${DecisionStrategy}`), this should ideally reference the DecisionStrategy enum or its string literal union for type safety.

🔧 Suggested type improvement
+import type { DecisionStrategy } from '../constants';
 import type { PolicyWithType } from '../policy';

 export type PermissionBinding = {
     permission: {
         name: string,
         client_id?: string | null,
         realm_id?: string | null,
-        decision_strategy?: string | null,
+        decision_strategy?: `${DecisionStrategy}` | null,
     },
     policies?: PolicyWithType[],
 };
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/access/src/permission/types.ts` around lines 10 - 18, The
PermissionBinding type declares decision_strategy as string | null which is too
permissive; update PermissionBinding to use the DecisionStrategy enum (or its
string-literal union) instead of plain string so callers are type-safe — replace
the decision_strategy type with DecisionStrategy | null (or
`${DecisionStrategy}` | null if the codebase uses template-literal typing) and
update imports/usages (e.g., where merge.ts casts to `${DecisionStrategy}`) to
align with the enum type.
apps/server-core/src/adapters/database/domains/client/repository.ts (2)

116-121: Sequential policy tree loading creates N+1 query pattern.

Each policy tree is loaded individually in a loop, resulting in N database round-trips where N is the number of unique policy IDs. This can significantly impact performance when many permissions have policies.

Consider adding a batch loading method to PolicyRepository or using Promise.all for parallel loading:

⚡ Parallel loading improvement
     private async loadPolicyTrees(policyIds: string[]): Promise<Record<string, PolicyWithType>> {
         if (policyIds.length === 0) {
             return {};
         }

-        const policyRepository = new PolicyRepository(this.#manager);
+        const policyRepository = new PolicyRepository(this.manager);
         const result: Record<string, PolicyWithType> = {};

-        for (const id of policyIds) {
-            const tree = await policyRepository.findDescendantsTreeById(id);
-            if (tree) {
-                result[id] = tree;
-            }
-        }
+        const trees = await Promise.all(
+            policyIds.map(async (id) => {
+                const tree = await policyRepository.findDescendantsTreeById(id);
+                return { id, tree };
+            })
+        );
+
+        for (const { id, tree } of trees) {
+            if (tree) {
+                result[id] = tree;
+            }
+        }

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

In `@apps/server-core/src/adapters/database/domains/client/repository.ts` around
lines 116 - 121, The loop over policyIds causes an N+1 query pattern by calling
policyRepository.findDescendantsTreeById serially; fix by loading trees in
parallel or adding a batch loader on PolicyRepository: either replace the
for-loop with Promise.all(policyIds.map(id =>
policyRepository.findDescendantsTreeById(id))) and then populate result[id] for
each resolved tree, or implement and call a new
policyRepository.findDescendantsTreesByIds(policyIds) that returns all trees in
one DB call and assign them into result using the policy id keys.

20-24: Redundant #manager field.

The ClientRepository extends Repository<ClientEntity> which already provides this.manager. Storing a separate #manager field is redundant since the same manager instance is accessible via the inherited property.

♻️ Remove redundant field
 export class ClientRepository extends Repository<ClientEntity> {
-    `#manager`: EntityManager;
-
     constructor(instance: DataSource | EntityManager) {
         super(ClientEntity, InstanceChecker.isDataSource(instance) ? instance.manager : instance);
-        this.#manager = InstanceChecker.isDataSource(instance) ? instance.manager : instance;
     }

Then use this.manager in loadPolicyTrees:

     private async loadPolicyTrees(policyIds: string[]): Promise<Record<string, PolicyWithType>> {
         // ...
-        const policyRepository = new PolicyRepository(this.#manager);
+        const policyRepository = new PolicyRepository(this.manager);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/adapters/database/domains/client/repository.ts` around
lines 20 - 24, ClientRepository currently defines a redundant private field
"#manager" and assigns it in the constructor even though
Repository<ClientEntity> already exposes this.manager; remove the "#manager"
declaration and any assignments to it in the constructor (keep the
super(ClientEntity, InstanceChecker.isDataSource(instance) ? instance.manager :
instance) call) and update loadPolicyTrees to reference this.manager instead of
this.#manager so the inherited manager is used consistently.
docs/src/sdks/javascript/access/permission-checker.md (2)

1-6: Consider renaming this documentation file.

The file is named permission-checker.md but now documents the PermissionEvaluator class. Consider renaming to permission-evaluator.md for consistency with the API changes.

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

In `@docs/src/sdks/javascript/access/permission-checker.md` around lines 1 - 6,
The documentation filename is inconsistent with the documented class: rename the
file permission-checker.md to permission-evaluator.md and update any internal
references/links to use the new name; ensure the header and any frontmatter
still reference PermissionEvaluator and that cross-references (if any) pointing
to permission-checker.md are updated to permission-evaluator.md so docs and API
names (PermissionEvaluator, PermissionMemoryProvider) match.

45-49: Inconsistent naming: repository parameter accepts a Provider.

The PermissionEvaluator constructor uses repository as the parameter name but is initialized with a PermissionMemoryProvider. Consider whether this parameter should be renamed to provider for consistency, or clarify in the documentation that providers implement the repository interface.

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

In `@docs/src/sdks/javascript/access/permission-checker.md` around lines 45 - 49,
The constructor parameter name is inconsistent: change the PermissionEvaluator
constructor parameter from repository to provider (and update all usages) so it
clearly accepts a PermissionMemoryProvider, i.e., update the PermissionEvaluator
signature and internal references to use "provider" and adjust the example in
permission-checker.md (where PermissionMemoryProvider is passed) to match;
alternatively, if you prefer to keep "repository", add a clarifying sentence in
the docs stating that providers implement the repository interface and are
accepted by PermissionEvaluator.
apps/server-core/test/unit/core/entities/client-scope/service.spec.ts (3)

31-42: Test description doesn't match the updated assertion.

The test description says "should call preCheckOneOf" but the assertion verifies preEvaluateOneOf.

📝 Suggested fix
-        it('should call preCheckOneOf with client permissions', async () => {
+        it('should call preEvaluateOneOf with client permissions', async () => {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/test/unit/core/entities/client-scope/service.spec.ts` around
lines 31 - 42, Update the test description to match the assertion: change the
it(...) string for the getMany spec to mention preEvaluateOneOf instead of
preCheckOneOf so it reads something like "should call preEvaluateOneOf with
client permissions"; locate the test around the service.getMany invocation and
the expectation on actor.permissionEvaluator.preEvaluateOneOf and only update
the description text to reflect the actual method being asserted.

102-109: Test description doesn't match the updated assertion.

The test description says "should call preCheck" but the assertion verifies preEvaluate.

📝 Suggested fix
-        it('should call preCheck with CLIENT_SCOPE_DELETE', async () => {
+        it('should call preEvaluate with CLIENT_SCOPE_DELETE', async () => {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/test/unit/core/entities/client-scope/service.spec.ts` around
lines 102 - 109, Update the test description to match the assertion: change the
it() message from "should call preCheck with CLIENT_SCOPE_DELETE" to "should
call preEvaluate with CLIENT_SCOPE_DELETE" (or vice-verify by replacing the
assertion to expect preCheck if that was intended). Locate the test using
service.delete(entity.id, actor) and the actor.permissionEvaluator.preEvaluate
call and make the description and assertion consistent (referencing
PermissionName.CLIENT_SCOPE_DELETE and actor.permissionEvaluator.preEvaluate).

76-82: Test description doesn't match the updated assertion.

The test description says "should call preCheck" but the assertion verifies preEvaluate.

📝 Suggested fix
-        it('should call preCheck with CLIENT_SCOPE_CREATE', async () => {
+        it('should call preEvaluate with CLIENT_SCOPE_CREATE', async () => {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/test/unit/core/entities/client-scope/service.spec.ts` around
lines 76 - 82, The test's description is out of sync with the assertion — update
the it() description to reflect that it verifies permissionEvaluator.preEvaluate
was called; specifically change the test description for the test that calls
service.create(...) to say "should call preEvaluate with CLIENT_SCOPE_CREATE"
(referencing the actor.permissionEvaluator.preEvaluate call and
PermissionName.CLIENT_SCOPE_CREATE) so the text matches the assertion.
apps/server-core/test/unit/core/entities/realm/service.spec.ts (2)

193-202: Test description doesn't match the updated assertion.

The test description says "should call preCheck" but the assertion verifies preEvaluate.

📝 Suggested fix
-        it('should call preCheck with REALM_DELETE permission', async () => {
+        it('should call preEvaluate with REALM_DELETE permission', async () => {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/test/unit/core/entities/realm/service.spec.ts` around lines
193 - 202, Update the test's description to match the actual assertion: change
the it(...) description for the test that calls service.delete to say "should
call preEvaluate with REALM_DELETE permission" (or similar) so it reflects the
call to actor.permissionEvaluator.preEvaluate; locate the test block referencing
repository.seed/createFakeRealm, service.delete, and PermissionName.REALM_DELETE
and update only the string passed to it(...) to match the assertion.

70-77: Test description doesn't match the updated assertion.

The test description says "should call preCheck" but the assertion verifies preEvaluate.

📝 Suggested fix
-        it('should call preCheck with REALM_CREATE permission', async () => {
+        it('should call preEvaluate with REALM_CREATE permission', async () => {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/test/unit/core/entities/realm/service.spec.ts` around lines
70 - 77, The test description is inaccurate: update the it() description to
reflect that the code asserts actor.permissionEvaluator.preEvaluate was called
(or alternatively change the assertion to preCheck if that was intended); locate
the test around service.create and the assertion referencing
actor.permissionEvaluator.preEvaluate and PermissionName.REALM_CREATE and rename
the string "should call preCheck with REALM_CREATE permission" to "should call
preEvaluate with REALM_CREATE permission" (or swap the assertion to use preCheck
if you prefer that behavior).
apps/server-core/test/unit/core/entities/client-permission/service.spec.ts (3)

31-41: Test description doesn't match the updated assertion.

The test description says "should call preCheckOneOf" but the assertion now verifies preEvaluateOneOf. Consider updating the description for consistency.

📝 Suggested fix
-        it('should call preCheckOneOf with correct permissions', async () => {
+        it('should call preEvaluateOneOf with correct permissions', async () => {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/test/unit/core/entities/client-permission/service.spec.ts`
around lines 31 - 41, Update the test description to match the actual assertion:
inside the describe('getMany') block change the it(...) title from "should call
preCheckOneOf with correct permissions" to "should call preEvaluateOneOf with
correct permissions" so it reflects that the test verifies
actor.permissionEvaluator.preEvaluateOneOf is called with the
PermissionName.CLIENT_PERMISSION_CREATE and
PermissionName.CLIENT_PERMISSION_DELETE keys; keep the existing call to
service.getMany({}, actor) and the expect for preEvaluateOneOf unchanged.

75-86: Test description doesn't match the updated assertion.

The test description says "should preCheck permission name" but the assertion verifies preEvaluate.

📝 Suggested fix
-        it('should preCheck permission name when permission is provided', async () => {
+        it('should preEvaluate permission name when permission is provided', async () => {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/test/unit/core/entities/client-permission/service.spec.ts`
around lines 75 - 86, The test description and assertion are inconsistent:
update either the it() description or the assertion so they match; specifically,
change the test title "should preCheck permission name when permission is
provided" to reflect that it verifies actor.permissionEvaluator.preEvaluate was
called (e.g., "should call preEvaluate for provided permission name"), or
alternatively change the assertion to expect the preCheck method if you intended
to assert preCheck; locate the test that calls service.create(...) and checks
actor.permissionEvaluator.preEvaluate and make the wording and the asserted
method (preEvaluate vs preCheck) consistent.

106-113: Test description doesn't match the updated assertion.

The test description says "should call preCheck" but the assertion verifies preEvaluate.

📝 Suggested fix
-        it('should call preCheck with CLIENT_PERMISSION_DELETE', async () => {
+        it('should call preEvaluate with CLIENT_PERMISSION_DELETE', async () => {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/test/unit/core/entities/client-permission/service.spec.ts`
around lines 106 - 113, Update the test description to match the assertion:
change the "should call preCheck with CLIENT_PERMISSION_DELETE" text to
something like "should call preEvaluate with CLIENT_PERMISSION_DELETE" so it
accurately describes that service.delete triggers
actor.permissionEvaluator.preEvaluate with { name:
PermissionName.CLIENT_PERMISSION_DELETE }; locate this in the test case around
service.delete(...) and actor.permissionEvaluator.preEvaluate to rename the
it(...) description accordingly.
packages/client-web-kit/src/composables/use-permission-check.ts (1)

8-13: Finish the checker→evaluator rename in this path.

usePermissionCheck() now accepts PermissionEvaluationContext, but it still delegates to createPermissionCheckerReactiveFn(). Keeping both terms in the same client-facing API makes the migration harder to follow and grep later. Consider renaming or re-exporting the helper under evaluator terminology in this PR.

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

In `@packages/client-web-kit/src/composables/use-permission-check.ts` around lines
8 - 13, The public API uses "evaluator" terminology but still calls
createPermissionCheckerReactiveFn; update this file to finish the rename by
importing and invoking the evaluator-named helper (e.g.,
createPermissionEvaluatorReactiveFn) or import a re-export from ../core that
maps createPermissionEvaluatorReactiveFn to the existing implementation, then
call that from usePermissionCheck(ctx: PermissionEvaluationContext) so the file
consistently uses evaluator names (referencing usePermissionCheck and
createPermissionCheckerReactiveFn/createPermissionEvaluatorReactiveFn to locate
where to change).
apps/server-core/src/app/modules/http/modules/middleware.ts (1)

143-149: Prefer resolving these authorization providers from DI.

Constructing PermissionDatabaseProvider and IdentityPermissionProvider here hard-wires the authorization path to a raw DataSource and concrete repositories. That makes auth the one place that can miss future container overrides, repository decoration, or lifecycle changes. Register these providers in the container and resolve them here instead.

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

In `@apps/server-core/src/app/modules/http/modules/middleware.ts` around lines 143
- 149, Instead of directly instantiating PermissionDatabaseProvider and
IdentityPermissionProvider with new (and new
ClientRepository/UserRepository/RobotRepository/RoleRepository using the raw
dataSource), resolve those providers from the DI container so container-managed
instances, decorators, and lifecycle are honored; replace the new
PermissionDatabaseProvider(...) and new IdentityPermissionProvider({ ... })
calls with container.resolve or the project’s DI helper to fetch
PermissionDatabaseProvider and IdentityPermissionProvider (which will already be
wired to the correct repository implementations), and remove the explicit
construction of ClientRepository/UserRepository/RobotRepository/RoleRepository
using dataSource in this module.
apps/server-core/test/unit/core/entities/robot-permission/service.spec.ts (1)

32-32: Nit: Test descriptions still reference old method names.

The test descriptions mention "preCheckOneOf" and "preCheck" while the assertions use preEvaluateOneOf and preEvaluate. Consider updating the descriptions for consistency.

Also applies to: 75-75, 106-106

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

In `@apps/server-core/test/unit/core/entities/robot-permission/service.spec.ts` at
line 32, Update the test description strings to match the current method names:
replace mentions of "preCheckOneOf" with "preEvaluateOneOf" and "preCheck" with
"preEvaluate" in the relevant it(...) blocks so the human-readable descriptions
align with the assertions that call preEvaluateOneOf and preEvaluate; search for
the failing specs in the robot-permission service tests (the it(...) blocks
around the assertions referencing preEvaluateOneOf and preEvaluate) and edit
their description text accordingly.
apps/server-core/test/unit/core/entities/robot/service.spec.ts (1)

128-128: Nit: Test descriptions reference old method names.

Several test descriptions still mention "checkOneOf" and "preCheck" while the actual assertions use evaluateOneOf and preEvaluate. Consider updating for consistency:

  • Line 128: "should call checkOneOf" → "should call evaluateOneOf"
  • Line 171: "should call preCheck" → "should call preEvaluate"
  • Line 227: "should call preCheck" → "should call preEvaluate"
  • Line 236: "should not call preCheck" → "should not call preEvaluate"

Also applies to: 171-171, 227-227, 236-236

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

In `@apps/server-core/test/unit/core/entities/robot/service.spec.ts` at line 128,
Update the test case descriptions to match the renamed methods: replace
occurrences of "checkOneOf" with "evaluateOneOf" and "preCheck" with
"preEvaluate" in the spec so descriptions accurately reflect the assertions.
Specifically change the "it" titles that reference checkOneOf to mention
evaluateOneOf and any titles that reference preCheck to mention preEvaluate,
ensuring consistency with the tested functions evaluateOneOf and preEvaluate in
service.spec.ts.
apps/server-core/src/adapters/database/domains/robot/repository.ts (1)

113-128: Avoid serial policy-tree lookups here.

loadPolicyTrees() waits for each findDescendantsTreeById() call before starting the next one. Since getBoundPermissions() now feeds permission evaluation and introspection, latency will grow linearly with the number of unique policy_ids. This is a good spot for batching or at least parallel resolution.

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

In `@apps/server-core/src/adapters/database/domains/robot/repository.ts` around
lines 113 - 128, loadPolicyTrees currently fetches each policy tree serially by
awaiting PolicyRepository.findDescendantsTreeById(id) inside the loop, causing
O(n) latency; change it to resolve trees in parallel (or use a batch repository
method if available) by invoking all lookups concurrently (e.g., Promise.all
over policyIds.map(id => policyRepository.findDescendantsTreeById(id))) and then
mapping results back to Record<string, PolicyWithType>; reference symbols:
loadPolicyTrees, PolicyRepository, findDescendantsTreeById, and callers such as
getBoundPermissions to ensure the parallelized results are used the same way.
apps/server-core/src/adapters/database/domains/role/repository.ts (1)

127-132: Sequential async calls create N+1 query pattern.

The for...of loop with await inside fetches policy trees sequentially. For roles with many distinct policies, this serializes database round-trips unnecessarily.

♻️ Parallelize policy tree loading
     private async loadPolicyTrees(policyIds: string[]): Promise<Record<string, PolicyWithType>> {
         if (policyIds.length === 0) {
             return {};
         }

         const policyRepository = new PolicyRepository(this.manager);
         const result: Record<string, PolicyWithType> = {};

-        for (const id of policyIds) {
-            const tree = await policyRepository.findDescendantsTreeById(id);
-            if (tree) {
-                result[id] = tree;
-            }
-        }
+        const trees = await Promise.all(
+            policyIds.map((id) => policyRepository.findDescendantsTreeById(id)),
+        );
+
+        for (let i = 0; i < policyIds.length; i++) {
+            if (trees[i]) {
+                result[policyIds[i]] = trees[i];
+            }
+        }

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

In `@apps/server-core/src/adapters/database/domains/role/repository.ts` around
lines 127 - 132, The loop over policyIds performs sequential awaits causing N+1
queries; change it to run finds in parallel by mapping policyIds to promises via
policyRepository.findDescendantsTreeById and awaiting Promise.all, then iterate
the resolved array to populate result (keep reference to policyIds order or
include id with each promise if needed); update the block that currently uses
"for (const id of policyIds)" and "await
policyRepository.findDescendantsTreeById(id)" to use Promise.all on the mapped
promises and then assign trees into the existing result object.
apps/server-core/src/core/identity/permission/module.ts (1)

99-116: Consider exhaustiveness check instead of silent fallback.

The return [] at line 115 is unreachable if identity.type is a discriminated union covering all cases. For better type safety and to catch future additions:

♻️ Add exhaustiveness check
         switch (identity.type) {
             case 'client': {
                 return this.getForClient(identity);
             }
             case 'user': {
                 return this.getForUser(identity);
             }
             case 'robot': {
                 return this.getForRobot(identity);
             }
             case 'role': {
                 return this.getForRole(identity);
             }
+            default: {
+                const _exhaustive: never = identity.type;
+                return [];
+            }
         }
-
-        return [];
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/core/identity/permission/module.ts` around lines 99 -
116, The switch in getFor(identity: IdentityPolicyData):
Promise<PermissionBinding[]> currently falls through to a silent `return []`;
replace that with an exhaustiveness check: add a `default`/`throw` branch (or an
assertNever helper) that takes the unhandled `identity.type` and throws a
descriptive error so the compiler will catch missing variants of the
discriminated union in IdentityPolicyData and avoid silent fallbacks in getFor.
apps/server-core/src/app/modules/http/modules/controller.ts (1)

252-260: Repeated instantiation of IdentityPermissionProvider and repositories.

createIdentityPermissionProvider is called 11 times throughout this module, each time creating 4 new repository instances. This results in ~44 repository objects instead of sharing a single provider instance.

Consider caching the provider instance or creating it once in mount() and passing it to factory methods.

♻️ Cache the provider instance
 export class HTTPControllerModule {
+    private identityPermissionProvider?: IdentityPermissionProvider;
+
+    private getIdentityPermissionProvider(container: IDIContainer): IdentityPermissionProvider {
+        if (!this.identityPermissionProvider) {
+            this.identityPermissionProvider = this.createIdentityPermissionProvider(container);
+        }
+        return this.identityPermissionProvider;
+    }
+
     async mount(router: Router, container: IDIContainer): Promise<void> {

Then replace all this.createIdentityPermissionProvider(container) calls with this.getIdentityPermissionProvider(container).

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

In `@apps/server-core/src/app/modules/http/modules/controller.ts` around lines 252
- 260, createIdentityPermissionProvider repeatedly constructs new
IdentityPermissionProvider and four repository instances each time it's called,
causing multiple duplicate objects; change this to create or cache a single
provider instance and reuse it. Implement a
getIdentityPermissionProvider(container) that returns a cached
IdentityPermissionProvider (create it on first call), or instantiate the
provider once inside mount() and pass that instance into places that currently
call createIdentityPermissionProvider; update all calls to
this.createIdentityPermissionProvider(container) to use
this.getIdentityPermissionProvider(container) or the single instance created in
mount(), referencing the createIdentityPermissionProvider,
getIdentityPermissionProvider and mount functions/classes to locate the code to
modify.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: ffe4cefe-ee17-4308-8cfd-f6d24b39e511

📥 Commits

Reviewing files that changed from the base of the PR and between dbbb7ad and e5d973a.

📒 Files selected for processing (82)
  • apps/client-web/config/layout/module.ts
  • apps/server-core/src/adapters/database/domains/client/repository.ts
  • apps/server-core/src/adapters/database/domains/permission/subscriber.ts
  • apps/server-core/src/adapters/database/domains/policy/repository.ts
  • apps/server-core/src/adapters/database/domains/robot/repository.ts
  • apps/server-core/src/adapters/database/domains/role/repository.ts
  • apps/server-core/src/adapters/database/domains/user/repository.ts
  • apps/server-core/src/adapters/http/controllers/entities/identity-provide-role/module.ts
  • apps/server-core/src/adapters/http/controllers/entities/identity-provider/module.ts
  • apps/server-core/src/adapters/http/controllers/entities/permission/module.ts
  • apps/server-core/src/adapters/http/controllers/entities/user-attribute/utils/authorization.ts
  • apps/server-core/src/adapters/http/controllers/workflows/token/module.ts
  • apps/server-core/src/adapters/http/middleware/built-in/authorization/module.ts
  • apps/server-core/src/adapters/http/middleware/built-in/authorization/types.ts
  • apps/server-core/src/adapters/http/request/helpers/actor.ts
  • apps/server-core/src/adapters/http/request/permission/helper.ts
  • apps/server-core/src/adapters/http/request/permission/module.ts
  • apps/server-core/src/app/modules/database/repositories/permission-provider/module.ts
  • apps/server-core/src/app/modules/http/modules/controller.ts
  • apps/server-core/src/app/modules/http/modules/middleware.ts
  • apps/server-core/src/core/entities/actor/types.ts
  • apps/server-core/src/core/entities/client-permission/service.ts
  • apps/server-core/src/core/entities/client-role/service.ts
  • apps/server-core/src/core/entities/client-scope/service.ts
  • apps/server-core/src/core/entities/client/service.ts
  • apps/server-core/src/core/entities/permission-policy/service.ts
  • apps/server-core/src/core/entities/permission/service.ts
  • apps/server-core/src/core/entities/policy/service.ts
  • apps/server-core/src/core/entities/realm/service.ts
  • apps/server-core/src/core/entities/robot-permission/service.ts
  • apps/server-core/src/core/entities/robot-role/service.ts
  • apps/server-core/src/core/entities/robot/service.ts
  • apps/server-core/src/core/entities/role-attribute/service.ts
  • apps/server-core/src/core/entities/role-permission/service.ts
  • apps/server-core/src/core/entities/role/service.ts
  • apps/server-core/src/core/entities/scope/service.ts
  • apps/server-core/src/core/entities/user-attribute/service.ts
  • apps/server-core/src/core/entities/user-permission/service.ts
  • apps/server-core/src/core/entities/user-role/service.ts
  • apps/server-core/src/core/entities/user/service.ts
  • apps/server-core/src/core/identity/permission/module.ts
  • apps/server-core/src/core/identity/permission/types.ts
  • apps/server-core/src/core/provisioning/synchronizer/role/module.ts
  • apps/server-core/src/core/security/policy/evaluator.ts
  • apps/server-core/test/unit/core/entities/client-permission/service.spec.ts
  • apps/server-core/test/unit/core/entities/client-role/service.spec.ts
  • apps/server-core/test/unit/core/entities/client-scope/service.spec.ts
  • apps/server-core/test/unit/core/entities/client/service.spec.ts
  • apps/server-core/test/unit/core/entities/permission/service.spec.ts
  • apps/server-core/test/unit/core/entities/realm/service.spec.ts
  • apps/server-core/test/unit/core/entities/robot-permission/service.spec.ts
  • apps/server-core/test/unit/core/entities/robot-role/service.spec.ts
  • apps/server-core/test/unit/core/entities/robot/service.spec.ts
  • apps/server-core/test/unit/core/entities/role-attribute/service.spec.ts
  • apps/server-core/test/unit/core/entities/role-permission/service.spec.ts
  • apps/server-core/test/unit/core/entities/role/service.spec.ts
  • apps/server-core/test/unit/core/entities/scope/service.spec.ts
  • apps/server-core/test/unit/core/entities/user-attribute/service.spec.ts
  • apps/server-core/test/unit/core/entities/user-permission/service.spec.ts
  • apps/server-core/test/unit/core/entities/user-role/service.spec.ts
  • apps/server-core/test/unit/core/entities/user/service.spec.ts
  • apps/server-core/test/unit/core/helpers/mock-actor.ts
  • docs/src/guide/user/permissions-and-policies.md
  • docs/src/sdks/javascript/access/api-reference.md
  • docs/src/sdks/javascript/access/permission-checker.md
  • packages/access/src/permission/checker/module.ts
  • packages/access/src/permission/checker/types.ts
  • packages/access/src/permission/helpers/equal.ts
  • packages/access/src/permission/helpers/key.ts
  • packages/access/src/permission/helpers/merge.ts
  • packages/access/src/permission/repository/memory.ts
  • packages/access/src/permission/repository/types.ts
  • packages/access/src/permission/types.ts
  • packages/access/test/unit/permission/checker.spec.ts
  • packages/access/test/unit/permission/escalation.spec.ts
  • packages/access/test/unit/permission/merge.spec.ts
  • packages/client-web-kit/src/components/entities/permission/APermissionCheck.ts
  • packages/client-web-kit/src/composables/use-permission-check.ts
  • packages/client-web-kit/src/core/permission-check/module.ts
  • packages/client-web-kit/src/core/permission-check/types.ts
  • packages/client-web-kit/src/core/store/create.ts
  • packages/client-web-nuxt/src/runtime/helpers/routing-interceptor.ts
✅ Files skipped from review due to trivial changes (5)
  • packages/client-web-kit/src/components/entities/permission/APermissionCheck.ts
  • packages/client-web-kit/src/core/permission-check/types.ts
  • apps/server-core/src/core/entities/role-attribute/service.ts
  • packages/access/test/unit/permission/escalation.spec.ts
  • packages/access/src/permission/checker/module.ts
🚧 Files skipped from review as they are similar to previous changes (14)
  • apps/server-core/src/adapters/database/domains/permission/subscriber.ts
  • apps/server-core/src/core/entities/policy/service.ts
  • apps/server-core/src/adapters/http/controllers/entities/identity-provide-role/module.ts
  • apps/server-core/src/app/modules/database/repositories/permission-provider/module.ts
  • apps/server-core/src/core/entities/client-permission/service.ts
  • packages/access/test/unit/permission/checker.spec.ts
  • packages/access/src/permission/repository/types.ts
  • apps/server-core/src/core/entities/user-permission/service.ts
  • packages/access/test/unit/permission/merge.spec.ts
  • apps/server-core/src/adapters/http/middleware/built-in/authorization/types.ts
  • apps/server-core/src/adapters/http/controllers/entities/permission/module.ts
  • apps/server-core/src/adapters/http/middleware/built-in/authorization/module.ts
  • packages/access/src/permission/helpers/key.ts
  • packages/access/src/permission/checker/types.ts

Comment on lines +33 to +40
await actor.permissionEvaluator.preEvaluateOneOf({
name: [
PermissionName.PERMISSION_READ,
PermissionName.PERMISSION_UPDATE,
],
});

return this.repository.findMany(query);

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 | 🔴 Critical

Add attribute-level authorization for reads (realm-scope bypass risk).

At Line 33 and Line 47, read paths only run preEvaluateOneOf(...) and then return data directly. This skips attribute-scoped evaluation (used in create/delete) and can leak cross-realm PermissionPolicy records when realm constraints depend on entity attributes.

Please add an evaluate(...) step with PolicyData (or enforce equivalent realm filter before fetch/return) for both getMany and getOne.

Also applies to: 47-59

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

In `@apps/server-core/src/core/entities/permission-policy/service.ts` around lines
33 - 40, The read paths (getMany and getOne) currently call
actor.permissionEvaluator.preEvaluateOneOf(...) and then return
repository.findMany/findOne, skipping attribute-level checks; update both
methods to call actor.permissionEvaluator.evaluate(...) with the appropriate
PolicyData (constructed from the query/entity attributes and the
PermissionName.PERMISSION_READ) and use the evaluator result to enforce
attribute-level filtering or to add an equivalent realm-scoped filter before
calling repository.findMany/findOne (or filter the returned result), referencing
the existing preEvaluateOneOf usage and the PermissionName.PERMISSION_READ
constant so the attribute-level evaluation is applied consistently for getMany
and getOne.

Comment on lines +68 to +76
await this.repository.validateJoinColumns(data);

if (data.permission) {
data.permission_realm_id = data.permission.realm_id;
}

if (data.policy) {
data.policy_realm_id = data.policy.realm_id;
}

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

Normalize realm IDs before validation and guard undefined overwrites.

At Line 68-76, join-column validation occurs before realm-id mapping, and mapping can overwrite fields with undefined. That allows post-validation mutation of scoped fields.

Suggested fix
-        await this.repository.validateJoinColumns(data);
-
-        if (data.permission) {
-            data.permission_realm_id = data.permission.realm_id;
-        }
-
-        if (data.policy) {
-            data.policy_realm_id = data.policy.realm_id;
-        }
+        if (data.permission?.realm_id !== undefined) {
+            data.permission_realm_id = data.permission.realm_id;
+        }
+
+        if (data.policy?.realm_id !== undefined) {
+            data.policy_realm_id = data.policy.realm_id;
+        }
+
+        await this.repository.validateJoinColumns(data);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
await this.repository.validateJoinColumns(data);
if (data.permission) {
data.permission_realm_id = data.permission.realm_id;
}
if (data.policy) {
data.policy_realm_id = data.policy.realm_id;
}
if (data.permission?.realm_id !== undefined) {
data.permission_realm_id = data.permission.realm_id;
}
if (data.policy?.realm_id !== undefined) {
data.policy_realm_id = data.policy.realm_id;
}
await this.repository.validateJoinColumns(data);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/core/entities/permission-policy/service.ts` around lines
68 - 76, Move the mapping of realm IDs for permission and policy to run before
calling this.repository.validateJoinColumns and ensure you only assign
permission_realm_id and policy_realm_id when the source realm_id is defined
(i.e. guard against undefined overwrites). Concretely, in the method containing
repository.validateJoinColumns, first normalize/set data.permission_realm_id =
data.permission.realm_id only if data.permission && data.permission.realm_id !==
undefined, and similarly for data.policy_realm_id, then call
this.repository.validateJoinColumns(data).

@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: 2

🧹 Nitpick comments (4)
apps/server-core/src/app/modules/http/modules/controller.ts (2)

525-525: Remove unnecessary async keyword.

The method body contains no await expressions after the default-policy lookup was removed. Update this method and its call site at line 170 to be synchronous.

♻️ Suggested changes

Line 525:

-    async createPermissionController(container: IDIContainer) {
+    createPermissionController(container: IDIContainer) {

Line 170:

-        const permissionController = await this.createPermissionController(container);
+        const permissionController = this.createPermissionController(container);

Also update the mount method signature if it was only async due to this call:

-    async mount(router: Router, container: IDIContainer): Promise<void> {
+    mount(router: Router, container: IDIContainer): void {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/app/modules/http/modules/controller.ts` at line 525, The
createPermissionController method is marked async but no longer awaits anything;
remove the unnecessary async from createPermissionController and update its call
site (the invocation at the location referenced as line 170) to treat it as a
synchronous function. Also check the containing mount method: if it was declared
async solely because it awaited createPermissionController, remove that async
and update its signature to be synchronous as well. Ensure you update any type
annotations or return types that assumed a Promise from
createPermissionController and mount so callers no longer expect a Promise.

252-260: Consider caching IdentityPermissionProvider to reduce redundant instantiation.

This method is called 11 times during controller wiring, each invocation creating 4 new repository instances. Since all calls share the same container context during a single mount(), consider creating the provider once and reusing it.

♻️ Suggested approach
+    private identityPermissionProvider: IdentityPermissionProvider | null = null;
+
     createIdentityPermissionProvider(container: IDIContainer) {
+        if (this.identityPermissionProvider) {
+            return this.identityPermissionProvider;
+        }
         const dataSource = container.resolve<DataSource>(DatabaseInjectionKey.DataSource);
-        return new IdentityPermissionProvider({
+        this.identityPermissionProvider = new IdentityPermissionProvider({
             clientRepository: new ClientRepository(dataSource),
             userRepository: new UserRepository(dataSource),
             robotRepository: new RobotRepository(dataSource),
             roleRepository: new RoleRepository(dataSource),
         });
+        return this.identityPermissionProvider;
     }

Alternatively, pass the provider as a parameter to the individual create*Controller methods from mount().

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

In `@apps/server-core/src/app/modules/http/modules/controller.ts` around lines 252
- 260, The createIdentityPermissionProvider function is instantiated repeatedly;
change it to return a cached singleton instead of recreating repositories each
call: in the controller module create a single cached variable (e.g.,
identityPermissionProviderCache) and in
createIdentityPermissionProvider(container: IDIContainer) return the cached
instance if present, otherwise build the IdentityPermissionProvider once (using
ClientRepository, UserRepository, RobotRepository, RoleRepository with the
resolved DataSource) and store it in the cache; alternatively, construct the
provider once in mount() and pass that provider into each create*Controller
method so createIdentityPermissionProvider and the create*Controller methods
reuse the same IdentityPermissionProvider instance.
apps/server-core/test/unit/core/entities/permission/service.spec.ts (2)

226-235: Avoid brittle non-null assertion in master realm test setup.

Line 228 uses actor.identity!, which can fail with an unclear runtime error if fixtures change. Add an explicit guard/assert before dereferencing for clearer failure diagnostics.

Proposed test hardening
 it('should set realm_id to master realm for master realm actor on create', async () => {
     const actor = createMasterRealmActor();
-    const masterRealmId = actor.identity!.data.realm_id;
+    if (!actor.identity?.data.realm_id) {
+        throw new Error('Expected master realm actor to have identity.data.realm_id');
+    }
+    const masterRealmId = actor.identity.data.realm_id;

     const result = await service.create(
         { name: 'global-perm' },
         actor,
     );

     expect(result.realm_id).toBe(masterRealmId);
 });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/test/unit/core/entities/permission/service.spec.ts` around
lines 226 - 235, The test uses a brittle non-null assertion actor.identity!
before creating the actor's masterRealmId; replace this with an explicit
guard/assert to fail with a clear message if the fixture lacks identity. Update
the test that calls createMasterRealmActor() (and before reading
identity.data.realm_id) to assert or expect actor.identity is defined (and
optionally actor.identity.data is defined) so subsequent dereference in the call
to service.create and the realm_id extraction are safe and produce actionable
test failures.

136-143: policy_id assertion is legacy-coupled after n:m restructuring.

On Line 142, asserting result.policy_id is undefined does not validate the new permission↔policy junction behavior. This can pass even if relation persistence/regression exists. Consider asserting through permissionPolicyRepository state instead.

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

In `@apps/server-core/test/unit/core/entities/permission/service.spec.ts` around
lines 136 - 143, The test currently asserts result.policy_id which is no longer
valid after the n:m permission↔policy redesign; update the spec to remove the
legacy policy_id assertion and instead query the junction repository
(permissionPolicyRepository) for entries linking the created permission (use
result.id) to any policy, and assert that no junction rows exist (e.g.,
find/filter for permission_id === result.id and expect zero results). Keep the
call to service.create({ name: 'no-policy-perm' }, createAllowAllActor()) and
replace the expect(result.policy_id).toBeUndefined() check with the
repository-based assertion to validate relation state.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/server-core/src/app/modules/database/repositories/policy/repository.ts`:
- Around line 165-167: The current truthy check "if (entity.parent_id)" skips
calling repository.updateClosureTable when parent_id is explicitly set to null
(reparent-to-root); change the condition to check definedness instead (e.g., use
"if (entity.parent_id !== undefined)") so that
repository.updateClosureTable(entity as PolicyEntity) is invoked for null
parent_id values as well, allowing updateClosureTable to clean up stale ancestor
relationships for PolicyEntity.

In `@apps/server-core/src/app/modules/provisioning/sources/default/module.ts`:
- Around line 70-90: Add end-to-end integration tests that assert policy
evaluation for SystemPolicyName.DEFAULT (built with
BuiltInPolicyType.REALM_MATCH and attribute_null_match_all: true) allows global
permissions to match identities regardless of their realm, and tests for
SystemPolicyName.REALM_BOUND (attribute_null_match_all: false) enforce
realm-specific matching; ensure tests exercise the same evaluator used in
production (the policy evaluator that reads realm_id from the evaluated entity's
attributes) and create example entities with differing realm_id values to verify
DEFAULT permits cross-realm matches while REALM_BOUND denies them.

---

Nitpick comments:
In `@apps/server-core/src/app/modules/http/modules/controller.ts`:
- Line 525: The createPermissionController method is marked async but no longer
awaits anything; remove the unnecessary async from createPermissionController
and update its call site (the invocation at the location referenced as line 170)
to treat it as a synchronous function. Also check the containing mount method:
if it was declared async solely because it awaited createPermissionController,
remove that async and update its signature to be synchronous as well. Ensure you
update any type annotations or return types that assumed a Promise from
createPermissionController and mount so callers no longer expect a Promise.
- Around line 252-260: The createIdentityPermissionProvider function is
instantiated repeatedly; change it to return a cached singleton instead of
recreating repositories each call: in the controller module create a single
cached variable (e.g., identityPermissionProviderCache) and in
createIdentityPermissionProvider(container: IDIContainer) return the cached
instance if present, otherwise build the IdentityPermissionProvider once (using
ClientRepository, UserRepository, RobotRepository, RoleRepository with the
resolved DataSource) and store it in the cache; alternatively, construct the
provider once in mount() and pass that provider into each create*Controller
method so createIdentityPermissionProvider and the create*Controller methods
reuse the same IdentityPermissionProvider instance.

In `@apps/server-core/test/unit/core/entities/permission/service.spec.ts`:
- Around line 226-235: The test uses a brittle non-null assertion
actor.identity! before creating the actor's masterRealmId; replace this with an
explicit guard/assert to fail with a clear message if the fixture lacks
identity. Update the test that calls createMasterRealmActor() (and before
reading identity.data.realm_id) to assert or expect actor.identity is defined
(and optionally actor.identity.data is defined) so subsequent dereference in the
call to service.create and the realm_id extraction are safe and produce
actionable test failures.
- Around line 136-143: The test currently asserts result.policy_id which is no
longer valid after the n:m permission↔policy redesign; update the spec to remove
the legacy policy_id assertion and instead query the junction repository
(permissionPolicyRepository) for entries linking the created permission (use
result.id) to any policy, and assert that no junction rows exist (e.g.,
find/filter for permission_id === result.id and expect zero results). Keep the
call to service.create({ name: 'no-policy-perm' }, createAllowAllActor()) and
replace the expect(result.policy_id).toBeUndefined() check with the
repository-based assertion to validate relation state.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 2313fdb3-de14-4f27-b7ef-4075f82c9607

📥 Commits

Reviewing files that changed from the base of the PR and between c0aa509 and e07599f.

📒 Files selected for processing (11)
  • apps/server-core/src/app/modules/database/repositories/policy/repository.ts
  • apps/server-core/src/app/modules/http/modules/controller.ts
  • apps/server-core/src/app/modules/provisioning/module.ts
  • apps/server-core/src/app/modules/provisioning/sources/default/module.ts
  • apps/server-core/src/core/entities/permission/service.ts
  • apps/server-core/src/core/provisioning/synchronizer/policy/module.ts
  • apps/server-core/src/core/provisioning/synchronizer/policy/types.ts
  • apps/server-core/test/unit/core/entities/permission/service.spec.ts
  • apps/server-core/test/unit/http/controllers/entities/permission/checker.spec.ts
  • apps/server-core/test/unit/modules/provisioning.spec.ts
  • packages/access/src/policy/built-in/realm-match/evaluator.ts
✅ Files skipped from review due to trivial changes (1)
  • apps/server-core/src/core/entities/permission/service.ts
🚧 Files skipped from review as they are similar to previous changes (6)
  • packages/access/src/policy/built-in/realm-match/evaluator.ts
  • apps/server-core/src/core/provisioning/synchronizer/policy/types.ts
  • apps/server-core/src/app/modules/provisioning/module.ts
  • apps/server-core/src/core/provisioning/synchronizer/policy/module.ts
  • apps/server-core/test/unit/http/controllers/entities/permission/checker.spec.ts
  • apps/server-core/test/unit/modules/provisioning.spec.ts

Comment on lines 70 to +90
extraAttributes: {
attributeName: ['realm_id'],
attributeNameStrict: false,
identityMasterMatchAll: true,
attribute_name: ['realm_id'],
attribute_name_strict: false,
identity_master_match_all: false,
attribute_null_match_all: true,
},
},
],
},
{
attributes: {
name: SystemPolicyName.REALM_BOUND,
type: BuiltInPolicyType.REALM_MATCH,
built_in: true,
realm_id: null,
},
extraAttributes: {
attribute_name: ['realm_id'],
attribute_name_strict: false,
attribute_null_match_all: false,
identity_master_match_all: false,

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate the realm-match implementation and the attribute-resolution logic.
fd 'realm-match' packages apps
rg -nC4 'REALM_MATCH|attribute_name(_strict)?|attribute_null_match_all|identity_master_match_all|\brealm_id\b' \
  packages/access apps/server-core -g '!**/dist/**'

# Inspect tests that lock down null-realm handling for the default and realm-bound paths.
rg -nC4 'REALM_BOUND|REALM_MATCH|attribute_null_match_all|identity_master_match_all' \
  apps/server-core/test packages -g '!**/dist/**'

Repository: authup/authup

Length of output: 50370


🏁 Script executed:

find packages/access/src/policy/built-in/realm-match -type f -name "*.ts" | head -20

Repository: authup/authup

Length of output: 292


🏁 Script executed:

cat packages/access/test/unit/policy/realm-match.spec.ts

Repository: authup/authup

Length of output: 4333


🏁 Script executed:

rg -A 20 "REALM_MATCH" packages/access/src/policy/built-in/realm-match -g '*.ts'

Repository: authup/authup

Length of output: 39


🏁 Script executed:

# Search for realm-match evaluation logic in the evaluator
rg -B 5 -A 15 "BuiltInPolicyType.REALM_MATCH|realm-match|RealmMatch" apps/server-core/src/core/security/policy/evaluator.ts

Repository: authup/authup

Length of output: 39


🏁 Script executed:

# Check for existing tests covering DEFAULT and REALM_BOUND with null realm
rg -B 3 -A 10 "attribute_null_match_all|REALM_BOUND|DEFAULT.*realm" apps/server-core/test packages/access/test -g '*.ts'

Repository: authup/authup

Length of output: 39


🏁 Script executed:

cat packages/access/src/policy/built-in/realm-match/evaluator.ts

Repository: authup/authup

Length of output: 5559


🏁 Script executed:

cat packages/access/src/policy/built-in/realm-match/types.ts

Repository: authup/authup

Length of output: 1359


🏁 Script executed:

# Find where DEFAULT and REALM_BOUND policies are evaluated in the system
rg -B 5 -A 10 "SystemPolicyName\.DEFAULT|SystemPolicyName\.REALM_BOUND" apps/server-core/src -g '*.ts' | head -100

Repository: authup/authup

Length of output: 9858


🏁 Script executed:

# Check the evaluator in server-core to see how it evaluates policies
cat apps/server-core/src/core/security/policy/evaluator.ts | head -150

Repository: authup/authup

Length of output: 4966


🏁 Script executed:

# Find where PolicyEvaluationContext is created and attributes are set
rg -B 5 -A 10 "definePolicyEvaluationContext|new PolicyData" apps/server-core/src -g '*.ts' | head -150

Repository: authup/authup

Length of output: 12078


🏁 Script executed:

# Check the PermissionBindingPolicyEvaluator more carefully for context setup
rg -B 10 -A 20 "engine.evaluate.*compositePolicy" apps/server-core/src/core/security/policy/evaluator.ts

Repository: authup/authup

Length of output: 671


🏁 Script executed:

# Search for where attributes are set in context during policy evaluation
rg -B 5 -A 5 "attributes.*realm_id|ctx\.data.*attributes" apps/server-core/src -g '*.ts' | head -100

Repository: authup/authup

Length of output: 10370


🏁 Script executed:

# Check tests to see how DEFAULT and REALM_BOUND are tested
rg -B 5 -A 15 "SystemPolicyName.DEFAULT|SystemPolicyName.REALM_BOUND" apps/server-core/test -g '*.ts' | head -150

Repository: authup/authup

Length of output: 12792


🏁 Script executed:

# Search for integration tests that actually evaluate permissions with these policies
rg -B 3 -A 15 "permissionEvaluator.evaluate|PermissionEvaluator" apps/server-core/test -g '*.spec.ts' | head -100

Repository: authup/authup

Length of output: 10672


🏁 Script executed:

# Check if there are any tests actually evaluating a resource/entity through DEFAULT or REALM_BOUND policies
rg -B 5 -A 20 "DEFAULT|REALM_BOUND" apps/server-core/test -g '*.spec.ts' | grep -A 15 "evaluate\|policy" | head -80

Repository: authup/authup

Length of output: 8132


🏁 Script executed:

# Search for integration tests that actually evaluate permissions end-to-end
rg -l "permissionEvaluator.evaluate|evaluate.*permission" apps/server-core/test -g '*.spec.ts' | head -5

Repository: authup/authup

Length of output: 387


🏁 Script executed:

# Check one of those files to see if they test realm behavior
head -200 apps/server-core/test/unit/core/identity/permission/module.spec.ts

Repository: authup/authup

Length of output: 182


🏁 Script executed:

# Search for any tests of realm-scoped permission evaluation
rg -B 5 -A 20 "realm.*permission|permission.*realm" apps/server-core/test -g '*.spec.ts' | head -100

Repository: authup/authup

Length of output: 9944


Add integration tests for DEFAULT and REALM_BOUND policy evaluation with realm matching.

The evaluator correctly reads realm_id from the evaluated entity's attributes (not the policy definition's realm_id: null). However, end-to-end tests covering both DEFAULT and REALM_BOUND policy evaluation are needed to lock down the intended behavior: DEFAULT should permit global permissions to match any identity realm via attribute_null_match_all: true, and REALM_BOUND should enforce realm-specific matching via attribute_null_match_all: false.

🤖 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/default/module.ts`
around lines 70 - 90, Add end-to-end integration tests that assert policy
evaluation for SystemPolicyName.DEFAULT (built with
BuiltInPolicyType.REALM_MATCH and attribute_null_match_all: true) allows global
permissions to match identities regardless of their realm, and tests for
SystemPolicyName.REALM_BOUND (attribute_null_match_all: false) enforce
realm-specific matching; ensure tests exercise the same evaluator used in
production (the policy evaluator that reads realm_id from the evaluated entity's
attributes) and create example entities with differing realm_id values to verify
DEFAULT permits cross-realm matches while REALM_BOUND denies them.

@tada5hi tada5hi changed the title feat: realm scoping & policy-permission restructuring feat: policy-based realm scoping and global entity support Mar 24, 2026
@tada5hi

tada5hi commented Mar 24, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Mar 24, 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: 3

Caution

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

⚠️ Outside diff range comments (3)
apps/server-core/test/unit/core/entities/permission/service.spec.ts (1)

144-151: ⚠️ Potential issue | 🟡 Minor

Test should verify junction table behavior instead of checking non-existent field.

The Permission entity does not have a policy_id field, so result.policy_id will always be undefined. The test passes but doesn't actually verify the intended behavior.

When a permission is created without an explicit policy, assignDefaultPolicy() is called (line 231 in the service), which creates a PermissionPolicy junction record via permissionPolicyRepository.save(). The test should verify this junction table behavior—that the default policy was assigned—rather than checking a non-existent field on the Permission entity.

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

In `@apps/server-core/test/unit/core/entities/permission/service.spec.ts` around
lines 144 - 151, The test is asserting a non-existent Permission.policy_id;
instead verify the junction record is created by assignDefaultPolicy when
service.create is called. Update the test for service.create(...) to either
spy/mock permissionPolicyRepository.save or query the PermissionPolicy junction
(e.g., permissionPolicyRepository.findOne/find) for a record linking the created
permission id to the default policy id, and assert that such a PermissionPolicy
exists (or that save was called with the expected PermissionPolicy payload).
Ensure you reference service.create and assignDefaultPolicy behavior and use
permissionPolicyRepository (or PermissionPolicy entity) in the assertion rather
than result.policy_id.
apps/server-core/src/core/entities/role/service.ts (1)

47-55: ⚠️ Potential issue | 🔴 Critical

Read paths never apply the realm-scoped policy to the returned role data.

preEvaluateOneOf() is only a coarse gate here. getOne() never evaluates the loaded role, and getMany() sends the raw query straight to the repository, so a grant scoped to realm A can still fetch or enumerate roles from realm B by id/name or by widening the query. getOne() needs entity-aware evaluation before return, and getMany() needs an evaluator-derived repository filter.

Also applies to: 62-75

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

In `@apps/server-core/src/core/entities/role/service.ts` around lines 47 - 55,
preEvaluateOneOf is only a coarse gate; you must apply realm-scoped policy to
returned role data: in getOne() call the permissionEvaluator to evaluate the
loaded Role entity (e.g., permissionEvaluator.evaluateEntityOnReturn or
evaluateEntity) and throw or return null if not allowed, and in getMany() derive
and apply an evaluator-derived repository filter (e.g.,
permissionEvaluator.buildRepositoryFilter or getFilterForQuery) instead of
calling this.repository.findMany(query) directly so results are pre-filtered to
the caller's permitted realm; use the existing actor.permissionEvaluator methods
and ensure unauthorized entities are excluded or cause an appropriate access
error.
apps/server-core/src/core/entities/policy/service.ts (1)

50-58: ⚠️ Potential issue | 🔴 Critical

Policy reads are still unscoped by the evaluated policy.

preEvaluateOneOf() only proves the actor has one of these permissions somewhere. Because getOne() does not evaluate the loaded policy and getMany() does not push evaluator scope into the repository query, a realm-scoped grant can still read policies from other realms.

Also applies to: 66-79

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

In `@apps/server-core/src/core/entities/policy/service.ts` around lines 50 - 58,
The permission check currently only verifies the actor has one of the
permissions via permissionEvaluator.preEvaluateOneOf but does not restrict the
repository query or validate the loaded resource, so realm-scoped grants can
read other realms; modify getMany (the code calling repository.findMany) to
obtain the evaluator's scope/filters from the permission evaluator and merge
those filters into the repository.findMany query (i.e., push evaluator scope
into the DB query), and modify getOne to call the evaluator to evaluate the
loaded policy resource (e.g., evaluateOnResource or equivalent) after loading so
the policy is validated against the actor's scope; use the existing
permissionEvaluator and actor symbols (preEvaluateOneOf, permissionEvaluator,
actor, repository.findMany, getOne/getMany) to locate and implement these
changes.
♻️ Duplicate comments (3)
apps/server-core/src/core/entities/permission/service.ts (2)

291-304: ⚠️ Potential issue | 🟡 Minor

Silent return when admin role is missing.

When adminRole is not found (line 293-295), the method silently returns without logging. While this may be acceptable during initial bootstrapping (before the admin role is provisioned), it could mask configuration issues in established environments. Consider adding a debug/warning log.

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

In `@apps/server-core/src/core/entities/permission/service.ts` around lines 291 -
304, The method assignToAdminRole currently silently returns if
roleRepository.findOneByName(ROLE_ADMIN_NAME) yields no adminRole; update this
to log a warning or debug message before returning (e.g., use this.logger.warn
or this.logger.debug) including ROLE_ADMIN_NAME and contextual info
(permission.id and permission.realm_id) so missing admin role is surfaced in
logs, then keep the early return; modify assignToAdminRole accordingly.

229-235: ⚠️ Potential issue | 🟠 Major

Non-atomic permission creation with post-save assignments.

The permission is saved (line 229) before the policy/role assignments (lines 231-233). If any assignment fails, the permission exists without proper security bindings. This was flagged in a previous review and should be wrapped in a transaction.

🔧 Suggested approach

Wrap the save and assignment operations in a database transaction:

// Example using TypeORM transaction pattern
await this.repository.manager.transaction(async (manager) => {
    entity = await manager.save(Permission, entity);
    await this.assignDefaultPolicy(entity, manager);
    await this.assignToAdminRole(entity, manager);
    await this.assignToRealmAdminRoles(entity, manager);
});
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/core/entities/permission/service.ts` around lines 229 -
235, The save + post-save assignment sequence in create permission is
non-atomic; wrap the save and subsequent calls to assignDefaultPolicy,
assignToAdminRole, and assignToRealmAdminRoles in a single database transaction
(use repository.manager.transaction or equivalent), perform the save via the
transaction manager (e.g., manager.save(Permission, entity)), and update those
assignment helpers to accept and use the transaction manager (or a transactional
repository) so failures roll back the permission creation.
docs/src/guide/user/permissions-and-policies.md (1)

110-111: ⚠️ Potential issue | 🟡 Minor

Junction policy scope incomplete in step 4.

Step 4 of the evaluation flow mentions "role or user assignment" but should include client/robot assignments for completeness, consistent with the Junction Policies section at line 126 which correctly lists all four types.

📝 Suggested fix
-4. If the permission was obtained through a role or user assignment that carries a **junction policy**, evaluate that policy as an additional restriction
+4. If the permission was obtained through an assignment (role, user, client, or robot) that carries a **junction policy**, evaluate that policy as an additional restriction
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/src/guide/user/permissions-and-policies.md` around lines 110 - 111, Step
4 of the evaluation flow omits client/robot assignments; update the wording in
"Step 4" to list all four assignment sources (role, user, client, robot) when
mentioning a permission obtained through an assignment so it matches the
"Junction Policies" section and ensures junction policies are evaluated for
role, user, client, and robot assignments.
🧹 Nitpick comments (3)
apps/server-core/src/adapters/database/extra-attribute-repository/tree/repository.ts (1)

221-223: Consider passing primaryKeyValue as a parameter to avoid redundant fetch.

The primaryKeyValue is already computed in updateClosureTable (line 202) but is fetched again here. Consider passing it as a parameter to executeClosureTableUpdate.

♻️ Suggested refactor
-    async updateClosureTable(entity: T, manager?: EntityManager) {
+    async updateClosureTable(entity: T, manager?: EntityManager): Promise<void> {
         const primaryKeyValue = this.metadata.primaryColumns[0].getEntityValue(entity);
         if (!primaryKeyValue) {
             return;
         }

         const closureTable = this.metadata.closureJunctionTable;
         if (!closureTable) {
             return;
         }

         if (manager) {
-            await this.executeClosureTableUpdate(entity, manager);
+            await this.executeClosureTableUpdate(entity, manager, primaryKeyValue);
         } else {
-            await this.manager.connection.transaction(async (manager) => {
-                await this.executeClosureTableUpdate(entity, manager);
+            await this.manager.connection.transaction(async (txManager) => {
+                await this.executeClosureTableUpdate(entity, txManager, primaryKeyValue);
             });
         }
     }

-    private async executeClosureTableUpdate(entity: T, manager: EntityManager) {
-        const primaryKeyValue = this.metadata.primaryColumns[0].getEntityValue(entity);
+    private async executeClosureTableUpdate(
+        entity: T,
+        manager: EntityManager,
+        primaryKeyValue: unknown,
+    ): Promise<void> {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@apps/server-core/src/adapters/database/extra-attribute-repository/tree/repository.ts`
around lines 221 - 223, The method executeClosureTableUpdate redundantly
recomputes primaryKeyValue from metadata.primaryColumns[0] even though
updateClosureTable already calculated it; change executeClosureTableUpdate
signature to accept primaryKeyValue as an extra parameter (e.g.,
executeClosureTableUpdate(entity: T, manager: EntityManager, primaryKeyValue:
any)) and update the call site(s) in updateClosureTable to pass the computed
primaryKeyValue, then remove the duplicate retrieval inside
executeClosureTableUpdate so it uses the passed-in value.
apps/server-core/src/core/provisioning/synchronizer/role/module.ts (1)

104-114: Consider batching permission junction synchronization for performance.

The current implementation iterates one permission at a time, calling synchronize for each. For roles with many permissions, this could result in N database operations.

However, since this is provisioning code (runs on startup, not in hot paths), the performance impact is likely acceptable. Leaving as an optional improvement if provisioning time becomes a concern.

🤖 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/role/module.ts` around
lines 104 - 114, The loop over permissions causing one synchronize call per
permission (see permissionJunction.synchronize invoked inside the for loop
referencing policyMap, permissions, and attributes) can be batched to reduce DB
round trips: group permissions by their resolved policyId (compute
policyMap.overrides.get(permission.name) ?? policyMap.defaultPolicyId for each
permission), then call permissionJunction.synchronize once per group with the
array of permissions for that policyId (or a single synchronize call if all
share the same policyId), passing the same attribute arguments and the policy
filter { policy_id: policyId } when applicable; update the code around
policyMap, permissions, and permissionJunction.synchronize accordingly.
docs/src/guide/user/permissions-and-policies.md (1)

127-127: Consider simplifying "adds an additional".

The phrase "adds an additional restriction" is slightly redundant.

📝 Suggested fix
-This **junction policy** adds an additional restriction on top of the permission's own policies.
+This **junction policy** adds a restriction on top of the permission's own policies.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/src/guide/user/permissions-and-policies.md` at line 127, The sentence
"This **junction policy** adds an additional restriction on top of the
permission's own policies." is redundant; update it to a simpler phrasing such
as "This **junction policy** adds a restriction on top of the permission's own
policies." (or "This **junction policy** imposes a restriction on the
permission's own policies.") — find the exact sentence in the document and
replace it with the chosen concise alternative.
🤖 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/adapters/database/extra-attribute-repository/tree/repository.ts`:
- Around line 229-235: The raw SQL in the tree repository (calls to
manager.query in the method containing the ancestors/descendants logic)
interpolates values like primaryKeyValue, descendantIds, tableName,
ancestorColumn.databasePath and descendantColumn.databasePath directly into
strings; replace these with parameterized queries: build the SQL with fixed
identifiers (keep table/column names from
tableName/ancestorColumn/descendantColumn but do not inject user data) and pass
values as parameters to manager.query (e.g., use placeholders for
primaryKeyValue and dynamically generate placeholders for IN clauses using
descendantIds), and apply this change to every manager.query call in the method
(the queries around ancestors, descendants, and any IN clauses) so all values
are passed as parameters rather than string-interpolated.

In `@apps/server-core/src/core/entities/permission/service.ts`:
- Around line 337-340: The current early return in the realm_admin assignment
path silently skips when a policy lookup (policyRepository.findOneByName) for
SystemPolicyName.REALM_BOUND or SystemPolicyName.REALM_OR_GLOBAL fails; update
the block that checks const policy = await
this.policyRepository.findOneByName(policyName) to log a warning (using the
existing logger/this.logger or processLogger) that includes the missing
policyName and context (e.g., "realm_admin assignment skipped, policy not
found") before returning so failures are visible while preserving the "fail
closed" behavior.

In `@apps/server-core/src/core/entities/policy/service.ts`:
- Around line 175-177: The uniqueness check is performed before the actor-based
fallback for realm_id, so update the flow in service.ts to ensure
validated.realm_id gets assigned from actor via getActorRealmId(actor) (when
isPropertySet(validated, 'realm_id') is false and actor.identity exists) before
calling checkUniqueness(), and apply the same change for the other similar block
around lines 179-184; in short, move or duplicate the realm_id fallback logic
(using isPropertySet, validated.realm_id, actor, and getActorRealmId) to run
prior to invoking checkUniqueness() and before saveWithEA() so uniqueness is
evaluated in the correct realm scope.

---

Outside diff comments:
In `@apps/server-core/src/core/entities/policy/service.ts`:
- Around line 50-58: The permission check currently only verifies the actor has
one of the permissions via permissionEvaluator.preEvaluateOneOf but does not
restrict the repository query or validate the loaded resource, so realm-scoped
grants can read other realms; modify getMany (the code calling
repository.findMany) to obtain the evaluator's scope/filters from the permission
evaluator and merge those filters into the repository.findMany query (i.e., push
evaluator scope into the DB query), and modify getOne to call the evaluator to
evaluate the loaded policy resource (e.g., evaluateOnResource or equivalent)
after loading so the policy is validated against the actor's scope; use the
existing permissionEvaluator and actor symbols (preEvaluateOneOf,
permissionEvaluator, actor, repository.findMany, getOne/getMany) to locate and
implement these changes.

In `@apps/server-core/src/core/entities/role/service.ts`:
- Around line 47-55: preEvaluateOneOf is only a coarse gate; you must apply
realm-scoped policy to returned role data: in getOne() call the
permissionEvaluator to evaluate the loaded Role entity (e.g.,
permissionEvaluator.evaluateEntityOnReturn or evaluateEntity) and throw or
return null if not allowed, and in getMany() derive and apply an
evaluator-derived repository filter (e.g.,
permissionEvaluator.buildRepositoryFilter or getFilterForQuery) instead of
calling this.repository.findMany(query) directly so results are pre-filtered to
the caller's permitted realm; use the existing actor.permissionEvaluator methods
and ensure unauthorized entities are excluded or cause an appropriate access
error.

In `@apps/server-core/test/unit/core/entities/permission/service.spec.ts`:
- Around line 144-151: The test is asserting a non-existent
Permission.policy_id; instead verify the junction record is created by
assignDefaultPolicy when service.create is called. Update the test for
service.create(...) to either spy/mock permissionPolicyRepository.save or query
the PermissionPolicy junction (e.g., permissionPolicyRepository.findOne/find)
for a record linking the created permission id to the default policy id, and
assert that such a PermissionPolicy exists (or that save was called with the
expected PermissionPolicy payload). Ensure you reference service.create and
assignDefaultPolicy behavior and use permissionPolicyRepository (or
PermissionPolicy entity) in the assertion rather than result.policy_id.

---

Duplicate comments:
In `@apps/server-core/src/core/entities/permission/service.ts`:
- Around line 291-304: The method assignToAdminRole currently silently returns
if roleRepository.findOneByName(ROLE_ADMIN_NAME) yields no adminRole; update
this to log a warning or debug message before returning (e.g., use
this.logger.warn or this.logger.debug) including ROLE_ADMIN_NAME and contextual
info (permission.id and permission.realm_id) so missing admin role is surfaced
in logs, then keep the early return; modify assignToAdminRole accordingly.
- Around line 229-235: The save + post-save assignment sequence in create
permission is non-atomic; wrap the save and subsequent calls to
assignDefaultPolicy, assignToAdminRole, and assignToRealmAdminRoles in a single
database transaction (use repository.manager.transaction or equivalent), perform
the save via the transaction manager (e.g., manager.save(Permission, entity)),
and update those assignment helpers to accept and use the transaction manager
(or a transactional repository) so failures roll back the permission creation.

In `@docs/src/guide/user/permissions-and-policies.md`:
- Around line 110-111: Step 4 of the evaluation flow omits client/robot
assignments; update the wording in "Step 4" to list all four assignment sources
(role, user, client, robot) when mentioning a permission obtained through an
assignment so it matches the "Junction Policies" section and ensures junction
policies are evaluated for role, user, client, and robot assignments.

---

Nitpick comments:
In
`@apps/server-core/src/adapters/database/extra-attribute-repository/tree/repository.ts`:
- Around line 221-223: The method executeClosureTableUpdate redundantly
recomputes primaryKeyValue from metadata.primaryColumns[0] even though
updateClosureTable already calculated it; change executeClosureTableUpdate
signature to accept primaryKeyValue as an extra parameter (e.g.,
executeClosureTableUpdate(entity: T, manager: EntityManager, primaryKeyValue:
any)) and update the call site(s) in updateClosureTable to pass the computed
primaryKeyValue, then remove the duplicate retrieval inside
executeClosureTableUpdate so it uses the passed-in value.

In `@apps/server-core/src/core/provisioning/synchronizer/role/module.ts`:
- Around line 104-114: The loop over permissions causing one synchronize call
per permission (see permissionJunction.synchronize invoked inside the for loop
referencing policyMap, permissions, and attributes) can be batched to reduce DB
round trips: group permissions by their resolved policyId (compute
policyMap.overrides.get(permission.name) ?? policyMap.defaultPolicyId for each
permission), then call permissionJunction.synchronize once per group with the
array of permissions for that policyId (or a single synchronize call if all
share the same policyId), passing the same attribute arguments and the policy
filter { policy_id: policyId } when applicable; update the code around
policyMap, permissions, and permissionJunction.synchronize accordingly.

In `@docs/src/guide/user/permissions-and-policies.md`:
- Line 127: The sentence "This **junction policy** adds an additional
restriction on top of the permission's own policies." is redundant; update it to
a simpler phrasing such as "This **junction policy** adds a restriction on top
of the permission's own policies." (or "This **junction policy** imposes a
restriction on the permission's own policies.") — find the exact sentence in the
document and replace it with the chosen concise alternative.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: d8d55389-ac85-48be-8378-d0c851a03664

📥 Commits

Reviewing files that changed from the base of the PR and between e07599f and 29dc325.

📒 Files selected for processing (18)
  • apps/server-core/src/adapters/database/extra-attribute-repository/tree/repository.ts
  • apps/server-core/src/app/modules/database/repositories/policy/repository.ts
  • apps/server-core/src/app/modules/provisioning/module.ts
  • apps/server-core/src/app/modules/provisioning/sources/default/module.ts
  • apps/server-core/src/core/entities/permission/service.ts
  • apps/server-core/src/core/entities/policy/service.ts
  • apps/server-core/src/core/entities/role/service.ts
  • apps/server-core/src/core/entities/scope/service.ts
  • apps/server-core/src/core/provisioning/entities/role/types.ts
  • apps/server-core/src/core/provisioning/synchronizer/role/module.ts
  • apps/server-core/test/unit/core/entities/permission/service.spec.ts
  • apps/server-core/test/unit/core/entities/role/service.spec.ts
  • apps/server-core/test/unit/core/entities/scope/service.spec.ts
  • docs/src/guide/deployment/provisioning.md
  • docs/src/guide/user/permissions-and-policies.md
  • packages/access/src/policy/built-in/constants.ts
  • packages/core-kit/src/domains/role/validator.ts
  • packages/core-kit/src/domains/scope/validator.ts
✅ Files skipped from review due to trivial changes (2)
  • packages/access/src/policy/built-in/constants.ts
  • apps/server-core/src/core/provisioning/entities/role/types.ts
🚧 Files skipped from review as they are similar to previous changes (5)
  • apps/server-core/src/app/modules/database/repositories/policy/repository.ts
  • apps/server-core/test/unit/core/entities/role/service.spec.ts
  • apps/server-core/test/unit/core/entities/scope/service.spec.ts
  • apps/server-core/src/core/entities/scope/service.ts
  • apps/server-core/src/app/modules/provisioning/module.ts

Comment on lines +337 to +340
const policy = await this.policyRepository.findOneByName(policyName);
if (!policy) {
return;
}

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

Silent return when required policy is missing for realm_admin assignment.

If SystemPolicyName.REALM_BOUND or SystemPolicyName.REALM_OR_GLOBAL policy is not found, the method silently skips assignment (lines 338-340). While the docstring says "fails closed," adding a warning log would help diagnose why realm_admin roles aren't receiving expected permissions.

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

In `@apps/server-core/src/core/entities/permission/service.ts` around lines 337 -
340, The current early return in the realm_admin assignment path silently skips
when a policy lookup (policyRepository.findOneByName) for
SystemPolicyName.REALM_BOUND or SystemPolicyName.REALM_OR_GLOBAL fails; update
the block that checks const policy = await
this.policyRepository.findOneByName(policyName) to log a warning (using the
existing logger/this.logger or processLogger) that includes the missing
policyName and context (e.g., "realm_admin assignment skipped, policy not
found") before returning so failures are visible while preserving the "fail
closed" behavior.

Comment on lines +175 to 177
if (!isPropertySet(validated, 'realm_id') && actor.identity) {
validated.realm_id = this.getActorRealmId(actor) || null;
}

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

Default realm_id before the create-path uniqueness check.

When realm_id is omitted, the earlier checkUniqueness() call on Line 151 runs before the actor fallback is applied, so it checks the wrong scope. That can miss a same-realm duplicate until saveWithEA() or reject a valid insert against the actor’s realm.

💡 Suggested fix
-        await this.repository.checkUniqueness(validated, entity || undefined);
-
         if (entity) {
             if (entity.built_in) {
                 throw new BadRequestError('A built-in policy can not be updated.');
             }
 
+            await this.repository.checkUniqueness(validated, entity);
             await actor.permissionEvaluator.evaluate({
                 name: PermissionName.PERMISSION_UPDATE,
                 input: new PolicyData({
                     [BuiltInPolicyType.ATTRIBUTES]: {
                         ...entity,
@@
         if (!isPropertySet(validated, 'realm_id') && actor.identity) {
             validated.realm_id = this.getActorRealmId(actor) || null;
         }
 
+        await this.repository.checkUniqueness(validated);
+
         await actor.permissionEvaluator.evaluate({
             name: PermissionName.PERMISSION_CREATE,
             input: new PolicyData({
                 [BuiltInPolicyType.ATTRIBUTES]: validated,
             }),

Also applies to: 179-184

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

In `@apps/server-core/src/core/entities/policy/service.ts` around lines 175 - 177,
The uniqueness check is performed before the actor-based fallback for realm_id,
so update the flow in service.ts to ensure validated.realm_id gets assigned from
actor via getActorRealmId(actor) (when isPropertySet(validated, 'realm_id') is
false and actor.identity exists) before calling checkUniqueness(), and apply the
same change for the other similar block around lines 179-184; in short, move or
duplicate the realm_id fallback logic (using isPropertySet, validated.realm_id,
actor, and getActorRealmId) to run prior to invoking checkUniqueness() and
before saveWithEA() so uniqueness is evaluated in the correct realm scope.

@tada5hi
tada5hi merged commit 1ae7d10 into master Mar 24, 2026
10 checks passed
@tada5hi
tada5hi deleted the 2926-realm-scoping branch March 24, 2026 10:52
@github-actions github-actions Bot mentioned this pull request Mar 21, 2026
@github-actions github-actions Bot mentioned this pull request Mar 29, 2026
@github-actions github-actions Bot mentioned this pull request Apr 16, 2026
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.

1 participant