Skip to content

fix: restore +secret field selection on GET /clients/:id - #3023

Merged
tada5hi merged 5 commits into
masterfrom
fix/client-get-fields-secret-regression
Apr 28, 2026
Merged

tada5hi merged 5 commits into
masterfrom
fix/client-get-fields-secret-regression

Conversation

@tada5hi

@tada5hi tada5hi commented Apr 28, 2026 •

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • Documentation

    • Updated commit message guidelines to disallow AI-attribution trailers.
  • New Features

    • Endpoints now forward query parameters when retrieving client and robot resources.
    • Repository/service lookups accept optional query filters and realm resolution.
    • Services recognize and optimize access when the caller is the same client/robot ("self").
  • Tests

    • Expanded unit tests to cover query forwarding, self-access behavior, and permission handling.

Copilot AI review requested due to automatic review settings April 28, 2026 14:35
@coderabbitai

coderabbitai Bot commented Apr 28, 2026 •

Copy link
Copy Markdown

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: d04dcc77-38da-425c-a152-db96e093c8ea

📥 Commits

Reviewing files that changed from the base of the PR and between 5e7d91a and 51038e0.

📒 Files selected for processing (6)
  • apps/server-core/src/core/entities/client/service.ts
  • apps/server-core/src/core/entities/robot/service.ts
  • apps/server-core/src/core/entities/user/service.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/user/service.spec.ts

📝 Walkthrough

Walkthrough

Introduces repository-level findOne methods and threads request query through controllers → services → repositories; updates service getOne signatures to accept query and implement self-access detection that can skip authorization checks; adds tests and a docs note banning AI-attribution commit trailers.

Changes

Cohort / File(s) Summary
Documentation
AGENTS.md
Adds guideline prohibiting AI-attribution trailers (e.g., Co-Authored-By: Claude ...) in commit messages.
Controllers
apps/server-core/src/adapters/http/controllers/entities/client/module.ts, apps/server-core/src/adapters/http/controllers/entities/robot/module.ts
Controllers now forward useRequestQuery(req) into service getOne calls (realmId becomes the 4th arg).
Repositories
apps/server-core/src/app/modules/database/repositories/client/repository.ts, apps/server-core/src/app/modules/database/repositories/robot/repository.ts
Add findOne(id, query?, realm?) methods that resolve by UUID or name (LIKE), optionally constrain by realm (early null on unresolved realm), apply applyQuery for allowed fields/relations, then return one entity.
Services
apps/server-core/src/core/entities/client/service.ts, apps/server-core/src/core/entities/robot/service.ts, apps/server-core/src/core/entities/user/service.ts
getOne signatures accept optional query; services delegate to repository.findOne, detect "isMe" (self) by id or name, and skip pre-/post-authorization when self remains true; if resolution mismatches, services fall back to normal authorization flow.
Types
apps/server-core/src/core/entities/client/types.ts, apps/server-core/src/core/entities/robot/types.ts
Repository interfaces gain findOne(id, query?, realm?); service getOne signatures updated to accept optional query.
Tests
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/user/service.spec.ts
Unit tests updated/added: fake repositories implement findOne, tests assert forwarding of query/realmId, self-access bypass of permission checks, and permission enforcement when resolved entity differs from actor.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

🐰 I hopped through controllers, services, and DB,
I nudged queries onward, then napped by a tree,
If you're the same rabbit, the gates stay wide,
Else the guards wake up — rules well applied. 🥕

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the primary fix: restoring the +secret field selection functionality on the GET /clients/:id endpoint, which aligns with the core changes across repository, service, and type definitions.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/client-get-fields-secret-regression

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.

Copilot AI 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.

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 optional query object and forward controller query params to it.
  • Update ClientService.getOne() to use findMany() with an enforced id/name filter when a query is provided (enabling +secret field 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.

Comment on lines 136 to 138
if (!entity) {
throw new NotFoundError();
}

Copilot AI Apr 28, 2026

Copy link

Choose a reason for hiding this comment

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

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.

Copilot uses AI. Check for mistakes.
filter.realm_id = realm.id;
}

const { data } = await this.repository.findMany({ ...query, filter });

Copilot AI Apr 28, 2026

Copy link

Choose a reason for hiding this comment

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

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.

Suggested change
const { data } = await this.repository.findMany({ ...query, filter });
const { data } = await this.repository.findMany({
...query,
filter,
offset: 0,
limit: 1,
});

Copilot uses AI. Check for mistakes.
Comment on lines +118 to +119
const { data } = await this.repository.findMany({ ...query, filter });
entity = data[0] ?? null;

Copilot AI Apr 28, 2026

Copy link

Choose a reason for hiding this comment

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

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.

Suggested change
const { data } = await this.repository.findMany({ ...query, filter });
entity = data[0] ?? null;
entity = await this.repository.findOne({ ...query, filter });

Copilot uses AI. Check for mistakes.
tada5hi added 2 commits April 28, 2026 16:48
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
@tada5hi
tada5hi force-pushed the fix/client-get-fields-secret-regression branch from 2a54c53 to 29e8338 Compare April 28, 2026 15:02
tada5hi added 2 commits April 28, 2026 17:15
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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (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

📥 Commits

Reviewing files that changed from the base of the PR and between 5d8c0bf and 5e7d91a.

📒 Files selected for processing (11)
  • AGENTS.md
  • apps/server-core/src/adapters/http/controllers/entities/client/module.ts
  • apps/server-core/src/adapters/http/controllers/entities/robot/module.ts
  • apps/server-core/src/app/modules/database/repositories/client/repository.ts
  • apps/server-core/src/app/modules/database/repositories/robot/repository.ts
  • apps/server-core/src/core/entities/client/service.ts
  • apps/server-core/src/core/entities/client/types.ts
  • apps/server-core/src/core/entities/robot/service.ts
  • apps/server-core/src/core/entities/robot/types.ts
  • apps/server-core/test/unit/core/entities/client/service.spec.ts
  • apps/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 });

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

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.

Suggested change
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.

Comment on lines +104 to +125
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);

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 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
@tada5hi
tada5hi merged commit cc789a9 into master Apr 28, 2026
3 of 4 checks passed
@tada5hi
tada5hi deleted the fix/client-get-fields-secret-regression branch April 28, 2026 20:58
@github-actions github-actions Bot mentioned this pull request Apr 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants