Repository navigation
fix: restore +secret field selection on GET /clients/:id - #3023
Conversation
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (6)
📝 WalkthroughWalkthroughIntroduces repository-level Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant Client
participant Controller
participant Service
participant Repo as Repository
participant DB as Database
participant Auth as AuthEvaluator
Client->>Controller: HTTP GET /entities/:id?...
Controller->>Service: getOne(id, actor, query, realmId)
Service->>Auth: preEvaluateOneOf(actor, permissions) (skipped if isMe)
Service->>Repo: findOne(idOrName, query, realmId)
Repo->>DB: SQL (by uuid OR name LIKE, + realm constraint, applyQuery)
DB-->>Repo: entity
Repo-->>Service: entity
Service->>Auth: evaluateOneOf(actor, entity) (skipped if isMe)
Service-->>Controller: entity
Controller-->>Client: HTTP 200 + entity
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Pull request overview
This PR restores support for selecting the secret field (e.g. fields=+secret) when fetching a single client via GET /clients/:id, by forwarding request query parameters down into the client service/repository lookup path.
Changes:
- Extend
IClientService.getOne()to accept an optionalqueryobject and forward controller query params to it. - Update
ClientService.getOne()to usefindMany()with an enforcedid/namefilter when a query is provided (enabling+secretfield selection). - Improve test infrastructure and add unit tests covering query forwarding and client self-access permission fallback behavior.
Reviewed changes
Copilot reviewed 5 out of 5 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
| apps/server-core/test/unit/core/helpers/fake-repository.ts | Adds basic query.filter support to the fake repository’s findMany() to support new tests. |
| apps/server-core/test/unit/core/entities/client/service.spec.ts | Adds unit tests for query forwarding and CLIENT_SELF_MANAGE fallback/self-access behavior. |
| apps/server-core/src/core/entities/client/types.ts | Extends getOne() service interface to accept an optional query. |
| apps/server-core/src/core/entities/client/service.ts | Implements query-aware single-client fetch via findMany(), and introduces self-access permission fallback logic. |
| apps/server-core/src/adapters/http/controllers/entities/client/module.ts | Forwards useRequestQuery(req) into service.getOne() for GET /clients/:id. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| if (!entity) { | ||
| throw new NotFoundError(); | ||
| } |
There was a problem hiding this comment.
Authorization is performed only after loading the client and throwing NotFoundError when missing. This enables resource enumeration (unauthorized callers can distinguish existing vs non-existing IDs/names by Forbidden vs NotFound), whereas other services typically preEvaluate before the lookup. Consider performing the preEvaluateOneOf check before loading the entity (except for an explicit self-access branch that can be determined without fetching the target), or normalizing the error behavior to avoid leaking existence.
| filter.realm_id = realm.id; | ||
| } | ||
|
|
||
| const { data } = await this.repository.findMany({ ...query, filter }); |
There was a problem hiding this comment.
When query is provided, getOne delegates to repository.findMany({ ...query, filter }). This forwards pagination params (offset/limit/page) from the request; e.g. a non-zero offset can cause data[0] to be empty and incorrectly return NotFound for an existing client. For a single-entity lookup, force offset=0 and limit=1 (and/or strip pagination/sort entirely), or use a dedicated repository method that applies fields/relations but executes a single getOne() query.
| const { data } = await this.repository.findMany({ ...query, filter }); | |
| const { data } = await this.repository.findMany({ | |
| ...query, | |
| filter, | |
| offset: 0, | |
| limit: 1, | |
| }); |
| const { data } = await this.repository.findMany({ ...query, filter }); | ||
| entity = data[0] ?? null; |
There was a problem hiding this comment.
Using findMany() for a GET-by-id/name path likely triggers getManyAndCount() in the DB adapter, which executes an extra COUNT query. This can significantly increase DB load for a frequently-hit endpoint. Prefer a findOne(...)/findOneWithQuery(...) path (similar to the UserRepositoryAdapter’s findOne which applies query modifiers but uses getOne()), or bypass findMany when the query doesn’t actually request additional fields/relations.
| const { data } = await this.repository.findMany({ ...query, filter }); | |
| entity = data[0] ?? null; | |
| entity = await this.repository.findOne({ ...query, filter }); |
The refactor in #2910 dropped the request query from ClientService.getOne, so applyQuery's field selection (allowed: ['secret']) was no longer reached and `?fields=+secret` silently returned no secret. - Add IClientRepository.findOne(id, query?, realm?) using applyQuery, mirroring the existing IUserRepository.findOne pattern; service's getOne now delegates to it - Align ClientService.getOne signature with IUserService.getOne: (idOrName, actor, query?, realmId?) - Mirror save()'s self-edit fallback: try CLIENT_READ/UPDATE/DELETE upfront, fall back to CLIENT_SELF_MANAGE when a client identity accesses its own record (verified against entity.id in the catch) - Skip the post-load ATTRIBUTES-based secret evaluation on self-access; CLIENT_SELF_MANAGE's ATTRIBUTE_NAMES denylist would otherwise reject the entity's own keys (active, realm_id, ...)
Same regression as #2910 introduced for clients: RobotService.getOne dropped the request query, so applyQuery's field selection was never reached and `?fields=+secret` returned no secret on GET /robots/:id. - Add IRobotRepository.findOne(id, query?, realm?) using applyQuery, matching the IUserRepository / IClientRepository pattern - Align RobotService.getOne signature with peers: (idOrName, actor, query?, realmId?) - Mirror save()'s self-edit fallback for ROBOT_SELF_MANAGE; getOne now lets a robot read its own record when it lacks ROBOT_READ etc. - Skip post-load ATTRIBUTES-based evaluation on self-access; the ATTRIBUTE_NAMES denylist on ROBOT_SELF_MANAGE would otherwise reject the entity's own keys
2a54c53 to
29e8338
Compare
Align ClientService.getOne and RobotService.getOne with UserService.getOne: when the actor's identity matches the requested id-or-name, skip the upfront permission gate and the post-load ATTRIBUTES evaluation. *_SELF_MANAGE was always semantically a write permission (its ATTRIBUTE_NAMES denylist constrains editable fields, not readable ones), so requiring it for self-read was the wrong fit. Self-read now works the same across user, client, and robot — any authenticated identity can fetch its own record without holding any *_READ / *_SELF_MANAGE. The +secret / +email opt-in fields still require the explicit ?fields=+... query param. Non-self lookups continue to require *_READ / *_UPDATE / *_DELETE.
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
apps/server-core/src/app/modules/database/repositories/robot/repository.ts (1)
127-141: Consider centralizing robot field projection config.The default field list here duplicates
findMany, which can drift. Extracting shared constants would reduce maintenance risk.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/app/modules/database/repositories/robot/repository.ts` around lines 127 - 141, The default field list passed into applyQuery (fields.default under defaultAlias 'robot') is duplicated elsewhere (e.g., findMany); extract that array into a single shared constant (e.g., ROBOT_DEFAULT_FIELDS or ROBOT_FIELD_PROJECTION) defined near the repository module (or a shared constants file), then replace the inline arrays in applyQuery and findMany to reference that constant so both use the same canonical projection and avoid drift.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@apps/server-core/src/app/modules/database/repositories/client/repository.ts`:
- Line 115: The query in repository.ts uses qb.where('client.name LIKE :name', {
name: id }) inside the getOne()/client lookup, which allows wildcard matching;
change the predicate to an exact equality check by replacing the LIKE condition
with '=' (e.g., qb.where('client.name = :name', { name: id })) so getOne()
performs deterministic exact name matching.
In `@apps/server-core/src/core/entities/robot/service.ts`:
- Around line 104-125: The self-detection logic using actor.identity and setting
isMe should be made realm-aware: when realmId is provided, only consider isMe
true if actor.identity.type === 'robot' AND actor.identity.data.id or .name
matches idOrName AND the actor's realm (actor.realmId or equivalent on
actor.identity) matches the requested realmId; otherwise treat as not-self and
run permission checks via permissionEvaluator.preEvaluateOneOf. Update the
computation of resolvedId and the check before calling
repository.findOne(resolvedId, query, realmId) so that self-resolution only
occurs when both identity match and realm match; keep existing permission names
and repository.findOne usage unchanged.
---
Nitpick comments:
In `@apps/server-core/src/app/modules/database/repositories/robot/repository.ts`:
- Around line 127-141: The default field list passed into applyQuery
(fields.default under defaultAlias 'robot') is duplicated elsewhere (e.g.,
findMany); extract that array into a single shared constant (e.g.,
ROBOT_DEFAULT_FIELDS or ROBOT_FIELD_PROJECTION) defined near the repository
module (or a shared constants file), then replace the inline arrays in
applyQuery and findMany to reference that constant so both use the same
canonical projection and avoid drift.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 8722d978-cc5c-4761-8fd8-b7e195dc19fb
📒 Files selected for processing (11)
AGENTS.mdapps/server-core/src/adapters/http/controllers/entities/client/module.tsapps/server-core/src/adapters/http/controllers/entities/robot/module.tsapps/server-core/src/app/modules/database/repositories/client/repository.tsapps/server-core/src/app/modules/database/repositories/robot/repository.tsapps/server-core/src/core/entities/client/service.tsapps/server-core/src/core/entities/client/types.tsapps/server-core/src/core/entities/robot/service.tsapps/server-core/src/core/entities/robot/types.tsapps/server-core/test/unit/core/entities/client/service.spec.tsapps/server-core/test/unit/core/entities/robot/service.spec.ts
| if (isUUID(id)) { | ||
| qb.where('client.id = :id', { id }); | ||
| } else { | ||
| qb.where('client.name LIKE :name', { name: id }); |
There was a problem hiding this comment.
Use exact match for name-based identifier lookup.
Line 115 uses LIKE for an identifier lookup. If id contains wildcard characters, it can match unintended clients and make getOne() nondeterministic. Use = for exact matching.
Proposed fix
- qb.where('client.name LIKE :name', { name: id });
+ qb.where('client.name = :name', { name: id });📝 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.
| qb.where('client.name LIKE :name', { name: id }); | |
| qb.where('client.name = :name', { name: id }); |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/server-core/src/app/modules/database/repositories/client/repository.ts`
at line 115, The query in repository.ts uses qb.where('client.name LIKE :name',
{ name: id }) inside the getOne()/client lookup, which allows wildcard matching;
change the predicate to an exact equality check by replacing the LIKE condition
with '=' (e.g., qb.where('client.name = :name', { name: id })) so getOne()
performs deterministic exact name matching.
| let isMe = false; | ||
| if (actor.identity && actor.identity.type === 'robot') { | ||
| if ( | ||
| actor.identity.data.id === idOrName || | ||
| actor.identity.data.name === idOrName | ||
| ) { | ||
| isMe = true; | ||
| } | ||
| } | ||
|
|
||
| let entity: Robot | null; | ||
| if (isUUID(idOrName)) { | ||
| entity = await this.repository.findOneById(idOrName); | ||
| } else if (realmId) { | ||
| const realm = await this.realmRepository.resolve(realmId); | ||
| entity = realm ? | ||
| await this.repository.findOneBy({ | ||
| name: idOrName, | ||
| realm_id: realm.id, | ||
| }) : | ||
| null; | ||
| } else { | ||
| entity = await this.repository.findOneByName(idOrName); | ||
| if (!isMe) { | ||
| await actor.permissionEvaluator.preEvaluateOneOf({ | ||
| name: [ | ||
| PermissionName.ROBOT_READ, | ||
| PermissionName.ROBOT_UPDATE, | ||
| PermissionName.ROBOT_DELETE, | ||
| ], | ||
| }); | ||
| } | ||
|
|
||
| const resolvedId = isMe ? actor.identity!.data.id : idOrName; | ||
| const entity = await this.repository.findOne(resolvedId, query, realmId); |
There was a problem hiding this comment.
Make self-detection realm-aware when realmId is provided.
Line 104 onward marks self-access by id/name only. In realm-scoped calls, this can resolve to the actor’s robot even when the requested realm key differs, because Line 125 then looks up by UUID and ignores realm scoping.
Suggested adjustment
let isMe = false;
if (actor.identity && actor.identity.type === 'robot') {
if (
actor.identity.data.id === idOrName ||
actor.identity.data.name === idOrName
) {
isMe = true;
}
}
+
+if (isMe && realmId) {
+ const realm = await this.realmRepository.resolve(realmId);
+ if (!realm || actor.identity?.data.realm_id !== realm.id) {
+ isMe = false;
+ }
+}🤖 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 104 - 125,
The self-detection logic using actor.identity and setting isMe should be made
realm-aware: when realmId is provided, only consider isMe true if
actor.identity.type === 'robot' AND actor.identity.data.id or .name matches
idOrName AND the actor's realm (actor.realmId or equivalent on actor.identity)
matches the requested realmId; otherwise treat as not-self and run permission
checks via permissionEvaluator.preEvaluateOneOf. Update the computation of
resolvedId and the check before calling repository.findOne(resolvedId, query,
realmId) so that self-resolution only occurs when both identity match and realm
match; keep existing permission names and repository.findOne usage unchanged.
Tentative self-detection (id-or-name match against actor identity) can falsely match when a name collides across realms — the loaded entity may belong to a different identity than the actor. Re-check after the lookup using the loaded entity's UUID against the actor's identity id; if they don't match, run the permission gate that was skipped pre-load. This mirrors the post-load self-edit verification already used in ClientService.save() / RobotService.save() / UserService.delete(), so read and write paths now share one self-detection idiom anchored on UUID equality. Applied to client, robot, and user getOne. Tests cover: - self-by-id and self-by-name (same entity) bypass permissions - self-by-name where the loaded entity's id differs from the actor's triggers the deferred preEvaluateOneOf and surfaces ForbiddenError
Summary by CodeRabbit
Documentation
New Features
Tests