Skip to content

feat(service-bridge): /v1 engine read ops — search, attachments, filters/sort, sub-collection paging - #22

Merged
PMQ9 merged 5 commits into
wiki-v2from
feat/159-v1-engine-service-bridge-ops
Sep 8, 2026
Merged

PMQ9 merged 5 commits into
wiki-v2from
feat/159-v1-engine-service-bridge-ops

Conversation

@PMQ9

@PMQ9 PMQ9 commented Sep 8, 2026

Copy link
Copy Markdown

What

The paired fork half of the /v1 API engine expansion (super-repo epic cccvu/wiki-v2#213, audit cccvu/wiki-v2#159). Four read-only service-bridge ops the platform's next /v1 commits consume. All changes live inside the CCC service-bridge/ subtree (fork-owned, boundary-excluded) plus the canonical service-bridge.openapi.json — no upstream-owned file is edited (check-upstream-boundary.sh passes).

Per the established paired-merge order, this PR merges first, then a single super-repo commit bumps the docmost/ submodule onto the merged SHA, then the platform consumers land.

The four ops

  1. POST /api/service/content/search (content:search) — exposes the fork's PDP-gated PdpSearchService (filter-then-retrieve; ADR-0005) so /v1 search can retire the broad-principal 503. A separate ServiceSearchService (keeps ServiceContentService's "no authorization collaborator" arity-2 invariant); ServiceBridgeModule now imports SearchModule (seam CCC header lockup + sidebar icon rail (incl. settings rail) #5 binds SearchService→PdpSearchService in remote mode). PII-free projection: no creatorId (ADR-0001), no rank/count (no side-channel).
  2. Attachments (attachments:read) — GET /api/service/attachments/:id/page (resolve attachment→page; Option A, no PDP tuple) + GET /api/service/attachments/by-page/:pageId (compact type='file' list). The bytes are not served here — the platform streams them through Docmost's native GET /api/files/:id/:name.
  3. Content-list filters + generalized sort keyset (content:read) — allowlisted filters (pages: parentPageId, titleContains, creatorId, updatedSince/Until; spaces: nameContains, date ranges) + sort {field,direction} pushed into the keyset SQL. Text sorts coalesce null→''; the cursor gains a generic value (legacy updatedAt still decodes).
  4. Opt-in sub-collection paging — {limit, before} keyset paging on space members + page ACL reads.

Backward compatibility (load-bearing)

Every change is additive and backward-compatible: with no new fields the compiled SQL is byte-identical to today (the content default keyset, created_at asc for sub-collections), and the response shapes are unchanged. So the currently-deployed platform keeps working across the submodule bump — the super-repo consumers opt into the new capabilities only after they land.

Tests

  • Unit (Kysely-spy SQL shape + projections) + the wire/contract/coverage fitness specs (openapi ↔ implementation ↔ scope map) — 18 service-bridge suites, 162 tests.
  • Real-Postgres (service-content.pg.spec.ts, service-space.pg.spec.ts): the generalized sort keyset (title asc across a duplicate-title boundary, null-coalesce, createdAt) and the sub-collection keyset (members walk across a shared-ms tie) page with no skip and no duplicate.
  • nest build (full typecheck), the AGPL import-boundary spec, and check-upstream-boundary.sh all green. service-bridge.openapi.json extended (2 new schemas + ContentSearchRequest + PublicAttachmentSummary + the two new paths + query params).

🤖 Generated with Claude Code

PMQ9 and others added 4 commits September 8, 2026 09:30
…rch)

Expose the fork's PDP-gated PdpSearchService as POST /api/service/content/search so
the platform's /v1 search can retire the broad-principal 503: search IS the
authorization gate (filter-then-retrieve; ADR-0005), not a privileged data plane, so
a principal too broad to LIST can still SEARCH.

- New ServiceSearchService — a SEPARATE provider from ServiceContentService, which
  keeps its structural "no authorization collaborator" invariant (the arity-2 proof
  in service-content.service.spec.ts). It injects the SearchService token, bound to
  PdpSearchService in AUTHZ_MODE=remote via seam #5 (ServiceBridgeModule now imports
  SearchModule — no cycle: SearchModule imports no modules).
- New least-privilege scope ServiceScope.ContentSearch, distinct from content:read.
- PII-free projection: drops creatorId (an ADR-0001 Docmost-user-id leak) and
  rank/slugId (no ranking side-channel). Keeps space{id,name,slug}; ISO timestamps.
- Wire/contract/coverage specs + service-bridge.openapi.json (ContentSearchRequest +
  PublicSearchHit) updated; a unit spec proves the projection, the userId/workspace
  threading, and that no shareId leaks onto the authenticated path.

Consumed by the platform's POST /v1/search (cccvu/wiki-v2#159, commit C11).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…:read)

Two read-only ops backing the platform's /v1 attachment surface (Option A —
resolve→page, no attachment tuple in the PDP):
- GET /api/service/attachments/:attachmentId/page → { attachmentId, pageId, spaceId }.
  The platform maps attachment→page, then authorizes page#view/#edit ITSELF (the
  schema already inherits attachment access from the page). pageId/spaceId are null
  for non-page attachments (avatars, workspace/space icons, chat), so the platform
  denies them. Workspace-scoped, active only; unknown/cross-workspace/deleted → 404.
- GET /api/service/attachments/by-page/:pageId → { items: PublicAttachmentSummary[] }.
  type='file' rows only, workspace-scoped + soft-delete-excluded, compact projection.

New ServiceAttachmentController + ServiceAttachmentService + ServiceScope.AttachmentsRead.
The service reads the attachments table with raw `sql` (mirroring ServiceContentService)
rather than adding a method to the upstream AttachmentRepo — so every change stays inside
the CCC service-bridge subtree (no upstream-owned-file edit, no boundary-check divergence).

Coverage/contract specs + service-bridge.openapi.json (PublicAttachmentSummary + the two
paths + attachments tag) updated; a unit spec proves the workspace/soft-delete scoping,
the null-page projection, the file-type filter, and the int8→number fileSize coercion.

The bytes themselves are NOT served here: the platform streams them through Docmost's
existing native GET /api/files/:id/:name. Consumed by /v1 attachments (cccvu/wiki-v2#159, C10).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…n content lists

Extend the /v1 content read model (listPagesByIds / listSpacesByIds) with an allowlist
of filters and a configurable sort key, all pushed into the keyset SQL (never a
post-filter). BACKWARD-COMPATIBLE: with no `sort`/filters the compiled SQL is
byte-identical to today (`date_trunc('milliseconds', updated_at) desc`, id-tiebroken),
so an un-updated platform (the C9 submodule-bump gap) and the SQL-shape guard tests are
unchanged.

- Filters (allowlist only): pages — parentPageId, titleContains (ilike; metacharacters
  escaped so %/_ match literally), creatorId (the platform translates identity→docmost
  id BEFORE calling), updatedSince/Until; spaces — nameContains, createdSince/Until,
  updatedSince/Until.
- Sort field∈{updatedAt,createdAt,title|name} × direction asc|desc, always id-tiebroken.
  title is pages-only / name spaces-only (a cross-resource field is a 400). The keyset
  generalizes to `(sortExpr, id) <op> (value, id)`; text sorts coalesce null→'' so null
  titles/names page deterministically. ContentCursorDto gains a generic `value` (the
  legacy `updatedAt` still decodes) — cursor encode/decode stays on the platform.
- Real-Postgres proof (service-content.pg.spec.ts): title asc walks the whole set two at
  a time across a duplicate-title boundary with NO skip and NO duplicate; a null title
  coalesces first; createdAt desc orders on created_at; titleContains narrows on the
  engine. Plus SQL-shape unit tests + the openapi ContentListRequest schema (the new
  fields + the generalized `before`).

Consumed by /v1 list filtering + sort + cursor-v2 (cccvu/wiki-v2#159, C12).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…CL reads

Add opt-in {limit, before} keyset paging to the two bare sub-collection reads
(GET /spaces/:id/members, GET /pages/:id/permissions). BACKWARD-COMPATIBLE: without
`limit` the reads stay unpaged and the query is byte-identical to today (`created_at
asc`), so an un-updated platform (the C9 submodule-bump gap) keeps getting all rows; the
response shapes (a bare array / {items}) are unchanged either way.

- Shared parseSubCollectionQuery({limit, beforeCreatedAt, beforeId}) — paging is opt-in
  on `limit`; a malformed limit, a half-supplied cursor, a cursor without a limit, or a
  non-ISO timestamp is a 400 (never a 500 at the SQL cast). Cap 200.
- When paged: walk `(date_trunc('milliseconds', created_at), id::text)` ascending
  (id-tiebroken, ms-truncated — the same discipline as the content keyset) and return
  limit+1 so the platform detects hasMore + builds the next cursor from the last kept row.
- Real-Postgres proof (service-space.pg.spec.ts): a 4-member walk across a shared-ms tie
  pages with NO skip and NO duplicate; unpaged still returns all members. Plus parser unit
  tests + SQL-shape unit tests for both reads + the openapi query params.

Consumed by /v1 opt-in members/permissions pagination (cccvu/wiki-v2#159, C14).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@PMQ9

PMQ9 commented Sep 8, 2026

Copy link
Copy Markdown
Author

🎨 Frontend / UI / UX Review

Reviewer: Frontend / UI / UX Reviewer
Model: Claude Opus 4.8
PR / Diff: #22 — feat(service-bridge): /v1 engine read ops @ e6c5ea19ea2c2d7ddd82a945128c3c3507bb506e
Visual check: not applicable — the diff has no renderable surface. All 24 changed files are server-side TypeScript + specs under apps/server/src/service-bridge/ (a AUTHZ_MODE=remote, non-browser-facing machine-to-machine API) plus one OpenAPI JSON doc. No components, JSX/TSX/Vue/Svelte, CSS/Tailwind, tokens, images, or anything that renders.
Design system: n/a — no client/UI code in scope, so no tokens or component library to hold the diff to.
Verdict: No frontend concerns — nothing user-facing in this diff.

Summary: This is a pure back-end service-bridge change (4 read-only M2M ops: content search, attachment→page resolution, content-list filters/sort, opt-in sub-collection keyset paging) with its OpenAPI contract. There is no UI surface for a frontend/UX lens to assess, so nothing here blocks merge on frontend grounds. Correctness, security (the privileged-data-plane vs authorization-gate distinction), performance (keyset SQL), and API/contract design belong to the sibling reviewers. One minor, pre-existing response-shape consistency observation is noted below as a cross-lane hand-off, not a defect this PR introduces.


Findings

2. Is it consistent with the rest of the app? (API-contract consistency — cross-lane note)

[Minor · Priority 2 · optional] — API response-shape consistency — docs/integrations/authorization/service-bridge.openapi.json

What: The new/adjacent collection ops are not uniform in their envelope. searchContent, listPageAttachments, and the page-ACL read return { items: [...] }, whereas listSpaceMembers returns a bare top-level array. For a machine client generating typed models from this contract, a mixed "sometimes {items}, sometimes bare array" convention is a small ongoing papercut (per-endpoint unwrap logic, easy to mis-type).
Who it hurts: the integrating platform's /v1 client code (a machine consumer, not a human) — marginally more contract surface to special-case; no end user is affected.
Fix: none warranted in this PR. The OpenAPI description explicitly documents the bare array as the unchanged, backward-compatible shape ("The response shape is unchanged (a bare array) either way"), so it is pre-existing and correctly preserved — normalizing it to {items} would be a breaking change and is out of scope. Flagging only for the API-design/architecture reviewer to decide whether a future contract version unifies the two. Not attributable to this PR; not blocking.


Checklist coverage

  • State & data correctness: – (no client state / rendered data in scope)
  • State coverage (loading / empty / error / disabled / focus): – (no UI states; note the API models empty results as {items:[]} / empty page — correct for the data plane)
  • Design-system adherence (tokens, variants, no one-offs): – (no UI)
  • Shared-primitive blast radius (callers checked): – (no shared UI primitive touched)
  • Bundle & load cost: – (no client bundle affected)
  • Runtime & rendering cost (CLS, thrash, waterfalls): – (nothing renders)
  • Accessibility (semantics, keyboard, focus, contrast, ARIA): – (no interactive surface)
  • Responsive & interaction UX (320→1440px, touch, error copy): – (no viewport / touch surface; API error copy is machine-facing and consistently specified via the shared BadRequest/Unauthorized/… responses)

Deferred to other reviewers

  • Privileged-data-plane vs authorization-gate semantics (search re-authorizes, list ops don't) and the "no creatorId / no rank" PII/side-channel invariants → pr-security-review.
  • Keyset-paging correctness (limit+1, (created_at,id) tiebreak, null-coalesced text sort, cursor-v2 back-compat) → pr-correctness-reviewer / pr-testing-reviewer.
  • Generalized keyset SQL push-down and byte-identical-default claim → pr-performance-reviewer.
  • The bare-array vs {items} contract-shape consistency above → pr-architecture-review / API-design lens.

@PMQ9

PMQ9 commented Sep 8, 2026

Copy link
Copy Markdown
Author

⚡ Performance Review

Reviewer: Performance Reviewer
Model: Claude Opus 4.8
PR / Diff: #22 (service-bridge read ops — search, attachment resolve/list, content-list filters + keyset sort, opt-in sub-collection paging) @ e6c5ea19ea2c2d7ddd82a945128c3c3507bb506e
Verdict: Merge OK, minor notes — no merge-blocking performance concerns.

Summary: Every new/changed op issues a single bounded SQL query (plus one lightweight resolveDefaultWorkspaceId); there is no N+1, no query-in-a-loop, no blocking I/O, and no unbounded materialization in the diff. The two things a perf reviewer would flinch at — the ilike '%…%' leading-wildcard filters and the expression-based keyset ORDER BY — are both safe here because they run over an already-bounded row set (an id-set-gated candidate set, or a single space's/page's rows), not a full-table scan. Two low-priority optional notes below; neither blocks merge.


Findings

[Minor] — Caching — apps/server/src/service-bridge/workspace-resolver.ts:24 (call sites added in this PR: service-search.service.ts:757, service-attachment.service.ts resolvePage/listByPage)

What: resolveDefaultWorkspaceId() runs SELECT id FROM workspaces WHERE deleted_at IS NULL ORDER BY created_at ASC LIMIT 1 on every service-bridge request. This PR adds three more call sites (the search op + the two attachment ops), so every /v1 search and attachment lookup now pays this extra round-trip on top of its own query.
Why it costs: One extra DB round-trip per request. It is not an N+1 (it runs once per request, not per row) and the query is cheap, so the cost is small and constant — but the resolved value is, by this module's own single-tenant invariant, effectively immutable for the process lifetime, so the query is pure repeated work.
Fix: This is a pre-existing shared pattern (all service-bridge ops already call it); the PR only follows it, so it is genuinely optional and out of this PR's core scope. If addressed, memoize the canonical workspace id in WorkspaceResolver (e.g. cache the resolved id with a short TTL, or a process-lifetime memo with an invalidation hook), which removes the extra round-trip from every op at once rather than per-endpoint. Optional. Priority Level 2 (Low).

[Nit] — Expensive-set ceiling (informational) — apps/server/src/service-bridge/service-content.service.ts:115 (listPagesByIds) / :141 (listSpacesByIds)

What: The content-list ops select the id = any($ids::uuid[]) candidate rows, then apply the new ilike / range filters and the generalized expression ORDER BY (coalesce(title,''), date_trunc('milliseconds', …), id::text) over that result set. CONTENT_LIST_MAX_IDS = 10_000, so a single call can fetch, filter and sort up to ~10k rows in memory before the limit+1 slice.
Why it costs: The per-call work scales with the caller-supplied id-set size (up to 10k), and the expression ORDER BY cannot use a column btree index, so Postgres always plans a sort node over that set. This is bounded and pre-existing — the legacy default path already sorted the same id-gated set by date_trunc(updated_at) desc, id::text desc; the new filters only narrow it and the generalized sort keeps the same cost class. No regression, and no action needed at realistic authorized-id-set sizes.
Fix: None required. Documenting the ceiling so it is a conscious bound: the dominant cost of these ops is the id-set fetch + in-memory sort, gated by CONTENT_LIST_MAX_IDS, not the new ilike/range predicates. Optional / informational. Priority Level 1 (Trivial).


Checklist coverage

  • N+1 queries: ✅ clean — each op (searchContent, resolvePage, listByPage, listPagesByIds, listSpacesByIds, listMembers, listPagePermissions) issues one SQL statement; the added filters/keyset/sort are pushed into that one statement, not iterated. No DB/API call inside any loop.
  • Unnecessary / repeated DB calls: ⚠️ one note — resolveDefaultWorkspaceId is an uncached per-request query, now with 3 more callers (finding above, P2). Otherwise no double-fetch; projections select only needed columns.
  • Expensive loops: ✅ clean — the only per-row loop is res.rows.map(toSummary/toSearchHit) (a pure O(rows) projection over an already-limit-bounded set). No accidental quadratic work, no per-iteration DB/recompute.
  • Memory allocations: ✅ clean — bounded result sets (limit+1, or id-set-capped ≤ CONTENT_LIST_MAX_IDS); no whole-table materialization, no unbounded accumulation. new Set in assertSortAllowed and the likeEscape regex run once per request — negligible.
  • Async misuse: ✅ clean — one await per op for the workspace id then one for the query; nothing independent is serialized. Search offset has no DTO @Max, but PdpSearchService caps the candidate scan at HARD_SCAN_CAP = 2048 rows (≤16 windows) regardless of offset, so it stays bounded — not a perf hole.
  • Blocking I/O: ✅ clean — all I/O is async Kysely/sql execution; no sync fs/network on the request path.
  • Caching opportunities: ⚠️ resolveDefaultWorkspaceId (finding above). Note: the ilike '%…%' leading-wildcard filters are not a seq-scan risk here — they are ANDed with id = any($ids::uuid[]), so the pkey fetches the bounded candidate set first and ilike is a cheap post-filter, not a table scan. listByPage is index-backed (idx_attachments_page_id); resolvePage is a pkey read; the sub-collection keyset reads are scoped to a single space_id/page_id. The permission-aware search's candidate-window scan budget lives in the pre-existing PdpSearchService (not in this diff); this PR only wires ServiceSearchService → searchPage.

@PMQ9

PMQ9 commented Sep 8, 2026

Copy link
Copy Markdown
Author

🏛️ Architecture Review

Reviewer: Architecture Reviewer
Model: Claude Opus 4.8
PR / Diff: #22 (feat/159-v1-engine-service-bridge-ops, HEAD e6c5ea19)
Verdict: Merge OK, minor notes — no blocking or Level-3+ findings.

Summary: Four read-only ops added cleanly inside the fork-owned service-bridge/ subtree, faithfully following the established controller→service→raw-sql pattern with matching wire/contract/coverage fitness specs. The AGPL/upstream boundary is respected (no upstream-owned file touched; SearchModule's seam #5 is imported, not modified), the search op is correctly split into its own provider to preserve ServiceContentService's arity-2 invariant, and every change is additive/backward-compatible. Findings are all minor polish: a hidden sort-guard precondition, an inconsistency in filter-vs-sort strictness on the shared ContentListDto, and two small consistency/duplication nits. None block merge.


Findings

[Minor] — Coupling / Abstraction boundaries — apps/server/src/service-bridge/service-content.service.ts:1051 (assertSortAllowed) vs :1085 (sortExpr)

What: sortExpr(field, textCol) and keysetCond(...) silently depend on assertSortAllowed(sort, textCol) having run first — its own comment says "assertSortAllowed guarantees field matches textCol." The validation is a separate step each public list method must remember to invoke before the SQL builders. If a future third list method (or a refactor) calls orderClause/keysetCond without the guard, sortExpr('title','name') emits coalesce(title,'') against spaces (a column that doesn't exist) → a 500, not a 400.
Why it costs: The safety of the generated SQL rests on call-order the type system doesn't enforce (temporal coupling). The next person extending this — the whole point of the generalized keyset — has to know the implicit precondition, and forgetting it fails at the DB, not at validation.
Fix: Make the illegal state unrepresentable: fold the resource check into the builder, e.g. a single resolveSort(sort, textCol) that validates once and returns { order, keyset }, or have sortExpr throw on a field∉{updatedAt,createdAt,textCol} itself. Then no caller can build invalid SQL by skipping a step. Optional; Level 2.

[Minor] — API / contract design — apps/server/src/service-bridge/dto/content-read.dto.ts:67 (ContentListDto) + service-content.service.ts:129,148

What: ContentListDto is a single shape carrying pages-only (parentPageId, titleContains, creatorId), spaces-only (nameContains, createdSince/Until), and shared fields, used by both listPagesByIds and listSpacesByIds. A cross-resource sort field is rejected with 400 (assertSortAllowed), but a cross-resource filter is silently ignored — send titleContains to /spaces/list and you get all spaces unfiltered, no error. The DTO also admits nonsensical combinations (parentPageId + nameContains together).
Why it costs: Inconsistent strictness (strict on sort, lenient on filters) is a surprising contract, and the silent drop can mask a caller bug as "unexpectedly broad results." The belt (authorized ids) means this is not a security leak — filters only narrow an already-authorized set — but it's a correctness-of-shape footgun for the consumer. It's a loose internal REST contract with a single trusted caller, so this is a real-but-low concern, not a blocker.
Fix: Either reject a filter that isn't valid for the addressed resource (symmetric with the sort 400), or explicitly document the silent-drop-by-resource contract on the DTO/openapi so the platform author knows a mis-targeted filter is a no-op. Optional; Level 2.

[Nit] — Code organization — apps/server/src/service-bridge/dto/sub-collection-page.dto.ts:26 (parseSubCollectionQuery)

What: Sub-collection paging validates input via a hand-rolled parseSubCollectionQuery(rawLimit, beforeCreatedAt, beforeId) taking three raw @Query() strings, whereas the rest of the module validates through class-validator DTOs (ContentListDto, ContentSearchDto). Two input-validation idioms now live side by side in one module.
Why it costs: A reader has to learn two patterns for "how does this endpoint validate query input." Minor.
Note / Fix: This is defensible — the cross-field rules (beforeCreatedAt+beforeId must come together; a cursor requires limit; 400-not-500 on a bad cast) are awkward in class-validator and clearer as an explicit, well-tested function. If left as-is, a one-line comment pointing at why it isn't a DTO would close the gap. Optional; Level 1.

[Nit] DOCS: — Responsibilities / documentation — apps/server/src/service-bridge/service-content.controller.ts:28

What: The class docstring asserts "A PRIVILEGED DATA PLANE, NOT an authorization gate: … these endpoints … do NOT re-authorize." The controller now also hosts search, which the code + its inline comment correctly call out as the opposite — it IS the authorization gate. The class-level blanket claim is now inaccurate for one of its handlers.
Why it costs: A future reader trusting the class doc could wrongly assume the search result is a pre-authorized data plane and post-filter it (exactly what the search handler warns against). Doc-only.
Fix: Add one clause to the class docstring noting search is the exception (self-gating via PdpSearchService). Optional; Level 1.

[Nit] — Coupling — apps/server/src/service-bridge/dto/content-search.dto.ts:17 (CONTENT_SEARCH_MAX_LIMIT = 100)

What: The 100 search page-size cap is duplicated across CONTENT_SEARCH_MAX_LIMIT (DTO), PdpSearchService.MAX_LIMIT (private static), and the openapi maximum: 100 — three places that must move together.
Why it costs: Change the server clamp and two other spots silently drift. Low: the DTO comment acknowledges the mirror and the server re-clamps regardless (PdpSearchService.MAX_LIMIT is private, so it can't be imported directly), so this is pragmatic. Optional; Level 1.


Positive notes (what the design gets right)

  • Boundary discipline is correct. No upstream-owned file is edited: search.module.ts's seam CCC header lockup + sidebar icon rail (incl. settings rail) #5 (the SearchService→PdpSearchService mode binding) is imported, not modified, and the attachment reads use raw sql against the attachments table precisely to avoid an upstream AttachmentRepo edit — consistent with ServiceContentService's existing pattern. Importing SearchModule into ServiceBridgeModule is a fork-owned-file change, not an upstream one, and it's safe (Nest dedupes the module already imported by CoreModule, so SearchController isn't double-registered; SearchModule imports no modules, so no cycle). The "should this have been an UPSTREAM_MODIFICATIONS edit?" question the review was asked to check: correctly answered — it shouldn't, and it isn't.
  • Search is split into its own ServiceSearchService rather than bolted onto ServiceContentService, deliberately preserving the latter's structural "no authorization collaborator" (arity-2) invariant. Good separation: privileged-data-plane vs authorization-gate stay distinct providers even though search is route-grouped under /content. The attachment op correctly gets its own controller because it's a new top-level /attachments route prefix — the controller-per-prefix convention is applied consistently.
  • Backward compatibility is engineered, not assumed. orderClause/keysetCond emit byte-identical legacy SQL when sort is absent, sub-collection paging is opt-in on limit, and the cursor before relaxation (updatedAt now optional + generic value) is additive — proven by both Kysely-spy shape tests and real-Postgres no-skip/no-dupe walks.
  • Anti-corruption mapping is clean: toSearchHit/toAttachmentSummary isolate the wire shape from upstream SearchResponseDto/table columns and drop the leak-prone fields (creatorId/rank/slugId), and the fitness specs (scope-coverage, contract openapi↔return-type, wire envelope) were extended in lockstep with the new controller/scopes.

Checklist coverage

  • Separation of concerns: ✅ — search (gate) vs content list (data plane) kept in distinct providers; mappers isolate projection from persistence.
  • Layering: ✅ — service-bridge depends inward on core/, authz/; no upward dependency; AGPL out-of-process boundary untouched.
  • Responsibilities: ⚠️ — DOCS: content controller docstring no longer describes its search handler (Level 1).
  • Coupling: ⚠️ — temporal coupling on the sort guard (Level 2); duplicated 100 limit constant (Level 1).
  • Abstraction boundaries: ✅ — raw-sql reads and RawBuilder fragments stay internal to the service; public shapes are plain interfaces.
  • API / contract design: ⚠️ — asymmetric strictness (filter silently dropped vs sort 400) on the shared ContentListDto (Level 2).
  • Code organization: ⚠️ — two query-input validation idioms in one module (Level 1, defensible).
  • Maintainability & change cost: ✅ — additive, backward-compatible, well-covered by unit + real-PG + fitness specs; no over-engineering (each new capability has a named C-series consumer).

@PMQ9

PMQ9 commented Sep 8, 2026

Copy link
Copy Markdown
Author

🧪 Test Review — QA Engineer's Eye

Reviewer role: Test Reviewer
Model: Claude Opus 4.8
PR / change: #22 — feat(service-bridge): /v1 engine read ops — search, attachments, filters/sort, sub-collection paging
Date: 2026-09-08
HEAD: e6c5ea19ea2c2d7ddd82a945128c3c3507bb506e

Verdict

💬 Comment

Genuinely well-tested — every new branch I enumerated has a test that would fail if it broke, and the keyset walks, the PII-projection, and the backward-compat default paths are all pinned with real assertions. I found no merge-blocking gap. Two optional depth gaps are worth the author's attention before merge (both Priority 3, both optional): the two new attachment SQL queries are never executed against real Postgres (only string-matched by the Kysely spy), and the class-validator DTO 400 paths are never run through a ValidationPipe.

Summary

The PR adds four read-only service-bridge ops: PDP-gated content search (ServiceSearchService), attachment resolve→page + by-page list (ServiceAttachmentService), allowlisted content filters + a generalized sort keyset (ServiceContentService), and opt-in {limit, before} sub-collection paging on space members + page ACLs. The security-load-bearing behaviors are the PII-free search projection (drop creatorId/rank/slugId), the byte-identical legacy SQL on the default path, and no-skip/no-duplicate keyset walks. I ran the non-pg suites: 18 suites / 162 tests green. A regression of the core behaviors here would be caught — the projection test asserts field absence, the default-path tests use negative assertions (not.toContain('coalesce(')), and the pg walks verify the tiebreak. The gaps are at the edges: unexecuted attachment SQL, untested declarative validators, and a couple of untested defensive 400 branches.

Findings

🟠 Major (optional, Priority 3) — The two new attachment queries are never executed on real Postgres

  • Category: Right layer / mocking the thing under test
  • Location: service-attachment.service.ts:486 (resolvePage) & :502 (listByPage) / only service-attachment.service.spec.ts (Kysely-spy, no .pg.spec.ts)
  • Gap: ServiceContentService and ServiceSpaceService each got a .pg.spec.ts that runs their raw SQL against a real schema — precisely because the Kysely spy never executes the query (it returns canned rows from respond). The new ServiceAttachmentService has no pg spec. Its raw column list (page_id, space_id, file_name, mime_type, file_size, type, created_at), the type = 'file' predicate, and workspace-scoping are only proven by sql.toLowerCase().toContain('from attachments')-style string matches.
  • Why it slips through: Rename file_size → filesize in the raw SQL (or mistype the table) and every attachment spec stays green — the spy asserts on the compiled string fragments and the mock rows, and nest build does not typecheck raw sql template contents. The wrong query would only fail in production.
  • Regression risk: A future column rename / schema migration silently breaks listByPage/resolvePage with a green suite.
  • Suggested test: Add service-attachment.pg.spec.ts mirroring the existing pg harness: insert a file, an avatar, a soft-deleted file, and a cross-workspace file; assert listByPage returns only the live file (correct fileSize coercion) and resolvePage returns the owning page/space, null for the avatar, and 404 for cross-workspace. Low effort given mkReadModelPg/createReadModelTables already exist.

🟠 Major (optional, Priority 3) — DTO 400 validation paths are never exercised through a ValidationPipe

  • Category: Uncovered failure mode
  • Location: dto/content-search.dto.ts, dto/content-read.dto.ts (ContentSortDto, filter fields) / no spec runs class-validator
  • Gap: The service-level 400s (assertSortAllowed cross-resource, keysetCond missing bound) and the hand-rolled parseSubCollectionQuery 400s are all well tested. But the declarative DTO constraints are not: the wire harness (service-bridge.wire.spec.ts:60-63) mounts the global prefix + interceptor but no useGlobalPipes(new ValidationPipe(...)), and no spec constructs a DTO and calls validate(). So @IsNotEmpty()/@MaxLength(1024) on query, @Max(100)/@Min(1) on limit, @IsUUID() on creatorId/parentPageId, @IsIn(CONTENT_SORT_FIELDS) on sort.field, and @IsISO8601() on the date filters have zero coverage.
  • Why it slips through: Delete @IsNotEmpty() from query, or @Max(CONTENT_SEARCH_MAX_LIMIT) from limit, and nothing reds. The stated design intent — "a malformed cursor is a 400 at validation, not a 500 at the cast" — is proven for the sub-collection function but not for these DTOs; a dropped @IsUUID() on parentPageId/creatorId would let a non-uuid reach ${dto.parentPageId} and 500 at the SQL bind.
  • Regression risk: A refactor that reshuffles/removes a decorator turns a clean 400 into a 500 or an unbounded input, with a green suite.
  • Suggested test: A small content-search.dto.spec.ts (and a few ContentListDto cases) using plainToInstance + validate() from class-validator: assert query:'' → non-empty error, limit:101 / limit:0 → range error, creatorId:'not-uuid' → uuid error, sort:{field:'bogus',direction:'asc'} → IsIn error. Mirrors the parseSubCollectionQuery spec that already exists for the hand-rolled path.

🟡 Minor (optional, Priority 2) — Legacy-path keyset cursor missing updatedAt → 400 is an untested branch

  • Category: Untested behavior
  • Location: service-content.service.ts:1072 — keysetCond default branch (if (before.updatedAt === undefined) throw new BadRequestException('cursor is missing updatedAt')) / no test
  • Gap: ContentCursorDto.updatedAt is now optional, so a caller can send before:{id:'x'} with no sort, which hits this legacy-path guard. The sort-path analog ("a text-sort cursor missing its bound value is a 400") is tested; the legacy analog is not.
  • Why it slips through: Delete that if/throw and every test still passes — the default-path tests never pass a before, and every test that passes a before also passes a sort (routing to the other branch) or a full updatedAt.
  • Regression risk: Losing the guard turns a malformed legacy cursor into a 500 at ${undefined}::timestamptz instead of a 400.
  • Suggested test: svc.listPagesByIds({ ids: IDS, before: { id: 'x' }, limit: 10 }) (no sort, no updatedAt) → rejects.toBeInstanceOf(BadRequestException).

🟡 Minor (optional, Priority 2) — Text-keyset no-skip across a duplicate-value page boundary isn't directly exercised

  • Category: Missing edge case
  • Location: service-content.pg.spec.ts:758 — the title-asc walk / self
  • Gap: With limit: 2 over ['', apple, banana(92), banana(93), cherry], the two banana rows always land together on page 2, so the cursor is only ever built after a completed duplicate run. The subtle no-skip case — cursor built from the first of a duplicate pair whose partner is on the next page — is never hit on the text keyset. (The members pg walk does hit it for the timestamp keyset: same-ms uuid(41)/uuid(42) straddle the page boundary; and both keysets use the same (expr, id::text) cmp (bound, id) row-tuple, so the mechanism is covered — hence Minor, not Major.)
  • Why it slips through: A bug that mishandled a text-tiebreak split (e.g. >= on the value alone instead of the row-tuple >) could skip banana(93); the current limit-2 walk wouldn't reveal it because 92/93 never split.
  • Regression risk: Low, given the shared construction and the timestamp walk, but the text path's split-duplicate has no dedicated assertion.
  • Suggested test: Re-run the title walk with limit: 3 (page 1 ends on banana(92); page 2 must return banana(93) + cherry(94) with no skip), or limit: 1.

🟡 Minor (optional, Priority 2) — parseSubCollectionQuery uses lenient Date.parse, so a non-instant can pass the 400 gate and 500 at the cast

  • Category: Missing edge case
  • Location: dto/sub-collection-page.dto.ts:283 — Number.isNaN(Date.parse(beforeCreatedAt)) / sub-collection-page.dto.spec.ts:229
  • Gap: The comment promises "a 400, not a 500 at the cast," but Date.parse accepts partial strings like '2026' / '2026-01' that ${beforeCreatedAt}::timestamptz will reject at the engine. The ContentCursorDto path uses the stricter @IsISO8601(); this hand-rolled parser doesn't. Only the fully-garbage 'not-a-date' case is tested.
  • Why it slips through: parseSubCollectionQuery('10', '2026', 'm-1') passes validation (no throw), then would 500 in Postgres — but no pg test walks that path, so it's invisible.
  • Regression risk: Low (the platform sends canonical ISO), but the parser under-delivers on its own contract.
  • Suggested test: Either tighten the check to an ISO-8601 regex/@IsISO8601 and add parseSubCollectionQuery('10','2026','m-1') → throws, or document that only well-formed-but-out-of-range is caught.

🟡 Minor (optional, Priority 1) — Trivial defensive branches unasserted (iso() string input, empty attachment list)

  • Category: Untested behavior (low value)
  • Location: service-search.service.ts:1332 / service-attachment.service.ts:455 — iso(d) string branch; listByPage empty-result mapping
  • Gap: Both iso() helpers accept Date | string but every fixture passes a Date, so new Date(d).toISOString() is never hit. listByPage's "unknown page → {items: []}" (per the openapi) has no explicit empty-mapping test.
  • Regression risk: Negligible — defensive coercion and a trivial .map over [].
  • Suggested test: Cheap to add a space:null already exists for search; add one hit with a string createdAt, and a listByPage case returning [].

Coverage map — behaviors vs. tests

Behavior / branch Covered? Test that guards it
Search: userId+workspaceId threaded, never shareId ✅ service-search.service.spec.ts:1255
Search: PII-free projection (drop creatorId/rank/slugId) ✅ strong (asserts absence) ...:1273
Search: null space maps through ✅ ...:1295
Search: DTO validation 400s (query/limit/offset/uuids) ❌ none — Major #2
Search: wire shape bare {items} ✅ service-bridge.wire.spec.ts:98
Search: scope content:search ✅ service-scope-coverage.spec.ts
Attachment: resolvePage page+space, ws-scoped, active ⚠️ shape only service-attachment.service.spec.ts:363 — not executed
Attachment: resolvePage null non-page / 404 unknown ✅ (mock) ...:373, ...:382
Attachment: listByPage file-only, deleted-excl, fileSize coerce ⚠️ shape only ...:389, ...:413 — not executed
Attachment: queries run on real Postgres ❌ none — Major #1
Content: default path = legacy SQL, no coalesce ✅ strong negative service-content.service.spec.ts:812
Content: page/space filters pushed, ilike escaped ✅ ...:822, ...:844
Content: sort createdAt/title/name keyset + coalesce ✅ unit+pg ...:859, ...:872, ...:888 + pg :748
Content: cross-resource sort field → 400 ✅ ...:898
Content: sort-path cursor missing bound → 400 ✅ ...:910
Content: legacy-path cursor missing updatedAt → 400 ❌ none — Minor #3
Content: title keyset duplicate split across page ⚠️ indirect timestamp analog in members pg walk — Minor #4
Content: ilike escape proven on engine ⚠️ pg only tests 'ban' (no metacharacter)
Sub-collection parse: all 400 shapes ✅ strong sub-collection-page.dto.spec.ts
Sub-collection parse: lenient Date.parse edge ⚠️ Minor #5
listMembers unpaged legacy / paged keyset walk ✅ unit+pg service-space.service.spec.ts:1503 + pg :1468
listPagePermissions unpaged / paged keyset ✅ shape only service-content.service.spec.ts:926 — not run on pg (members proves pattern)

What I checked

  • Behavior coverage — each new branch mapped; two untested (legacy-cursor 400, DTO validators) + attachment SQL unexecuted
  • Edge cases and boundaries — ms-truncation ties, same-ms/duplicate-title tiebreaks, null title/name coalesce, null fileSize, limit+1 overflow all pinned; text split-duplicate is the one edge left indirect
  • Failure modes — 404 (attachment), cross-resource 400, missing-bound 400 covered; DTO-level 400s not
  • Assertions are meaningful — projection asserts field absence, default path uses not.toContain, keyset asserts limit+1 param and exact id order; verified they'd go red on a real break
  • Tests aren't brittle — pg fixtures control created_at explicitly (no wall-clock), walks assert set-size not just order, no sleeps/UUID-equality
  • Regression resistance — the PII leak, the byte-identical legacy SQL, and no-skip/no-dupe would all be caught; attachment SQL and validator regressions would NOT
  • Test design — clean; the shared pg harness and Kysely-spy are reused well

Open questions for the author

  1. Was the attachment pg spec deliberately skipped (queries deemed too simple), or is it a follow-up? Content and space each got one for the same raw-SQL pattern.
  2. Is DTO validation intended to be covered by a super-repo/platform-side test (the real /v1 ValidationPipe), rather than here? If so, a one-line note would settle whether the fork owns that coverage.

@PMQ9

PMQ9 commented Sep 8, 2026

Copy link
Copy Markdown
Author

🔒 Security Review

Security Reviewer: Security Reviewer — Claude (independent Security lens, PR #22)
Model: Claude Opus 4.8
PR: #22 — feat(service-bridge): /v1 engine read ops — search, attachments, filters/sort, sub-collection paging
Commit / branch: e6c5ea19ea2c2d7ddd82a945128c3c3507bb506e (feat/159-v1-engine-service-bridge-ops)
Date: 2026-09-08
Files reviewed: 24 changed file(s) — all under apps/server/src/service-bridge/ + docs/integrations/authorization/service-bridge.openapi.json

Verdict

🟡 Approve with comments. No merge-blocking security issues. This is a security-conscious change: every new SQL fragment is parameterized through Kysely's sql tag, ILIKE metacharacters are escaped, the search projection is a genuine construct-new allowlist (not a delete-from), the PDP gate was confirmed authoritative (a caller-supplied spaceId cannot bypass it), and every new read is workspace-scoped + soft-delete-filtered. Three optional hardening notes below (all Priority ≤2); none has a concrete exploit under the service-secret-guarded, platform-only trust model.

Summary

Severity Count
🔴 Critical 0
🟠 High 0
🟡 Medium 0
🔵 Low 1
⚪ Info 2

Task-scale mapping: BLOCKING: 0 · OPTIONAL: 3 · Priority-Level-3+ among optional: 0 · MAXSEV: 2.

What I verified clean (the load-bearing checks)

  • Injection (SQL) — clean. All dynamic values reach Postgres as bound parameters via Kysely sql\…${v}…`; the only interpolated *fragments* (dir/cmp/sortExpr) are hardcoded sql`asc|desc|>|<|coalesce(title,'')…` selected by an allowlisted enum (@isin(CONTENT_SORT_FIELDS)+assertSortAllowed). No user string ever becomes SQL text or an identifier. Tests assert the bound params ('%road\%map%', 'Roadmap', 11, 26`).
  • ILIKE metacharacter escaping — correct. likeEscape escapes \ % _ with a backslash (Postgres' default LIKE escape) and the pattern is a bound parameter, so standard_conforming_strings is irrelevant. A stray %/_ matches literally (service-content.service.ts:31-33).
  • Search auth gate is real and authoritative. In AUTHZ_MODE=remote (the only mode where the whole surface is reachable — RemoteOnlyGuard 404s otherwise) SearchModule binds SearchService → PdpSearchService (search.provider.ts:35-37). ServiceSearchService always passes opts.userId and never shareId, so the per-principal filter-then-retrieve loop runs, and the PDP-backed filterAccessiblePageIds ignores the caller's spaceId and checks view/page per candidate for that userId (pdp-page-permission.repo.ts:52-59). A caller naming a space the user isn't in leaks nothing.
  • PII projection strips what it claims. toSearchHit constructs a new object (id/title/icon/parentPageId/space{id,name,slug}/highlight/dates) — creatorId, rank, slugId are never copied, and space is reconstructed field-by-field (service-search.service.ts:74-86). Guarded by a regression test. No ADR-0001 Docmost-user-id leak, no ADR-0005 rank side-channel.
  • Tenant + soft-delete scoping on every new read. Attachment resolvePage/listByPage both filter workspace_id = … and deleted_at is null (+ type='file' for the list); content filters and both keyset paths are ANDed onto the existing workspace_id/deleted_at is null/ids predicates.
  • Filters can only narrow, never widen. ContentListDto.ids stays required (@IsArray @ArrayMaxSize @IsUUID(each)) and id = any(ids::uuid[]) is always present; every new filter/keyset is an additional AND (sql.join(conds, ' and ')). Result ⊆ the platform's authorized-id belt.
  • Guards + scopes + limits. New routes carry RemoteOnlyGuard, ServiceAuthGuard + @RequireServiceScope(content:search | attachments:read); the scope-coverage spec fails if any handler lacks a declaration; the shared credential includes the new scopes; ParseUUIDPipe on path ids; query length bounded (1024, ReDoS-guarded twice), limit bounded, sub-collection limit ≤200. Secret compare is constant-time; header-auth (no CSRF/CORS surface).

Findings

[LOW] Malformed keyset cursor casts to a 500, not the intended 400 (robustness) — optional, Priority 2

  • Category: Architecture / fail-closed input validation
  • Location: apps/server/src/service-bridge/dto/content-read.dto.ts:59-63 + service-content.service.ts:1080-1082; apps/server/src/service-bridge/dto/sub-collection-page.dto.ts:283-286
  • Why it's exploitable: The DTO comments promise "a malformed cursor is a 400 at validation, not a 500 at the cast." That holds for the legacy updatedAt field (@IsISO8601()), but the new generalized value field is only @IsString @MaxLength(512). When sort.field ∈ {updatedAt, createdAt} the code does sql\${before.value}::timestamptz`, so a non-timestamp valuethrows a Postgres cast error → **500** instead of 400. The sub-collection path has the same shape:parseSubCollectionQuerygates onDate.parse(beforeCreatedAt)(lenient, accepts strings Postgres'::timestamptzmay reject) and passes the *original* string to the cast. **Security impact is negligible** — the surface is reachable only by a caller holdingPLATFORM_AUTHZ_SERVICE_SECRET` (fully trusted, all scopes), the platform always encodes canonical values, and the effect is a single request-scoped 500 (no data exposure, no crash, no DoS). Raising it because the code's own invariant isn't fully met and it straddles the correctness lens.
  • Recommended fix: For a timestamp-typed active sort, validate value as ISO before the cast (or try/catch the cast into a BadRequestException); in parseSubCollectionQuery, validate against a strict ISO-8601 regex rather than Date.parse, or normalize to a canonical instant before binding. (The beforeId OpenAPI format: uuid is likewise unenforced in parseSubCollectionQuery, but it's bound as ::text so it's injection-safe and cannot 500 — spec/impl nit only.)

[INFO] content/search offset has no upper bound — optional, Priority 1

  • Category: Architecture / resource bounds
  • Location: apps/server/src/service-bridge/dto/content-search.dto.ts:181-184
  • Why it's exploitable: offset is @IsInt @Min(0) with no @Max. It is not a DoS — PdpSearchService caps the candidate scan at HARD_SCAN_CAP=2048 regardless of need = offset + limit, so a huge offset just yields a bounded scan then an empty slice. Flagging only for explicitness: an out-of-range offset silently returns empty rather than being rejected at the edge.
  • Recommended fix: Add a sane @Max (e.g. a few thousand) so a nonsensical offset is a 400, keeping edge validation aligned with the other bounded inputs.

[INFO] highlight carries ts_headline markup + verbatim page text — downstream must encode — optional, Priority 1, DOCS

  • Category: XSS (downstream / defense-in-depth)
  • Location: surfaced via service-search.service.ts:80 (passes r.highlight through); generated upstream in pdp-search.service.ts:137-139 (ts_headline)
  • Why it's exploitable: highlight contains <b>…</b> fragments plus surrounding page content. It is not a confidentiality leak here (filter-then-retrieve admits only pages the caller may view, so the snippet is authorized content) and it is not new behavior (upstream search already returns it). But a /v1 consumer that renders highlight as HTML without context-correct encoding would have stored XSS. This is the consuming platform's responsibility, not fixable in this fork PR.
  • Recommended fix: No change required in this PR. Note in the /v1 contract (super-repo) that highlight is untrusted HTML — consumers must HTML-encode (or sanitize with a vetted sanitizer) on render.

Checklist coverage

  • ✅ Authentication — service-secret guard is constant-time, fail-closed (503/401/403), rate-limited; unchanged by this PR, re-verified for the new routes.
  • ✅ Authorization — RemoteOnlyGuard + scoped ServiceAuthGuard; search runs the PDP gate (confirmed spaceId is not a bypass); list/attachment ops are documented privileged-data-planes the platform authorizes first; filters strictly narrow within the mandatory ids belt.
  • ✅ Injection — all parameterized; ILIKE metacharacters escaped; sort fields/directions allowlisted; no dynamic identifiers.
  • ⚠️ XSS — clean in-scope; one downstream-consumer note on highlight (Info, not this repo's fix).
  • ➖ CSRF / CORS — header-authenticated machine-to-machine, not browser-facing, not cookie-authenticated.
  • ✅ Secrets — none introduced; secret stays env-loaded.
  • ✅ File uploads — none; attachment ops are metadata-only reads (bytes ride the native file endpoint), workspace-scoped, type='file', soft-delete-excluded.
  • ➖ SSRF — no server-side outbound fetch of caller-controlled URLs.
  • ➖ Unsafe redirects — none.
  • ✅ Sensitive logging / data exposure — no new logging in the added services; projections are PII-free (no creatorId/rank/slugId).
  • ➖ Deserialization / unsafe parsing — JSON DTOs via class-validator only.
  • ✅ Path traversal — no filesystem paths; attachment reads are id→row DB lookups.
  • ➖ Crypto — none introduced.
  • ✅ Dependencies — no new packages (pg-tsquery is pre-existing).
  • ✅ Business logic / race conditions — keyset paging is stateless read-only (ms-truncated, id-tiebroken, limit+1); no read-modify-write.
  • ✅ PII / data protection — search hit is minimized and PII-free; attachment summary carries no creator/uploader id.
  • ✅ Audit logging / auditability — API audit is the platform's job (out of scope for the fork data plane); no regression.
  • ➖ Security headers / transport / cookies — east-west JSON, no cookies/headers changed.
  • ✅ Architecture / missing layers — the "absence is a finding" pass turned up only the two optional hardening items above (cursor-cast 400-vs-500, offset @Max); the substantive controls (authz, tenant scoping, soft-delete, input bounds, narrowing-only filters) are all present.

Notes

  • Trust model (accepted, correctly documented): the whole /api/service/* surface trusts any caller holding PLATFORM_AUTHZ_SERVICE_SECRET. "Search as arbitrary userId," "resolve any attachment→page," and "list any page's attachments" are all by-design — the platform is the authorization authority and (for the data-plane ops) authorizes page#view before use. That is exactly the model the OpenAPI description spells out; the new ops fit it faithfully. My review assumes the platform-side /v1 PRs (separate repo) actually perform those page/space decisions before serving bytes — that is the security anchor for the attachment and content-list ops and is out of this diff's scope.
  • Module import is safe: ServiceBridgeModule importing SearchModule shares the (mode-selected) SearchService provider only; NestJS does not re-register SearchController, so no north-south route is duplicated or newly exposed.
  • Standalone/native mode: RemoteOnlyGuard (checked before the secret, driven by the @Global boot-validated AUTHZ_MODE) 404s the entire surface in native mode, so none of these ops exist for a standalone fork — the new scopes/routes cannot be reached even with a mis-set secret.
  • Findings F1/F2 also touch the correctness lens (cursor robustness) — I've kept them Low/Info here because the security consequence is negligible under the trusted-caller model.

@PMQ9

PMQ9 commented Sep 8, 2026

Copy link
Copy Markdown
Author

🚀 DevOps / Operations / Reliability Review

Reviewer role: DevOps / Operations / Reliability Reviewer
Model: Claude Opus 4.8
PR / change: #22 — feat(service-bridge): /v1 engine read ops — search, attachments, filters/sort, sub-collection paging
Date: 2026-09-08

Verdict

✅ Approve

Safe to deploy and operate. This is additive, backward-compatible application code on a privileged east-west read surface — no infra, migration, env, or config changes; new behavior is opt-in; the module-wiring change is a safe Nest diamond import; rollback is a submodule-pointer revert. No merge-blocking operational risk in the DevOps/reliability lane. Three optional notes below, one at Priority 3.

Blast radius

Application-only: 4 new read-only ops under apps/server/src/service-bridge/ (permission-aware search, attachment resolve→page + list, plus content-list filters/sort and opt-in keyset paging on two sub-collection reads) + the inbound OpenAPI contract. The one operationally load-bearing change is imports: [SearchModule] on ServiceBridgeModule (a DI/boot path exercised by the fork-standalone-smoke). No Dockerfile/compose/k8s/Terraform/CI-workflow/migration/env delta; the fork ships first, then the super-repo bumps the submodule onto it, so the runtime rollout window is new fork + old platform.

Summary

The change exposes existing engine capabilities (the Phase-5 PdpSearchService, the attachments table, keyset list SQL) through four new /api/service/* ops behind the existing fail-closed guards (RemoteOnlyGuard → 404 unless remote; scoped ServiceAuthGuard). I traced the boot/DI path, the failure modes on the new reads, the backward-compat/rollout story, and the rollback path — all hold up. Result: safe to operate, 3 optional findings (0 blocking).

Operationally the strong parts are worth naming, because they're the things that usually break this class of change and here they're done right:

  • Boot/DI is safe. SearchModule is already in the graph via core.module.ts; it declares no imports: and exports: [SearchService], so ServiceBridgeModule importing it a second time is a deduped diamond import, not a cycle or a re-instantiation. searchServiceProvider injects only tokens that already resolve today (AUTHZ_MODE, Kysely, four repos) and in native mode returns the stock SearchService — so the native standalone-boot smoke has nothing new that can fail to resolve.
  • New scopes can't ship dark. The shared credential's scope set is new Set(Object.values(ServiceScope)) (service-auth.guard.ts), so content:search and attachments:read are auto-granted the moment the enum gains them — no separate allowlist to forget, no post-deploy 403 on a well-formed call. Per-scope rate limiting (429 backstop) also applies to the new scopes automatically.
  • Rollout is expand/contract, not a flag day. Every new capability is opt-in and the legacy SQL is preserved byte-for-byte when the new inputs are absent (tests assert order by created_at asc / date_trunc('milliseconds', updated_at) desc with not.toContain('date_trunc') / not.toContain('coalesce(') on the default paths). The before cursor contract is relaxed (required ["updatedAt","id"] → ["id"], value added) — a superset, so an un-updated platform's {updatedAt,id} cursor still validates and still hits the legacy keyset branch. New fork + old platform is fully compatible.
  • The heaviest new path is bounded. Search delegates to PdpSearchService, which clamps limit to 100 and hard-caps the candidate scan (HARD_SCAN_CAP = 2048, ≤16 DB+PDP round-trips) regardless of offset, and logs when the budget is hit (server-side signal, not silent). Query length is bounded (ReDoS guard). So the unbounded-offset shape at the edge is not a real DoS — I checked and am explicitly not flagging it.

Findings

🟡 Minor — listByPage is a new unbounded array read, the exact smell this PR pages elsewhere

  • Area: Operations (scalability)
  • Location: apps/server/src/service-bridge/service-attachment.service.ts — listByPage (select … from attachments … order by created_at asc, id::text asc, no LIMIT)
  • Problem: listByPage returns all type='file' attachments on a page with no limit and no paging. This PR simultaneously adds opt-in keyset paging to the two adjacent sub-collection reads (listMembers, listPagePermissions) with the stated rationale that "these reads are unbounded arrays today" — but introduces listByPage as a brand-new unbounded array read.
  • Production scenario: A page with a very large number of file attachments (image-heavy or programmatically-populated) — materialized in full by the fork, then again by the platform's /v1 layer proxying it.
  • Consequence: No incident at realistic wiki volumes (attachments-per-page has a far lower natural ceiling than members-per-space, and the endpoint is rate-limited), so this is not merge-blocking — but it's an internal inconsistency with the PR's own bounding discipline and a latent scalability cliff at 10x on a pathological page.
  • Suggested fix: Apply the same opt-in SubCollectionPage paging you just built for members/ACL grants ((created_at, id) keyset — nearly free given the query already orders by exactly that), or at minimum a defensive sanity LIMIT. Contract-compatible either way (paging is opt-in; the bare {items} shape is unchanged).

🟡 Minor — attachment endpoints' envelope-skip (@SkipTransform) has no runtime wire test (docmost#181 regression class) DOCS:-adjacent

  • Area: Deployment (response-contract regression)
  • Location: apps/server/src/service-bridge/service-attachment.controller.ts (both @SkipTransform handlers) vs apps/server/src/service-bridge/service-bridge.wire.spec.ts (added a runtime test for the new search endpoint only)
  • Problem: Incident fix: added env variable for support for forcepathstyle on s3 docmost/docmost#181 was a production envelope leak (the upstream {data,success,status} wrapper reaching the wire), and the contract explicitly tells consumers to fail closed on a mis-shaped 2xx. The wire spec was extended to prove the bare {items} shape for the new /content/search op through the real response pipeline, but the two new attachment ops are only checked structurally by the contract spec (return-type ↔ OpenAPI keys), never exercised through the interceptor stack.
  • Production scenario: If @SkipTransform failed to apply on an attachment handler (decorator ordering / the blank line between @SkipTransform() and @Get), the envelope would leak and the platform would fail-closed on the surface.
  • Consequence: Low probability — the search endpoint uses the identical decorator pattern and is wire-tested green, so the mechanism itself is proven — but it's the same regression class that already shipped a DEGRADED release once, and it's on a path with no runtime coverage.
  • Suggested fix: Add one app.inject wire assertion for GET /api/service/attachments/by-page/:pageId (bare {items}) mirroring the search test. Primarily a testing-lens item — defer depth to that reviewer — but noting it here because a leaked envelope is an operational contract break, not just a test gap.

🟡 Minor — OpenAPI info.version not bumped despite an additive contract expansion DOCS:

  • Area: Operations (contract hygiene)
  • Location: docs/integrations/authorization/service-bridge.openapi.json — info.version stays "1.1.1"
  • Problem: This revision adds 3 endpoints (search + 2 attachment ops), 2 scopes, 3 schemas, and new list filters/sort/cursor fields, but leaves info.version unchanged. The version was bumped for prior contract changes (history shows 1.0.0 → 1.1.1), so two materially different contracts now share one version string.
  • Production scenario: A consumer/integrator (or a future contract-diff tool) inspecting info.version to negotiate or pin capabilities can't tell the expanded surface from the prior one.
  • Consequence: No build breaks — I confirmed no fork spec asserts the version string, so this is pure hygiene, not a functional risk. It just erodes the version field's usefulness as a contract signal.
  • Suggested fix: Bump to 1.2.0 (additive/minor) in the same PR.

What I checked and considered fine

Infrastructure

  • Environment variables — no new vars referenced; MAX_SEARCH_QUERY_LENGTH / SERVICE_BRIDGE_RATE_LIMIT are pre-existing and unchanged
  • Secrets — none added, logged, or embedded; auth stays on the existing shared-secret + constant-time compare
  • Configuration — no new config; new scopes auto-included in the shared credential (Object.values(ServiceScope)), so no post-deploy scope-grant step
  • CI/CD — no pipeline/workflow changes; fork tests + fork-standalone-smoke / fork-contract-replacement-smoke run in the super-repo on the submodule bump
  • No Docker/k8s/Terraform surface in this diff

Reliability

  • Search path bounded — MAX_LIMIT=100, HARD_SCAN_CAP=2048 (≤16 round-trips) independent of offset, query-length ReDoS guard; over-budget scans are logged
  • Per-scope rate limiting (429) applies to the two new scopes automatically as a DoS backstop
  • New DB reads use the same bound-param raw-SQL + connection-pool pattern as the existing service-bridge reads (no new pooling/txn/lock surface; ilike metacharacters escaped, bounds cast fail as 400 not 500)
  • Resource cleanup — no manual connections/txns/locks introduced; Kysely .execute over the shared pool, unchanged
  • ⚠️ Statement-level timeouts on the raw reads are not set here — but that's the established module pattern (not a regression), and the search path is budget-bounded

Observability

  • No new secret/PII in logs; search projection deliberately strips creatorId/rank/slugId before the wire
  • The one genuinely new failure mode (search scan-budget exhaustion) is already logged server-side by PdpSearchService
  • ⚠️ New ops add no metrics/logs of their own — consistent with the existing service-bridge design (API audit lives at the platform edge), so not flagged as new

Deployment

  • Backward compatible in the new-fork + old-platform window — every new input is optional; default paths emit the byte-identical legacy SQL (asserted)
  • Cursor contract relaxed as a superset (required narrowed to ["id"], value added) — old {updatedAt,id} cursors still validate and route to the legacy keyset branch
  • No migration, no schema change, no flag-day coupling
  • Rollback = revert the submodule pointer; no migrated data or one-way state

Operations

  • Boot/DI safety of the SearchModule import verified against the module graph (already-registered, no imports, exported token, native-mode-resolvable factory)
  • Failure modes bounded and understood; no new stateful component or ownership gap
  • Scalability — search bounded; the one open item is listByPage (finding feat(public): anonymous front page + discovery endpoint (wiki-v2 #26) #1)

Open questions for the author

@PMQ9

PMQ9 commented Sep 8, 2026

Copy link
Copy Markdown
Author

🐛 Correctness Review — Bug Hunter

Reviewer role: Correctness Reviewer
Model: Claude Opus 4.8
PR / change: #22 — feat(service-bridge): /v1 engine read ops — search, attachments, filters/sort, sub-collection paging
Date: 2026-09-08
Reviewed at SHA: e6c5ea19ea2c2d7ddd82a945128c3c3507bb506e

Verdict

✅ Approve

Safe to merge on correctness grounds. I traced every hot-spot the change is built around — the generalized keyset SQL (asc/desc × timestamp/text), the byte-identical backward-compat invariant, the null-title coalesce, the int8→number coercion, the value ?? updatedAt cursor fallback, and the PDP-gating of the new search op — and they all hold up. The three findings below are validation-completeness and test-depth gaps that only bite a direct service-bridge caller (not the platform, which sends canonical inputs); none produces a wrong/skipped/duplicated row on the real call path, so none blocks merge.

Summary

This adds four read-only service-bridge ops: PDP-gated content/search, attachment resolve→page + by-page list, allowlisted content filters with a generalized (sortExpr, id::text) keyset, and opt-in {limit, before} keyset paging on space-members / page-ACL reads. I verified the load-bearing claims against the actual code (checkout is at the PR HEAD): the search token resolves to PdpSearchService in remote mode and the whole surface is RemoteOnlyGuard-gated, so search is always filter-then-retrieve; searchPage's signature and SearchDTO fields match the call; the default (no-sort) content keyset compiles byte-identically to the pre-PR SQL (same predicate text, same bound-param order); the asc/desc/text/timestamp keyset comparisons are all directionally correct with a consistent id::text tiebreak; the int8 fileSize and null coalesces are handled. 3 findings, 0 critical, 0 major — all Minor / test-depth, all optional.

Findings

🟡 Minor — Sub-collection cursor uses lenient Date.parse, can still 500 at the ::timestamptz cast

  • Category: Validation / Error handling
  • Location: apps/server/src/service-bridge/dto/sub-collection-page.dto.ts:283 (parseSubCollectionQuery)
  • Problem: The guard is if (Number.isNaN(Date.parse(beforeCreatedAt))) throw BadRequestException. JS Date.parse is looser than Postgres's timestamptz input grammar, so there is a class of strings that pass this check and then reach ${before.createdAt}::timestamptz in the paged keyset SQL. Confirmed locally: Date.parse('2026') → 1767225600000 (valid in JS), but a bare '2026'::timestamptz is not valid Postgres timestamp syntax and raises at the cast → 500, which is the exact "400 not 500" outcome the parse guard exists to prevent. This diverges from the body-path cursor (ContentCursorDto.updatedAt uses the stricter @IsISO8601()), so the two cursor entry points don't validate the same way. (Secondary, harmless: Number('0x10')/'1e2'/' 10 ' are accepted as limit — lenient but still range-bounded, so no defect.)
  • Trigger: A direct service-bridge caller sends ?limit=2&beforeCreatedAt=2026&beforeId=<uuid> (or any Date.parse-valid but PG-invalid instant) to GET /api/service/spaces/:id/members or .../pages/:id/permissions.
  • Consequence: 500 instead of 400. Not reachable from the platform (it sends canonical ISO), and it's a request-shape error from a trusted internal caller — no data corruption, no leak. Low impact.
  • Suggested fix: Match the body path — validate with a strict ISO-8601 regex / the same check IsISO8601 applies, or narrow the accepted grammar to what ::timestamptz will parse, rather than Date.parse.

🟡 Minor — Cross-resource filters and a mismatched-type cursor are silently accepted, not rejected

  • Category: Validation / Business rule
  • Location: apps/server/src/service-bridge/dto/content-read.dto.ts (shared ContentListDto) + service-content.service.ts:1075 (keysetCond, the before.value ?? before.updatedAt fallback)
  • Problem: Two related completeness gaps:
    • (a) ContentListDto is shared by pages and spaces. listPagesByIds reads only parentPageId/titleContains/creatorId/updatedSince/updatedUntil; listSpacesByIds reads only nameContains/created*/updated*. A page-list request carrying createdSince/nameContains, or a space-list request carrying parentPageId/titleContains/creatorId, is silently ignored — no 400, and the caller gets a broader-than-intended set (still bounded to the authorized ids, so not a confidentiality issue). The OpenAPI documents these as resource-specific but nothing enforces it server-side.
    • (b) For a text sort (sort.field = 'title' | 'name'), keysetCond computes bound = before.value ?? before.updatedAt. If a caller sends a legacy cursor (before.updatedAt set, before.value absent) alongside a text sort, the timestamp string is used as a ::text bound and compared against coalesce(title,'') — wrong pagination, no error. The unit test only covers the both-absent case (before:{id} → 400); the timestamp-present-with-text-sort case slips through.
  • Trigger: A direct caller mixes a resource's filter/cursor with the other resource's sort. The platform builds matched sort+cursor pairs, so it won't hit this.
  • Consequence: Silently over-broad results (a) or silently wrong page boundaries (b) — never a leak (the authorized-id belt still applies), never a crash.
  • Suggested fix: Optional. Either reject unknown-for-resource filters in listPagesByIds/listSpacesByIds, or (for b) require before.value when sort is a text field and 400 otherwise (mirror the existing "cursor is missing its bound value" guard but keyed on sort type).

🟡 Minor (test depth) — No real-Postgres walk for the generalized timestamp keyset or the value='' null-title bound

  • Category: Regression / test coverage
  • Location: apps/server/src/service-bridge/service-content.pg.spec.ts (C12 block)
  • Problem: The pg walk that proves no-skip/no-dup across a boundary is exercised only for title asc (and the sub-collection created_at walk in service-space.pg.spec.ts). The generalized timestamp sort keyset (createdAt/updatedAt with a before cursor) is only checked as a single full-limit sort, never paged across a same-ms tie — even though that path exercises the value ?? updatedAt fallback + the un-truncated ${bound}::timestamptz bound vs. the date_trunc('milliseconds', …) LHS, which is precisely the ms-truncation-tie hazard a walk test is meant to catch. It's structurally identical to the proven legacy updated_at keyset, so I judge it correct — but it's the highest-value missing test. Separately, the title walk never lands the null-title row (value = '') as a mid-walk cursor, so the coalesce-'' bound edge isn't walked either.
  • Trigger: N/A (coverage gap, not a live defect).
  • Consequence: A future edit to keysetCond/sortExpr on the timestamp branch could regress paging without a red test.
  • Suggested fix: Add a paged walk over createdAt desc (2-at-a-time across the uuid(1..3) fixtures, cursor value = last.createdAt) and a title asc walk whose first page ends on the null-title row so value = '' is used as the next bound.

What I checked and considered fine

  • Backward-compat invariant (byte-identical SQL): orderClause(undefined) returns the exact legacy order by date_trunc('milliseconds', updated_at) desc, id::text desc with no surrounding whitespace, embedded at the same position; keysetCond(undefined) returns the exact legacy predicate + the same two bound params in the same order; the conds array preserves order (new filters slot before before, which stays last). The sub-collection unpaged path is semantically identical (order by created_at asc, no date_trunc, no limit, unchanged response shape). Verified against the SQL-shape guard tests.
  • Keyset direction: row-value comparison (expr, id::text) < (bound, id) for desc and > for asc is correct SQL tuple semantics; ORDER BY and the keyset use the same expr and the same id::text tiebreak with the same direction — no skip/dup at boundaries. date_trunc('millisecond') LHS vs. ms-precision bound (from a JS-Date-derived ISO) line up, matching the proven legacy behavior.
  • Null-title coalesce: coalesce(title,'') used identically in ORDER BY and keyset; value = '' is preserved through before.value ?? before.updatedAt ('' ?? x === ''), so a null-title cursor doesn't wrongly fall back to updatedAt. pg fixture (uuid(90) null title) sorts first as expected.
  • int8 → number fileSize: r.fileSize == null ? null : Number(r.fileSize) — string-from-pg coerces correctly, null stays null (not 0); the <2^53 assumption is documented and realistic. Null case is unit-tested.
  • Search is PDP-gated: SearchModule binds the SearchService token to PdpSearchService in remote mode (seam CCC header lockup + sidebar icon rail (incl. settings rail) #5), the whole surface is RemoteOnlyGuard (404 unless remote), and ContentSearchDto.userId is required → PdpSearchService always takes the per-principal filter-then-retrieve path (never the anonymous super() path). A bogus-but-valid UUID userId fails closed (empty member-spaces + empty PDP filter → []).
  • Search projection is PII-free: toSearchHit drops creatorId/rank/slugId, handles space: null, maps ISO dates; searchPage receives no shareId. createdAt/updatedAt come from NOT-NULL page columns as Dates, so iso() won't hit Invalid Date.
  • Attachment ops: type = AttachmentType.File (= 'file', verified) correctly excludes avatars/icons/chat; workspace-scoped + deleted_at is null; resolve→page returns null page/space for non-page attachments and 404s unknown/cross-workspace; empty-list (not 404) for an unknown page is intentional. No attachment-tuple authz here — Option A, platform authorizes the resolved page (privileged data plane, as documented).
  • ilike escaping: likeEscape escapes \ % _; contains('road%map') → %road\%map%, matched literally under the default backslash escape — no wildcard injection, unit-tested.
  • Route disambiguation: :attachmentId/page vs by-page/:pageId don't collide for real (uuid) traffic; ParseUUIDPipe 400s any non-uuid that could reach either. @HttpCode(OK) present on the POST search (else 201).
  • Scope + contract wiring: new content:search / attachments:read scopes added, scope-coverage + contract + wire specs updated for the 3 new methods and 2 new schemas; assertSortAllowed rejects cross-resource sort fields (title↔pages, name↔spaces) with 400 before any SQL is built, so sortExpr's non-exhaustive switch never receives a mismatched field.

Open questions for the author

  1. Does Postgres's ::timestamptz cast accept the full set of strings JS Date.parse accepts (e.g. bare '2026')? If not, Finding 1 is a live 500 vector for a direct caller — worth tightening parseSubCollectionQuery to a strict ISO check to match the body-path cursor.
  2. Is the silent-ignore of cross-resource filters (Finding 2a) intended contract behavior, or should a page request that carries a spaces-only filter (and vice-versa) be a 400?

…ge, DTO validation, keyset hardening

All four round-justifying (non-blocking Level-3) findings from the 7-lens review, plus overlapping Level-2
robustness folded in while in the same files:

- [Testing L3 / DevOps L3] listByPage: give it opt-in {limit,before} keyset paging (consistent with the
  members/ACL reads), and add service-attachment.pg.spec.ts — resolvePage + listByPage now execute on real
  Postgres (a raw-sql column/table typo no longer ships green), and the paging keyset walks a shared-ms tie
  with no skip / no duplicate.
- [Testing L3] Add dto-validation.spec.ts — the new class-validator DTOs (ContentSearchDto, ContentSortDto,
  ContentCursorDto, ContentListDto incl. nested sort) now run through validate(), so dropping a constraint
  (@Max/@IsUUID/@IsIn/@IsNotEmpty/@IsISO8601, …) reds a test.
- [Correctness L3] Add a real-Postgres walk for the generalized TIMESTAMP keyset (only title was walked) and
  for value='' (null-title) as a mid-walk cursor bound.
- [Security F1 / Correctness #1 / Testing P2] A malformed keyset/cursor timestamp now 400s instead of
  500-ing at the ::timestamptz cast: a shared isIsoInstant() guard (rejects Date.parse-lenient-but-PG-invalid
  values like '2026') used by parseSubCollectionQuery and the content keyset builder.
- [Correctness #2] A text sort (title/name) now REQUIRES its cursor `value` (400) instead of silently
  falling back to a timestamp `updatedAt` and paginating on the wrong boundary.
- [DevOps #3] Bump service-bridge.openapi.json version 1.1.1 → 1.2.0 (additive expansion).

Non-blocking Level ≤2 polish is deferred to a follow-up issue. Verified: nest build, 19 service-bridge suites
(179 tests), 3 real-Postgres pg specs (30 tests), eslint, import-boundary — all green.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@PMQ9

PMQ9 commented Sep 8, 2026

Copy link
Copy Markdown
Author

Round 1 addressed — HEAD → c83387fa

Thanks all. Zero merge-blockers surfaced; the four round-justifying (non-blocking Level-3) findings are fixed in-PR, the overlapping Level-2 robustness folded in, and the remaining non-blocking Level ≤2 polish is deferred to cccvu/wiki-v2#215 (P2). Fix commit c83387fa. Per lens:

Testing (L3 ×2) — FIXED both:

  • Attachment SQL now executes on real Postgres — new service-attachment.pg.spec.ts runs resolvePage + listByPage (a raw-sql column/table typo no longer ships green) and walks the paging keyset across a shared-ms tie (no skip / no duplicate).
  • The new class-validator DTOs now run through validate() — new dto-validation.spec.ts pins @IsUUID/@Max(100)/@IsIn/@IsNotEmpty/@IsISO8601 incl. the nested sort. The P2 lenient Date.parse is fixed (below); the P1 defensive branches → issue 215.

DevOps (L3) — FIXED: listByPage gains opt-in {limit,before} keyset paging (consistent with members/ACL), so a heavily-attached page gets a bounded read instead of an unbounded array. Openapi version bumped 1.1.1 → 1.2.0 (#3). The attachment @SkipTransform wire test (#2) → issue 215 (the coverage spec already pins the metadata).

Correctness (L3 + P2 ×2) — FIXED: added a real-Postgres walk for the generalized timestamp keyset (updatedAt asc across a shared-ms tie) and for value='' (null title) as a mid-walk cursor bound. The lenient sub-collection date-parse now 400s (shared isIsoInstant). A text sort (title/name) now REQUIRES its cursor value (400) instead of falling back to a timestamp updatedAt and paginating on the wrong boundary. The silent cross-resource filter half → issue 215.

Security (Approve) — FIXED F1: a malformed keyset/cursor timestamp now 400s instead of 500-ing at the ::timestamptz cast — isIsoInstant() rejects Date.parse-lenient-but-PG-invalid values like '2026', used by both the query parser and the content keyset builder. F2 (offset @Max) + F3 (highlight HTML-encode, a downstream/platform concern) → issue 215. Thanks for tracing the PDP-gate + PII-projection paths.

Architecture (Approve) — all 5 findings are Level ≤2 → issue 215 (assertSortAllowed temporal coupling, filter-vs-sort strictness, duplicated cap, the docstring, validation idioms). Thanks for confirming the AGPL/boundary + DI reasoning.

Performance (Approve) — both notes are pre-existing Level ≤2 → issue 215.

Frontend (Approve) — the bare-array-vs-{items} shape note is pre-existing Level 2 → issue 215.

Re-review incoming at c83387fa.

@PMQ9

PMQ9 commented Sep 8, 2026

Copy link
Copy Markdown
Author

🎨 Frontend / UI / UX Re-review (round 2)

Reviewer: Frontend / UI / UX Reviewer
Model: Claude Opus 4.8
PR / Diff: #22 — re-review of delta e6c5ea19..c83387fa (HEAD c83387fa)
Visual check: not applicable — the round-1 delta is 10 server-side .ts files (service-bridge + specs) plus service-bridge.openapi.json. No components, JSX/TSX/Vue/Svelte, CSS/Tailwind, tokens, or anything that renders appeared.
Verdict: No frontend concerns — nothing user-facing in this diff or its delta.

Summary: I re-reviewed the round-1 changes for my lens only. The delta stays entirely in the machine-to-machine service-bridge layer: opt-in keyset paging is extended to listPageAttachments (response shape unchanged — still {items}, backward-compatible default) and a new isIsoInstant cursor guard rejects Date.parse-lenient-but-Postgres-invalid timestamps with a clean 400 instead of a 500 at the ::timestamptz cast. There is still no UI surface, so nothing in the Frontend/UX lane blocks merge.

Round-1 note follow-up

  • My only prior observation (bare-array listSpaceMembers vs {items} elsewhere) was deferred to cccvu/wiki-v2#215 as a pre-existing Level-2 API-shape consistency item. It is unchanged by this delta, remains out of the frontend lane, and I can name no Level-3+/blocking consequence — so it stays deferred, not re-raised.

Positive note (not a finding)

  • The isIsoInstant guard (dto/sub-collection-page.dto.ts) turns a confusing 500 into a documented 400 on a malformed cursor — a genuine (machine-)client DX improvement over round 1.

Checklist coverage (all n/a — no UI)

  • State & data correctness: – · State coverage: – · Design-system adherence: – · Shared-primitive blast radius: – · Bundle & load cost: – · Runtime & rendering cost: – · Accessibility: – · Responsive & interaction UX: –

Deferred to other reviewers

  • Attachment keyset-paging correctness (limit+1, date_trunc('milliseconds', …) tiebreak, unpaged-default byte-identity) and the new isIsoInstant regex/Date.parse guard → pr-correctness-reviewer / pr-testing-reviewer.

@PMQ9

PMQ9 commented Sep 8, 2026

Copy link
Copy Markdown
Author

⚡ Performance Re-Review (round 2)

Reviewer: Performance Reviewer
Model: Claude Opus 4.8
PR / Diff: #22 — re-review of delta e6c5ea19..c83387fa @ HEAD c83387fa
Verdict: Approve — no merge-blocking performance concerns; the round-1 fix is a net improvement in my lane and introduces no new perf cost.

Summary: Re-checked my two round-1 notes and swept the delta for anything the fix introduced in the Performance lane. The one runtime-affecting change (listByPage opt-in {limit,before} keyset paging) is a positive change — it converts a previously-unbounded per-page array into a bounded, index-anchored read. The keyset-validation hardening is pure per-request input validation with no query cost. No new findings.


Prior findings — status

  • [P2 · Caching] uncached resolveDefaultWorkspaceId — Unchanged and expected: listByPage still calls it once per request (one bounded query, not N+1). Correctly dispositioned to cccvu/wiki-v2#215 as a pre-existing, cross-surface Level-≤2 item. I cannot name a concrete Level-3+/blocking consequence, so it stays optional, out of scope for this PR. Standing.
  • [P1 · informational] content-list 10k id-set filter/sort ceiling — The delta does not touch the content-list candidate fetch/sort (only the keyset-cursor validation changed, no query-shape change). Ceiling unchanged; tracked in wiki-v2#215. Standing, informational.

Delta review — new code in the Performance lane

  • listByPage opt-in keyset paging (service-attachment.service.ts) — ✅ improvement, not a regression. Paged path adds limit ${limit+1} + (date_trunc('milliseconds', created_at), id::text) > (…), all scoped to a single page_id (backed by idx_attachments_page_id). Index behavior matches the members/ACL keyset reads: the date_trunc(...) expression order can't use a composite index, but the row set is bounded to one page's type='file' attachments and the paged path now returns a bounded window instead of the prior unbounded array — the exact bounded-read fix a perf reviewer wants. The unpaged default query (order by created_at asc, id::text asc, no LIMIT) is byte-for-byte unchanged, so no backward-compat cost. No N+1, no query-in-a-loop.
  • Content keyset builder guards (service-content.service.ts) + shared isIsoInstant() (sub-collection-page.dto.ts) — ✅ clean. A regex test + Date.parse run once per request on the cursor bound; the pattern is linear (no nested quantifiers → no catastrophic backtracking) and the input is bounded, so no ReDoS/CPU concern. As noted, no new query cost — this rejects a bad bound at 400 before the ::timestamptz cast rather than adding work.
  • New *.spec.ts / *.pg.spec.ts files — test-only, no runtime path cost.

Checklist coverage (delta)

  • N+1 queries: ✅ clean — listByPage remains one statement; paging pushed into it.
  • Unnecessary / repeated DB calls: ⚠️ carried P2 (resolveDefaultWorkspaceId, deferred to feat: draw.io (diagrams.net) integration docmost/docmost#215) — no new instance.
  • Expensive loops: ✅ clean — projection map over a now-limit-bounded set.
  • Memory allocations: ✅ improved — paged listByPage is bounded (limit+1) vs. the prior unbounded array.
  • Async misuse: ✅ clean.
  • Blocking I/O: ✅ clean.
  • Caching opportunities: ⚠️ carried P2 only (deferred); the new keyset validation is not a cache candidate.

No merge-blocking or Level-3+ performance findings at c83387fa.

@PMQ9

PMQ9 commented Sep 8, 2026

Copy link
Copy Markdown
Author

🔒 Security Re-Review (round 2)

Security Reviewer: Security Reviewer — Claude (independent Security lens, PR #22)
Model: Claude Opus 4.8
PR: #22 — feat(service-bridge): /v1 engine read ops — search, attachments, filters/sort, sub-collection paging
Reviewed delta: e6c5ea19 → c83387fa (round-1 fixes)
Date: 2026-09-08

Verdict

✅ Approve. The round-1 fix resolves my one Low finding cleanly and introduces no new security issue in my lane. No blocking issues; no open Security findings remain.

Prior findings — disposition

[LOW → RESOLVED] Malformed keyset cursor casts to 500 not 400 (F1, was Priority 2)

Fixed correctly. A shared isIsoInstant() guard (dto/sub-collection-page.dto.ts) now strict-validates a timestamp bound before it reaches a ::timestamptz cast, and it's applied on both paths I flagged:

  • parseSubCollectionQuery replaces the lenient Date.parse check with isIsoInstant (sub-collection-page.dto.ts:58).
  • The content keyset builder guards the timestamp-sort bound: if (isTimestamp && !isIsoInstant(bound)) throw BadRequestException (service-content.service.ts:210-213).

I checked the guard for the two things that matter to this lens:

  • Closes the gap: the regex requires a full YYYY-MM-DD[…] shape and re-checks Date.parse, so the exact Date.parse-lenient-but-Postgres-invalid values ('2026', '2026-01') that previously 500'd are now a 400 up front. Directly unit-tested (sub-collection-page.dto.spec.ts:38-55, dto-validation.spec.ts).
  • No ReDoS introduced: the regex ^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$ is anchored, has no overlapping/nested ambiguous quantifiers (its optional sub-groups begin with disjoint characters), and its only + (\.\d+) scans linearly — worst-case is O(n) even on a long input. Safe.

The related text-sort change (a title/name sort now requires before.value rather than silently falling back to updatedAt) is a correctness improvement that does not weaken any control — the text bound is still compared as ::text, which never cast-errors.

[INFO — deferred, agreed] Search offset unbounded (F2) · highlight is untrusted HTML downstream (F3)

Both were deferred to cccvu/wiki-v2#215 as Level ≤2. I have no concrete Level-3+/blocking consequence to escalate either: offset is bounded in effect by PdpSearchService's HARD_SCAN_CAP (no DoS, just an empty slice), and highlight carries only content the caller is already authorized to view (filter-then-retrieve), so it is not a confidentiality leak — HTML-encoding on render is the consuming platform's responsibility, not fixable in this fork. Agreed to defer; out of scope for this PR.

New surface in the delta — reviewed clean

listByPage gained opt-in {limit, before} keyset paging (service-attachment.service.ts). Same safe pattern as the members/ACL paging I reviewed in round 1:

  • All predicates parameterized via Kysely sql (page_id, workspace_id, type='file', deleted_at is null, and the keyset tuple); order/limit fragments are hardcoded with a bound limit+1.
  • The cursor beforeCreatedAt is validated by isIsoInstant in parseSubCollectionQuery before the ::timestamptz cast (400 not 500); beforeId is bound as ::text (injection-safe, cast-safe).
  • Opt-in and backward-compatible (no limit → unpaged, unchanged shape); the keyset only narrows (an extra AND) and bounds — no widening. Workspace + soft-delete + type='file' scoping intact; PII-free projection unchanged (no creator/uploader id).
  • Route guards unchanged (RemoteOnlyGuard + scoped ServiceAuthGuard + attachments:read); no new scope. OpenAPI bumped to 1.2.0 with the paging params (the beforeId format: uuid vs ::text binding is the same pre-existing doc nit — no security impact).

No new untrusted-input→sink paths, no weakened control, nothing new to raise.

Checklist coverage (delta)

  • ⚠️→✅ Injection / input validation — F1 resolved; new isIsoInstant guard is correct and ReDoS-safe.
  • ✅ Authorization — unchanged; listByPage paging stays a workspace-scoped, platform-authorized privileged data plane.
  • ✅ Architecture / fail-closed — malformed cursor now fails closed at validation (400) on every timestamp path.
  • ✅ PII / data protection — projection unchanged, still creator-id-free.
  • ➖ Everything else — untouched by this delta (re-verified: no new routes, secrets, logging, crypto, or dependencies).

Notes

The trust-model anchor from round 1 is unchanged and still holds: this whole surface is reachable only in AUTHZ_MODE=remote behind the constant-time service-secret guard, the platform is the authorization authority for the data-plane ops, and search runs the authoritative per-principal PDP gate. Nothing in this delta alters that.

VERDICT: Approve | BLOCKING: 0 | OPTIONAL: 0 | L3PLUS: 0 | MAXSEV: 1 | SHA: c83387f | LENS: Security

@PMQ9

PMQ9 commented Sep 8, 2026

Copy link
Copy Markdown
Author

🚀 DevOps / Operations / Reliability Re-Review (round 2)

Reviewer role: DevOps / Operations / Reliability Reviewer
Model: Claude Opus 4.8
PR / change: #22 — re-review at HEAD c83387fa
Date: 2026-09-08
Prior review: round 1 (Approve; 0 blocking, 3 optional)

Verdict

✅ Approve

Both actionable findings from round 1 are fixed; the third is an accepted L2 deferral. The delta is fail-closed hardening plus test coverage — I found nothing new in the DevOps/reliability lane, and the operationally load-bearing surfaces (module wiring, boot path, rollout/rollback, env/infra) are untouched.

Delta reviewed

git log -p e6c5ea19..c83387fa — one commit (c83387fa), 11 files: DTO validation + real-PG specs, listByPage paging, a shared ISO-instant guard, keyset cursor hardening, and the OpenAPI version bump. No module, Dockerfile, compose, Terraform, CI-workflow, migration, or env change.

Prior findings — status

✅ FIXED — 🟡 #1 (P3) listByPage unbounded array read

listByPage(pageId, page?: SubCollectionPage) now takes opt-in {limit, before} keyset paging identical to the members / ACL reads ((date_trunc('milliseconds', created_at), id::text) > (…), order by … asc, limit page.limit + 1), wired through @Query + parseSubCollectionQuery on the controller. Verified the backward-compat property holds: the unpaged path (no limit) emits SQL semantically identical to before (order by created_at asc, id::text asc, no keyset, no limit) — asserted by the new unit spec, so an un-updated platform's call is unchanged. service-attachment.pg.spec.ts now executes both resolvePage and listByPage on real Postgres, including a shared-millisecond tie walk that proves the keyset pages with no skip / no duplicate. Clean fix, consistent with the bounding discipline elsewhere in the PR.

✅ FIXED — 🟡 #3 (P2, DOCS) OpenAPI info.version not bumped

info.version 1.1.1 → 1.2.0 (additive/minor). listPageAttachments also gained the limit/beforeCreatedAt/beforeId query params and a paging description matching the members/ACL contract, so the published contract now reflects the new opt-in paging.

⤴ DEFERRED (accepted) — 🟡 #2 (P2) attachment @SkipTransform wire path untested → cccvu/wiki-v2#215

This was Level 2 in round 1 (low probability — the identical @SkipTransform pattern is wire-tested green on /content/search, and a coverage spec pins the metadata). I have no concrete Level-3+/blocking consequence to name, so the deferral to docmost#215 stands. Not re-raised.

Hunt — anything the fix introduced in my lane

Traced the new code paths; all are fail-closed improvements or test-only, no new operational risk:

  • isIsoInstant() (new, shared guard) — a net reliability gain. It replaces Number.isNaN(Date.parse(...)) in parseSubCollectionQuery and is reused by the content keyset builder, so a Date.parse-lenient-but-Postgres-invalid bound (e.g. bare '2026') now returns 400 at validation instead of 500 at the ::timestamptz cast. That removes a spurious-500 failure mode (fewer false pages for on-call) and it's a single choke point (no guard drift), now also covering the new attachment paging cursor. I checked the regex ^\d{4}-\d{2}-\d{2}([T ]…)?$ for catastrophic backtracking — it's linear (no nested unbounded quantifiers), and the only unbounded input it sees is the ≤512-char cursor value, so no ReDoS.
  • Keyset cursor hardening preserves backward compat. Text sorts (title/name) now require value (400) rather than silently falling back to a timestamp updatedAt (which would paginate on the wrong boundary); timestamp sorts still accept the legacy updatedAt-only cursor, so an old platform's cursor keeps working. The isTimestamp computation was hoisted above its first use (no double-declaration — nest build is green). The legacy no-sort default path is untouched.
  • No boot/rollout/rollback change. No module file is in the delta — the SearchModule diamond import and native-boot resolution are exactly as reviewed in round 1. No new env/config/secret, no migration, no infra. Rollback is still a submodule-pointer revert.

What I checked and considered fine

  • listByPage unpaged default SQL unchanged (backward compatible on the C9 bump)
  • isIsoInstant guard is fail-closed (500→400) and ReDoS-safe on bounded input
  • Keyset cursor changes preserve the legacy updatedAt-only cursor; text-sort mis-cursor now 400s
  • No module/DI/boot change; standalone-boot smoke path unaffected
  • No env/config/secret/migration/infra delta; rollback unchanged
  • Version bumped; contract documents the new paging params

No open findings. Approve.

@PMQ9

PMQ9 commented Sep 8, 2026

Copy link
Copy Markdown
Author

🏛️ Architecture Re-Review (round 2)

Reviewer: Architecture Reviewer
Model: Claude Opus 4.8
PR / Diff: #22 — delta e6c5ea19..c83387fa
Verdict: Approve (Architecture lens) — no blocking, no Level-3+ findings. The additive changes are pattern-consistent; two new low-severity polish notes, both deferrable.

Summary: The round-1 fix (c83387fa) is structurally clean. listByPage gains opt-in SubCollectionPage paging that mirrors the members/ACL contract exactly, the content keyset builder's cursor-validation guards are a cohesive addition, and a shared isIsoInstant helper de-duplicates the ISO guard. My 5 round-1 findings were all Level ≤2 and are consciously deferred to cccvu/wiki-v2#215 — I re-checked each and can name no Level-3+/blocking consequence, so they stay out of scope. The only thing the fix newly surfaces in my lane is that the sub-collection keyset block now has a third copy (rule-of-three) — Level 2 polish, a natural addition to docmost#215.


Prior findings — status at c83387fa

All 5 confirmed still present and intentionally deferred to docmost#215; none is Level-3+ or blocking, so none is re-raised here:

  1. assertSortAllowed↔sortExpr temporal coupling (L2) — still separated. The round-1 fix touched the same keysetCond method (added cursor-bound guards) but did not fold the resource check into the builder. No new consequence; deferred.
  2. Filter-vs-sort strictness asymmetry on ContentListDto (L2) — unchanged; deferred.
  3. Duplicated 100 page-size cap (L1) — unchanged; deferred.
  4. ServiceContentController "NOT an authorization gate" docstring vs the search handler (L1 DOCS) — unchanged; deferred.
  5. Two query-input validation idioms (L1) — the fix applied parseSubCollectionQuery to attachments too, so the manual-parser idiom is now used by all three sub-collection reads. This makes the idiom internally consistent (a small improvement) even though the DTO-vs-parser split with the rest of the module persists; deferred.

New findings introduced by the delta

[Minor] — Coupling / Maintainability (rule of three) — service-attachment.service.ts:86, service-content.service.ts:260, service-space.service.ts:137

What: Applying opt-in keyset paging to listByPage adds the third near-identical copy of the sub-collection-paging block. listMembers, listPagePermissions, and now listByPage each independently hand-build the same four fragments: const paged = page?.limit !== undefined;, the keyset predicate (date_trunc('milliseconds', created_at), id::text) > (${before.createdAt}::timestamptz, ${before.id}::text), the order ternary, and the limit ${page.limit + 1} ternary — differing only in the column alias (pp.created_at/pp.id in the ACL join vs bare columns).
Why it costs: The keyset discipline here is correctness-load-bearing (ms-truncation + id::text tiebreak + limit+1 + opt-in-on-limit). With three copies, a future correction to that discipline must be made in three places and kept in sync, and a fourth sub-collection read will copy a fourth time. This is the classic missing-extraction signal — but there's no defect today (each copy is correct and has its own real-Postgres no-skip/no-dupe spec), so it's polish, not a blocker.
Fix: Extract a shared helper that takes the base conds, the SubCollectionPage, and the column expressions and returns { order, limitClause } (plus the optional keyset cond) — e.g. applySubCollectionKeyset(conds, page, { createdAtCol: sqlpp.created_at, idCol: sqlpp.id }). This is a natural companion to the deferred parseSubCollectionQuery idiom; recommend folding it into docmost#215 rather than blocking here. Optional; Level 2.

[Nit] — Code organization — dto/sub-collection-page.dto.ts:24 (isIsoInstant) imported by service-content.service.ts:12

What: The new shared isIsoInstant guard lives in dto/sub-collection-page.dto.ts, but it's a general ISO-8601-instant/cursor-bound util now imported by the content-list keyset builder, which is not sub-collection paging.
Why it costs: Reaching into a sub-collection-specific DTO file for a generic cursor util is a mild misplacement — a reader looking for the content-cursor validation won't expect it to live there. Trivial.
Fix: If touched again, hoist isIsoInstant to a neutral dto/ or cursor util module both callers import. Optional; Level 1 — fine to bundle with docmost#215.


Checklist coverage (delta)

  • Separation of concerns: ✅ — keysetCond guards stay a single cohesive "build the active-sort predicate" responsibility; paging logic stays in the service layer.
  • Layering: ✅ — no new cross-layer or upstream-file dependency; isIsoInstant is a within-module fork-owned util.
  • Responsibilities: ✅ — listByPage paging lives in the service, controller just parses query params (consistent with members/ACL controllers).
  • Coupling: ⚠️ — third copy of the sub-collection keyset block (L2, new); isIsoInstant placement (L1, new). Neither blocks.
  • Abstraction boundaries: ✅ — raw-sql fragments and the ISO guard stay internal; public { items } shape unchanged (backward-compatible).
  • API / contract design: ✅ — listByPage paging is additive and opt-in (unpaged default unchanged); openapi bumped to 1.2.0 with the same param block as members/ACL. Consistent.
  • Code organization: ⚠️ — see the two new notes; otherwise the new spec files (dto-validation.spec.ts, service-attachment.pg.spec.ts) sit correctly beside their subjects.
  • Maintainability & change cost: ⚠️/✅ — the rule-of-three duplication is the one real (low) maintainability note; every new capability remains test-covered (unit + real-PG) and additive. No over-engineering.

Net: Approve for the Architecture lens. Recommend the two new L≤2 notes join the existing docmost#215 polish bucket; nothing here warrants another blocking round.

@PMQ9

PMQ9 commented Sep 8, 2026

Copy link
Copy Markdown
Author

🧪 Test Re-Review — QA Engineer's Eye (round 2)

Reviewer role: Test Reviewer
Model: Claude Opus 4.8
PR / change: #22 — /v1 engine read ops
Date: 2026-09-08
Re-reviewed at HEAD: c83387fa (delta from prior review e6c5ea19)

Verdict

✅ Approve (Testing lens)

Both of my Priority-3 gaps and the Priority-2 lenient-date gap are fixed with real, non-vacuous tests, and the fix introduced no new testing gap in my lane. Suite green at HEAD: 19 suites / 179 tests (was 18 / 162); dto-validation.spec.ts executes (12 pass, not skipped), and service-attachment.pg.spec.ts self-skips its 6 engine tests without AUTHZ_TEST_PG_URL while keeping a non-vacuity sentinel.

Prior findings — status

✅ FIXED — Major/P3 #1: attachment queries now executed on real Postgres

service-attachment.pg.spec.ts (new) builds a faithful attachments table and runs both queries on the engine: resolvePage proves page-attachment → page+space, avatar → null/null, and cross-workspace / soft-deleted / unknown → 404 (three separate cases, engine-enforced, not a mock). listByPage proves type='file'-only (chat excluded), workspace-scoping, other-page exclusion, oldest-first order, numeric fileSize, the unpaged-returns-all default, and a keyset walk across a shared-ms tie (uuid(12)/uuid(13)) with no skip / no duplicate. I traced the limit-2 walk: the cursor is built from uuid(12) while its same-ms partner uuid(13) is on the next page — so this exercises the real no-skip tiebreak case, not just ordering. A raw-SQL column/table typo now reds. Exactly the gap I flagged, plus coverage for the newly-added paging.

✅ FIXED — Major/P3 #2: DTO 400 paths now run through validate()

dto-validation.spec.ts (new) drives ContentSearchDto, ContentSortDto, ContentCursorDto, and ContentListDto through class-validator: non-uuid/missing userId, empty and 1025-char query, limit 101/0, offset -1, out-of-allowlist sort.field ('password'), bad direction, non-uuid id in the ids array, over-cap limit, non-ISO updatedAt, and — importantly — the nested sort object (sort:{field:'evil'} fails, proving @ValidateNested+@Type actually cascade). A dropped @IsUUID/@Max/@IsIn/@IsNotEmpty/@IsISO8601 now reds. I verified non-vacuity: for each single-constraint field tested, removing that decorator drops the error count to 0. (Minor style note, non-blocking: assertions use toBeGreaterThan(0) rather than pinning the specific failing constraint — fine here because the inputs isolate one constraint each, but a future multi-constraint case would want a message assertion.)

✅ FIXED — Minor/P2 #5: lenient Date.parse replaced with a strict isIsoInstant

New isIsoInstant (regex-anchored full YYYY-MM-DD + Date.parse) rejects '2026'/'2026-01' that previously passed the 400 gate and would 500 at ::timestamptz. It is covered directly (isIsoInstant unit cases), wired into parseSubCollectionQuery (new parseSubCollectionQuery('10','2026','m-1') → 400 case), and propagated into the content keysetCond timestamp path with its own test (before:{value:'2026'} on an updatedAt sort → 400). Broader than I asked — the same 400-not-500 guard now holds on both cursor paths.

〰️ Substantially strengthened — Minor/P2 #4: keyset duplicate/tie split across a page boundary

The refactor added a timestamp-keyset split-tie walk (updatedAt asc over the shared-truncated-ms uuid(1)/uuid(2): cursor built from uuid(1), uuid(2) correctly returned on the next page) and a text-keyset no-re-inclusion proof (null-title '' bound does not re-admit uuid(90)). Together with the round-1 limit-2 title walk, this covers the shared (expr, id::text) cmp (bound, id) construction for both a timestamp and a text bound. Residual (the text path's second-of-an-equal-title-pair on the next page specifically) is now negligible given the identical construction and the timestamp split-tie proof — no longer worth carrying.

Carry-forward (optional, non-blocking)

🟡 Minor (optional, Priority 2) — legacy-path cursor missing updatedAt → 400 remains untested

  • Location: service-content.service.ts:196 — keysetCond default branch (if (before.updatedAt === undefined) throw 'cursor is missing updatedAt') / no test
  • Gap: The two new 400 tests cover the sort paths (text-sort-without-value, timestamp-sort-with-invalid-instant). The no-sort legacy path with before:{id:'x'} (updatedAt optional on the DTO, so this validates and reaches the throw) still has no test — deleting that guard reds nothing.
  • Risk: Low and unchanged — the platform always sends updatedAt on the legacy cursor; only a direct service-bridge caller triggers it. Non-blocking; fine as a follow-up (or fold into feat: draw.io (diagrams.net) integration docmost/docmost#215).
  • Suggested test: svc.listPagesByIds({ ids: IDS, before: { id: 'x' }, limit: 10 }) (no sort) → rejects.toBeInstanceOf(BadRequestException).

The P1 trivial defensive branches (iso() string input, empty-list mapping) deferred to cccvu/wiki-v2#215 are correctly scoped out — I have no concrete Level-3+ consequence to reopen them.

New-gap sweep (did the fix add anything untested?)

  • New listByPage opt-in paging: covered at both layers — SQL-shape unit tests (unpaged legacy vs. ms-truncated keyset + limit+1=21) and the pg keyset walk. ✅
  • New keysetCond branching (text sort must carry value; timestamp bound isIsoInstant-guarded): both new branches have tests; the round-1 "text-sort cursor missing bound" test still hits the before.value===undefined throw. ✅
  • Controller @Query wiring on listByPage: shares the already-tested parseSubCollectionQuery. ✅

No regressions to prior coverage; all round-1 tests remain present and green.

@PMQ9

PMQ9 commented Sep 8, 2026

Copy link
Copy Markdown
Author

🐛 Correctness Review — Bug Hunter (Re-review, round 2)

Reviewer role: Correctness Reviewer
Model: Claude Opus 4.8
PR / change: #22 — /v1 engine read ops
Date: 2026-09-08
Re-reviewed at SHA: c83387fa (round-1 review was at e6c5ea19; delta = the single commit c83387fa)

Verdict

✅ Approve — 0 merge-blocking.

The round-1 fixes are real and I traced each one on the engine's terms. All three prior findings are resolved on the platform call path; the one residual below is a narrower recurrence of my round-1 #1 (a 500 reachable only by a direct, secret-holding service-bridge caller sending a malformed cursor — never by the platform, which sends canonical toISOString() output). It's the same Minor/optional class as before, not a blocker. The new listByPage paging is correct.

Prior findings — status

#1 (lenient date parse → 500 at ::timestamptz) — ⚠️ Partially resolved (fixed on 2 of 3 paths; see R2-1)

  • Sub-collection path (parseSubCollectionQuery): fixed — now routes through the new strict isIsoInstant() (sub-collection-page.dto.ts:140), which requires a full YYYY-MM-DD and rejects Date.parse-lenient values ('2026', '2026-01'). Unit-tested (sub-collection-page.dto.spec.ts + a dedicated isIsoInstant block). ✔
  • Generalized-sort timestamp branch (keysetCond): fixed — if (isTimestamp && !isIsoInstant(bound)) throw at service-content.service.ts:212, covering both before.value and the before.updatedAt fallback. Unit-tested (value:'2026' → 400). ✔
  • Legacy no-sort branch: not fixed — see finding R2-1 below.

#2 (text-cursor timestamp fallback + cross-resource filters) — ✅ (b) resolved / ⏸️ (a) deferred

  • (b) text sort must carry value, no timestamp fallback: fixed — const bound = isTimestamp ? (before.value ?? before.updatedAt) : before.value (service-content.service.ts:202); a text sort with only a legacy updatedAt cursor now 400s (sort by 'title' requires a cursor 'value'). Unit-tested (before:{updatedAt,…} + title sort → 400). The value='' null-title bound is correctly preserved ('' !== undefined), verified by the new pg walk. ✔
  • (a) cross-resource filter silently ignored: deferred → cccvu/wiki-v2#215 (Level 2). I re-checked for a concrete Level-3+/blocking consequence and there is none: an out-of-resource filter is dropped, so the result is broader than the caller intended but stays bounded to the authorized ids belt (no leak, no wrong-security outcome, no crash). Correctly non-blocking. ✔

#3 (no real-PG walk for the generalized timestamp keyset / value='' bound) — ✅ Resolved

  • service-content.pg.spec.ts now adds (a) an updatedAt asc paged walk across a shared-ms tie, and (b) a title asc walk that lands the null-title row (value='') as the page-2 cursor bound and asserts it isn't re-included. I confirmed non-vacuity: the fixtures place uuid(1)/uuid(2) at the same truncated millisecond (base …00:00:00Z + sub-ms micros 900/100, both truncating to .000) with uuid(1) the smaller id but later raw sub-ms — so the id::text tiebreak is genuinely exercised (a broken tiebreak would skip or duplicate uuid(2)). The walk asserts [1,2,3], once each. ✔

New findings (introduced or surfaced by the fix)

🟡 Minor — Legacy no-sort cursor still 500s on an @IsISO8601-valid-but-PG-invalid updatedAt (isIsoInstant not applied here)

  • Category: Validation / Error handling (incomplete fix of feat(public): anonymous front page + discovery endpoint (wiki-v2 #26) #1)
  • Location: apps/server/src/service-bridge/service-content.service.ts:196 — the if (!sort) branch of keysetCond.
  • Problem: That branch casts ${before.updatedAt}::timestamptz without the new isIsoInstant guard, relying solely on the DTO's @IsISO8601(). I verified empirically that class-validator's isISO8601('2026') === true (and '2026-01' too) — so a bare year passes DTO validation and reaches the raw cast. This is the same 500 the fix explicitly set out to prevent (its own comment at :211 cites bare '2026' 500-ing at ::timestamptz), but the guard was added only to the generalized-sort branch, not the legacy default-sort branch that carries the identical cast. My round-1 write-up called @IsISO8601 "the stricter" check — that was my error; it is not strict enough to close this.
  • Trigger: A direct service-bridge caller (remote mode, holds the service secret) sends POST /content/pages/list (or spaces) with before:{ updatedAt:"2026", id:"x" } and no sort.
  • Consequence: 500 at the cast instead of a 400. No wrong data, no skipped/duplicated row, no leak — and unreachable from the platform, which always sends Date.prototype.toISOString() (full ISO). Same low-severity, direct-caller-only class as round-1 feat(public): anonymous front page + discovery endpoint (wiki-v2 #26) #1.
  • Priority: Level 2. Optional, non-blocking.
  • Suggested fix: One line — apply the guard in the no-sort branch too: after the undefined check, if (!isIsoInstant(before.updatedAt)) throw new BadRequestException('cursor bound is not a valid ISO-8601 timestamp');. (Optionally add a {updatedAt:'2026'} → 400 case to dto-validation.spec.ts/the service spec so the default path is covered like the generalized one.)
  • Residual edges in isIsoInstant itself (trivial, same non-blocking class — noting for completeness, not asking for action): the regex admits '0000-01-01' (year zero, Date.parse-valid) which PG still rejects → a vanishingly-narrow residual false-accept of the same 500 class; and it rejects a 2-digit timezone offset like '…+00' (PG-valid) → a false-reject, which is fail-safe (400, not wrong data). Neither is reachable from the platform.

New code review — listByPage opt-in paging

Traced the added paging on service-attachment.service.ts:398:

  • Keyset is correct: (date_trunc('milliseconds', created_at), id::text) > (bound::timestamptz, id::text) with matching ORDER BY date_trunc('milliseconds', created_at) asc, id::text asc and limit+1 — ascending, self-consistent, id-tiebroken. The new service-attachment.pg.spec.ts walks uuid(12)/uuid(13) across a shared-ms tie and asserts [11,12,13,14] once each (no skip / no dup). ✔
  • Backward-compat preserved: the unpaged branch keeps the exact prior order by created_at asc, id::text asc, no date_trunc, no limit; parseSubCollectionQuery() with no query params → {} → unpaged → all file rows. An existing platform caller is unaffected. Unit-tested. ✔
  • type='file' + workspace-scope + deleted_at is null stay in conds for both paged and unpaged. ✔
  • The by-page cursor's beforeCreatedAt is validated by the same isIsoInstant via parseSubCollectionQuery, so this path does not share the R2-1 gap. ✔

What I re-checked and considered fine

  • isIsoInstant accepts every input the platform actually sends (toISOString() → full …Z), so no false-reject on the real path (the pg walks would red otherwise).
  • updatedAt asc timestamp walk is non-vacuous (real shared-ms tie in the fixtures).
  • value='' (null-title) bound survives ?? and is not re-included as a boundary row.
  • Text sort now hard-requires value; timestamp sort still accepts the legacy updatedAt cursor (both instants).
  • listByPage paging keyset direction/tiebreak/limit+1 and its unpaged backward-compat.
  • No new duplicate-const/scope issue from moving isTimestamp above its use.
  • Deferred #2a carries no Level-3+ consequence (bounded by the authorized-id belt).

Verdict line

Approve · 0 merge-blocking · 1 optional (Level 2) open · #1 partially closed (1 path still open, non-blocking), #2b closed, #2a deferred→docmost#215, #3 closed.

@PMQ9

PMQ9 commented Sep 8, 2026

Copy link
Copy Markdown
Author

✅ 7-lens comprehensive review GREEN at c83387fa — ready for human merge

All seven independent reviewers approve the current HEAD c83387fa (BLOCKING: 0 | L3PLUS: 0 on every lens; Frontend confirms no UI surface). Round 1's four round-justifying Level-3 findings are verified resolved:

  • attachment SQL now runs on real Postgres (service-attachment.pg.spec.ts),
  • the new DTOs run through validate() (dto-validation.spec.ts),
  • listByPage gained opt-in keyset paging (bounded read, consistent with members/ACL),
  • a real-PG walk for the generalized timestamp keyset + value='' mid-cursor.

Testing flipped Comment → Approve, and both MAX-tier lenses (Security, Correctness) approve — each traced the fixes non-vacuously (keyset no-skip/no-dup walks, ReDoS-free isIsoInstant).

Non-blocking Level ≤2 polish is tracked in cccvu/wiki-v2#215 (P2), including one residual surfaced in re-review: the legacy no-sort cursor path still 500s on an @IsISO8601-valid '2026' (direct-caller-only — the platform sends toISOString() and never triggers it). None blocks merge.

Rounds used: 1 of 5 (stopped because no merge-blocking or non-blocking Level-3+ findings remain). Handing off to a human to review + merge — I never merge. Per the paired-merge order, this fork PR merges FIRST; then the super-repo bumps the docmost/ submodule onto the merge commit (super-repo epic cccvu/wiki-v2#213, commit C9).

@PMQ9
PMQ9 merged commit 0d20d54 into wiki-v2 Sep 8, 2026
@PMQ9
PMQ9 deleted the feat/159-v1-engine-service-bridge-ops branch September 8, 2026 16:05
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