Skip to content

test: add core entity service tests - #2912

Merged
tada5hi merged 10 commits into
masterfrom
2911-tests
Mar 18, 2026
Merged

tada5hi merged 10 commits into
masterfrom
2911-tests

Conversation

@tada5hi

@tada5hi tada5hi commented Mar 16, 2026 •

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • Bug Fixes

    • Password recovery now rolls back reset tokens if email delivery fails.
    • Name-lock behavior corrected to preserve/restore profile names as intended.
  • New Features

    • Broader permission checks and refined ownership rules for robots and users.
    • Improved per-record permission handling and self-access flows across services.
  • Documentation

    • Added testing guidance, test layers, Docker test service notes, coverage reporting, and an auto-generated dependency graph; README badges updated.
  • Tests

    • Extensive new unit test suites and reusable test helpers for core services and identity flows.

@coderabbitai

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

Adds many unit tests and test helpers for server-core, tweaks permission/ownership logic in User/Robot services, adds rollback on password-recovery email failure, introduces an autogenerated dependency graph and a skill to regenerate it, updates README badges, and allows importing TypeScript extensions in apps/server-core tsconfig.

Changes

Cohort / File(s) Summary
Documentation & Graph
README.md, .agents/testing.md, .claude/skills/update-dependency-graph/SKILL.md, DEPENDENCY_GRAPH.md
Added test-layer docs and Docker/coverage guidance, two README badges, a skill to regenerate the dependency graph, and an auto-generated Mermaid dependency graph.
TS Config
apps/server-core/tsconfig.json
Enabled allowImportingTsExtensions in compilerOptions.
Service logic
apps/server-core/src/core/entities/robot/service.ts, apps/server-core/src/core/entities/user/service.ts
Switched some permission checks to one-of checks; added ownership-aware gating for robot deletion; adjusted name-lock restore condition in user save logic.
Password recovery
apps/server-core/src/core/identity/password-recovery/service.ts
Wrapped reset-email send in try/catch; on failure roll back reset_hash/reset_expires, persist, and surface a BadRequestError.
Test helpers
apps/server-core/test/unit/core/helpers/*
apps/server-core/test/unit/core/helpers/fake-repository.ts, .../fake-realm-repository.ts, .../mock-actor.ts, .../index.ts
Added in-memory FakeEntityRepository, FakeRealmRepository (with master fallback and resolve overloads), mock actor factories (allow/deny/master/non-master), and a helpers barrel.
Test domains & utils
apps/server-core/test/utils/domains/*
apps/server-core/test/utils/domains/role-attribute.ts, .../index.ts
Added createFakeRoleAttribute helper and re-exported it from domains index.
Unit tests — entities
apps/server-core/test/unit/core/entities/*
apps/server-core/test/unit/core/entities/*.service.spec.ts
Added comprehensive unit tests across many entity services (clients, roles, robots, permissions, realms, scopes, users, attributes, relations) covering CRUD, permission checks, realm defaulting, error cases, secrets, and ownership logic.
Unit tests — identity
apps/server-core/test/unit/core/identity/*
.../password-recovery/service.spec.ts, .../registration/service.spec.ts
Added tests for password recovery and registration, including feature-flag validation, mail-send rollback behavior, token flows, activation, and related validations.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant PasswordRecoveryService as Service
  participant UserRepository as Repository
  participant MailClient as Mail

  Client->>Service: forgotPassword(request)
  Service->>UserRepository: find user by email/name
  UserRepository-->>Service: user entity
  Service->>Service: generate reset_hash & reset_expires
  Service->>UserRepository: save(updated user)
  Service->>Mail: sendResetEmail(user, reset_link)
  alt Mail send succeeds
    Mail-->>Service: emailSent
    Service-->>Client: success
  else Mail send fails
    Mail-->>Service: error
    Service->>UserRepository: clear reset_hash/reset_expires and save
    Service-->>Client: throw BadRequestError (email send failed)
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~85 minutes

Possibly related PRs

Poem

🐇 I stitched small fakes in moonlit code,

Rolled back a token when an email slowed,
Permission gates and tiny seeds,
Tests now guard our branching deeds,
I hop away, nose twitching — well tested code!

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'test: add core entity service tests' clearly and directly describes the main change: adding comprehensive unit tests for core entity services. It follows a conventional format and accurately summarizes the primary purpose of the PR.

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

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 2911-tests
📝 Coding Plan
  • Generate coding plan for human review comments

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

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (9)
apps/server-core/src/core/entities/robot/service.ts (1)

260-263: Make isOwner explicitly boolean for clarity.

Line 260 currently relies on truthy chaining; coercing to boolean makes intent and type behavior clearer.

Suggested refactor
-        const isOwner = entity.user_id &&
+        const isOwner = Boolean(entity.user_id &&
             actor.identity &&
             actor.identity.type === 'user' &&
-            actor.identity.data.id === entity.user_id;
+            actor.identity.data.id === entity.user_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/robot/service.ts` around lines 260 - 263,
The isOwner variable currently relies on truthy chaining which yields a
non-explicit boolean; update the isOwner expression in service.ts (the isOwner
assignment) to explicitly coerce to boolean (e.g., use !! or Boolean(...)) so it
always produces a true/false value while preserving the same checks
(entity.user_id, actor.identity, actor.identity.type === 'user',
actor.identity.data.id === entity.user_id).
apps/server-core/test/unit/core/entities/client-permission/service.spec.ts (1)

43-45: Use specific error assertions for deny-path tests.

The current rejects.toThrow() checks are broad; asserting the expected authorization error type/message will make failures more diagnostic.

Also applies to: 89-93

🤖 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 43 - 45, Replace broad rejects.toThrow() assertions in the
deny-path tests with specific checks for the expected authorization error: call
service.getMany({}, createDenyAllActor()) and assert that the rejection is an
instance of the app's authorization error class (or has the exact error
name/message) instead of a generic toThrow; update both the test at
service.getMany with createDenyAllActor() and the similar deny-path test at
lines 89-93 to assert the concrete error type/message (use the project's
AuthorizationError/ForbiddenError symbol or exact error string) so failures are
diagnostic.
apps/server-core/test/unit/core/entities/robot-permission/service.spec.ts (1)

61-87: Verify baseline create permission is asserted in tests.

Line 76 onward only checks dynamic permission-name preCheck. If create also requires PermissionName.ROBOT_PERMISSION_CREATE, add an explicit assertion to guard against authorization regressions.

🤖 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`
around lines 61 - 87, The test is missing an assertion that the baseline
permission PermissionName.ROBOT_PERMISSION_CREATE is asserted when calling
service.create; update the second test (the one invoking service.create with
permission { name: 'custom-perm' }) to also expect that
actor.permissionChecker.preCheck was called with the baseline permission
(PermissionName.ROBOT_PERMISSION_CREATE) in addition to the dynamic permission
check, referencing the service.create call and actor.permissionChecker.preCheck
to locate where to add the assertion.
apps/server-core/test/unit/core/entities/user-role/service.spec.ts (1)

92-103: Add delete authorization assertions for parity and regression safety.

Line 92 onward validates delete success/not-found, but does not verify permission enforcement (preCheck) or deny-actor rejection on delete.

Suggested test additions
 describe('delete', () => {
   it('should delete an existing entity', async () => {
@@
   it('should throw NotFoundError when entity does not exist', async () => {
     await expect(service.delete(randomUUID(), createAllowAllActor())).rejects.toThrow(NotFoundError);
   });
+
+  it('should call preCheck with USER_ROLE_DELETE', async () => {
+    const id = randomUUID();
+    repository.seed([{ id } as UserRole]);
+    const actor = createAllowAllActor();
+    await service.delete(id, actor);
+    expect(actor.permissionChecker.preCheck).toHaveBeenCalledWith({
+      name: PermissionName.USER_ROLE_DELETE,
+    });
+  });
+
+  it('should throw when actor lacks permission', async () => {
+    await expect(service.delete(randomUUID(), createDenyAllActor())).rejects.toThrow();
+  });
 });
🤖 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/user-role/service.spec.ts` around
lines 92 - 103, Add tests to cover delete authorization: after seeding and
calling service.delete(id, createAllowAllActor()) assert that the authorization
pre-check was invoked (mock/spied) for the delete flow (reference service.delete
and the auth preCheck hook used by the service) and add a test that calling
service.delete with a denying actor (e.g., createDenyAllActor or a mocked actor
that returns deny) rejects with the appropriate authorization error; ensure the
new specs mirror the existing success and NotFoundError cases but assert
permission enforcement and deny-actor rejection for parity and regression
safety.
apps/server-core/test/unit/core/entities/robot-role/service.spec.ts (1)

92-103: Add delete permission-path assertions.

Line 92 onward validates behavior for existing/missing entities, but not authorization behavior for delete (preCheck invocation and deny-actor rejection).

Suggested test additions
 describe('delete', () => {
@@
   it('should throw NotFoundError when entity does not exist', async () => {
     await expect(service.delete(randomUUID(), createAllowAllActor())).rejects.toThrow(NotFoundError);
   });
+
+  it('should call preCheck with ROBOT_ROLE_DELETE', async () => {
+    const id = randomUUID();
+    repository.seed([{ id } as RobotRole]);
+    const actor = createAllowAllActor();
+    await service.delete(id, actor);
+    expect(actor.permissionChecker.preCheck).toHaveBeenCalledWith({
+      name: PermissionName.ROBOT_ROLE_DELETE,
+    });
+  });
+
+  it('should throw when actor lacks permission', async () => {
+    await expect(service.delete(randomUUID(), createDenyAllActor())).rejects.toThrow();
+  });
 });
🤖 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-role/service.spec.ts` around
lines 92 - 103, Add tests to assert authorization is invoked for delete: in the
'delete' describe block add one test that calls service.delete with
createDenyAllActor() and expects a rejection (AuthorizationError or the
project's deny error), and another test that spies/mocks the authorization
pre-check (e.g., preCheck or the policy check used by service.delete) to verify
it was called when deleting an existing seeded entity (use repository.seed([{ id
} as RobotRole]) and then call service.delete(id, createAllowAllActor()) and
expect the preCheck spy toHaveBeenCalled). Reference service.delete,
repository.seed, createAllowAllActor/createDenyAllActor, and the preCheck/policy
method name to locate where to add the assertions.
apps/server-core/test/unit/core/entities/role-permission/service.spec.ts (1)

127-149: Add a deny-actor test for delete authorization.

The delete suite verifies preCheck invocation but does not assert that deletion is rejected when the actor lacks permission.

Suggested test addition
 describe('delete', () => {
@@
   it('should call preCheck with ROLE_PERMISSION_DELETE', async () => {
@@
   });
+
+  it('should throw when actor lacks permission', async () => {
+    await expect(service.delete(randomUUID(), createDenyAllActor())).rejects.toThrow();
+  });
 });
🤖 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/role-permission/service.spec.ts`
around lines 127 - 149, Add a test to the delete suite that verifies deletion is
rejected for an actor without permission: seed the repository with a
RolePermission id using repository.seed([{ id } as RolePermission]), create a
denying actor via createDenyAllActor() (or construct an actor whose
permissionChecker denies), call service.delete(id, denyActor) and assert it
rejects (e.g., await expect(...).rejects.toThrow()), and also assert that the
actor.permissionChecker.preCheck was called with { name:
PermissionName.ROLE_PERMISSION_DELETE } to ensure the authorization check ran.
apps/server-core/test/unit/core/entities/client-role/service.spec.ts (1)

92-103: Complete delete authorization coverage.

Line 92 onward does not verify delete permission enforcement (preCheck) and lacks a deny-actor delete test, so delete auth regressions may slip through.

Suggested test additions
 describe('delete', () => {
@@
   it('should throw NotFoundError when entity does not exist', async () => {
     await expect(service.delete(randomUUID(), createAllowAllActor())).rejects.toThrow(NotFoundError);
   });
+
+  it('should call preCheck with CLIENT_ROLE_DELETE', async () => {
+    const id = randomUUID();
+    repository.seed([{ id } as ClientRole]);
+    const actor = createAllowAllActor();
+    await service.delete(id, actor);
+    expect(actor.permissionChecker.preCheck).toHaveBeenCalledWith({
+      name: PermissionName.CLIENT_ROLE_DELETE,
+    });
+  });
+
+  it('should throw when actor lacks permission', async () => {
+    await expect(service.delete(randomUUID(), createDenyAllActor())).rejects.toThrow();
+  });
 });
🤖 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-role/service.spec.ts` around
lines 92 - 103, Add coverage for delete authorization by adding tests that
assert permission enforcement: 1) seed an entity, spy/stub the auth pre-check
used by the client-role service (the preCheck/policy method invoked by
service.delete) to ensure it is called when service.delete(id,
createAllowAllActor()) succeeds; 2) add a deny-actor test that seeds an entity
and calls service.delete(id, createDenyActor()) and expects the call to reject
with the authorization error thrown by your auth layer (e.g.,
AuthorizationError/ForbiddenError); reference service.delete, repository.seed,
createAllowAllActor and the deny-actor factory (createDenyActor or equivalent)
when adding these tests.
apps/server-core/test/unit/core/helpers/fake-realm-repository.ts (1)

41-43: Return a copy of masterRealm to avoid accidental external mutation.

Both fallback resolution and getMasterRealm() currently expose the internal reference. Returning a shallow copy makes this helper safer and less state-coupled in tests.

Suggested hardening
     async resolve(id: string | undefined, withFallback?: boolean): Promise<Realm | null> {
         if (id) {
             const entity = await this.findOneByIdOrName(id);
             if (entity) return entity;
         }

         if (withFallback) {
-            return this.masterRealm;
+            return { ...this.masterRealm };
         }

         return null;
     }

     getMasterRealm(): Realm {
-        return this.masterRealm;
+        return { ...this.masterRealm };
     }

Also applies to: 48-50

🤖 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/fake-realm-repository.ts` around
lines 41 - 43, The helper currently returns the internal masterRealm object by
reference (see the branch in the method returning "this.masterRealm" and the
getMasterRealm() accessor), which allows external tests to mutate internal
state; change both return sites to return a shallow copy of masterRealm (e.g.,
via object spread or structured clone) so callers receive a copy rather than the
original internal object.
apps/server-core/test/unit/core/helpers/fake-repository.ts (1)

57-59: create() always overwrites provided id with a new UUID.

The current implementation always assigns a new id via { id: randomUUID(), ...data }, which means any id provided in data will be overwritten. This may be intentional for test isolation, but could cause unexpected behavior if tests need to create entities with specific IDs.

Consider preserving an existing id if provided:

♻️ Proposed fix to preserve provided id
 create(data: Partial<T>): T {
-    return { id: randomUUID(), ...data } as T;
+    return { id: data.id ?? randomUUID(), ...data } as T;
 }
🤖 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/fake-repository.ts` around lines 57 -
59, The create method in FakeRepository (create) currently always overwrites any
provided id by constructing { id: randomUUID(), ...data }; change it to preserve
a caller-supplied id by only generating randomUUID() when data.id is undefined
(e.g., compute const id = (data as any).id ?? randomUUID() and return { id,
...data } as T or spread data then default id when missing). Update the create
function to use the existing id if present and fallback to randomUUID()
otherwise, keeping the rest of the payload intact.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In @.claude/skills/update-dependency-graph/SKILL.md:
- Around line 23-27: Remove the broken require('glob') line and the
platform-specific ls fallback in the scan function: delete the `const glob =
require('glob') || {};` statement and replace the
`require('child_process').execSync('ls ' + pattern)` usage inside `scan` with a
cross-platform `fs.readdirSync` + filtering approach (use
`fs.statSync`/`fs.lstatSync` or name filtering to match the pattern) when
`fs.globSync` is not present; update the `scan` implementation to rely on
`fs.globSync` when available or use `fs.readdirSync`-based directory listing to
produce the same `files` array.

In `@apps/server-core/test/unit/core/entities/permission/service.spec.ts`:
- Around line 164-171: The test assertion is expecting undefined but the
Permission.policy_id is typed as Policy['id'] | null and the ORM stores unset
values as null; update the spec so the assertion uses toBeNull() instead of
toBeUndefined() — specifically change the expectation in the 'should not assign
default policy_id when none configured' test that checks result.policy_id (from
service.create(...)) to expect null.

In `@apps/server-core/test/unit/core/entities/role-attribute/service.spec.ts`:
- Around line 46-53: The mock for actor.permissionChecker.checkOneOf is brittle
because it throws on the second call (callCount); change it to examine the
actual permission target argument and throw only when the target matches the
record you intend to filter (e.g., inspect the passed entity/record id or
permission scope inside the mockImplementation callback), so update
vi.mocked(actor.permissionChecker.checkOneOf).mockImplementation to accept the
actual args and throw new ForbiddenError() when the predicate (arg.id ===
targetId or similar) is true, otherwise return normally; this keeps the test
stable regardless of record iteration order.

In `@apps/server-core/test/unit/core/identity/registration/service.spec.ts`:
- Around line 194-205: The test uses a broad rejects.toThrow() for
RegistrationService.register which can mask unrelated failures; update the
assertion to explicitly expect a BadRequestError (e.g., use
expect(...).rejects.toBeInstanceOf(BadRequestError) or
rejects.toThrow(BadRequestError)) and add the necessary import for
BadRequestError at the top of the spec; target the test that calls
service.register(...) and replace the generic rejection assertion with the
explicit BadRequestError check to lock the validation contract.

---

Nitpick comments:
In `@apps/server-core/src/core/entities/robot/service.ts`:
- Around line 260-263: The isOwner variable currently relies on truthy chaining
which yields a non-explicit boolean; update the isOwner expression in service.ts
(the isOwner assignment) to explicitly coerce to boolean (e.g., use !! or
Boolean(...)) so it always produces a true/false value while preserving the same
checks (entity.user_id, actor.identity, actor.identity.type === 'user',
actor.identity.data.id === entity.user_id).

In `@apps/server-core/test/unit/core/entities/client-permission/service.spec.ts`:
- Around line 43-45: Replace broad rejects.toThrow() assertions in the deny-path
tests with specific checks for the expected authorization error: call
service.getMany({}, createDenyAllActor()) and assert that the rejection is an
instance of the app's authorization error class (or has the exact error
name/message) instead of a generic toThrow; update both the test at
service.getMany with createDenyAllActor() and the similar deny-path test at
lines 89-93 to assert the concrete error type/message (use the project's
AuthorizationError/ForbiddenError symbol or exact error string) so failures are
diagnostic.

In `@apps/server-core/test/unit/core/entities/client-role/service.spec.ts`:
- Around line 92-103: Add coverage for delete authorization by adding tests that
assert permission enforcement: 1) seed an entity, spy/stub the auth pre-check
used by the client-role service (the preCheck/policy method invoked by
service.delete) to ensure it is called when service.delete(id,
createAllowAllActor()) succeeds; 2) add a deny-actor test that seeds an entity
and calls service.delete(id, createDenyActor()) and expects the call to reject
with the authorization error thrown by your auth layer (e.g.,
AuthorizationError/ForbiddenError); reference service.delete, repository.seed,
createAllowAllActor and the deny-actor factory (createDenyActor or equivalent)
when adding these tests.

In `@apps/server-core/test/unit/core/entities/robot-permission/service.spec.ts`:
- Around line 61-87: The test is missing an assertion that the baseline
permission PermissionName.ROBOT_PERMISSION_CREATE is asserted when calling
service.create; update the second test (the one invoking service.create with
permission { name: 'custom-perm' }) to also expect that
actor.permissionChecker.preCheck was called with the baseline permission
(PermissionName.ROBOT_PERMISSION_CREATE) in addition to the dynamic permission
check, referencing the service.create call and actor.permissionChecker.preCheck
to locate where to add the assertion.

In `@apps/server-core/test/unit/core/entities/robot-role/service.spec.ts`:
- Around line 92-103: Add tests to assert authorization is invoked for delete:
in the 'delete' describe block add one test that calls service.delete with
createDenyAllActor() and expects a rejection (AuthorizationError or the
project's deny error), and another test that spies/mocks the authorization
pre-check (e.g., preCheck or the policy check used by service.delete) to verify
it was called when deleting an existing seeded entity (use repository.seed([{ id
} as RobotRole]) and then call service.delete(id, createAllowAllActor()) and
expect the preCheck spy toHaveBeenCalled). Reference service.delete,
repository.seed, createAllowAllActor/createDenyAllActor, and the preCheck/policy
method name to locate where to add the assertions.

In `@apps/server-core/test/unit/core/entities/role-permission/service.spec.ts`:
- Around line 127-149: Add a test to the delete suite that verifies deletion is
rejected for an actor without permission: seed the repository with a
RolePermission id using repository.seed([{ id } as RolePermission]), create a
denying actor via createDenyAllActor() (or construct an actor whose
permissionChecker denies), call service.delete(id, denyActor) and assert it
rejects (e.g., await expect(...).rejects.toThrow()), and also assert that the
actor.permissionChecker.preCheck was called with { name:
PermissionName.ROLE_PERMISSION_DELETE } to ensure the authorization check ran.

In `@apps/server-core/test/unit/core/entities/user-role/service.spec.ts`:
- Around line 92-103: Add tests to cover delete authorization: after seeding and
calling service.delete(id, createAllowAllActor()) assert that the authorization
pre-check was invoked (mock/spied) for the delete flow (reference service.delete
and the auth preCheck hook used by the service) and add a test that calling
service.delete with a denying actor (e.g., createDenyAllActor or a mocked actor
that returns deny) rejects with the appropriate authorization error; ensure the
new specs mirror the existing success and NotFoundError cases but assert
permission enforcement and deny-actor rejection for parity and regression
safety.

In `@apps/server-core/test/unit/core/helpers/fake-realm-repository.ts`:
- Around line 41-43: The helper currently returns the internal masterRealm
object by reference (see the branch in the method returning "this.masterRealm"
and the getMasterRealm() accessor), which allows external tests to mutate
internal state; change both return sites to return a shallow copy of masterRealm
(e.g., via object spread or structured clone) so callers receive a copy rather
than the original internal object.

In `@apps/server-core/test/unit/core/helpers/fake-repository.ts`:
- Around line 57-59: The create method in FakeRepository (create) currently
always overwrites any provided id by constructing { id: randomUUID(), ...data };
change it to preserve a caller-supplied id by only generating randomUUID() when
data.id is undefined (e.g., compute const id = (data as any).id ?? randomUUID()
and return { id, ...data } as T or spread data then default id when missing).
Update the create function to use the existing id if present and fallback to
randomUUID() otherwise, keeping the rest of the payload intact.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: e61b1234-c71e-4ebd-8f41-f215a36d1773

📥 Commits

Reviewing files that changed from the base of the PR and between 7d13390 and b921c50.

📒 Files selected for processing (31)
  • .agents/testing.md
  • .claude/skills/update-dependency-graph/SKILL.md
  • DEPENDENCY_GRAPH.md
  • README.md
  • apps/server-core/src/core/entities/robot/service.ts
  • apps/server-core/src/core/entities/user/service.ts
  • apps/server-core/src/core/identity/password-recovery/service.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/fake-realm-repository.ts
  • apps/server-core/test/unit/core/helpers/fake-repository.ts
  • apps/server-core/test/unit/core/helpers/index.ts
  • apps/server-core/test/unit/core/helpers/mock-actor.ts
  • apps/server-core/test/unit/core/identity/password-recovery/service.spec.ts
  • apps/server-core/test/unit/core/identity/registration/service.spec.ts
  • apps/server-core/tsconfig.json

Comment on lines +23 to +27
const glob = require('glob') || {};

function scan(pattern) {
const files = fs.globSync ? fs.globSync(pattern) : require('child_process').execSync('ls ' + pattern).toString().trim().split('\n');
const result = {};

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
set -euo pipefail

echo "== Is 'glob' declared in repository manifests? =="
rg -n '"glob"\s*:' -g 'package.json' || true

echo
echo "== Does current Node runtime expose fs.globSync? =="
node - <<'NODE'
const fs = require('fs');
console.log('fs.globSync available:', typeof fs.globSync === 'function');
NODE

Repository: authup/authup

Length of output: 187


🏁 Script executed:

fd -t f "SKILL.md" ".claude/skills/update-dependency-graph/"

Repository: authup/authup

Length of output: 104


🏁 Script executed:

cat -n ".claude/skills/update-dependency-graph/SKILL.md" | sed -n '20,35p'

Repository: authup/authup

Length of output: 847


Remove the broken glob require; it's not a declared dependency and blocks script execution.

Line 23 (const glob = require('glob') || {};) will throw MODULE_NOT_FOUND before the script runs—the || {} operator cannot catch require() errors, and glob is not in any project manifest. Since fs.globSync is available in all supported Node versions (^20.19.0+), the require is redundant and should be removed entirely.

The fallback to ls (line 26) is also platform-specific and fragile; use fs.readdirSync with directory filtering instead.

Proposed fix
-const glob = require('glob') || {};
-
 function scan(pattern) {
-  const files = fs.globSync ? fs.globSync(pattern) : require('child_process').execSync('ls ' + pattern).toString().trim().split('\n');
+  const files = fs.readdirSync(pattern, { withFileTypes: true })
+    .filter((d) => d.isDirectory())
+    .map((d) => path.join(pattern, d.name, 'package.json'))
+    .filter((p) => fs.existsSync(p));
   const result = {};
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In @.claude/skills/update-dependency-graph/SKILL.md around lines 23 - 27, Remove
the broken require('glob') line and the platform-specific ls fallback in the
scan function: delete the `const glob = require('glob') || {};` statement and
replace the `require('child_process').execSync('ls ' + pattern)` usage inside
`scan` with a cross-platform `fs.readdirSync` + filtering approach (use
`fs.statSync`/`fs.lstatSync` or name filtering to match the pattern) when
`fs.globSync` is not present; update the `scan` implementation to rely on
`fs.globSync` when available or use `fs.readdirSync`-based directory listing to
produce the same `files` array.

Comment on lines +164 to +171
it('should not assign default policy_id when none configured', async () => {
const result = await service.create(
{ name: 'no-policy-perm' },
createAllowAllActor(),
);

expect(result.policy_id).toBeUndefined();
});

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
# Check how the PermissionService handles policy_id when not configured
ast-grep --pattern $'class PermissionService {
  $$$
  create($$$) {
    $$$
  }
  $$$
}'

Repository: authup/authup

Length of output: 39


🏁 Script executed:

fd -t f "service\.(ts|js)" apps/server-core/src --path "*permission*" | head -20

Repository: authup/authup

Length of output: 290


🏁 Script executed:

fd "service.ts" apps/server-core/src | grep -i permission

Repository: authup/authup

Length of output: 364


🏁 Script executed:

cat -n apps/server-core/src/core/entities/permission/service.ts | head -250

Repository: authup/authup

Length of output: 9452


🏁 Script executed:

fd -t f "types.ts" apps/server-core/src/core/entities/permission | head -5

Repository: authup/authup

Length of output: 111


🏁 Script executed:

cat -n apps/server-core/src/core/entities/permission/types.ts

Repository: authup/authup

Length of output: 1591


🏁 Script executed:

rg "export.*type Permission" --type ts -A 10 | head -30

Repository: authup/authup

Length of output: 2102


🏁 Script executed:

rg "interface Permission|type Permission" packages/core-kit -A 15 | head -50

Repository: authup/authup

Length of output: 2137


The assertion should be toBeNull() instead of toBeUndefined().

The Permission interface defines policy_id as Policy['id'] | null, not undefined. When the service does not assign a policy_id, the ORM converts the undefined value to null when creating the entity. Update the assertion to expect(result.policy_id).toBeNull() to match the actual type definition and ORM behavior.

🤖 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 164 - 171, The test assertion is expecting undefined but the
Permission.policy_id is typed as Policy['id'] | null and the ORM stores unset
values as null; update the spec so the assertion uses toBeNull() instead of
toBeUndefined() — specifically change the expectation in the 'should not assign
default policy_id when none configured' test that checks result.policy_id (from
service.create(...)) to expect null.

@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 (9)
apps/server-core/test/unit/core/entities/client/service.spec.ts (2)

114-128: Add the denial-path assertion for plaintext-secret reads in getOne.

Line 127 confirms invocation, but not outcome. Add a case where checkOneOf rejects and assert ForbiddenError, so the sensitive-record guard is fully pinned.

Suggested test addition
+        it('should throw when per-record check fails for plaintext secret entity', async () => {
+            const id = randomUUID();
+            repository.seed([{
+                id,
+                name: 'secret-client',
+                secret: 'plain',
+                secret_encrypted: false,
+                secret_hashed: false,
+            } as Client]);
+
+            const actor = createAllowAllActor();
+            vi.mocked(actor.permissionChecker.checkOneOf).mockRejectedValue(new ForbiddenError());
+
+            await expect(service.getOne(id, actor)).rejects.toThrow(ForbiddenError);
+        });
🤖 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/service.spec.ts` around lines
114 - 128, Add a second spec to assert the denial path for plaintext-secret
reads by making actor.permissionChecker.checkOneOf reject and expecting
service.getOne(id, actor) to throw ForbiddenError; reuse the existing setup
(seed repository with a plaintext secret record via repository.seed and
id/randomUUID) but stub/mock actor.permissionChecker.checkOneOf to return a
rejected promise or throw, then assert that calling getOne results in a
ForbiddenError being thrown to fully verify the sensitive-record guard in
getOne.

184-246: Consider explicit permission-denied tests for update and save.

Authorization is already asserted for getMany/create/delete; adding equivalent denial tests here will close the remaining auth-regression gap.

Suggested test additions
+        it('should throw when actor lacks permission', async () => {
+            const id = randomUUID();
+            repository.seed([{ id, name: 'client' } as Client]);
+            await expect(
+                service.update(id, { name: 'blocked-update' }, createDenyAllActor()),
+            ).rejects.toThrow(ForbiddenError);
+        });
+        it('should throw when actor lacks permission on save', async () => {
+            await expect(
+                service.save(undefined, { name: 'blocked-save' }, createDenyAllActor()),
+            ).rejects.toThrow(ForbiddenError);
+        });
🤖 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/service.spec.ts` around lines
184 - 246, Add explicit permission-denied unit tests for service.update and
service.save: in the 'update' describe block add a test that calls
service.update(id, {...}, createDenyActor()) (or an actor that lacks update
permission) and assert it rejects with the authorization error (e.g.,
ForbiddenError); in the 'save (upsert)' describe block add two tests — one for
create-path (undefined id) and one for update-path (existing id) that call
service.save(..., createDenyActor()) and assert they reject with the same
authorization error; reference the service.update and service.save calls and
reuse the existing actor helpers (createAllowAllActor) pattern to introduce a
deny/unauthorized actor helper used in these new tests.
apps/server-core/test/unit/core/entities/client-permission/service.spec.ts (2)

97-117: Consider asserting delete side-effect, not only return payload.

At Line 100, validating returned id is good; adding a follow-up existence check would better verify repository state mutation.

Optional side-effect assertion
         it('should delete an existing entity', async () => {
             const id = randomUUID();
             repository.seed([{ id } as ClientPermission]);
             const result = await service.delete(id, createAllowAllActor());
             expect(result.id).toBe(id);
+            await expect(service.getOne(id, createAllowAllActor())).rejects.toThrow(NotFoundError);
         });
🤖 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 97 - 117, The test currently only asserts the returned payload from
service.delete; after calling service.delete(id, createAllowAllActor()) also
assert the repository no longer contains the entity to verify the side-effect
(e.g., call repository.find(id) or repository.exists(id) and expect null/false).
Update the test that seeds the repository and calls service.delete to follow up
with an existence check on the same repository instance to ensure the entity was
actually removed.

76-87: Tighten create permission-call assertions to catch ordering regressions.

At Line 84, asserting only toHaveBeenCalledWith({ name: 'custom-perm' }) can miss regressions in the base CLIENT_PERMISSION_CREATE pre-check flow.

Suggested assertion hardening
         it('should preCheck permission name when permission is provided', async () => {
             const actor = createAllowAllActor();
             await service.create({
                 client_id: randomUUID(),
                 permission_id: randomUUID(),
                 permission: { name: 'custom-perm', realm_id: null },
             }, actor);

-            expect(actor.permissionChecker.preCheck).toHaveBeenCalledWith({
-                name: 'custom-perm',
-            });
+            expect(actor.permissionChecker.preCheck).toHaveBeenNthCalledWith(1, {
+                name: PermissionName.CLIENT_PERMISSION_CREATE,
+            });
+            expect(actor.permissionChecker.preCheck).toHaveBeenNthCalledWith(2, {
+                name: 'custom-perm',
+            });
+            expect(actor.permissionChecker.preCheck).toHaveBeenCalledTimes(2);
         });
🤖 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 76 - 87, The test for service.create only checks that
actor.permissionChecker.preCheck was called with the custom permission object,
which can miss ordering regressions in the base CLIENT_PERMISSION_CREATE check;
update the spec to assert the exact call order using
actor.permissionChecker.preCheck calls (e.g.,
expect(preCheck).toHaveBeenNthCalledWith(1, { name: CLIENT_PERMISSION_CREATE })
and expect(preCheck).toHaveBeenNthCalledWith(2, { name: 'custom-perm' }) or
equivalent) so the first preCheck verifies the base CLIENT_PERMISSION_CREATE and
the second verifies the provided permission when invoking service.create.
apps/server-core/test/unit/core/entities/user-permission/service.spec.ts (1)

49-60: Consider adding permission check verification for consistency.

Unlike getMany and delete tests, the getOne tests don't verify that the permission checker is invoked. For consistency with other operations and complete coverage, consider adding a test that verifies the expected permission check.

💡 Suggested test addition
     describe('getOne', () => {
         it('should return entity by id', async () => {
             const id = randomUUID();
             repository.seed([{ id } as UserPermission]);
             const result = await service.getOne(id, createAllowAllActor());
             expect(result.id).toBe(id);
         });

         it('should throw NotFoundError when entity does not exist', async () => {
             await expect(service.getOne(randomUUID(), createAllowAllActor())).rejects.toThrow(NotFoundError);
         });
+
+        it('should call preCheckOneOf with correct permissions', async () => {
+            const id = randomUUID();
+            repository.seed([{ id } as UserPermission]);
+            const actor = createAllowAllActor();
+            await service.getOne(id, actor);
+            expect(actor.permissionChecker.preCheckOneOf).toHaveBeenCalledWith({
+                name: [
+                    PermissionName.USER_PERMISSION_CREATE,
+                    PermissionName.USER_PERMISSION_DELETE,
+                    PermissionName.USER_PERMISSION_READ,
+                ],
+            });
+        });
     });
🤖 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/user-permission/service.spec.ts`
around lines 49 - 60, Add assertions that the permission check is invoked when
calling service.getOne: after calling service.getOne(id, createAllowAllActor())
verify the permission checker mock (the same mock used in getMany/delete tests)
was called with the retrieved entity and the actor; and for the NotFoundError
case assert the permission checker was not erroneously called (or assert it was
called with undefined/appropriate args per existing behavior). Locate the
service.getOne tests, reference repository.seed([{ id } as UserPermission]) and
createAllowAllActor(), and add expectations against the permission checker mock
consistent with other tests' patterns.
apps/server-core/test/unit/core/entities/realm/service.spec.ts (2)

86-90: Consider a more specific error assertion.

The regex /name/i is somewhat fragile as it only checks that the error message contains "name" somewhere. If the validation library changes its error format, this test could pass incorrectly or fail unexpectedly.

Consider asserting against a more specific error type or message pattern if the validation library provides one, or at minimum document that this is intentionally loose to accommodate varying validation error formats.

🤖 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
86 - 90, The test for service.create({ name: 'ab' }, createAllowAllActor())
should assert a more specific validation failure instead of the loose /name/i
regex; update the assertion in the 'should reject invalid name (too short)' spec
to either expect a concrete validation error type (e.g., assert the thrown error
is an instance of your validation error class such as ValidationError) or match
a precise message pattern (e.g., toThrowErrorMatchingInlineSnapshot or
toThrow(/must be at least 3 characters/i) / toThrow(/too short/i)) that targets
the "too short" condition, referencing the service.create call and
createAllowAllActor to locate the test.

103-139: Consider adding permission tests for update operations.

The create and delete test suites verify permission checking (both preCheck invocation and ForbiddenError on denial), but the update suite lacks equivalent permission tests. For consistency and complete coverage, consider adding:

  1. A test verifying preCheck is called with REALM_UPDATE permission
  2. A test verifying ForbiddenError when the actor lacks update permission
📝 Suggested additional tests
it('should call preCheck with REALM_UPDATE permission', async () => {
    const id = randomUUID();
    repository.seed([{
        id, name: 'test-realm', built_in: false,
    } as Realm]);

    const actor = createAllowAllActor();
    await service.update(id, { name: 'updated' }, actor);

    expect(actor.permissionChecker.preCheck).toHaveBeenCalledWith({
        name: PermissionName.REALM_UPDATE,
    });
});

it('should throw when actor lacks update permission', async () => {
    const id = randomUUID();
    repository.seed([{
        id, name: 'test-realm', built_in: false,
    } as Realm]);

    await expect(
        service.update(id, { name: 'updated' }, createDenyAllActor()),
    ).rejects.toThrow(ForbiddenError);
});
🤖 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
103 - 139, Add permission tests for the update suite: ensure service.update
triggers the actor permission check by asserting
actor.permissionChecker.preCheck was called with { name:
PermissionName.REALM_UPDATE } when using createAllowAllActor(), and add a test
that seeding a realm and calling service.update(...) with createDenyAllActor()
rejects with ForbiddenError; reference the service.update method,
PermissionName.REALM_UPDATE, actor.permissionChecker.preCheck,
createAllowAllActor, createDenyAllActor, and ForbiddenError to locate where to
add these two tests.
apps/server-core/test/unit/core/entities/robot/service.spec.ts (2)

130-136: Assert the negative permission path in the checkOneOf test.

Line 130 validates that checkOneOf is called, but it doesn’t assert that check is not called. Adding that makes the regression guard explicit.

Suggested assertion addition
             await service.getOne(id, actor);
             expect(actor.permissionChecker.checkOneOf).toHaveBeenCalled();
+            expect(actor.permissionChecker.check).not.toHaveBeenCalled();
🤖 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` around lines
130 - 136, The test currently asserts that actor.permissionChecker.checkOneOf
was called for per-record permission in service.getOne, but doesn’t assert the
negative path; update the test to also assert that actor.permissionChecker.check
was not called (e.g.,
expect(actor.permissionChecker.check).not.toHaveBeenCalled()) after invoking
service.getOne(id, actor) — locate the assertion near the existing
expect(actor.permissionChecker.checkOneOf) and add the not-to-have-been-called
check to make the regression guard explicit; use the same test setup
(repository.seed, createAllowAllActor, service.getOne) so the new assertion
validates the negative permission call path.

77-109: Align the self-access test assertion with its title.

Line 77 says “without per-record check”, but the test currently only checks returned data. Add an explicit call-count assertion so the behavior is actually enforced.

Suggested test tightening
             const result = await service.getMany({}, actor);
             expect(result.data).toHaveLength(1);
             expect(result.data[0].id).toBe(robotId);
+            expect(actor.permissionChecker.checkOneOf).toHaveBeenCalledTimes(1);
🤖 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` around lines
77 - 109, The test titled 'should include self-access entities without
per-record check' is missing an explicit assertion that the per-record
permission method isn't invoked; after calling service.getMany({}, actor) add a
call-count assertion on actor.permissionChecker.checkOneOf (e.g.,
expect(actor.permissionChecker.checkOneOf).not.toHaveBeenCalled() or
toHaveBeenCalledTimes(0)) so the test enforces that service.getMany returns the
self robot without performing per-record checkOneOf.
🤖 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/test/unit/core/entities/robot/service.spec.ts`:
- Around line 164-172: The test should stop relying on a bcrypt-specific regex
and instead verify that the plaintext secret returned by service.create (and
service.update) does not match the secret persisted in storage: after calling
service.create({ name: ... }) (and similarly for service.update), load the saved
Robot entity via the repository/find method used in tests (e.g.,
robotRepository.findById or service.get/find) using the returned id, then assert
result.secret is defined and result.secret !== persistedEntity.secret to ensure
the API returns plaintext while the DB stores a different (hashed) value; apply
this change to both the create and update test cases.

---

Nitpick comments:
In `@apps/server-core/test/unit/core/entities/client-permission/service.spec.ts`:
- Around line 97-117: The test currently only asserts the returned payload from
service.delete; after calling service.delete(id, createAllowAllActor()) also
assert the repository no longer contains the entity to verify the side-effect
(e.g., call repository.find(id) or repository.exists(id) and expect null/false).
Update the test that seeds the repository and calls service.delete to follow up
with an existence check on the same repository instance to ensure the entity was
actually removed.
- Around line 76-87: The test for service.create only checks that
actor.permissionChecker.preCheck was called with the custom permission object,
which can miss ordering regressions in the base CLIENT_PERMISSION_CREATE check;
update the spec to assert the exact call order using
actor.permissionChecker.preCheck calls (e.g.,
expect(preCheck).toHaveBeenNthCalledWith(1, { name: CLIENT_PERMISSION_CREATE })
and expect(preCheck).toHaveBeenNthCalledWith(2, { name: 'custom-perm' }) or
equivalent) so the first preCheck verifies the base CLIENT_PERMISSION_CREATE and
the second verifies the provided permission when invoking service.create.

In `@apps/server-core/test/unit/core/entities/client/service.spec.ts`:
- Around line 114-128: Add a second spec to assert the denial path for
plaintext-secret reads by making actor.permissionChecker.checkOneOf reject and
expecting service.getOne(id, actor) to throw ForbiddenError; reuse the existing
setup (seed repository with a plaintext secret record via repository.seed and
id/randomUUID) but stub/mock actor.permissionChecker.checkOneOf to return a
rejected promise or throw, then assert that calling getOne results in a
ForbiddenError being thrown to fully verify the sensitive-record guard in
getOne.
- Around line 184-246: Add explicit permission-denied unit tests for
service.update and service.save: in the 'update' describe block add a test that
calls service.update(id, {...}, createDenyActor()) (or an actor that lacks
update permission) and assert it rejects with the authorization error (e.g.,
ForbiddenError); in the 'save (upsert)' describe block add two tests — one for
create-path (undefined id) and one for update-path (existing id) that call
service.save(..., createDenyActor()) and assert they reject with the same
authorization error; reference the service.update and service.save calls and
reuse the existing actor helpers (createAllowAllActor) pattern to introduce a
deny/unauthorized actor helper used in these new tests.

In `@apps/server-core/test/unit/core/entities/realm/service.spec.ts`:
- Around line 86-90: The test for service.create({ name: 'ab' },
createAllowAllActor()) should assert a more specific validation failure instead
of the loose /name/i regex; update the assertion in the 'should reject invalid
name (too short)' spec to either expect a concrete validation error type (e.g.,
assert the thrown error is an instance of your validation error class such as
ValidationError) or match a precise message pattern (e.g.,
toThrowErrorMatchingInlineSnapshot or toThrow(/must be at least 3 characters/i)
/ toThrow(/too short/i)) that targets the "too short" condition, referencing the
service.create call and createAllowAllActor to locate the test.
- Around line 103-139: Add permission tests for the update suite: ensure
service.update triggers the actor permission check by asserting
actor.permissionChecker.preCheck was called with { name:
PermissionName.REALM_UPDATE } when using createAllowAllActor(), and add a test
that seeding a realm and calling service.update(...) with createDenyAllActor()
rejects with ForbiddenError; reference the service.update method,
PermissionName.REALM_UPDATE, actor.permissionChecker.preCheck,
createAllowAllActor, createDenyAllActor, and ForbiddenError to locate where to
add these two tests.

In `@apps/server-core/test/unit/core/entities/robot/service.spec.ts`:
- Around line 130-136: The test currently asserts that
actor.permissionChecker.checkOneOf was called for per-record permission in
service.getOne, but doesn’t assert the negative path; update the test to also
assert that actor.permissionChecker.check was not called (e.g.,
expect(actor.permissionChecker.check).not.toHaveBeenCalled()) after invoking
service.getOne(id, actor) — locate the assertion near the existing
expect(actor.permissionChecker.checkOneOf) and add the not-to-have-been-called
check to make the regression guard explicit; use the same test setup
(repository.seed, createAllowAllActor, service.getOne) so the new assertion
validates the negative permission call path.
- Around line 77-109: The test titled 'should include self-access entities
without per-record check' is missing an explicit assertion that the per-record
permission method isn't invoked; after calling service.getMany({}, actor) add a
call-count assertion on actor.permissionChecker.checkOneOf (e.g.,
expect(actor.permissionChecker.checkOneOf).not.toHaveBeenCalled() or
toHaveBeenCalledTimes(0)) so the test enforces that service.getMany returns the
self robot without performing per-record checkOneOf.

In `@apps/server-core/test/unit/core/entities/user-permission/service.spec.ts`:
- Around line 49-60: Add assertions that the permission check is invoked when
calling service.getOne: after calling service.getOne(id, createAllowAllActor())
verify the permission checker mock (the same mock used in getMany/delete tests)
was called with the retrieved entity and the actor; and for the NotFoundError
case assert the permission checker was not erroneously called (or assert it was
called with undefined/appropriate args per existing behavior). Locate the
service.getOne tests, reference repository.seed([{ id } as UserPermission]) and
createAllowAllActor(), and add expectations against the permission checker mock
consistent with other tests' patterns.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: f70eaede-3602-4a6c-8d71-206973cee2be

📥 Commits

Reviewing files that changed from the base of the PR and between b921c50 and 64f7d5c.

📒 Files selected for processing (18)
  • 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/identity/registration/service.spec.ts
🚧 Files skipped from review as they are similar to previous changes (12)
  • apps/server-core/test/unit/core/entities/user-role/service.spec.ts
  • apps/server-core/test/unit/core/entities/client-scope/service.spec.ts
  • apps/server-core/test/unit/core/identity/registration/service.spec.ts
  • apps/server-core/test/unit/core/entities/role-attribute/service.spec.ts
  • apps/server-core/test/unit/core/entities/user-attribute/service.spec.ts
  • apps/server-core/test/unit/core/entities/robot-role/service.spec.ts
  • apps/server-core/test/unit/core/entities/user/service.spec.ts
  • apps/server-core/test/unit/core/entities/client-role/service.spec.ts
  • apps/server-core/test/unit/core/entities/permission/service.spec.ts
  • apps/server-core/test/unit/core/entities/role-permission/service.spec.ts
  • apps/server-core/test/unit/core/entities/scope/service.spec.ts
  • apps/server-core/test/unit/core/entities/role/service.spec.ts

Comment on lines +164 to +172
it('should return plaintext secret after create (not the hash)', async () => {
const result = await service.create(
{ name: 'plain-secret-robot' },
createAllowAllActor(),
);

expect(result.secret).toBeDefined();
expect(result.secret).not.toMatch(/^\$2[aby]\$/);
});

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

Make plaintext-secret assertions algorithm-agnostic.

The bcrypt-prefix regex at Line 171 can miss regressions if hashing changes (e.g., non-bcrypt hashes). Prefer comparing returned secret with persisted secret for both create and update paths.

Suggested robust assertions
         it('should return plaintext secret after create (not the hash)', async () => {
             const result = await service.create(
                 { name: 'plain-secret-robot' },
                 createAllowAllActor(),
             );

             expect(result.secret).toBeDefined();
-            expect(result.secret).not.toMatch(/^\$2[aby]\$/);
+            const persisted = await repository.findOneWithSecret({ id: result.id });
+            expect(persisted?.secret).toBeDefined();
+            expect(result.secret).not.toBe(persisted?.secret);
         });
...
         it('should return plaintext secret after update with new secret', async () => {
             const id = randomUUID();
             repository.seed([{ id, name: 'robot' } as Robot]);

             const result = await service.update(id, { secret: 'new-secret-value' }, createAllowAllActor());
             expect(result.secret).toBe('new-secret-value');
+            const persisted = await repository.findOneWithSecret({ id });
+            expect(persisted?.secret).toBeDefined();
+            expect(persisted?.secret).not.toBe('new-secret-value');
         });

Also applies to: 212-218

🤖 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` around lines
164 - 172, The test should stop relying on a bcrypt-specific regex and instead
verify that the plaintext secret returned by service.create (and service.update)
does not match the secret persisted in storage: after calling service.create({
name: ... }) (and similarly for service.update), load the saved Robot entity via
the repository/find method used in tests (e.g., robotRepository.findById or
service.get/find) using the returned id, then assert result.secret is defined
and result.secret !== persistedEntity.secret to ensure the API returns plaintext
while the DB stores a different (hashed) value; apply this change to both the
create and update test cases.

@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/test/unit/core/helpers/fake-repository.ts (1)

87-89: No-op uniqueness checks can hide service-level regressions.

Line 87 currently lets duplicate entities pass in tests. Consider adding a minimal in-memory uniqueness strategy (or a configurable hook) so uniqueness-dependent service tests don’t produce false positives.

🤖 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/test/unit/core/helpers/fake-repository.ts`:
- Line 19: The fake repository's method signatures must match the interface:
update the async findMany method in fake-repository to accept the same parameter
(e.g., query) as declared on IEntityRepository and update validateJoinColumns to
accept the same parameter (e.g., data) so the fake remains substitutable; keep
the parameters even if unused (you can ignore them inside the body) and preserve
return types (EntityRepositoryFindManyResult<T> etc.) and async behavior to
exactly mirror the interface method signatures.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: cf7ccf8d-f689-4bca-90be-eb82dcd0e7cd

📥 Commits

Reviewing files that changed from the base of the PR and between 64f7d5c and 54d904a.

📒 Files selected for processing (1)
  • apps/server-core/test/unit/core/helpers/fake-repository.ts

@tada5hi

tada5hi commented Mar 16, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

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

@tada5hi

tada5hi commented Mar 16, 2026 •

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Mar 16, 2026

Copy link
Copy Markdown
✅ Actions performed

Review triggered.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
apps/server-core/test/unit/core/entities/role/service.spec.ts (1)

29-32: Match IRoleRepository.checkUniqueness() in the fake.

apps/server-core/src/core/entities/role/service.ts calls this hook with the validated data and, on updates, the current entity. The zero-arg stub won't surface contract drift in these specs.

Suggested change
 class FakeRoleRepository extends FakeEntityRepository<Role> implements IRoleRepository {
-    async checkUniqueness(): Promise<void> {
+    async checkUniqueness(_data: Partial<Role>, _entity?: Role): Promise<void> {
         // no-op
     }
 }
🤖 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/role/service.spec.ts` around lines
29 - 32, The FakeRoleRepository.checkUniqueness stub has the wrong signature
(zero-arg) and should match IRoleRepository.checkUniqueness so tests catch
contract drift; update FakeRoleRepository.checkUniqueness to accept the
validated data parameter (and the optional current entity parameter used on
updates) and implement a no-op that preserves the same parameter names/types as
in the real interface so service.spec.ts exercises the same call signature as
role service (reference FakeRoleRepository.checkUniqueness and
IRoleRepository.checkUniqueness).
apps/server-core/test/unit/core/identity/registration/service.spec.ts (1)

20-23: Mirror IUserRepository.checkUniqueness() signature in the fake.

Update FakeUserRepository.checkUniqueness() to accept the same parameters as the interface: data: Partial<User>, existing?: User. The current zero-arg stub will go unnoticed if registration service ever starts calling this method with arguments, allowing the test to silently pass with incorrect mocking. Even if the parameters stay unused, matching the interface prevents contract drift.

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

In `@apps/server-core/test/unit/core/identity/registration/service.spec.ts` around
lines 20 - 23, Update the FakeUserRepository.checkUniqueness signature to match
the interface by adding parameters (data: Partial<User>, existing?: User) while
keeping the body a no-op; specifically change
FakeUserRepository.checkUniqueness() to FakeUserRepository.checkUniqueness(data:
Partial<User>, existing?: User): Promise<void> so it mirrors
IUserRepository.checkUniqueness and prevents silent contract drift in tests.
🤖 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/test/unit/core/helpers/fake-repository.ts`:
- Around line 20-28: The fake findMany implementation in FakeRepository
currently ignores the query and returns the whole store with hard-coded meta;
update the findMany(query) in FakeRepository to honor supported query fields by
(1) applying filter conditions from query (e.g., equality or provided
predicates) to produce a filtered array from this.store, (2) computing total as
the length of the filtered results, (3) reading offset and limit from query
(with sensible defaults) and returning a sliced page of the filtered results,
and (optionally) (4) applying any simple sort instructions if your tests depend
on ordering; ensure the returned object still matches
EntityRepositoryFindManyResult<T> with data set to the paged slice and
meta.total/offset/limit reflecting the applied query.

---

Nitpick comments:
In `@apps/server-core/test/unit/core/entities/role/service.spec.ts`:
- Around line 29-32: The FakeRoleRepository.checkUniqueness stub has the wrong
signature (zero-arg) and should match IRoleRepository.checkUniqueness so tests
catch contract drift; update FakeRoleRepository.checkUniqueness to accept the
validated data parameter (and the optional current entity parameter used on
updates) and implement a no-op that preserves the same parameter names/types as
in the real interface so service.spec.ts exercises the same call signature as
role service (reference FakeRoleRepository.checkUniqueness and
IRoleRepository.checkUniqueness).

In `@apps/server-core/test/unit/core/identity/registration/service.spec.ts`:
- Around line 20-23: Update the FakeUserRepository.checkUniqueness signature to
match the interface by adding parameters (data: Partial<User>, existing?: User)
while keeping the body a no-op; specifically change
FakeUserRepository.checkUniqueness() to FakeUserRepository.checkUniqueness(data:
Partial<User>, existing?: User): Promise<void> so it mirrors
IUserRepository.checkUniqueness and prevents silent contract drift in tests.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: a8007700-d3ff-446f-955a-5259b0de1109

📥 Commits

Reviewing files that changed from the base of the PR and between 54d904a and fbc99b8.

📒 Files selected for processing (6)
  • apps/server-core/test/unit/core/entities/client/service.spec.ts
  • apps/server-core/test/unit/core/entities/role/service.spec.ts
  • apps/server-core/test/unit/core/entities/user-attribute/service.spec.ts
  • apps/server-core/test/unit/core/helpers/fake-repository.ts
  • apps/server-core/test/unit/core/identity/password-recovery/service.spec.ts
  • apps/server-core/test/unit/core/identity/registration/service.spec.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • apps/server-core/test/unit/core/identity/password-recovery/service.spec.ts
  • apps/server-core/test/unit/core/entities/user-attribute/service.spec.ts
  • apps/server-core/test/unit/core/entities/client/service.spec.ts

Comment on lines +20 to +28
async findMany(query: Record<string, any>): Promise<EntityRepositoryFindManyResult<T>> {
return {
data: [...this.store],
meta: {
total: this.store.length,
offset: 0,
limit: 50,
},
};

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

Honor query in findMany().

This fake always returns the full store with hard-coded pagination metadata, so any spec that passes filters/offsets/limits through findMany() can still go green when production query handling is broken. Either apply the supported query fields here or keep this helper out of query-sensitive 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/helpers/fake-repository.ts` around lines 20 -
28, The fake findMany implementation in FakeRepository currently ignores the
query and returns the whole store with hard-coded meta; update the
findMany(query) in FakeRepository to honor supported query fields by (1)
applying filter conditions from query (e.g., equality or provided predicates) to
produce a filtered array from this.store, (2) computing total as the length of
the filtered results, (3) reading offset and limit from query (with sensible
defaults) and returning a sliced page of the filtered results, and (optionally)
(4) applying any simple sort instructions if your tests depend on ordering;
ensure the returned object still matches EntityRepositoryFindManyResult<T> with
data set to the paged slice and meta.total/offset/limit reflecting the applied
query.

@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

♻️ Duplicate comments (1)
apps/server-core/test/unit/core/identity/registration/service.spec.ts (1)

209-211: ⚠️ Potential issue | 🟡 Minor

Assert invalid-email failure by error type, not only message text.

toThrow(/email/i) can still pass on non-contract exceptions. Please assert BadRequestError explicitly (and optionally keep the message assertion).

Suggested change
-            await expect(
-                service.register({ name: faker.internet.username(), email: 'not-an-email', password: 'securepass123' }),
-            ).rejects.toThrow(/email/i);
+            const promise = service.register({
+                name: faker.internet.username(),
+                email: 'not-an-email',
+                password: 'securepass123',
+            });
+
+            await expect(promise).rejects.toThrow(BadRequestError);
+            await expect(promise).rejects.toThrow(/email/i);
#!/bin/bash
# Verify validation-error assertion style consistency in unit specs.
rg -n --type=ts -C2 "rejects\.toThrow\((BadRequestError|/email/i)\)|rejects\.toBeInstanceOf\(BadRequestError\)" apps/server-core/test/unit
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/test/unit/core/identity/registration/service.spec.ts` around
lines 209 - 211, Replace the loose message-only assertion with an explicit
error-type assertion: change the test that calls service.register(...) to expect
the promise to reject with an instance of BadRequestError (e.g., use
rejects.toBeInstanceOf(BadRequestError)) and you may optionally keep the regex
message check as a separate assertion; target the service.register invocation
and ensure BadRequestError (imported from the same error module used by the
service) is asserted rather than only using toThrow(/email/i).
🧹 Nitpick comments (14)
apps/server-core/test/utils/domains/index.ts (1)

16-17: Inconsistent file extension usage in re-exports.

Lines 8–15 omit the .ts extension while lines 16–17 include it. Consider aligning the style for consistency within the barrel file.

♻️ Suggested fix for consistency

Either add extensions to all exports or remove them from lines 16-17:

-export * from './role-attribute.ts';
-export * from './user-attribute.ts';
+export * from './role-attribute';
+export * from './user-attribute';
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/test/utils/domains/index.ts` around lines 16 - 17, The
barrel file mixes re-export styles: keep them consistent by aligning
'./role-attribute.ts' and './user-attribute.ts' with the other exports; update
these two exports in apps/server-core/test/utils/domains/index.ts to remove the
".ts" extension (i.e., use './role-attribute' and './user-attribute') so all
exports in the file use the same extension-less style.
apps/server-core/test/unit/core/entities/scope/service.spec.ts (2)

115-119: Consider a more specific error assertion.

The regex /name/i is quite loose and would match any error message containing "name". For more precise validation testing, consider asserting on the specific error class or a more detailed message pattern.

💡 Example of more specific assertion
 it('should reject invalid name (too short)', async () => {
     await expect(
         service.create({ name: 'ab' }, createAllowAllActor()),
-    ).rejects.toThrow(/name/i);
+    ).rejects.toThrow(/name.*too short|length/i);
 });

Alternatively, if there's a specific validation error class:

).rejects.toThrow(ValidationError);
🤖 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/scope/service.spec.ts` around lines
115 - 119, The test currently uses a loose regex (/name/i) when expecting
service.create({ name: 'ab' }, createAllowAllActor()) to reject; change the
assertion to target a specific validation error by either asserting the exact
error message or the error class (e.g.,
expect(...).rejects.toThrow(ValidationError) or
expect(...).rejects.toThrow(/name must be at least \d+ characters/i)),
referencing the failing call to service.create and the helper
createAllowAllActor to locate the test; update the expectation to the more
specific predicate that your validation layer actually throws.

122-135: Consider adding permission check test for update.

For consistency with the create tests, consider adding a test that verifies preCheck is called with SCOPE_UPDATE permission, and another for the forbidden error case.

💡 Suggested additional tests
it('should call preCheck with SCOPE_UPDATE permission', async () => {
    const entity = repository.seed(createFakeScope());
    const actor = createAllowAllActor();
    await service.update(entity.id, { name: 'new-name' }, actor);

    expect(actor.permissionChecker.preCheck).toHaveBeenCalledWith({
        name: PermissionName.SCOPE_UPDATE,
    });
});

it('should throw when actor lacks permission', async () => {
    const entity = repository.seed(createFakeScope());
    await expect(
        service.update(entity.id, { name: 'new-name' }, createDenyAllActor()),
    ).rejects.toThrow(ForbiddenError);
});
🤖 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/scope/service.spec.ts` around lines
122 - 135, Add two unit tests to the existing update describe block to cover
permission checks: 1) a test that seeds an entity via
repository.seed(createFakeScope()), uses an allow-all actor from
createAllowAllActor(), calls service.update(entity.id, { name: 'new-name' },
actor) and asserts actor.permissionChecker.preCheck was called with { name:
PermissionName.SCOPE_UPDATE }; 2) a test that seeds an entity, uses
createDenyAllActor(), calls service.update(...) and expects the call to reject
with ForbiddenError; reference service.update, PermissionName.SCOPE_UPDATE,
actor.permissionChecker.preCheck, createAllowAllActor, createDenyAllActor,
repository.seed and createFakeScope to locate where to add them.
apps/server-core/test/unit/core/identity/registration/service.spec.ts (1)

62-67: Consider extracting a small createService() test helper.

RegistrationService construction is repeated across cases; a helper would reduce duplication and make option deltas clearer per test.

Also applies to: 75-80, 89-94, 116-121, 133-138, 153-158, 169-174, 186-191, 202-207, 224-229, 239-244

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

In `@apps/server-core/test/unit/core/identity/registration/service.spec.ts` around
lines 62 - 67, Extract a small test helper named createService() that returns a
new RegistrationService with sensible defaults (e.g., options: {
registrationEnabled: false }, and the shared mailClient, repository,
realmRepository mocks) and accept an overrides parameter so individual tests can
pass partial option deltas or replace dependencies; replace each repeated new
RegistrationService({...}) instantiation in the spec with calls to
createService({ options: {...} }) or createService({ mailClient: myMock }) to
reduce duplication and make per-test differences explicit.
apps/server-core/test/unit/core/entities/client/service.spec.ts (2)

197-229: Consider adding permission check test for update.

The update test suite lacks a test verifying that preCheck is called with CLIENT_UPDATE permission. This is inconsistent with the create and delete suites which both verify their respective permission checks.

💡 Suggested test to add
+        it('should call preCheck with CLIENT_UPDATE', async () => {
+            const entity = repository.seed(createFakeClient());
+            const actor = createAllowAllActor();
+            await service.update(entity.id, { name: 'updated' }, actor);
+            expect(actor.permissionChecker.preCheck).toHaveBeenCalledWith({
+                name: PermissionName.CLIENT_UPDATE,
+            });
+        });
+
+        it('should throw when actor lacks permission', async () => {
+            const entity = repository.seed(createFakeClient());
+            await expect(
+                service.update(entity.id, { name: 'x' }, createDenyAllActor()),
+            ).rejects.toThrow(ForbiddenError);
+        });
🤖 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/service.spec.ts` around lines
197 - 229, Add a unit test in the existing describe('update') suite that
spies/mock the service.preCheck method and asserts it is called with the
CLIENT_UPDATE permission when service.update is invoked; e.g., seed an entity
via repository.seed (using createFakeClient), prepare an actor
(createAllowAllActor()), call service.update(entity.id, { ... }, actor) and then
expect the spy toHaveBeenCalledWith(CLIENT_UPDATE, actor) (restore/mock
implementation so update proceeds normally).

129-141: Consider asserting the permission check arguments.

The test verifies that permissionChecker.checkOneOf is called, but doesn't verify the specific permissions being checked. This could allow regressions where the wrong permissions are validated.

💡 Suggested improvement
             const actor = createAllowAllActor();
             await service.getOne(entity.id, actor);

-            expect(actor.permissionChecker.checkOneOf).toHaveBeenCalled();
+            expect(actor.permissionChecker.checkOneOf).toHaveBeenCalledWith(
+                expect.objectContaining({ name: expect.any(Array) }),
+            );

Or verify the exact permission names if they're known.

🤖 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/service.spec.ts` around lines
129 - 141, The test should assert the exact permissions passed to the permission
checker to prevent regressions: update the spec around the call to
service.getOne(entity.id, actor) so that instead of only
expect(actor.permissionChecker.checkOneOf).toHaveBeenCalled() you assert the
call arguments (e.g.,
expect(actor.permissionChecker.checkOneOf).toHaveBeenCalledWith(...) or
toHaveBeenCalledWith(expect.arrayContaining([...]))); locate the mock on
actor.permissionChecker.checkOneOf used in this test and specify the expected
permission names (or an arrayContaining of them) that getOne should check for
the plaintext secret entity created by createFakeClient.
apps/server-core/test/unit/core/entities/client-role/service.spec.ts (1)

91-110: Consider adding permission denial test for delete.

The delete suite verifies preCheck is called with CLIENT_ROLE_DELETE, but unlike the create suite, it doesn't test that ForbiddenError is thrown when the actor lacks permission. This creates an inconsistency within the same test file.

💡 Suggested test to add
         it('should throw NotFoundError when entity does not exist', async () => {
             await expect(service.delete('non-existent-id', createAllowAllActor())).rejects.toThrow(NotFoundError);
         });
+
+        it('should throw when actor lacks permission', async () => {
+            const entity = repository.seed({} as ClientRole);
+            await expect(service.delete(entity.id, createDenyAllActor())).rejects.toThrow(ForbiddenError);
+        });
     });
🤖 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-role/service.spec.ts` around
lines 91 - 110, Add a test in the delete suite that verifies a ForbiddenError is
thrown when the actor lacks CLIENT_ROLE_DELETE permission: seed an entity with
repository.seed({} as ClientRole), create or mock an actor whose
permissionChecker.preCheck for PermissionName.CLIENT_ROLE_DELETE denies
permission (e.g., a createDenyActor or mock preCheck to throw or return a
rejected promise), call service.delete(entity.id, thatActor) and assert it
rejects with ForbiddenError; ensure the test also asserts preCheck was called
with { name: PermissionName.CLIENT_ROLE_DELETE } to mirror the existing preCheck
test.
apps/server-core/test/unit/core/entities/client-permission/service.spec.ts (1)

95-114: Consider adding permission denial test for delete.

For consistency with other test files and complete coverage, consider adding a test that verifies ForbiddenError is thrown when the actor lacks CLIENT_PERMISSION_DELETE permission.

💡 Suggested test to add
         it('should call preCheck with CLIENT_PERMISSION_DELETE', async () => {
             const entity = repository.seed({} as ClientPermission);
             const actor = createAllowAllActor();
             await service.delete(entity.id, actor);
             expect(actor.permissionChecker.preCheck).toHaveBeenCalledWith({
                 name: PermissionName.CLIENT_PERMISSION_DELETE,
             });
         });
+
+        it('should throw when actor lacks permission', async () => {
+            const entity = repository.seed({} as ClientPermission);
+            await expect(service.delete(entity.id, createDenyAllActor())).rejects.toThrow(ForbiddenError);
+        });
     });
🤖 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 95 - 114, Add a test to assert a ForbiddenError is thrown when the
actor lacks the CLIENT_PERMISSION_DELETE permission: in the describe('delete')
block create an entity via repository.seed and an actor that denies the
permission (e.g., use or add a createDenyAllActor / mock actor whose
permissionChecker.preCheck returns false or throws ForbiddenError), call
service.delete(entity.id, denyingActor) and assert the promise rejects with
ForbiddenError; also optionally verify permissionChecker.preCheck was invoked
with { name: PermissionName.CLIENT_PERMISSION_DELETE } to mirror existing tests.
apps/server-core/test/unit/core/identity/password-recovery/service.spec.ts (1)

52-324: Consider extracting a local service factory to reduce repeated setup.

new PasswordRecoveryService(...) is repeated in most tests. A small helper will cut duplication and make per-test option overrides clearer.

Refactor sketch
 describe('core/identity/password-recovery/service', () => {
     let repository: FakeUserRepository;
     let realmRepository: FakeRealmRepository;
     let mailClient: IMailClient;
+    const createService = (options: Record<string, boolean> = {}) => new PasswordRecoveryService({
+        options: {
+            passwordRecoveryEnabled: true,
+            emailVerificationEnabled: true,
+            ...options,
+        },
+        mailClient,
+        repository,
+        realmRepository,
+    });

@@
-            const service = new PasswordRecoveryService({
-                options: { passwordRecoveryEnabled: false },
-                mailClient,
-                repository,
-                realmRepository,
-            });
+            const service = createService({ passwordRecoveryEnabled: false });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/test/unit/core/identity/password-recovery/service.spec.ts`
around lines 52 - 324, Many tests repeatedly construct new
PasswordRecoveryService with the same dependencies and similar options; create a
local factory function (e.g., createService or makePasswordRecoveryService)
inside the describe blocks to centralize construction, accept an optional
partial options/overrides parameter, and return new PasswordRecoveryService({
options: { passwordRecoveryEnabled: true, emailVerificationEnabled: true,
...overrides.options }, mailClient, repository, realmRepository, ...overrides
}); then replace direct new PasswordRecoveryService(...) calls in tests with
calls to this factory to reduce duplication and allow per-test option overrides.
apps/server-core/test/unit/core/entities/user/service.spec.ts (3)

386-396: Assert the update payload actually persisted in the upsert update test.

This test currently only checks created === false, so a no-op update could still pass.

Proposed assertion strengthening
-            const { created } = await service.save(
+            const { created, entity: updatedEntity } = await service.save(
                 entity.id,
                 { display_name: 'updated' },
                 createAllowAllActor(),
             );

             expect(created).toBe(false);
+            expect(updatedEntity.display_name).toBe('updated');
🤖 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/user/service.spec.ts` around lines
386 - 396, The test only asserts that save returned created === false but
doesn't verify the update persisted; modify the 'should update when entity
found' test to fetch the updated entity after calling service.save (using
repository.find or service.get with entity.id) and assert that the display_name
(and/or other changed fields) equals 'updated' to ensure the upsert actually
applied; keep the existing repository.seed(entity) and service.save(...) calls
and add a follow-up retrieval and expect on the retrieved object's display_name.

337-341: Validate deletion side effect, not only return payload.

The current assertion can pass even if repository state is unchanged.

Proposed side-effect assertion
         it('should delete an existing user', async () => {
             const entity = repository.seed(createFakeUser());
             const result = await service.delete(entity.id, createAllowAllActor());
             expect(result.id).toBe(entity.id);
+            await expect(repository.findOne(entity.id)).resolves.toBeNull();
         });
🤖 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/user/service.spec.ts` around lines
337 - 341, The test only asserts the return payload from service.delete; update
it to also assert the repository state changed by verifying the seeded entity no
longer exists after calling service.delete(entity.id, createAllowAllActor()) —
e.g., call the repository lookup method used elsewhere in tests (such as
repository.findById(entity.id) or repository.get(entity.id) /
repository.exists(entity.id)) and expect null/undefined or false; keep using the
same helpers (repository.seed, createFakeUser, createAllowAllActor) and assert
both the returned result.id equals entity.id and the repository lookup confirms
the entity was removed.

180-188: Use the existing compare() helper instead of duplicating hash-prefix assertions.

Tests hardcode the bcrypt pattern /^\$2[aby]\$/ across multiple files (user/service.spec.ts, registration/service.spec.ts, password-recovery/service.spec.ts). Replace these with the algorithm-agnostic compare() function from packages/server-kit/src/crypto/hash/compare.ts to verify that hashed passwords match plaintext inputs. This eliminates duplication and ensures tests remain stable if the hashing implementation changes.

🤖 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/user/service.spec.ts` around lines
180 - 188, The test should use the algorithm-agnostic compare helper instead of
asserting a bcrypt prefix: import the compare function from
packages/server-kit/src/crypto/hash/compare.ts and replace the existing
assertions in the it('should hash password on create') case (which currently
check result.password !== 'plaintext123' and regex /^\$2[aby]\$/) with a single
call that awaits compare('plaintext123', result.password) (or the test's
plaintext variable) and asserts it returns true; keep the async signature and
remove the hardcoded regex check so the test will validate the hash regardless
of the underlying algorithm.
apps/server-core/test/unit/core/entities/user-attribute/service.spec.ts (2)

212-219: Constrain the actor so this really covers self-manage.

createUserActor() currently allows every permission, so this still passes if delete() accidentally requires the broader manage path. Deny USER_UPDATE and leave only self-manage available here.

🔐 One way to isolate the self-manage path
             const actor = createUserActor(userId);
+            vi.mocked(actor.permissionChecker.checkOneOf).mockImplementation(
+                async ({ name }: { name: PermissionName | PermissionName[] }) => {
+                    const names = Array.isArray(name) ? name : [name];
+                    if (!names.includes(PermissionName.USER_SELF_MANAGE)) {
+                        throw new ForbiddenError();
+                    }
+                },
+            );
+            vi.mocked(actor.permissionChecker.check).mockImplementation(
+                async ({ name }: { name: PermissionName }) => {
+                    if (name === PermissionName.USER_UPDATE) {
+                        throw new ForbiddenError();
+                    }
+                },
+            );
             const result = await service.delete(entity.id, actor);
             expect(result.id).toBe(entity.id);
🤖 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/user-attribute/service.spec.ts`
around lines 212 - 219, The test uses createUserActor(...) which currently
grants all permissions, so update this spec to construct an actor that
explicitly denies USER_UPDATE and only grants the self-manage capability for the
target user; locate the test block using createUserActor and the call to
service.delete(entity.id, actor) and change the actor creation so USER_UPDATE is
revoked (or omitted) while the self-manage permission for userId remains,
ensuring the delete call exercises the self-manage path only.

165-179: Make this test prove what the title says.

Right now it only proves checkOneOf() ran. It would still pass if preCheckOneOf() also ran, and the exact payload match is brittle if the service adds extra context or reorders the names.

🧪 Suggested tightening
             const actor = createAllowAllActor();
             await service.update(entity.id, { value: 'new' }, actor);

-            expect(actor.permissionChecker.checkOneOf).toHaveBeenCalledWith({
-                name: [
-                    PermissionName.USER_UPDATE,
-                    PermissionName.USER_SELF_MANAGE,
-                ],
-            });
+            expect(actor.permissionChecker.preCheckOneOf).not.toHaveBeenCalled();
+            expect(actor.permissionChecker.checkOneOf).toHaveBeenCalledWith(
+                expect.objectContaining({
+                    name: expect.arrayContaining([
+                        PermissionName.USER_UPDATE,
+                        PermissionName.USER_SELF_MANAGE,
+                    ]),
+                }),
+            );
🤖 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/user-attribute/service.spec.ts`
around lines 165 - 179, The test title claims only checkOneOf (not
preCheckOneOf) is used, but currently it only asserts checkOneOf ran and uses an
exact payload match which is brittle; update the test for the service.update
call to (1) assert actor.permissionChecker.preCheckOneOf was NOT called (e.g.,
toHaveBeenCalledTimes(0) or toHaveBeenCalledWith/not.toHaveBeenCalled), and (2)
assert actor.permissionChecker.checkOneOf was called with an argument whose name
array contains PermissionName.USER_UPDATE and PermissionName.USER_SELF_MANAGE
without requiring exact order or no extra context (use an assertion that matches
arrayContaining/contains semantics or objectContaining for the payload). Ensure
these checks reference service.update, actor.permissionChecker.checkOneOf,
actor.permissionChecker.preCheckOneOf, and PermissionName.USER_UPDATE /
PermissionName.USER_SELF_MANAGE.
🤖 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/testing.md:
- Around line 72-79: Update the examples for the PATTERN path filter to include
POSIX-style variants alongside the existing Windows examples: add examples like
core/entities, core/oauth2, core/identity, and core/entities.*service (using
forward slashes) next to the double-escaped backslash versions so Linux/macOS
users see the equivalent POSIX patterns; keep the existing Windows note about
escaped backslashes but add a short note that POSIX uses '/' and does not
require double-escaping.

---

Duplicate comments:
In `@apps/server-core/test/unit/core/identity/registration/service.spec.ts`:
- Around line 209-211: Replace the loose message-only assertion with an explicit
error-type assertion: change the test that calls service.register(...) to expect
the promise to reject with an instance of BadRequestError (e.g., use
rejects.toBeInstanceOf(BadRequestError)) and you may optionally keep the regex
message check as a separate assertion; target the service.register invocation
and ensure BadRequestError (imported from the same error module used by the
service) is asserted rather than only using toThrow(/email/i).

---

Nitpick comments:
In `@apps/server-core/test/unit/core/entities/client-permission/service.spec.ts`:
- Around line 95-114: Add a test to assert a ForbiddenError is thrown when the
actor lacks the CLIENT_PERMISSION_DELETE permission: in the describe('delete')
block create an entity via repository.seed and an actor that denies the
permission (e.g., use or add a createDenyAllActor / mock actor whose
permissionChecker.preCheck returns false or throws ForbiddenError), call
service.delete(entity.id, denyingActor) and assert the promise rejects with
ForbiddenError; also optionally verify permissionChecker.preCheck was invoked
with { name: PermissionName.CLIENT_PERMISSION_DELETE } to mirror existing tests.

In `@apps/server-core/test/unit/core/entities/client-role/service.spec.ts`:
- Around line 91-110: Add a test in the delete suite that verifies a
ForbiddenError is thrown when the actor lacks CLIENT_ROLE_DELETE permission:
seed an entity with repository.seed({} as ClientRole), create or mock an actor
whose permissionChecker.preCheck for PermissionName.CLIENT_ROLE_DELETE denies
permission (e.g., a createDenyActor or mock preCheck to throw or return a
rejected promise), call service.delete(entity.id, thatActor) and assert it
rejects with ForbiddenError; ensure the test also asserts preCheck was called
with { name: PermissionName.CLIENT_ROLE_DELETE } to mirror the existing preCheck
test.

In `@apps/server-core/test/unit/core/entities/client/service.spec.ts`:
- Around line 197-229: Add a unit test in the existing describe('update') suite
that spies/mock the service.preCheck method and asserts it is called with the
CLIENT_UPDATE permission when service.update is invoked; e.g., seed an entity
via repository.seed (using createFakeClient), prepare an actor
(createAllowAllActor()), call service.update(entity.id, { ... }, actor) and then
expect the spy toHaveBeenCalledWith(CLIENT_UPDATE, actor) (restore/mock
implementation so update proceeds normally).
- Around line 129-141: The test should assert the exact permissions passed to
the permission checker to prevent regressions: update the spec around the call
to service.getOne(entity.id, actor) so that instead of only
expect(actor.permissionChecker.checkOneOf).toHaveBeenCalled() you assert the
call arguments (e.g.,
expect(actor.permissionChecker.checkOneOf).toHaveBeenCalledWith(...) or
toHaveBeenCalledWith(expect.arrayContaining([...]))); locate the mock on
actor.permissionChecker.checkOneOf used in this test and specify the expected
permission names (or an arrayContaining of them) that getOne should check for
the plaintext secret entity created by createFakeClient.

In `@apps/server-core/test/unit/core/entities/scope/service.spec.ts`:
- Around line 115-119: The test currently uses a loose regex (/name/i) when
expecting service.create({ name: 'ab' }, createAllowAllActor()) to reject;
change the assertion to target a specific validation error by either asserting
the exact error message or the error class (e.g.,
expect(...).rejects.toThrow(ValidationError) or
expect(...).rejects.toThrow(/name must be at least \d+ characters/i)),
referencing the failing call to service.create and the helper
createAllowAllActor to locate the test; update the expectation to the more
specific predicate that your validation layer actually throws.
- Around line 122-135: Add two unit tests to the existing update describe block
to cover permission checks: 1) a test that seeds an entity via
repository.seed(createFakeScope()), uses an allow-all actor from
createAllowAllActor(), calls service.update(entity.id, { name: 'new-name' },
actor) and asserts actor.permissionChecker.preCheck was called with { name:
PermissionName.SCOPE_UPDATE }; 2) a test that seeds an entity, uses
createDenyAllActor(), calls service.update(...) and expects the call to reject
with ForbiddenError; reference service.update, PermissionName.SCOPE_UPDATE,
actor.permissionChecker.preCheck, createAllowAllActor, createDenyAllActor,
repository.seed and createFakeScope to locate where to add them.

In `@apps/server-core/test/unit/core/entities/user-attribute/service.spec.ts`:
- Around line 212-219: The test uses createUserActor(...) which currently grants
all permissions, so update this spec to construct an actor that explicitly
denies USER_UPDATE and only grants the self-manage capability for the target
user; locate the test block using createUserActor and the call to
service.delete(entity.id, actor) and change the actor creation so USER_UPDATE is
revoked (or omitted) while the self-manage permission for userId remains,
ensuring the delete call exercises the self-manage path only.
- Around line 165-179: The test title claims only checkOneOf (not preCheckOneOf)
is used, but currently it only asserts checkOneOf ran and uses an exact payload
match which is brittle; update the test for the service.update call to (1)
assert actor.permissionChecker.preCheckOneOf was NOT called (e.g.,
toHaveBeenCalledTimes(0) or toHaveBeenCalledWith/not.toHaveBeenCalled), and (2)
assert actor.permissionChecker.checkOneOf was called with an argument whose name
array contains PermissionName.USER_UPDATE and PermissionName.USER_SELF_MANAGE
without requiring exact order or no extra context (use an assertion that matches
arrayContaining/contains semantics or objectContaining for the payload). Ensure
these checks reference service.update, actor.permissionChecker.checkOneOf,
actor.permissionChecker.preCheckOneOf, and PermissionName.USER_UPDATE /
PermissionName.USER_SELF_MANAGE.

In `@apps/server-core/test/unit/core/entities/user/service.spec.ts`:
- Around line 386-396: The test only asserts that save returned created ===
false but doesn't verify the update persisted; modify the 'should update when
entity found' test to fetch the updated entity after calling service.save (using
repository.find or service.get with entity.id) and assert that the display_name
(and/or other changed fields) equals 'updated' to ensure the upsert actually
applied; keep the existing repository.seed(entity) and service.save(...) calls
and add a follow-up retrieval and expect on the retrieved object's display_name.
- Around line 337-341: The test only asserts the return payload from
service.delete; update it to also assert the repository state changed by
verifying the seeded entity no longer exists after calling
service.delete(entity.id, createAllowAllActor()) — e.g., call the repository
lookup method used elsewhere in tests (such as repository.findById(entity.id) or
repository.get(entity.id) / repository.exists(entity.id)) and expect
null/undefined or false; keep using the same helpers (repository.seed,
createFakeUser, createAllowAllActor) and assert both the returned result.id
equals entity.id and the repository lookup confirms the entity was removed.
- Around line 180-188: The test should use the algorithm-agnostic compare helper
instead of asserting a bcrypt prefix: import the compare function from
packages/server-kit/src/crypto/hash/compare.ts and replace the existing
assertions in the it('should hash password on create') case (which currently
check result.password !== 'plaintext123' and regex /^\$2[aby]\$/) with a single
call that awaits compare('plaintext123', result.password) (or the test's
plaintext variable) and asserts it returns true; keep the async signature and
remove the hardcoded regex check so the test will validate the hash regardless
of the underlying algorithm.

In `@apps/server-core/test/unit/core/identity/password-recovery/service.spec.ts`:
- Around line 52-324: Many tests repeatedly construct new
PasswordRecoveryService with the same dependencies and similar options; create a
local factory function (e.g., createService or makePasswordRecoveryService)
inside the describe blocks to centralize construction, accept an optional
partial options/overrides parameter, and return new PasswordRecoveryService({
options: { passwordRecoveryEnabled: true, emailVerificationEnabled: true,
...overrides.options }, mailClient, repository, realmRepository, ...overrides
}); then replace direct new PasswordRecoveryService(...) calls in tests with
calls to this factory to reduce duplication and allow per-test option overrides.

In `@apps/server-core/test/unit/core/identity/registration/service.spec.ts`:
- Around line 62-67: Extract a small test helper named createService() that
returns a new RegistrationService with sensible defaults (e.g., options: {
registrationEnabled: false }, and the shared mailClient, repository,
realmRepository mocks) and accept an overrides parameter so individual tests can
pass partial option deltas or replace dependencies; replace each repeated new
RegistrationService({...}) instantiation in the spec with calls to
createService({ options: {...} }) or createService({ mailClient: myMock }) to
reduce duplication and make per-test differences explicit.

In `@apps/server-core/test/utils/domains/index.ts`:
- Around line 16-17: The barrel file mixes re-export styles: keep them
consistent by aligning './role-attribute.ts' and './user-attribute.ts' with the
other exports; update these two exports in
apps/server-core/test/utils/domains/index.ts to remove the ".ts" extension
(i.e., use './role-attribute' and './user-attribute') so all exports in the file
use the same extension-less style.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 3bbad4a0-3fd9-43ba-a57f-2d0851559a60

📥 Commits

Reviewing files that changed from the base of the PR and between fbc99b8 and dccedf2.

📒 Files selected for processing (23)
  • .agents/testing.md
  • 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/fake-repository.ts
  • apps/server-core/test/unit/core/identity/password-recovery/service.spec.ts
  • apps/server-core/test/unit/core/identity/registration/service.spec.ts
  • apps/server-core/test/utils/domains/index.ts
  • apps/server-core/test/utils/domains/role-attribute.ts
🚧 Files skipped from review as they are similar to previous changes (6)
  • apps/server-core/test/unit/core/entities/user-role/service.spec.ts
  • apps/server-core/test/unit/core/entities/realm/service.spec.ts
  • apps/server-core/test/unit/core/entities/client-scope/service.spec.ts
  • apps/server-core/test/unit/core/entities/user-permission/service.spec.ts
  • apps/server-core/test/unit/core/helpers/fake-repository.ts
  • apps/server-core/test/unit/core/entities/robot-permission/service.spec.ts

Comment thread .agents/testing.md
Comment on lines +72 to +79
Replace `PATTERN` with a path fragment to filter files. Examples:
- `core\\\\entities` — all entity service/type files
- `core\\\\oauth2` — OAuth2 module
- `core\\\\identity` — registration and password recovery
- `core\\\\entities.*service` — only service implementation files

**Note:** Windows paths use `\\\\` (double-escaped backslash) in the filter string.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Add POSIX path-filter examples alongside Windows examples.

The examples currently show escaped Windows separators only. Adding / variants will avoid confusion for Linux/macOS users.

Doc tweak suggestion
 Replace `PATTERN` with a path fragment to filter files. Examples:
-- `core\\\\entities` — all entity service/type files
-- `core\\\\oauth2` — OAuth2 module
-- `core\\\\identity` — registration and password recovery
-- `core\\\\entities.*service` — only service implementation files
+- POSIX: `core/entities` — all entity service/type files
+- POSIX: `core/oauth2` — OAuth2 module
+- POSIX: `core/identity` — registration and password recovery
+- Regex-like fragment: `core/entities.*service` — only service implementation files
+- Windows (escaped): `core\\\\entities`, `core\\\\oauth2`, `core\\\\identity`
 
 **Note:** Windows paths use `\\\\` (double-escaped backslash) in the filter string.
📝 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
Replace `PATTERN` with a path fragment to filter files. Examples:
- `core\\\\entities` — all entity service/type files
- `core\\\\oauth2` — OAuth2 module
- `core\\\\identity` — registration and password recovery
- `core\\\\entities.*service` — only service implementation files
**Note:** Windows paths use `\\\\` (double-escaped backslash) in the filter string.
Replace `PATTERN` with a path fragment to filter files. Examples:
- POSIX: `core/entities` — all entity service/type files
- POSIX: `core/oauth2` — OAuth2 module
- POSIX: `core/identity` — registration and password recovery
- Regex-like fragment: `core/entities.*service` — only service implementation files
- Windows (escaped): `core\\\\entities`, `core\\\\oauth2`, `core\\\\identity`
**Note:** Windows paths use `\\\\` (double-escaped backslash) in the filter string.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In @.agents/testing.md around lines 72 - 79, Update the examples for the PATTERN
path filter to include POSIX-style variants alongside the existing Windows
examples: add examples like core/entities, core/oauth2, core/identity, and
core/entities.*service (using forward slashes) next to the double-escaped
backslash versions so Linux/macOS users see the equivalent POSIX patterns; keep
the existing Windows note about escaped backslashes but add a short note that
POSIX uses '/' and does not require double-escaping.

@tada5hi

tada5hi commented Mar 16, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Mar 16, 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 (4)
apps/server-core/test/unit/core/identity/registration/service.spec.ts (1)

201-212: ⚠️ Potential issue | 🟡 Minor

Assert the invalid-email error class explicitly.

On Line 211, matching only /email/i can pass on unintended failures. Assert BadRequestError to lock the contract.

Suggested change
             await expect(
                 service.register({ name: faker.internet.username(), email: 'not-an-email', password: 'securepass123' }),
-            ).rejects.toThrow(/email/i);
+            ).rejects.toThrow(BadRequestError);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/test/unit/core/identity/registration/service.spec.ts` around
lines 201 - 212, The test currently only asserts the error message matches
`/email/i`, which is too loose; update the expectation in the registration unit
test for RegistrationService to assert the specific error class
(BadRequestError) instead of just the regex. Replace the current
rejects.toThrow(/email/i) with an assertion that the rejected error is an
instance of or thrown as BadRequestError (and optionally also assert the message
contains "email"), making sure to import/reference BadRequestError so the test
fails on contract changes rather than unrelated message text.
apps/server-core/test/unit/core/helpers/fake-repository.ts (1)

20-28: ⚠️ Potential issue | 🟠 Major

findMany() ignores query, making query-sensitive tests unreliable.

Line 20 accepts query but Lines 21–28 always return the whole store with hard-coded pagination metadata. This can let filtering/pagination regressions pass green in unit tests.

Suggested fix
 async findMany(query: Record<string, any>): Promise<EntityRepositoryFindManyResult<T>> {
+    const where = query?.where && typeof query.where === 'object' ? query.where : {};
+    const offset = Number.isInteger(query?.offset) ? query.offset : 0;
+    const limit = Number.isInteger(query?.limit) ? query.limit : 50;
+
+    const filtered = this.store.filter((entity) => this.matchesWhere(entity, where));
+    const paged = filtered.slice(offset, offset + limit);
+
     return {
-        data: [...this.store],
+        data: paged,
         meta: {
-            total: this.store.length,
-            offset: 0,
-            limit: 50,
+            total: filtered.length,
+            offset,
+            limit,
         },
     };
 }
🤖 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/fake-repository.ts` around lines 20 -
28, The findMany method currently ignores the incoming query and always returns
the whole this.store with hard-coded meta; update findMany(query: Record<string,
any>) in the fake repository to apply the query filters and pagination from the
query before building the EntityRepositoryFindManyResult<T>. Specifically,
filter this.store by matching simple equality for keys present in query (e.g.,
fields like id, status), then read pagination parameters (offset, limit, or
page) from query and slice the filtered results accordingly, and finally return
data: slicedResults and meta: { total: filtered.length, offset, limit } so tests
that exercise query-sensitive behavior will exercise realistic filtering and
paging.
.agents/testing.md (1)

72-79: ⚠️ Potential issue | 🟡 Minor

Add POSIX path-filter examples next to Windows-escaped examples.

The current examples are Windows-only; adding / variants avoids ambiguity for Linux/macOS contributors.

Doc tweak
 Replace `PATTERN` with a path fragment to filter files. Examples:
-- `core\\\\entities` — all entity service/type files
-- `core\\\\oauth2` — OAuth2 module
-- `core\\\\identity` — registration and password recovery
-- `core\\\\entities.*service` — only service implementation files
+- POSIX: `core/entities` — all entity service/type files
+- POSIX: `core/oauth2` — OAuth2 module
+- POSIX: `core/identity` — registration and password recovery
+- Regex-like fragment: `core/entities.*service` — only service implementation files
+- Windows (escaped): `core\\\\entities`, `core\\\\oauth2`, `core\\\\identity`
 
-**Note:** Windows paths use `\\\\` (double-escaped backslash) in the filter string.
+**Note:** POSIX paths use `/` (no double escaping). Windows paths use `\\\\` in the filter string.
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/testing.md around lines 72 - 79, The examples under PATTERN are
Windows-only; add POSIX-style equivalents next to each Windows-escaped example
so Linux/macOS users see clear alternatives (e.g., alongside `core\\\\entities`
add `/core/entities`, `core\\\\oauth2` → `/core/oauth2`, `core\\\\identity` →
`/core/identity`, and `core\\\\entities.*service` → `/core/entities.*service`),
and update the note to state that Windows paths require `\\\\` escaping while
POSIX paths use plain `/` with no escaping.
apps/server-core/test/unit/core/entities/permission/service.spec.ts (1)

164-171: ⚠️ Potential issue | 🟡 Minor

Use toBeNull() for the unset policy_id assertion.

At Line 170, this expectation should be nullable (null) rather than undefined for policy_id in this service flow.

Suggested fix
-            expect(result.policy_id).toBeUndefined();
+            expect(result.policy_id).toBeNull();

Use this read-only check to confirm type + service behavior:

#!/bin/bash
set -euo pipefail

echo "1) Permission type definition (look for nullable policy_id):"
sed -n '1,140p' apps/server-core/src/core/entities/permission/types.ts

echo
echo "2) PermissionService create/save logic (look for defaultPolicyId + policy_id handling):"
sed -n '120,190p' apps/server-core/src/core/entities/permission/service.ts

echo
echo "3) Current test assertion block:"
sed -n '158,176p' apps/server-core/test/unit/core/entities/permission/service.spec.ts

Expected result: type/service behavior indicates nullable policy_id, so the assertion should use toBeNull().

🤖 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 164 - 171, Update the test assertion in the "should not assign default
policy_id when none configured" spec to expect a null policy_id instead of
undefined: change the assertion on result.policy_id produced by
service.create(...) to use toBeNull() so it aligns with the Permission type and
PermissionService create/save behavior that treat policy_id as nullable; ensure
the test references the same result variable from the spec's call to
service.create and only adjusts the expectation.
🧹 Nitpick comments (1)
apps/server-core/test/unit/core/identity/registration/service.spec.ts (1)

62-67: Extract a small service factory to remove constructor duplication.

new RegistrationService({...}) is repeated in many tests with mostly identical wiring. A local helper would reduce noise and make option-specific intent clearer.

Also applies to: 75-80, 89-94, 116-121, 133-138, 153-158, 169-174, 186-191, 202-207, 224-229, 239-244

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

In `@apps/server-core/test/unit/core/identity/registration/service.spec.ts` around
lines 62 - 67, Tests repeatedly construct RegistrationService with the same
collaborators; extract a small factory function (e.g., makeRegistrationService
or createService) inside the spec that accepts an optional overrides object and
returns new RegistrationService({...}) wired with the shared mailClient,
repository, realmRepository and default options (registrationEnabled: false) so
each test can call the factory with only the differing options or mocks; update
all occurrences that call new RegistrationService(...) to use the factory to
reduce duplication and clarify intent.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In @.agents/testing.md:
- Around line 72-79: The examples under PATTERN are Windows-only; add
POSIX-style equivalents next to each Windows-escaped example so Linux/macOS
users see clear alternatives (e.g., alongside `core\\\\entities` add
`/core/entities`, `core\\\\oauth2` → `/core/oauth2`, `core\\\\identity` →
`/core/identity`, and `core\\\\entities.*service` → `/core/entities.*service`),
and update the note to state that Windows paths require `\\\\` escaping while
POSIX paths use plain `/` with no escaping.

In `@apps/server-core/test/unit/core/entities/permission/service.spec.ts`:
- Around line 164-171: Update the test assertion in the "should not assign
default policy_id when none configured" spec to expect a null policy_id instead
of undefined: change the assertion on result.policy_id produced by
service.create(...) to use toBeNull() so it aligns with the Permission type and
PermissionService create/save behavior that treat policy_id as nullable; ensure
the test references the same result variable from the spec's call to
service.create and only adjusts the expectation.

In `@apps/server-core/test/unit/core/helpers/fake-repository.ts`:
- Around line 20-28: The findMany method currently ignores the incoming query
and always returns the whole this.store with hard-coded meta; update
findMany(query: Record<string, any>) in the fake repository to apply the query
filters and pagination from the query before building the
EntityRepositoryFindManyResult<T>. Specifically, filter this.store by matching
simple equality for keys present in query (e.g., fields like id, status), then
read pagination parameters (offset, limit, or page) from query and slice the
filtered results accordingly, and finally return data: slicedResults and meta: {
total: filtered.length, offset, limit } so tests that exercise query-sensitive
behavior will exercise realistic filtering and paging.

In `@apps/server-core/test/unit/core/identity/registration/service.spec.ts`:
- Around line 201-212: The test currently only asserts the error message matches
`/email/i`, which is too loose; update the expectation in the registration unit
test for RegistrationService to assert the specific error class
(BadRequestError) instead of just the regex. Replace the current
rejects.toThrow(/email/i) with an assertion that the rejected error is an
instance of or thrown as BadRequestError (and optionally also assert the message
contains "email"), making sure to import/reference BadRequestError so the test
fails on contract changes rather than unrelated message text.

---

Nitpick comments:
In `@apps/server-core/test/unit/core/identity/registration/service.spec.ts`:
- Around line 62-67: Tests repeatedly construct RegistrationService with the
same collaborators; extract a small factory function (e.g.,
makeRegistrationService or createService) inside the spec that accepts an
optional overrides object and returns new RegistrationService({...}) wired with
the shared mailClient, repository, realmRepository and default options
(registrationEnabled: false) so each test can call the factory with only the
differing options or mocks; update all occurrences that call new
RegistrationService(...) to use the factory to reduce duplication and clarify
intent.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 7e6e811b-6005-4572-ba34-741f99c67f63

📥 Commits

Reviewing files that changed from the base of the PR and between fbc99b8 and dccedf2.

📒 Files selected for processing (23)
  • .agents/testing.md
  • 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/fake-repository.ts
  • apps/server-core/test/unit/core/identity/password-recovery/service.spec.ts
  • apps/server-core/test/unit/core/identity/registration/service.spec.ts
  • apps/server-core/test/utils/domains/index.ts
  • apps/server-core/test/utils/domains/role-attribute.ts
🚧 Files skipped from review as they are similar to previous changes (11)
  • apps/server-core/test/unit/core/entities/user-permission/service.spec.ts
  • apps/server-core/test/unit/core/entities/role-attribute/service.spec.ts
  • apps/server-core/test/unit/core/identity/password-recovery/service.spec.ts
  • apps/server-core/test/unit/core/entities/scope/service.spec.ts
  • apps/server-core/test/unit/core/entities/role-permission/service.spec.ts
  • apps/server-core/test/unit/core/entities/user-attribute/service.spec.ts
  • apps/server-core/test/unit/core/entities/client-permission/service.spec.ts
  • apps/server-core/test/unit/core/entities/client/service.spec.ts
  • apps/server-core/test/unit/core/entities/robot/service.spec.ts
  • apps/server-core/test/unit/core/entities/client-scope/service.spec.ts
  • apps/server-core/test/unit/core/entities/robot-permission/service.spec.ts

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