Skip to content

fix(platform): close document review, cascade and blob-leak gaps - #3227

Merged
larryro merged 20 commits into
mainfrom
fix/documents-integrity
Sep 5, 2026
Merged

larryro merged 20 commits into
mainfrom
fix/documents-integrity

Conversation

@larryro

@larryro larryro commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Closes the twelve confirmed findings of the backend deep review's documents theme: controlled-record dead ends (attest refusals answered as 500 and unattestable text types; a review with no exit once the designee is gone), the project cascade that destroyed retained records, two blob-leak rotations (agent refresh, project-text saves), the audit-before-purge order on hard delete, a project-text read that turned a store outage into data loss, the un-shimmed folder listing behind every agent-node folder mount, a silently capped hub list, and three dead-code / dead-route sweeps.

Findings fixed

  • documents-1 — attest_document_bytes.ts attests every DOCUMENT_UPLOAD_ALLOWED_EXTENSIONS member (UTF-8 text types + the opaque .ac2), parity-tested; replacement.ts answers a mismatch as DocumentError('UPLOAD_MIME_MISMATCH', …, 400) the client already maps. The .ac2 branch admits any generic container signature (ZIP, gzip, stream-less CFB) and refuses only bytes another allowed document type claims, so a real ledger stays replaceable.
  • documents-2 — submitRecordForReview echoes the pending row only for the SAME designee; naming another reviewer falls through to mint-and-supersede. The product door: a Change reviewer row action (recordReassign, visible in_review to any writer — the server's write gate stays the authority) opens DocumentRecordSubmitDialog in a standingReviewer mode (standing designee excluded, title/hint/confirm/toasts say the pending request moves); en/de/fr strings, docs name the door. Pinned by document-row-actions.test.tsx (offered in in_review, not in draft), project-files-tab.test.tsx, and a new integration lane: submit to a stand-in, re-designate to the reviewer → new approvalId, stand-in row rejected + supersededBy, record.reviewerUserId = reviewer, stand-in's decision refused.
  • documents-3 — documents/internal_queries:listFilesByFolderInternal is answered by the automations shim through a 0.5 port of the 0.4 listing (agent-list.ts listFilesByFolder: id or hub path, bounded recursive walk, mount-relative safe names, honest truncated); domains/automations/shim.test.ts is the exhaustiveness gate the chat/sandbox surfaces already had.
  • documents-4 — deleteProject cascade pre-walks the project's documents with the documents domain's trash predicate (recordTrashRefusalFromJson, exported) and the legal-hold guard before any write: PROJECT_HAS_PROTECTED_RECORDS naming the records / PROJECT_LEGAL_HOLD; the delete dialog surfaces it (en/de/fr).
  • documents-5 — agent document refresh unbinds + trashes the previous blob's row and enqueues knowledge.release_refs in the same transaction (the replacement lane's rotation).
  • documents-6 — project-text saves run assertProjectFolderWrite before storing bytes, rotate the previous blob out on rewrite, and delete the just-written blob + row when the bind fails.
  • documents-7 — deleteDocumentHard purges first and audits after; PurgeIncompleteError answers as a coded 503 on the document, folder AND DELETE /api/v1/documents/:id doors (the REST door previously fell to domainErrorResponse, which rethrows anything without a 4xx status as a bare 500; v1-core.test.ts pins it).
  • documents-8 — the Convex-era half of core/documents/access.ts (and the three modules + parseJson that only served it) removed; WebDAV README points at the live filter.
  • documents-9 — getOrgUsageMetrics (0.4 handler) + get_user_names_batch.ts + the external_identities.ts re-export shim removed.
  • documents-10 — GET /search, POST /from-upload, GET /:id/url, POST /:id/{trash,restore,attach-to-project} and setDocumentTrashed / attachDocumentToProject / searchDocumentsForMention removed; the integration check exercises the live doors instead (blob-upload bind, /files/:ref/url, /:id/delete, project-seeded detach).
  • documents-11 — readProjectTextValues answers {} only for absence (s3GetObjectBytesIfExists → 404) and raises PROJECT_TEXT_READ_FAILED (503) for everything else.
  • documents-12 — GET /documents answers { documents, truncated }; the contract, adapter, useDocuments and the comparison dialog carry the flag (muted notice, en/de/fr).

Skipped

None.

Review repair — round 1

Addressed the adversarial review (1 blocking, 6 non-blocking) in five follow-up commits, no history rewritten:

  • Blocking — documents-2 had no UI door: 01e05253c adds the Change reviewer action, dialog mode, en/de/fr strings, docs sentence, hook/dialog + Files-tab tests, and the integration lane described above.
  • REST DELETE /documents/:id left out of the PURGE_INCOMPLETE shape → 3d2f4a8d7 (+ test).
  • .ac2 refused when file-type detected any signature → 54c7b270a (accepts what no other allowed type claims; + tests incl. an Office CFB under .ac2 still refused).
  • releasePreviousBlob lived in agent-write.ts and was imported by project-text.ts → 6d26f407d moves it to domains/documents/blob-rotation.ts.
  • service.delete.test.ts header now says it stubs the predicate → b4044b8b8.
  • The purge-then-audit crash window and the s3GetObjectBytes 404 text were recorded as no-change by the review; unchanged.

Tests & gates observed

All on the final tree (HEAD b4044b8b8, based on origin/main fe27bd32b; origin/main has since moved to c9a58dfec — git merge-tree reports no conflicts):

  • services/platform: bunx tsc --noEmit — exit 0; bunx oxlint --type-aware — exit 0.
  • Root bun run check — Tasks: 40 successful, 40 total, exit 0; inside it @tale/platform:test Test Files 504 passed (504) / Tests 73199 passed (73199), @tale/platform:test:ui Test Files 456 passed (456) / Tests 3508 passed (3508), @tale/ui:test 124 passed, @tale/docs:test 30 passed.
  • Targeted: bunx vitest --run --project server on v1-core, agent-write, project-text, attest_document_bytes, projects/service.delete — Test Files 5 passed (5) / Tests 64 passed (64); bunx vitest --run --config vitest.ui.config.ts on document-row-actions.test.tsx + project-files-tab.test.tsx — Test Files 2 passed (2) / Tests 39 passed (39).
  • Root bun run knip:check — exit 0 (the cron-parser configuration hint is present on main as well).
  • Integration proof (run-itest.sh, real Postgres + MinIO, with PR fix(platform): pass the corpus scope rows as one jsonb parameter #3222's aa3d1d7a9 cherry-picked -n for the run and dropped with git reset --hard afterwards — not in this branch): [itest] 468/469 checks passed across 133/133 lanes, no RUN TRUNCATED. The one failure is webdav re-home (protocol + tree + locks + visibility on pg) — red on main before this campaign and identically red in the other themes' runs. New probes passing: record re-designation while in_review supersedes the standing request (standIn=ok, redesignate=new-id, standInRow=rejected/supersededBy=true, record=in_review → reviewer, pending=true/true, standInDecides → 400); agent-node folder mount lists the tree through the run shim; project cascade delete refuses a protected controlled record untouched (400 PROJECT_HAS_PROTECTED_RECORDS naming the record, record kept); document.list tells the truth: truncated over the cap; the retargeted document probes (blob-upload bind, /files/:ref/url, /:id/delete, project-seeded detach); the corpus-scope reconcile probe with the drifted indexed document.

Notes for the reviewer

  • checkCorpusScopeReconcile (PR fix(platform): pass the corpus scope rows as one jsonb parameter #3222's lane) picked "the first live file-backed document" with no ORDER BY and no corpus check; retargeting the documents probes changed heap order and it read drifted=null. The last commit makes it pick the oldest live document that has a corpus row — no overlap with fix(platform): pass the corpus scope rows as one jsonb parameter #3222's files.
  • The new domains/automations/shim.test.ts gate excepts by name the two refs the host schedules (automations/agent_host:start/driveWorkflowAgentTurn) — those are answered by automationShimScheduler, which the reachability walk cannot see.
  • projects/service.ts now imports recordTrashRefusalFromJson from documents/service.ts (which already imports loadProjectOrThrow from projects) — a function-level cycle, permitted in this workspace (import/no-cycle off), no top-level evaluation crosses it.
  • PROJECT_LEGAL_HOLD was mapped in the delete dialog and its locales existed, but nothing emitted it; the cascade pre-walk now does (a held document translates to the project door's code).
  • The de-CH overlay needs no override for the new strings (no ß, no currency/number); the DE/FR reassign hints are written active (Tale zieht … zurück / Tale retire …).
  • v1-core.test.ts now carries one vi.mock (with importOriginal) over documents/service.ts for the DELETE probe — only getDocumentById and deleteDocumentHard are replaced; the other describes in that file do not touch the documents service.

The replacement finalize called the core byte attester directly. Its maps
knew only the pdf/Office/image/csv/txt families, so a controlled record
whose file is .md/.json/.yaml/.yml/.py/.ac2 — every one an extension the
upload lane admits — could never complete "Replace file": attest threw
before bind on each attempt, the intent flipped to failed, and the user
saw Internal Server Error while an error report went out per try. For the
known types a spoofed file hit the same path: the attester speaks the
runtime-neutral AppError, which no document route maps, so the client's
UPLOAD_MIME_MISMATCH → record.replace.contentMismatch mapping never fired.

attest_document_bytes.ts now splits UTF-8 text by every text-typed
allowed extension and admits the opaque .ac2 container as an octet stream
when no signature claims the bytes; a parity test pins that every member
of DOCUMENT_UPLOAD_ALLOWED_EXTENSIONS has a passing fixture. replacement.ts
translates the attester's refusal into the door's own coded
DocumentError('UPLOAD_MIME_MISMATCH', …, 400) so last_error carries the
sentence and the client gets the 400 it is built for.

Finding: documents-1.
deleteDocumentHard committed the sync stop, the `document.deleted` audit
row and the hint in a transaction, and only then called purgeDocument —
which by contract keeps the row and throws PurgeIncompleteError when a
corpus or blob release fails. A failed purge therefore left a
tamper-evident receipt for a deletion that had not happened, the retry
that did delete wrote a second success row, and no route mapped the error,
so the user saw a text 500 with an error report per attempt.

The single-document lane now purges first and audits after (the folder
cascade's order), and the document and folder doors answer
PurgeIncompleteError as a coded 503 { error: 'PURGE_INCOMPLETE', message }
through one shared helper.

Finding: documents-7.
readProjectTextValues wrapped the slug lookup, the store resolution, the
S3 GET and the decode in one catch that logged and answered {} — so an
unreachable store, a 5xx or a denied key read exactly like "no file yet".
The settings panel then pre-filled its declared defaults and the
operator's next Save wrote them over the real file.

The S3 read now distinguishes absence from failure
(s3GetObjectBytesIfExists answers null on 404 and throws otherwise);
only absence is the empty map, everything else is a coded
DocumentError('PROJECT_TEXT_READ_FAILED', …, 503) the panel already
renders as its load-failed state. DocumentError admits 503 for a
dependency that failed to answer.

Finding: documents-11.
submitRecordForReview answered any submit while in_review with the live
pending row, ignoring the reviewer named — the idempotent echo won
unconditionally. Once the designee left the org, was disabled or lost the
document's scope, nobody could decide the review and the submitter could
not re-designate; replace, revise, trash and delete all refuse in_review,
so the record and its file were frozen for good.

The echo now holds only for the SAME designee; naming another reviewer
falls through to the existing mint-and-supersede path (the stale row is
rejected with supersededBy and the stale reviewer's bell dismissed), so a
re-submit is the re-designation exit.

Finding: documents-2.
upsertAgentDocument's refresh rewrote file_ref to the new blob and left the
previous blob's file_metadata row bound and active: the liveness predicate
kept its bytes, the temp-file sweep ignores bound rows, and a purge
released only the current ref — so every re-run of a report-writing
automation (the tool's advertised idempotent refresh) leaked one blob,
counted against the uploader's quota, orphaned permanently on delete.

The locked read now carries file_ref; when the refresh swaps the bytes the
previous row is unbound and trashed and a knowledge.release_refs job is
enqueued in the same transaction — the replacement lane's rotation.

Finding: documents-5.
ensureProjectTextDocument stored the bytes and registered a 'project_text'
file row BEFORE the transaction whose getOrCreateProjectFolder was the only
authorization: any org member could put up to the body cap into org
storage before being refused, and every refused or failed save left a row
+ blob nothing reaps (sweepTempFiles takes 'user'/'agent' only). A
successful re-save swapped file_ref and left the previous row bound and
active — one leaked blob per settings save, for good.

The project's edit gate (assertProjectFolderWrite, now exported) runs
before the store write; a rewrite rotates the previous blob out through
the shared release idiom; a bind that fails after the bytes landed deletes
the unbound row and the blob it just wrote.

Finding: documents-6.
`handler_names` declared documents/internal_queries:listFilesByFolderInternal
and the automation agent host dispatched it for every `files:` entry that
named a folder (a folder-id string, {folderId} or a hub {folderPath}), but
no shim table defined it: the ctx shim threw its un-shimmed-query error and
the turn failed before the host's own not-found / truncated refusals could
speak. Inline {content} mounts worked; a folder mount never did.

The automations shim now answers it through a 0.5 port of the 0.4 listing
(domains/documents/agent-list.ts listFilesByFolder): any folder of the org
by id or a hub folder by path, the subtree walked in one bounded recursive
CTE, mount-relative names (subfolder prefix + a path-safe leaf with the
stored extension re-attached), blob-backed live rows only, and an honest
`truncated` at the 500-file / depth caps. domains/automations/shim.test.ts
is the exhaustiveness gate the chat and sandbox surfaces already had: every
internal ref the stepper and the agent host can reach must have a handler
(the two scheduler-dispatched refs excepted by name). The integration check
lists a seeded tree through the run shim on real Postgres.

Finding: documents-3.
deleteProject's cascade expired every document in the project with no
record or hold check — the one delete door that skipped the guard trash,
hard delete and the folder cascade all apply. An admin cascade-deleting a
project destroyed its approved controlled records (the signed, retained
artifacts the lifecycle exists to preserve): the retention sweep purged the
'expired' rows with only the legal-hold custodian filter, and their pending
reviews stayed in the reviewer's inbox.

The cascade now pre-walks the project's documents with the documents
domain's own trash predicate (recordTrashRefusalFromJson, exported) and the
legal-hold guard before any write: one protected record refuses the whole
cascade as PROJECT_HAS_PROTECTED_RECORDS naming the records, a held
document as the door's PROJECT_LEGAL_HOLD (which the dialog already mapped
but nothing emitted). A detach destroys nothing and is untouched. The
delete dialog surfaces the refusal with the record titles; the string ships
in en, de and fr. Unit tests pin the order (walk before write), the named
refusal and the detach; the integration check cascades a project holding
an approved record on real Postgres and reads the record back untouched.

Finding: documents-4.
core/documents/access.ts carried two halves: the pure controlled-record
guards the WebDAV lane imports, and the 0.4 ctx.db visibility and
knowledge-access resolvers (isProjectScopedDocument,
checkProjectDocumentAccess, canReadDocument, assertDocumentVisibleToUser,
resolveKnowledgeAccessForUser, NO_KNOWLEDGE_ACCESS) that no 0.5 host can
run and nothing imports — their twins live in domains/documents/service.ts
and the chat shim. The WebDAV README kept the half alive by citing a
`webdav/visibility.ts` that does not exist.

The ctx-bound half goes with its test file, and with it the three modules
that only served it: core/projects/resolve_project_access.ts,
core/lib/get_user_teams.ts and core/lib/rls/organization/
get_organization_member.ts (+ test). Comments that cited them are reworded;
the README now points at the live filter in domains/webdav/handlers.ts.

Finding: documents-8.
core/documents/get_user_names_batch.ts had one importer: getOrgUsageMetrics
in core/governance/get_org_usage_metrics.ts, which iterated the Convex
`usageLedger` and had no backend caller or handler-name entry — the live
route serves getOrgUsageMetricsPg over the same pure fold. Both go, along
with core/identities/external_identities.ts, the re-export shim whose only
importer was the name batch (the helpers module it re-exported stays, the
identities domain imports it directly).

Finding: documents-9.
GET /documents capped the hub listing at 200 rows (500 at most) and
answered the prefix with no truncation signal. Its one product consumer,
the comparison dialog's "Existing" pickers, offered the newest documents
as if they were all of them — the silent-partial class the bounded folder
reader was written to prevent.

listDocuments now reads one row past its bound and answers
{ documents, truncated }, the cut judged on stored rows so a row the caller
may not see never masks it; the route, the contract, the adapter row and
useDocuments carry the flag, and the dialog shows a muted notice (en, de,
fr) pointing at its own Upload tab when the list is cut. Unit tests pin the
bound, the honest flag and the visibility-independent judgement; the dialog
test pins the notice; the integration check reads the flag on the wire.

Finding: documents-12.
GET /documents/search, POST /documents/from-upload, GET /:id/url and
POST /:id/{trash,restore,attach-to-project} had no product caller: the
app's search adapter targets /search-hub, file URLs go through
/files/:id/url, the document list hard-deletes through /:id/delete, the
governance trash page restores through its own door, and nothing attaches
a hub document to a project (project files are bound there directly).
/from-upload was also the weaker binding door — it bound any org
file_metadata id with no uploader-ownership proof, which /from-blob-upload
requires.

The routes go with setDocumentTrashed, attachDocumentToProject and
searchDocumentsForMention (createDocumentFromUpload stays: the REST
project door binds through it). The integration check now exercises the
live doors instead: every register+from-upload pair binds through
/from-blob-upload (the file row read back by blob ref), the serve probe
reads /files/:ref/url, the record-in-review, legal-hold and single-file
sync-stop probes go through /:id/delete, and the project-scope probes seed
the file into the project and prove detach.

Finding: documents-10.
lib/utils/type-utils.ts parseJson had one importer, the Convex-era
core/lib/get_user_teams.ts that went with the document access module's
dead half; knip now flags the export as unused.

Finding: documents-8 (follow-up).
checkCorpusScopeReconcile picked "the first live file-backed document"
with no ORDER BY and no check that the corpus holds a row for it, so its
outcome was heap order: an unindexed pick has no stamp to drift and the
lane read "drifted=null". Retargeting the documents probes at the live
doors changed which rows get updated and surfaced the fragility. The probe
now picks the oldest live document whose blob ref has a corpus row.

Finding: documents-10 (harness follow-up).
submitRecordForReview re-designates when a different reviewer is named
while the record is in_review (783d526), but no product surface could
send that request: the only door was the recordSubmit row action, visible
in draft alone, and the review dialog is the designee's decision. A record
whose designee left the org, was disabled or lost the document's scope was
still frozen for the user — the dead-end had moved from the server to the
UI (documents-2, PR #3227 review).

- use-document-record-actions: a recordReassign row action (in_review,
  canWrite — the server's requireDocumentWriteAccess stays the authority)
  opens DocumentRecordSubmitDialog with the standing reviewer.
- document-record-submit-dialog: a standingReviewer prop turns the dialog
  into the Change reviewer door — the standing designee is not offered
  again, title/hint/confirm/toasts say the pending request moves.
- en/de/fr: record.actions.changeReviewer, record.reassign.*, the two
  toasts; de-CH needs no override. Docs name the door in the submit step.
- Tests: document-row-actions pins the action in in_review (not draft) and
  the dialog mode; project-files-tab asserts the entry; the integration
  check's in_review lane submits to a stand-in, re-designates to the
  reviewer and checks the new approvalId, the superseded row
  (rejected + supersededBy), record.reviewerUserId and that the stand-in
  can no longer respond.
… door

DELETE /api/v1/documents/:id calls deleteDocumentHard and falls through to
domainErrorResponse, whose isDomainError admits only a 4xx status — a
PurgeIncompleteError (no status) still rethrew as a bare 500 there while
the session and folder doors already answered 503 PURGE_INCOMPLETE through
lib/purge-incomplete-response.ts (documents-7 follow-up, PR #3227 review).
The REST door now takes the same arm; v1-core.test pins the shape.
The opaque-container branch accepted .ac2 bytes only when file-type
detected nothing. Banana's format is proprietary with no published magic
number, so a real ledger may well carry a ZIP, gzip or Compound File
signature — and such a controlled record could never be replaced, the very
frozen-record class documents-1 set out to close (PR #3227 review).

The branch now refuses only bytes that a document type some OTHER allowed
extension claims: a signature-detected MIME in the map, or a CFB carrying
one of the legacy Office directory streams. Tests cover ZIP, gzip and a
stream-less CFB passing, and an Office CFB under .ac2 refused.
…ion module

The helper rotates the blob a rewrite replaces (unbind + trash the file
row, enqueue knowledge.release_refs in-tx) for both the agent refresh and
the project-text rewrite; project-text.ts importing it from agent-write.ts
read as one lane reaching into another's internals (PR #3227 review). Same
code, neutral home; both writers import it from there.
service.delete.test.ts replaces recordTrashRefusalFromJson with a local
re-implementation to keep the documents<->projects import cycle out of the
test, so it proves the cascade's wiring — not the predicate. The header now
says so and points at the predicate's own tests and the integration probe
(PR #3227 review).
@larryro
larryro enabled auto-merge (squash) September 5, 2026 10:33
@larryro
larryro merged commit 4a24de2 into main Sep 5, 2026
14 of 15 checks passed
@larryro
larryro deleted the fix/documents-integrity branch September 5, 2026 10:34
larryro added a commit that referenced this pull request Sep 5, 2026
Resolves two conflicts with #3227 and #3225:
- domains/automations/shim.ts: main added the same
  listFilesByFolderInternal handler backed by
  documents/agent-list.ts:listFilesByFolder; keep main's, drop this
  branch's copy, and un-export listWorkflowFolderFiles (its one remaining
  consumer is the workflow document.list native in the same file).
- lib/connectors/natives/imap-smtp.ts: keep main's From lane
  (resolveReplyFrom) beside this branch's attachment resolver.
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