Repository navigation
feat: default policy synchronisation - #2904
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThis PR adds explicit system policy provisioning (system.default + children), a PolicyProvisioningSynchronizer, config-gated default policy assignment with startup backfill, wires defaultPolicyId into permission creation and synchronizers, and removes the in-memory synthesized default policy from the permission DB provider. Changes
Sequence Diagram(s)sequenceDiagram
participant PM as ProvisionerModule
participant CFG as Config
participant PR as PolicyRepository
participant PPS as PolicyProvisioningSynchronizer
participant BF as Backfill
participant PerPS as PermissionProvisioningSynchronizer
participant DB as Database
PM->>CFG: Load permissionsDefaultPolicyAssignment
alt enabled
PM->>PR: Resolve system.default → defaultPolicyId
end
PM->>PPS: Phase 1: synchronize policies (system.default + children)
PPS->>DB: upsert policies, attach parents, cleanup stale children
DB-->>PPS: persisted policy tree
alt enabled
PM->>BF: Phase 1b: backfill NULL permission.policy_id → defaultPolicyId
BF->>DB: UPDATE permissions WHERE policy_id IS NULL
DB-->>BF: backfill complete
end
PM->>PerPS: Phase 2: synchronize permissions (inject defaultPolicyId)
PerPS->>DB: create/update permissions (assign default when missing)
DB-->>PerPS: persisted permissions
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes Possibly related issues
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
📝 Coding Plan
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 8
🧹 Nitpick comments (1)
apps/server-core/src/app/modules/provisioning/module.ts (1)
118-126: Log how many rows the backfill touches.This is the rollout-critical data migration step. Capturing
execute().affectedhere will make it much easier to verify and troubleshoot behavior across environments.🤖 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 118 - 126, The backfill currently runs the update built from dataSource.createQueryBuilder().update(PermissionEntity)...where(...).andWhere(...).execute() but doesn't record how many rows were touched; capture the result of execute() (e.g., const result = await ...execute()) and log result.affected along with context (e.g., that this is the permission policy backfill and the defaultPolicy.id/created_at) so you can verify counts across environments; update the block that uses policyRepository.findOneByName(SystemPolicyName.DEFAULT) and defaultPolicy to store execute()'s return value and emit an info/debug log with the affected count.
🤖 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:
- Line 223: Update the architecture doc to reflect the new policy provisioning
changes: change the synchronization order line referencing
GraphProvisioningSynchronizer to "policies → permissions → roles → scopes →
realms"; add a "Repository Pattern" subsection documenting IPolicyRepository and
its responsibilities; add a "Policy Provisioning Subsystem" section describing
PolicyProvisioningSynchronizer, the system policy provisioning module/source,
and the default policy assignment mechanism invoked during provisioning;
document the PERMISSIONS_DEFAULT_POLICY_ASSIGNMENT configuration flag and its
behavior; and add an "Integration Points" paragraph explaining how policy
repositories (IPolicyRepository) are used by HTTP controllers and the
provisioning layers (PolicyProvisioningSynchronizer /
GraphProvisioningSynchronizer).
In
`@apps/server-core/src/adapters/http/controllers/entities/permission/module.ts`:
- Around line 366-368: The default policy assignment (this.defaultPolicyId ->
data.policy_id) is happening too late and bypasses checks; move the assignment
so it occurs before calling this.repository.validateJoinColumns(data) and before
the realm guard logic around policy checks (the block using the realm guard and
the policy validation), ensuring the auto-assigned policy is subject to
validateJoinColumns and realm validation; adjust code in the create/update
handler where this.defaultPolicyId, data.policy_id,
repository.validateJoinColumns, and the realm guard are used so the assignment
happens immediately after input normalization and prior to those validations.
In `@apps/server-core/src/core/provisioning/synchronizer/policy/module.ts`:
- Around line 29-33: The merge/save block for policies (repository.merge and
saveWithEA) only persists type and built_in, so parent relationships set earlier
via child.attributes.parent_id and child.attributes.parent are never written
back; update the merge call in module.ts to include parent_id and parent (or the
attributes used to represent parent linkage) so that when resync runs it
reattaches existing leaf policies to the correct parent, and ensure the same
change is applied to the analogous update at lines 55-56 to persist the parent
linkage during saveWithEA.
- Around line 22-36: The synchronize method currently does a findOneBy then
create/saveWithEA which is vulnerable to TOCTOU races; modify
PolicyProvisioningSynchronizer.synchronize to perform the upsert atomically by
either (1) wrapping the read-and-write in a transaction and using a SELECT ...
FOR UPDATE (or your ORM's equivalent) before create to serialize concurrent
boots, or (2) attempt an insert/upsert (ON CONFLICT DO UPDATE) instead of
create, and if your DB/ORM doesn't support upsert, catch a unique-constraint
error from repository.saveWithEA, re-load the existing entity via
repository.findOneBy and then merge/saveWithEA to retry; reference the
synchronize function, repository.findOneBy, repository.create and
repository.saveWithEA when implementing the transactional/upsert or
retry-on-conflict logic.
In `@policies-plan.md`:
- Around line 77-82: The fenced code blocks showing the policy trees (e.g., the
block containing "CompositePolicy (UNANIMOUS) ├ IdentityPolicy ├
PermissionBindingPolicy └ RealmMatchPolicy" and the later block showing
"system.default (CompositePolicy, UNANIMOUS) ..." ) are missing language
identifiers; update each triple-backtick fence to include the language tag
"text" (i.e., ```text) so markdownlint MD040 is satisfied for both the block
around CompositePolicy and the later block around system.default.
In `@policies-release-n.md`:
- Around line 134-142: The fenced block showing the policy tree (starting with
"system.default (CompositePolicy, UNANIMOUS, built_in: true)" and its children)
needs a language label to satisfy markdownlint MD040; edit the opening fence
from ``` to ```text so the block is declared as plain text (e.g., change the
triple backticks before "system.default..." to ```text) and save the update.
- Around line 84-95: Update the rollout note to reflect the shipped wiring:
replace the outdated controller and synchronizer paths with the actual modules
now used, state that the Permission HTTP controller receives a defaultPolicyId
injected from the provisioning module (rather than resolving the policy by
name), and note that the provisioning synchronizer no longer resolves
SystemPolicyName.DEFAULT itself but receives/uses the injected defaultPolicyId
from the provisioning module (refer to symbols Permission controller,
provisioning synchronizer, defaultPolicyId, and SystemPolicyName.DEFAULT when
editing the text).
In `@policies-release-n1.md`:
- Around line 30-33: Update the checklist entry titled "Permission HTTP
controller" so it points to the controller's current module location in the
repository (the controller has been moved into the server-core app) instead of
the outdated adapters path; verify and, if needed, adjust the three bullets to
match the current implementation—remove the auto-assign block for default
policy, drop IPolicyRepository from the controller context only if it was solely
used for that behavior, and confirm new permissions continue to be created with
policy_id staying null (unrestricted).
---
Nitpick comments:
In `@apps/server-core/src/app/modules/provisioning/module.ts`:
- Around line 118-126: The backfill currently runs the update built from
dataSource.createQueryBuilder().update(PermissionEntity)...where(...).andWhere(...).execute()
but doesn't record how many rows were touched; capture the result of execute()
(e.g., const result = await ...execute()) and log result.affected along with
context (e.g., that this is the permission policy backfill and the
defaultPolicy.id/created_at) so you can verify counts across environments;
update the block that uses
policyRepository.findOneByName(SystemPolicyName.DEFAULT) and defaultPolicy to
store execute()'s return value and emit an info/debug log with the affected
count.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 98d6af38-8e6d-467d-a1d3-4dea5540b73a
📒 Files selected for processing (25)
.agents/architecture.mdapps/server-core/src/adapters/http/controllers/entities/permission/module.tsapps/server-core/src/app/modules/config/constants.tsapps/server-core/src/app/modules/config/normalize.tsapps/server-core/src/app/modules/config/parse.tsapps/server-core/src/app/modules/config/read/env.tsapps/server-core/src/app/modules/config/types.tsapps/server-core/src/app/modules/http/modules/controller.tsapps/server-core/src/app/modules/provisioning/module.tsapps/server-core/src/app/modules/provisioning/system-policies.tsapps/server-core/src/core/provisioning/entities/index.tsapps/server-core/src/core/provisioning/entities/policy/index.tsapps/server-core/src/core/provisioning/entities/policy/types.tsapps/server-core/src/core/provisioning/synchronizer/index.tsapps/server-core/src/core/provisioning/synchronizer/permission/module.tsapps/server-core/src/core/provisioning/synchronizer/permission/types.tsapps/server-core/src/core/provisioning/synchronizer/policy/index.tsapps/server-core/src/core/provisioning/synchronizer/policy/module.tsapps/server-core/src/core/provisioning/synchronizer/policy/types.tsapps/server-core/src/security/permission/provider/db.tspackages/access/src/policy/built-in/constants.tspolicies-plan.mdpolicies-release-n.mdpolicies-release-n1.mdprovisioning-refactor-plan.md
| ### Synchronization Order | ||
|
|
||
| `GraphProvisioningSynchronizer` processes: permissions → roles → scopes → realms. | ||
| `GraphProvisioningSynchronizer` processes in order: permissions → roles → scopes → realms. |
There was a problem hiding this comment.
Document the new policy provisioning architecture introduced in this PR.
The textual clarification ("in order") is a good improvement. However, according to the PR summary, this PR introduces extensive policy provisioning features that represent a significant architectural change, yet this architecture document hasn't been updated to reflect these changes:
Missing documentation includes:
- Updated synchronization order: System policies now provision before permissions, but line 223 still shows "permissions → roles → scopes → realms" (should likely be "policies → permissions → roles → scopes → realms")
- Policy repository pattern: No mention of
IPolicyRepositoryin the "Repository Pattern" section - Policy provisioning subsystem: The "Provisioning Architecture" section should document:
PolicyProvisioningSynchronizerand its role- System policy provisioning module/source
- Default policy assignment mechanism during provisioning
- Configuration: The
PERMISSIONS_DEFAULT_POLICY_ASSIGNMENTflag and its behavior - Integration points: How policy repositories integrate with HTTP controllers and provisioning layers
As per coding guidelines, the .agents directory files should be kept updated as the project evolves, including architectural changes, new patterns, and important conventions. Policy-based access control represents exactly this type of architectural evolution.
Would you like me to draft the documentation sections covering the policy provisioning architecture based on the implementation details from this PR?
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In @.agents/architecture.md at line 223, Update the architecture doc to reflect
the new policy provisioning changes: change the synchronization order line
referencing GraphProvisioningSynchronizer to "policies → permissions → roles →
scopes → realms"; add a "Repository Pattern" subsection documenting
IPolicyRepository and its responsibilities; add a "Policy Provisioning
Subsystem" section describing PolicyProvisioningSynchronizer, the system policy
provisioning module/source, and the default policy assignment mechanism invoked
during provisioning; document the PERMISSIONS_DEFAULT_POLICY_ASSIGNMENT
configuration flag and its behavior; and add an "Integration Points" paragraph
explaining how policy repositories (IPolicyRepository) are used by HTTP
controllers and the provisioning layers (PolicyProvisioningSynchronizer /
GraphProvisioningSynchronizer).
| async synchronize(input: PolicyProvisioningEntity): Promise<PolicyProvisioningEntity> { | ||
| let entity = await this.repository.findOneBy({ | ||
| name: input.attributes.name, | ||
| realm_id: input.attributes.realm_id || null, | ||
| }); | ||
|
|
||
| if (entity) { | ||
| entity = this.repository.merge(entity, { | ||
| type: input.attributes.type, | ||
| built_in: input.attributes.built_in, | ||
| }); | ||
| await this.repository.saveWithEA(entity, input.ea); | ||
| } else { | ||
| entity = this.repository.create(input.attributes); | ||
| await this.repository.saveWithEA(entity, input.ea); |
There was a problem hiding this comment.
Avoid a startup TOCTOU here.
Lines 23-36 do findOneBy() and then create()/saveWithEA(). apps/server-core/src/app/modules/provisioning/module.ts Lines 111-112 call this on every boot, so two instances starting together can both miss the same built-in policy and one will fail on insert or create a duplicate depending on the DB constraint. Please make this path atomic or retry after a unique-conflict reload.
🤖 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/policy/module.ts` around
lines 22 - 36, The synchronize method currently does a findOneBy then
create/saveWithEA which is vulnerable to TOCTOU races; modify
PolicyProvisioningSynchronizer.synchronize to perform the upsert atomically by
either (1) wrapping the read-and-write in a transaction and using a SELECT ...
FOR UPDATE (or your ORM's equivalent) before create to serialize concurrent
boots, or (2) attempt an insert/upsert (ON CONFLICT DO UPDATE) instead of
create, and if your DB/ORM doesn't support upsert, catch a unique-constraint
error from repository.saveWithEA, re-load the existing entity via
repository.findOneBy and then merge/saveWithEA to retry; reference the
synchronize function, repository.findOneBy, repository.create and
repository.saveWithEA when implementing the transactional/upsert or
retry-on-conflict logic.
| **a) Permission HTTP controller** (`adapters/http/controllers/entities/permission/module.ts`): | ||
| - Remove the block that checks `config.permissionsDefaultPolicyAssignment` and auto-assigns `system.default` | ||
| - Remove `IPolicyRepository` from controller context if it was only needed for this | ||
| - New permissions created without `policy_id` → `policy_id` stays `null` (unrestricted) |
There was a problem hiding this comment.
Fix the controller path in this cleanup checklist.
Line 30 still references adapters/http/controllers/entities/permission/module.ts, but the controller now lives under apps/server-core/src/app/modules/http/controllers/entities/permission/module.ts.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@policies-release-n1.md` around lines 30 - 33, Update the checklist entry
titled "Permission HTTP controller" so it points to the controller's current
module location in the repository (the controller has been moved into the
server-core app) instead of the outdated adapters path; verify and, if needed,
adjust the three bullets to match the current implementation—remove the
auto-assign block for default policy, drop IPolicyRepository from the controller
context only if it was solely used for that behavior, and confirm new
permissions continue to be created with policy_id staying null (unrestricted).
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@policies-plan.md`:
- Around line 441-455: The write() example performs a per-request lookup with
policyRepository.findOneByName(SystemPolicyName.DEFAULT); change it to use the
provisioned/injected defaultPolicyId instead: when !entity && !data.policy_id
and config.permissionsDefaultPolicyAssignment is true, set data.policy_id =
this.defaultPolicyId (or the injected defaultPolicyId from the
controller/synchronizer context) and remove the findOneByName call so no runtime
repository lookup is done per request.
- Around line 179-182: Update the "Current Behavior" block to reflect the
shipped logic: PermissionDatabaseRepository.findOne() does not fall back to
getDefaultPolicy() when entity.policy is null, it returns policy: undefined
instead; replace the sentence that states it returns getDefaultPolicy() with one
that clearly says findOne() returns policy: undefined for null entity.policy and
only loads a policy tree when entity.policy exists (reference
PermissionDatabaseRepository.findOne and getDefaultPolicy in the text to make
the distinction explicit).
In `@policies-release-n.md`:
- Around line 88-94: The docs are ambiguous about “without policy_id” while the
controller uses a falsy check and treats explicit null the same as absent;
update the text in the write method and the Permission provisioning synchronizer
note (reference validateJoinColumns, defaultPolicyId and
core/provisioning/synchronizer/permission/module.ts) to explicitly state current
behavior: that when policy_id is missing or explicitly null the system will
assign defaultPolicyId before validateJoinColumns, or alternatively change the
controller logic to only treat undefined (absent) as assignable — pick one
approach and make the docs and code consistent.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: b5afd6d1-f9dc-4843-923c-af48ffab5bb0
📒 Files selected for processing (4)
apps/server-core/src/adapters/http/controllers/entities/permission/module.tsapps/server-core/src/core/provisioning/synchronizer/policy/module.tspolicies-plan.mdpolicies-release-n.md
🚧 Files skipped from review as they are similar to previous changes (1)
- apps/server-core/src/core/provisioning/synchronizer/policy/module.ts
| **a) Permission HTTP controller** (`adapters/http/controllers/entities/permission/module.ts`): | ||
|
|
||
| In the `write()` method, after validation and before save, if creating a new permission and `policy_id` is not set: | ||
|
|
||
| ```typescript | ||
| if (!entity && !data.policy_id) { | ||
| const config = container.resolve<Config>(ConfigInjectionKey); | ||
| if (config.permissionsDefaultPolicyAssignment) { | ||
| const defaultPolicy = await this.policyRepository.findOneByName(SystemPolicyName.DEFAULT); | ||
| if (defaultPolicy) { | ||
| data.policy_id = defaultPolicy.id; | ||
| } | ||
| } | ||
| } | ||
| ``` |
There was a problem hiding this comment.
Controller write-path example no longer matches shipped wiring.
The example still shows resolving system.default inside the controller via policyRepository.findOneByName(...). Current wiring resolves once during provisioning and injects defaultPolicyId into controller/synchronizer contexts. Please align this snippet to avoid reintroducing per-request lookup patterns.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@policies-plan.md` around lines 441 - 455, The write() example performs a
per-request lookup with
policyRepository.findOneByName(SystemPolicyName.DEFAULT); change it to use the
provisioned/injected defaultPolicyId instead: when !entity && !data.policy_id
and config.permissionsDefaultPolicyAssignment is true, set data.policy_id =
this.defaultPolicyId (or the injected defaultPolicyId from the
controller/synchronizer context) and remove the findOneByName call so no runtime
repository lookup is done per request.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
apps/server-core/src/core/provisioning/synchronizer/policy/module.ts (1)
55-69: Consider usingfor...offor sequential async iteration.The
reducepattern for sequential async processing works but is less readable than afor...ofloop. Also, theas anycast on line 64 bypasses type safety.♻️ Suggested refactor for clarity
private async synchronizeChildren( parentId: string, children: PolicyProvisioningEntity[], ): Promise<void> { const declaredNames = children.map((c) => c.attributes.name); - await children.reduce(async (prev, child) => { - await prev; + for (const child of children) { child.attributes.parent_id = parentId; - child.attributes.parent = { id: parentId } as any; + child.attributes.parent = { id: parentId } as Policy; await this.synchronize(child); - }, Promise.resolve()); + } await this.cleanupStaleChildren(parentId, declaredNames); }🤖 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/policy/module.ts` around lines 55 - 69, The sequential async loop in synchronizeChildren uses children.reduce which is less readable and the attributes.parent assignment uses an unsafe "as any" cast; replace the reduce with an explicit for...of loop over children so you await this.synchronize(child) sequentially, and set child.attributes.parent_id = parentId and child.attributes.parent = { id: parentId } using the correct typed shape (or a safer cast) instead of "as any"—update the synchronizeChildren method and ensure the assigned parent object matches the attribute type expected by the PolicyProvisioningEntity interface.
🤖 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/policy/module.ts`:
- Around line 71-87: The matching currently treats undefined names as valid
entries because declaredNames is (string | undefined)[]; filter out undefined
values before comparing so DB children with name === undefined aren’t treated as
declared. In cleanupStaleChildren, derive a cleaned set (e.g., const declaredSet
= new Set(declaredNames.filter((n): n is string => n !== undefined))) and use
declaredSet.has(child.name) (or explicitly check typeof child.name === 'string'
before lookup) instead of declaredNames.indexOf(...), then proceed to call
cleanupStaleChild for stale entries; keep references to cleanupStaleChildren,
declaredNames, existingChildren, staleChildren and cleanupStaleChild when making
the change.
---
Nitpick comments:
In `@apps/server-core/src/core/provisioning/synchronizer/policy/module.ts`:
- Around line 55-69: The sequential async loop in synchronizeChildren uses
children.reduce which is less readable and the attributes.parent assignment uses
an unsafe "as any" cast; replace the reduce with an explicit for...of loop over
children so you await this.synchronize(child) sequentially, and set
child.attributes.parent_id = parentId and child.attributes.parent = { id:
parentId } using the correct typed shape (or a safer cast) instead of "as
any"—update the synchronizeChildren method and ensure the assigned parent object
matches the attribute type expected by the PolicyProvisioningEntity interface.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 7d1bdec6-8317-4167-aeab-472ba161145d
📒 Files selected for processing (4)
apps/server-core/src/app/modules/provisioning/module.tsapps/server-core/src/core/provisioning/synchronizer/policy/module.tsapps/server-core/src/core/provisioning/synchronizer/policy/types.tspolicies-release-n.md
| private async cleanupStaleChildren( | ||
| parentId: string, | ||
| declaredNames: (string | undefined)[], | ||
| ): Promise<void> { | ||
| const existingChildren = await this.repository.findManyBy({ | ||
| parent_id: parentId, | ||
| }); | ||
|
|
||
| const staleChildren = existingChildren.filter( | ||
| (child) => declaredNames.indexOf(child.name) === -1, | ||
| ); | ||
|
|
||
| await staleChildren.reduce(async (prev, child) => { | ||
| await prev; | ||
| await this.cleanupStaleChild(child); | ||
| }, Promise.resolve()); | ||
| } |
There was a problem hiding this comment.
Potential false positive when matching undefined names.
The declaredNames array is typed as (string | undefined)[]. If any child in the declaration has an undefined name, and a stale DB child also has name === undefined, it would incorrectly be considered "declared" and not cleaned up. While this is unlikely in practice (policies should have names), consider filtering out undefined values for robustness.
🛡️ Proposed fix
private async cleanupStaleChildren(
parentId: string,
- declaredNames: (string | undefined)[],
+ declaredNames: string[],
): Promise<void> {And update the caller:
- const declaredNames = children.map((c) => c.attributes.name);
+ const declaredNames = children.map((c) => c.attributes.name).filter((n): n is string => !!n);🤖 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/policy/module.ts` around
lines 71 - 87, The matching currently treats undefined names as valid entries
because declaredNames is (string | undefined)[]; filter out undefined values
before comparing so DB children with name === undefined aren’t treated as
declared. In cleanupStaleChildren, derive a cleaned set (e.g., const declaredSet
= new Set(declaredNames.filter((n): n is string => n !== undefined))) and use
declaredSet.has(child.name) (or explicitly check typeof child.name === 'string'
before lookup) instead of declaredNames.indexOf(...), then proceed to call
cleanupStaleChild for stale entries; keep references to cleanupStaleChildren,
declaredNames, existingChildren, staleChildren and cleanupStaleChild when making
the change.
There was a problem hiding this comment.
🧹 Nitpick comments (4)
apps/server-core/test/unit/modules/policy-provisioning.spec.ts (4)
220-233: Same refactor applies here.Apply the same pattern of storing
buildSystemPolicyProvisioningEntities()result in a variable before using it.♻️ Proposed fix
+ const baseEntities = buildSystemPolicyProvisioningEntities(); const inputWithExtra: PolicyProvisioningEntity = { - ...buildSystemPolicyProvisioningEntities(), + ...baseEntities, children: [ - ...buildSystemPolicyProvisioningEntities().children!, + ...baseEntities.children!, { attributes: { name: 'system.referenced-child', type: BuiltInPolicyType.IDENTITY, built_in: true, realm_id: null, }, }, ], };🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/test/unit/modules/policy-provisioning.spec.ts` around lines 220 - 233, The test currently calls buildSystemPolicyProvisioningEntities() multiple times when constructing inputWithExtra; capture the result once in a const (e.g., const base = buildSystemPolicyProvisioningEntities()) and then use base and base.children when building inputWithExtra (instead of repeated calls), ensuring inputWithExtra: PolicyProvisioningEntity spreads base and appends the extra child to base.children to avoid duplicate/unevaluated invocations.
131-131: Consider using typed EA access if available.The
as anycast bypasses type checking for EA attributes. If there's a typed interface or helper for accessing extended attributes (likedecisionStrategy), consider using it for better type safety. Otherwise, document 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/test/unit/modules/policy-provisioning.spec.ts` at line 131, The test currently casts defaultPolicy to any to access its extended attribute decisionStrategy; replace the unsafe cast by using the typed extended attributes interface or accessor for policy EAs (e.g., a PolicyWithEAs or getExtendedAttribute/getEA helper) so you can assert (defaultPolicy as PolicyWithEAs).decisionStrategy === DecisionStrategy.UNANIMOUS, or if no typed EA exists add a small interface for the expected EA shape and cast to that type (or add a comment explaining why the cast is necessary) to preserve type safety when referencing decisionStrategy on defaultPolicy.
280-284: Consider verifying the assigned policy is specificallysystem.DEFAULT.The test only checks that
policy_idis not null, but doesn't verify it's the expectedsystem.DEFAULTpolicy. This could mask issues where a wrong policy is assigned.♻️ Proposed enhancement
+ const defaultPolicy = await policyRepositoryAdapter.findOneByName(SystemPolicyName.DEFAULT); const updated = await permissionRepo.findOneBy({ name: 'old_permission' }); expect(updated).toBeDefined(); expect(updated!.policy_id).toBeDefined(); - expect(updated!.policy_id).not.toBeNull(); + expect(updated!.policy_id).toBe(defaultPolicy!.id);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/test/unit/modules/policy-provisioning.spec.ts` around lines 280 - 284, Update the test that fetches the updated permission via permissionRepo.findOneBy to assert the assigned policy is exactly system.DEFAULT instead of only checking non-null; change the assertion from expect(updated!.policy_id).not.toBeNull() to expect(updated!.policy_id).toEqual(system.DEFAULT) and ensure the test file imports or references the correct system.DEFAULT symbol used by your policy constants so the comparison is valid.
187-200: Avoid callingbuildSystemPolicyProvisioningEntities()multiple times.The function is called twice in this expression: once for the spread and once for
.children. This is inefficient and could cause issues if the function had side effects. Store the result in a variable first.♻️ Proposed fix
+ const baseEntities = buildSystemPolicyProvisioningEntities(); const inputWithExtra: PolicyProvisioningEntity = { - ...buildSystemPolicyProvisioningEntities(), + ...baseEntities, children: [ - ...buildSystemPolicyProvisioningEntities().children!, + ...baseEntities.children!, { attributes: { name: 'system.stale-child', type: BuiltInPolicyType.IDENTITY, built_in: true, realm_id: null, }, }, ], };🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/test/unit/modules/policy-provisioning.spec.ts` around lines 187 - 200, The test calls buildSystemPolicyProvisioningEntities() twice when constructing inputWithExtra; capture its result in a local const (e.g., const base = buildSystemPolicyProvisioningEntities()) and then spread base and use base.children when building inputWithExtra so the function is invoked once and the same data is reused for PolicyProvisioningEntity creation (update the inputWithExtra construction and any references to children accordingly).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@apps/server-core/test/unit/modules/policy-provisioning.spec.ts`:
- Around line 220-233: The test currently calls
buildSystemPolicyProvisioningEntities() multiple times when constructing
inputWithExtra; capture the result once in a const (e.g., const base =
buildSystemPolicyProvisioningEntities()) and then use base and base.children
when building inputWithExtra (instead of repeated calls), ensuring
inputWithExtra: PolicyProvisioningEntity spreads base and appends the extra
child to base.children to avoid duplicate/unevaluated invocations.
- Line 131: The test currently casts defaultPolicy to any to access its extended
attribute decisionStrategy; replace the unsafe cast by using the typed extended
attributes interface or accessor for policy EAs (e.g., a PolicyWithEAs or
getExtendedAttribute/getEA helper) so you can assert (defaultPolicy as
PolicyWithEAs).decisionStrategy === DecisionStrategy.UNANIMOUS, or if no typed
EA exists add a small interface for the expected EA shape and cast to that type
(or add a comment explaining why the cast is necessary) to preserve type safety
when referencing decisionStrategy on defaultPolicy.
- Around line 280-284: Update the test that fetches the updated permission via
permissionRepo.findOneBy to assert the assigned policy is exactly system.DEFAULT
instead of only checking non-null; change the assertion from
expect(updated!.policy_id).not.toBeNull() to
expect(updated!.policy_id).toEqual(system.DEFAULT) and ensure the test file
imports or references the correct system.DEFAULT symbol used by your policy
constants so the comparison is valid.
- Around line 187-200: The test calls buildSystemPolicyProvisioningEntities()
twice when constructing inputWithExtra; capture its result in a local const
(e.g., const base = buildSystemPolicyProvisioningEntities()) and then spread
base and use base.children when building inputWithExtra so the function is
invoked once and the same data is reused for PolicyProvisioningEntity creation
(update the inputWithExtra construction and any references to children
accordingly).
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 4319ae0c-c3c1-483b-8b0b-2429ca82d323
📒 Files selected for processing (2)
apps/server-core/src/app/modules/provisioning/index.tsapps/server-core/test/unit/modules/policy-provisioning.spec.ts
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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/permission/module.ts`:
- Around line 61-63: The current check uses typeof input.attributes.policy_id
=== 'undefined' which treats an explicit property set to undefined the same as
an omitted property; change the logic to test key presence instead so we only
default when the key is omitted: replace the condition with a key-presence check
such as if (this.defaultPolicyId &&
!Object.prototype.hasOwnProperty.call(input.attributes, 'policy_id')) {
input.attributes.policy_id = this.defaultPolicyId; } (ensure you reference the
same this.defaultPolicyId and input.attributes.policy_id symbols and handle the
case where input.attributes exists).
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 94658343-b678-474c-9e20-dcd0a79b0c26
📒 Files selected for processing (3)
apps/server-core/src/adapters/http/controllers/entities/permission/module.tsapps/server-core/src/core/provisioning/synchronizer/permission/module.tsapps/server-core/test/unit/modules/policy-provisioning.spec.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- apps/server-core/test/unit/modules/policy-provisioning.spec.ts
- apps/server-core/src/adapters/http/controllers/entities/permission/module.ts
| if (this.defaultPolicyId && typeof input.attributes.policy_id === 'undefined') { | ||
| input.attributes.policy_id = this.defaultPolicyId; | ||
| } |
There was a problem hiding this comment.
Use key-presence check to enforce “omitted only” behavior.
Line 61 checks undefined value, not property omission. This will also default when policy_id is explicitly present as undefined, which does not strictly match the stated intent.
Suggested fix
- if (this.defaultPolicyId && typeof input.attributes.policy_id === 'undefined') {
+ if (
+ this.defaultPolicyId &&
+ !Object.prototype.hasOwnProperty.call(input.attributes, 'policy_id')
+ ) {
input.attributes.policy_id = this.defaultPolicyId;
}🤖 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/permission/module.ts`
around lines 61 - 63, The current check uses typeof input.attributes.policy_id
=== 'undefined' which treats an explicit property set to undefined the same as
an omitted property; change the logic to test key presence instead so we only
default when the key is omitted: replace the condition with a key-presence check
such as if (this.defaultPolicyId &&
!Object.prototype.hasOwnProperty.call(input.attributes, 'policy_id')) {
input.attributes.policy_id = this.defaultPolicyId; } (ensure you reference the
same this.defaultPolicyId and input.attributes.policy_id symbols and handle the
case where input.attributes exists).
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 3
♻️ Duplicate comments (1)
apps/server-core/src/core/provisioning/synchronizer/policy/module.ts (1)
71-87:⚠️ Potential issue | 🟡 MinorFilter out
undefinednames to prevent false matches in cleanup.The
declaredNamesarray is typed as(string | undefined)[]. If a child policy has an undefinedname, and a stale DB child also hasname === undefined, it would incorrectly be considered "declared" and not cleaned up. Filter out undefined values for robustness.🛡️ Proposed fix
private async cleanupStaleChildren( parentId: string, - declaredNames: (string | undefined)[], + declaredNames: string[], ): Promise<void> { const existingChildren = await this.repository.findManyBy({ parent_id: parentId, }); const staleChildren = existingChildren.filter( - (child) => declaredNames.indexOf(child.name) === -1, + (child) => !child.name || !declaredNames.includes(child.name), );And update the caller at line 59:
- const declaredNames = children.map((c) => c.attributes.name); + const declaredNames = children.map((c) => c.attributes.name).filter((n): n is string => !!n);🤖 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/policy/module.ts` around lines 71 - 87, The cleanup logic uses declaredNames:(string|undefined)[] which can contain undefined and cause undefined DB child names to be treated as declared; inside cleanupStaleChildren, first create a filtered array of only defined strings (e.g., filter declaredNames where value !== undefined) and use that filteredNames for the indexOf check when building staleChildren, then await cleanupStaleChild as before; also ensure the caller that builds declaredNames (the caller invoking cleanupStaleChildren) is updated to filter out undefined entries before passing them in.
🧹 Nitpick comments (3)
apps/server-core/src/core/provisioning/synchronizer/policy/module.ts (1)
63-65: Consider improving type safety for parent assignment.The
as anycast on line 64 obscures type checking. IfPolicyhas a proper type for theparentrelation, consider using that type instead.♻️ Suggested improvement
child.attributes.parent_id = parentId; - child.attributes.parent = { id: parentId } as any; + child.attributes.parent = { id: parentId } as Pick<Policy, 'id'>;Or if the type system allows, use a proper partial type.
🤖 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/policy/module.ts` around lines 63 - 65, Replace the unsafe cast on child.attributes.parent = { id: parentId } as any with a properly typed assignment: use the actual Policy (or PolicyRelation) interface/type for the parent relation (or Partial<Policy> / { id: string } typed to that relation) so TypeScript can validate the shape; update the assignment in the synchronizer where child.attributes.parent is set (reference: child.attributes.parent, parentId, and the method this.synchronize) to construct the parent object with the correct type instead of casting to any..agents/architecture.md (1)
216-226: Partial update to architecture documentation.The synchronization order is now documented correctly (policies → permissions → roles → scopes → realms). However, per coding guidelines requiring
.agentsfiles to be updated as the project evolves, consider adding:
IPolicyRepositoryto the Repository Pattern section (line 106 mentions policy in "Complex with EA" but no interface documentation)- A brief mention of
PolicyProvisioningSynchronizerin the synchronizer list- The
PERMISSIONS_DEFAULT_POLICY_ASSIGNMENTconfig flag behaviorAs per coding guidelines, "Keep .agents directory files updated as the project evolves, including architectural changes, new patterns, and important conventions."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In @.agents/architecture.md around lines 216 - 226, Update the .agents architecture doc to (1) add an entry describing the IPolicyRepository interface in the Repository Pattern section (mention its responsibility for CRUD and query operations for Policy entities and how it fits with existing repositories), (2) add PolicyProvisioningSynchronizer to the synchronizers list and explain its place in the synchronization order (policies → permissions → roles → scopes → realms), and (3) document the PERMISSIONS_DEFAULT_POLICY_ASSIGNMENT config flag and its behavior (what default policy assignment it controls and how synchronizers/apply logic use it).apps/server-core/test/unit/modules/provisioning.spec.ts (1)
200-200: Consider typed access for entity properties instead ofanycasts.Several tests use
as anyto access entity properties:
- Line 200:
(defaultPolicy as any).decisionStrategy- Lines 245-247:
(realmMatch as any).attributeName, etc.- Line 375:
policy_id: null as anyFor lines 200 and 245-247, consider adding proper type guards or extending the test types to include these properties.
For line 375, the
null as anycast works around a type restriction but correctly tests the intended behavior. Ifpolicy_id: nullis a valid input for "unrestricted" permissions, thePermissionProvisioningEntityattributes type could be updated to allow explicitnull.Also applies to: 245-247, 375-375
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/test/unit/modules/provisioning.spec.ts` at line 200, Tests use unsafe `as any` casts to access entity properties (e.g., defaultPolicy.decisionStrategy, realmMatch.attributeName, and policy_id) — replace these with typed access or type-safe guards: update the test fixture types or create minimal test-specific interfaces that include decisionStrategy on defaultPolicy and attributeName/attributeValue on realmMatch so you can access them without `any`, add a small type guard/helper in the spec to narrow the entity type before asserting those properties, and if `policy_id: null` is valid for PermissionProvisioningEntity adjust the PermissionProvisioningEntity attributes type to allow null for policy_id (or add an explicit test-only factory type that permits null) so the test no longer needs `null as any`.
🤖 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 273-280: The reducer that builds the ancestor map (variable acc in
the ancestorsOfDescendants.reduce) initializes
acc[curr[descendantColumn.databasePath]] as an array but then assigns a string:
acc[curr[descendantColumn.databasePath]] = curr[ancestorColumn.databasePath];
change the reducer to push the ancestor into the array (e.g.,
acc[key].push(...)) so acc[...] remains string[]; update the reducer handling
around ancestorsOfDescendants and the keys derived from
descendantColumn.databasePath and ancestorColumn.databasePath to accumulate
ancestors rather than overwrite them, ensuring later code that calls .indexOf on
ancestors arrays works correctly.
In `@apps/server-core/src/app/modules/http/modules/controller.ts`:
- Around line 492-505: The PermissionController is initialized with a cached
defaultPolicyId at module mount which can become stale; instead remove
defaultPolicyId from the constructor args and have PermissionController resolve
the default policy at runtime (e.g., inside its create/update handlers) by
calling policyRepository.findOneByName(SystemPolicyName.DEFAULT) when policy_id
is omitted, or inject policyRepository (or a small cache-with-invalidation
wrapper) into PermissionController so it can fetch/refresh the default policy
dynamically; update the module code to pass policyRepository (or the cache
wrapper) and adjust PermissionController to perform the lookup rather than using
the exported defaultPolicyId variable.
In `@apps/server-core/src/app/modules/provisioning/module.ts`:
- Around line 238-248: The current backfill updates all PermissionEntity rows
WHERE policy_id IS NULL which will overwrite intentionally unrestricted
permissions; update the backfill logic in the block that checks
config.permissionsDefaultPolicyAssignment (the code using
policyRepository.findOneByName(SystemPolicyName.DEFAULT) and
dataSource.createQueryBuilder().update(PermissionEntity).set({ policy_id:
defaultPolicy.id }).where('policy_id IS NULL').execute()) to only target legacy
rows by adding an additional filter (e.g., AND created_at < FEATURE_LAUNCH_DATE
or use a new config flag like config.permissionsDefaultPolicyBackfillCutoff) so
only permissions created before the feature launch are backfilled, and add a
short comment explaining the cutoff and how to disable backfill via
permissionsDefaultPolicyAssignment=false.
---
Duplicate comments:
In `@apps/server-core/src/core/provisioning/synchronizer/policy/module.ts`:
- Around line 71-87: The cleanup logic uses declaredNames:(string|undefined)[]
which can contain undefined and cause undefined DB child names to be treated as
declared; inside cleanupStaleChildren, first create a filtered array of only
defined strings (e.g., filter declaredNames where value !== undefined) and use
that filteredNames for the indexOf check when building staleChildren, then await
cleanupStaleChild as before; also ensure the caller that builds declaredNames
(the caller invoking cleanupStaleChildren) is updated to filter out undefined
entries before passing them in.
---
Nitpick comments:
In @.agents/architecture.md:
- Around line 216-226: Update the .agents architecture doc to (1) add an entry
describing the IPolicyRepository interface in the Repository Pattern section
(mention its responsibility for CRUD and query operations for Policy entities
and how it fits with existing repositories), (2) add
PolicyProvisioningSynchronizer to the synchronizers list and explain its place
in the synchronization order (policies → permissions → roles → scopes → realms),
and (3) document the PERMISSIONS_DEFAULT_POLICY_ASSIGNMENT config flag and its
behavior (what default policy assignment it controls and how synchronizers/apply
logic use it).
In `@apps/server-core/src/core/provisioning/synchronizer/policy/module.ts`:
- Around line 63-65: Replace the unsafe cast on child.attributes.parent = { id:
parentId } as any with a properly typed assignment: use the actual Policy (or
PolicyRelation) interface/type for the parent relation (or Partial<Policy> / {
id: string } typed to that relation) so TypeScript can validate the shape;
update the assignment in the synchronizer where child.attributes.parent is set
(reference: child.attributes.parent, parentId, and the method this.synchronize)
to construct the parent object with the correct type instead of casting to any.
In `@apps/server-core/test/unit/modules/provisioning.spec.ts`:
- Line 200: Tests use unsafe `as any` casts to access entity properties (e.g.,
defaultPolicy.decisionStrategy, realmMatch.attributeName, and policy_id) —
replace these with typed access or type-safe guards: update the test fixture
types or create minimal test-specific interfaces that include decisionStrategy
on defaultPolicy and attributeName/attributeValue on realmMatch so you can
access them without `any`, add a small type guard/helper in the spec to narrow
the entity type before asserting those properties, and if `policy_id: null` is
valid for PermissionProvisioningEntity adjust the PermissionProvisioningEntity
attributes type to allow null for policy_id (or add an explicit test-only
factory type that permits null) so the test no longer needs `null as any`.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: ea74fc73-b091-4d32-8161-151b2719b300
📒 Files selected for processing (19)
.agents/architecture.mdapps/server-core/src/adapters/database/extra-attribute-repository/tree/repository.tsapps/server-core/src/adapters/http/controllers/entities/permission/module.tsapps/server-core/src/app/modules/http/modules/controller.tsapps/server-core/src/app/modules/provisioning/index.tsapps/server-core/src/app/modules/provisioning/module.tsapps/server-core/src/app/modules/provisioning/sources/composite/module.tsapps/server-core/src/app/modules/provisioning/sources/default/module.tsapps/server-core/src/core/provisioning/entities/policy/types.tsapps/server-core/src/core/provisioning/entities/root/types.tsapps/server-core/src/core/provisioning/synchronizer/permission/module.tsapps/server-core/src/core/provisioning/synchronizer/policy/module.tsapps/server-core/src/core/provisioning/synchronizer/root/module.tsapps/server-core/src/core/provisioning/synchronizer/root/types.tsapps/server-core/test/unit/modules/provisioning.spec.tsdocs/src/guide/deployment/configuration-server-core.mddocs/src/guide/deployment/provisioning.mddocs/src/guide/user/permissions-and-policies.mdpolicies-release-n.md
💤 Files with no reviewable changes (1)
- apps/server-core/src/app/modules/provisioning/index.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- apps/server-core/src/core/provisioning/entities/policy/types.ts
- apps/server-core/src/adapters/http/controllers/entities/permission/module.ts
- policies-release-n.md
| let defaultPolicyId: string | undefined; | ||
| if (config.permissionsDefaultPolicyAssignment) { | ||
| const defaultPolicy = await policyRepository.findOneByName(SystemPolicyName.DEFAULT); | ||
| if (defaultPolicy) { | ||
| defaultPolicyId = defaultPolicy.id; | ||
| } | ||
| } | ||
|
|
||
| return new PermissionController({ | ||
| repository, | ||
| realmRepository: new RealmRepositoryAdapter(realmRepository), | ||
| dataSource, | ||
| defaultPolicyId, | ||
| }); |
There was a problem hiding this comment.
Resolve the default policy dynamically instead of caching its ID at startup.
This resolves defaultPolicyId once while the HTTP module is mounting, but the same module also exposes PolicyController, so policy state can change after startup. Because PermissionController stores and reuses this value when policy_id is omitted, later sync/delete/recreate leaves new permissions using a stale ID—or no default at all if the policy is provisioned after boot. Move the lookup into the create path, or inject the policy repository behind a cache with invalidation.
🤖 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 492
- 505, The PermissionController is initialized with a cached defaultPolicyId at
module mount which can become stale; instead remove defaultPolicyId from the
constructor args and have PermissionController resolve the default policy at
runtime (e.g., inside its create/update handlers) by calling
policyRepository.findOneByName(SystemPolicyName.DEFAULT) when policy_id is
omitted, or inject policyRepository (or a small cache-with-invalidation wrapper)
into PermissionController so it can fetch/refresh the default policy
dynamically; update the module code to pass policyRepository (or the cache
wrapper) and adjust PermissionController to perform the lookup rather than using
the exported defaultPolicyId variable.
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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 282-289: The loop over Object.keys(acc) skips descendants that
have no entries in acc, causing missing closure inserts; change the logic to
iterate the full set of descendant IDs (e.g., use an existing
descendantIds/descendants array or build one beforehand) and for each descendant
use const ancestorsOfDescendent = acc[descendant] || [] so descendants with no
pre-existing ancestors are still processed and the inner loop over ancestorIds
will create the missing ancestor-descendant relations; update the block using
accKeys/ancestorsOfDescendent/ancestorIds in repository.ts accordingly.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 182cd022-7d23-40e7-ae52-d8ef1ff70ec7
📒 Files selected for processing (1)
apps/server-core/src/adapters/database/extra-attribute-repository/tree/repository.ts
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (3)
.claude/skills/investigate-pr-comments/SKILL.md (1)
11-11: Consider slightly more formal wording in the opening instruction.Line 11 reads clearly, but “resolve” may be a bit more formal than “fix” for this context.
✏️ Optional wording tweak
-Fetch all review comments on the current PR, investigate each one against the actual code, and fix real issues. +Fetch all review comments on the current PR, investigate each one against the actual code, and resolve confirmed issues.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In @.claude/skills/investigate-pr-comments/SKILL.md at line 11, Change the phrasing in the instruction line that reads "Fetch all review comments on the current PR, investigate each one against the actual code, and fix real issues." to use a slightly more formal word—replace "fix real issues" with "resolve real issues" (or "address real issues") so the sentence reads "...investigate each one against the actual code, and resolve real issues."; update the literal string in SKILL.md accordingly..agents/plans/policies-plan.md (2)
38-38: Tighten wording for readability on Line 38Consider replacing “in order to” with “to” for concision.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In @.agents/plans/policies-plan.md at line 38, Replace the phrase "in order to" with the more concise "to" in the sentence "A Policy defines conditions that must be satisfied in order to execute a permission." so it reads "A Policy defines conditions that must be satisfied to execute a permission." This change occurs in the sentence on the policies-plan content and is the only edit needed for tighter wording.
503-521: Refresh checklist state to avoid stale.agentsguidanceThe implementation checklist is still mostly unchecked, which can mislead future contributors about what actually shipped in this PR. Please either update each checkbox to current status or label this section explicitly as a historical plan snapshot.
As per coding guidelines, ".agents/**/*: Keep .agents directory files updated as the project evolves, including architectural changes, new patterns, and important conventions".
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In @.agents/plans/policies-plan.md around lines 503 - 521, The checklist in the policies-plan is stale; update the checked/unchecked boxes or mark the section as a historical snapshot so it no longer misleads contributors. Edit the checklist block to reflect the current implementation status (toggle the relevant boxes for SystemPolicyName constants, ProvisionerModule.start(), IPolicyRepository-based synchronizer, PermissionDatabaseRepository.findOne() behavior, PERMISSIONS_DEFAULT_POLICY_ASSIGNMENT config, etc.) or prepend a clear label like “Historical plan snapshot — do not treat as current” so items such as SystemPolicyName.DEFAULT, ProvisionerModule.start(), IPolicyRepository, PermissionDatabaseRepository.findOne(), and PERMISSIONS_DEFAULT_POLICY_ASSIGNMENT are not shown as pending work when they’re complete.
🤖 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/plans/policies-release-n.md:
- Around line 96-113: Update the header count in
.agents/plans/policies-release-n.md: change the line "Policy provisioning tests
in `test/unit/modules/policy-provisioning.spec.ts` (11 tests):" to reflect the
actual number of scenarios listed (13 tests), ensuring the header number matches
the table entries.
- Around line 65-68: Clarify the first-startup and backfill behavior: state that
defaultPolicyId (resolved at startup when permissionsDefaultPolicyAssignment is
enabled) may be undefined on first run, that
GraphProvisioningSynchronizer.synchronize(data) creates
policies/permissions/roles/scopes/realms and so permissions created during that
sync may initially lack the default policy, and that the backfill step (the
UPDATE permissions SET policy_id = :defaultId WHERE policy_id IS NULL)
re-queries/resolves the system.default policy from the DB independently before
applying it to avoid race conditions; explicitly mention these three points so
readers understand the difference between the startup resolution of
defaultPolicyId and the backfill’s independent re-resolution.
In @.agents/plans/policies-release-n1.md:
- Around line 22-27: The checklist references stale module paths; update each
entry to point to the current files that contain the referenced symbols
(PERMISSIONS_DEFAULT_POLICY_ASSIGNMENT enum, permissionsDefaultPolicyAssignment
in the Config type and zod schema, the default in normalize, and the
readBool(ConfigEnvironmentVariableName.PERMISSIONS_DEFAULT_POLICY_ASSIGNMENT)
block) by locating those symbols in the repo and replacing the old paths with
the exact current module paths so the checklist directly maps to real files;
ensure the `.agents/*` checklist lines reflect the new structure and run a quick
search for the three unique identifiers (PERMISSIONS_DEFAULT_POLICY_ASSIGNMENT,
permissionsDefaultPolicyAssignment,
readBool(ConfigEnvironmentVariableName.PERMISSIONS_DEFAULT_POLICY_ASSIGNMENT))
to verify and update all occurrences.
---
Nitpick comments:
In @.agents/plans/policies-plan.md:
- Line 38: Replace the phrase "in order to" with the more concise "to" in the
sentence "A Policy defines conditions that must be satisfied in order to execute
a permission." so it reads "A Policy defines conditions that must be satisfied
to execute a permission." This change occurs in the sentence on the
policies-plan content and is the only edit needed for tighter wording.
- Around line 503-521: The checklist in the policies-plan is stale; update the
checked/unchecked boxes or mark the section as a historical snapshot so it no
longer misleads contributors. Edit the checklist block to reflect the current
implementation status (toggle the relevant boxes for SystemPolicyName constants,
ProvisionerModule.start(), IPolicyRepository-based synchronizer,
PermissionDatabaseRepository.findOne() behavior,
PERMISSIONS_DEFAULT_POLICY_ASSIGNMENT config, etc.) or prepend a clear label
like “Historical plan snapshot — do not treat as current” so items such as
SystemPolicyName.DEFAULT, ProvisionerModule.start(), IPolicyRepository,
PermissionDatabaseRepository.findOne(), and
PERMISSIONS_DEFAULT_POLICY_ASSIGNMENT are not shown as pending work when they’re
complete.
In @.claude/skills/investigate-pr-comments/SKILL.md:
- Line 11: Change the phrasing in the instruction line that reads "Fetch all
review comments on the current PR, investigate each one against the actual code,
and fix real issues." to use a slightly more formal word—replace "fix real
issues" with "resolve real issues" (or "address real issues") so the sentence
reads "...investigate each one against the actual code, and resolve real
issues."; update the literal string in SKILL.md accordingly.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 834a596a-49ce-4760-b0a8-60a74e404104
📒 Files selected for processing (6)
.agents/plans/policies-plan.md.agents/plans/policies-release-n.md.agents/plans/policies-release-n1.md.agents/skills/update-docs/SKILL.md.claude/skills/investigate-pr-comments/SKILL.mdapps/server-core/src/adapters/database/extra-attribute-repository/tree/repository.ts
💤 Files with no reviewable changes (1)
- .agents/skills/update-docs/SKILL.md
| 1. **Resolve `defaultPolicyId`** — If `permissionsDefaultPolicyAssignment` is enabled, looks up `system.default` from DB (exists from previous runs; `undefined` on first startup). Logs deprecation warning. | ||
| 2. **Root sync** — Delegates to `GraphProvisioningSynchronizer.synchronize(data)` which processes: policies → permissions → roles → scopes → realms. | ||
| 3. **Backfill** — If config enabled: `UPDATE permissions SET policy_id = :defaultId WHERE policy_id IS NULL` (covers first-startup and pre-existing permissions). | ||
|
|
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Verify how defaultPolicyId is resolved and used in provisioning startup flow.
set -euo pipefail
# Locate the provisioning module and print relevant sections with context.
fd 'module\.ts$' apps/server-core/src/app/modules/provisioning | while read -r f; do
echo "===== $f ====="
rg -n -C4 'defaultPolicyId|permissionsDefaultPolicyAssignment|synchronize\(|policy_id IS NULL|UPDATE permissions' "$f" || true
done
# Check permission controller wiring for defaultPolicyId lifecycle.
fd 'module\.ts$' apps/server-core/src/adapters/http/controllers/entities/permission | while read -r f; do
echo "===== $f ====="
rg -n -C4 'defaultPolicyId|policy_id|typeof data\.policy_id' "$f" || true
doneRepository: authup/authup
Length of output: 3860
🏁 Script executed:
# Check PermissionProvisioningSynchronizer to see how defaultPolicyId is used during sync
fd 'synchronizer' apps/server-core/src/app/modules/provisioning/synchronizers | grep -i permission | head -5Repository: authup/authup
Length of output: 203
🏁 Script executed:
# Also get more context from the .agents document around those lines
cat -n .agents/plans/policies-release-n.md | sed -n '50,80p'Repository: authup/authup
Length of output: 2307
🏁 Script executed:
# Find and examine PermissionProvisioningSynchronizer implementation
fd 'permission' apps/server-core/src/app/modules/provisioning/synchronizers --type f | head -10Repository: authup/authup
Length of output: 203
🏁 Script executed:
# If not found, search more broadly
fd -e ts -e js apps/server-core/src/app/modules/provisioning | grep -i synchronizer | grep -i permissionRepository: authup/authup
Length of output: 542
🏁 Script executed:
# Find PermissionProvisioningSynchronizer
fd --full-path 'provisioning.*synchronizer.*permission' -e tsRepository: authup/authup
Length of output: 273
🏁 Script executed:
# Alternative: list the provisioning directory structure
find apps/server-core/src/app/modules/provisioning -name '*permission*' -o -name '*synchronizer*' | head -20Repository: authup/authup
Length of output: 39
🏁 Script executed:
# Examine the PermissionProvisioningSynchronizer module implementation
cat -n apps/server-core/src/core/provisioning/synchronizer/permission/module.ts | head -150Repository: authup/authup
Length of output: 3414
Clarify first-startup behavior and backfill re-resolution in lines 65–68.
Lines 65–68 describe the sequence but don't clarify that defaultPolicyId is undefined on first startup during sync, and that backfill re-resolves the policy independently from the database before applying it. The current wording could mislead readers into thinking the initial resolution covers first-startup permissions, when in fact the backfill's independent re-resolution is what ensures coverage. Update to explicitly state: (1) defaultPolicyId is resolved once at startup (undefined on first run), (2) permissions created during sync may lack the default policy until backfill runs, and (3) backfill re-queries the policy from DB to ensure no race conditions. This aligns better with Section 5's clearer explanation.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In @.agents/plans/policies-release-n.md around lines 65 - 68, Clarify the
first-startup and backfill behavior: state that defaultPolicyId (resolved at
startup when permissionsDefaultPolicyAssignment is enabled) may be undefined on
first run, that GraphProvisioningSynchronizer.synchronize(data) creates
policies/permissions/roles/scopes/realms and so permissions created during that
sync may initially lack the default policy, and that the backfill step (the
UPDATE permissions SET policy_id = :defaultId WHERE policy_id IS NULL)
re-queries/resolves the system.default policy from the DB independently before
applying it to avoid race conditions; explicitly mention these three points so
readers understand the difference between the startup resolution of
defaultPolicyId and the backfill’s independent re-resolution.
| Policy provisioning tests in `test/unit/modules/policy-provisioning.spec.ts` (11 tests): | ||
|
|
||
| | Area | What to test | Status | | ||
| |------|-------------|--------| | ||
| | Policy sync | Creates all leaf policies with correct type, `built_in: true`, `realm_id: null` | ✅ | | ||
| | Policy sync | Creates `system.default` composite with correct children, `decisionStrategy: UNANIMOUS` | ✅ | | ||
| | Policy sync | Idempotent — running twice produces same result, no duplicates | ✅ | | ||
| | Policy sync | `system.realm-match` EA attributes correctly set | ✅ | | ||
| | Policy sync | Stale child without permission references is deleted | ✅ | | ||
| | Policy sync | Stale child with permission references is detached (`parent_id = null`, `built_in = false`) | ✅ | | ||
| | Backfill | Assigns `system.default` to permissions with `policy_id IS NULL` (config-gated) | ✅ | | ||
| | Backfill | Does not touch permissions that already have a `policy_id` | ✅ | | ||
| | Built-in guards | Update/delete of built-in policy returns 400 | ✅ (in `policy/module.spec.ts`) | | ||
| | Built-in guards | Update/delete of non-built-in policy works | ✅ (in `policy/module.spec.ts`) | | ||
| | Config | `defaultPolicyId` set → assigns `system.default` to new permissions | ✅ | | ||
| | Config | `defaultPolicyId` not set → leaves `policy_id = null` | ✅ | | ||
| | Config | Explicit `policy_id: null` not overridden by `defaultPolicyId` | ✅ | | ||
|
|
There was a problem hiding this comment.
Fix the test count in the section header.
Line 96 says 11 tests, but the table lists 13 scenarios. Please align the header count with the listed cases.
As per coding guidelines, “.agents/**/*: Keep .agents directory files updated as the project evolves, including architectural changes, new patterns, and important conventions”.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In @.agents/plans/policies-release-n.md around lines 96 - 113, Update the header
count in .agents/plans/policies-release-n.md: change the line "Policy
provisioning tests in `test/unit/modules/policy-provisioning.spec.ts` (11
tests):" to reflect the actual number of scenarios listed (13 tests), ensuring
the header number matches the table entries.
| | `app/modules/config/constants.ts` | `PERMISSIONS_DEFAULT_POLICY_ASSIGNMENT` from `ConfigEnvironmentVariableName` enum | | ||
| | `app/modules/config/types.ts` | `permissionsDefaultPolicyAssignment` from `Config` type | | ||
| | `app/modules/config/parse.ts` | `permissionsDefaultPolicyAssignment` from zod schema | | ||
| | `app/modules/config/normalize.ts` | `permissionsDefaultPolicyAssignment` default value | | ||
| | `app/modules/config/read/env.ts` | `readBool(ConfigEnvironmentVariableName.PERMISSIONS_DEFAULT_POLICY_ASSIGNMENT)` block | | ||
|
|
There was a problem hiding this comment.
Update checklist paths to current repo locations.
Several referenced paths look stale/partial (e.g., app/modules/..., adapters/http/..., core/provisioning/...) and don’t match the current structure shown elsewhere (apps/server-core/src/..., packages/access/src/...). Please normalize these to exact current paths so the N+1 checklist is directly executable.
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: 30-36
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In @.agents/plans/policies-release-n1.md around lines 22 - 27, The checklist
references stale module paths; update each entry to point to the current files
that contain the referenced symbols (PERMISSIONS_DEFAULT_POLICY_ASSIGNMENT enum,
permissionsDefaultPolicyAssignment in the Config type and zod schema, the
default in normalize, and the
readBool(ConfigEnvironmentVariableName.PERMISSIONS_DEFAULT_POLICY_ASSIGNMENT)
block) by locating those symbols in the repo and replacing the old paths with
the exact current module paths so the checklist directly maps to real files;
ensure the `.agents/*` checklist lines reflect the new structure and run a quick
search for the three unique identifiers (PERMISSIONS_DEFAULT_POLICY_ASSIGNMENT,
permissionsDefaultPolicyAssignment,
readBool(ConfigEnvironmentVariableName.PERMISSIONS_DEFAULT_POLICY_ASSIGNMENT))
to verify and update all occurrences.
Summary by CodeRabbit
New Features
Behavior Changes
Documentation