Repository navigation
fix(docs): enforce row-level security on doc collection deletion - #316
Conversation
|
@SinghAstra is attempting to deploy a commit to the MagicAPI Team on Vercel. A member of the Team first needs to authorize it. |
|
Important Review available on request
Reviews should be triggered manually for repositories with fewer than 10 stars. Select Trigger review above or comment ⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Plus Run ID: Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
imshashank
left a comment
There was a problem hiding this comment.
Thanks for taking this one on, and for picking the option deliberately rather than just bolting a check on. The direction is right and the core of the fix is correct.
I checked this out and verified a few things before writing this up:
- The authorization check covers exactly the rows the bulk
UPDATEtouches. Both useWHERE collection_id = X, and nested descendants do carrycollection_idbecauseadoptDescendantspropagates it, so your "all nested documents" claim holds. - Your test genuinely fails without the change. I reverted just the source file and re-ran it, and it fails as expected.
- Your
FOR UPDATEapproach is correct, and you can stop worrying about the race. I probed it against a live Postgres: becausedoc.collection_idhas a foreign key todoc_collection.id, Postgres takes aFOR KEY SHARElock on the collection row for any insert or update that places a doc in it, and that conflicts withFOR UPDATE. A concurrent insert blocks for the full duration of the transaction and only lands after commit. The third commit landed on the right answer.
One thing worth knowing, because it makes your choice better founded than the issue assumed: Option 2 from the issue is not actually implementable as written. The foreign key is ON DELETE SET NULL, so deleting the collection unfiles the un-relocated docs anyway, which is exactly the bug, and it would happen without a sync_id bump or a SyncAction, so realtime clients would go stale. Option 1 really is the better call here.
Changes I would like before this merges
1. The refusal has to tell the user something they can act on. This is the important one.
Right now the blocking document is completely invisible to the person deleting. I probed it: listDocs returns an empty list for them, and then the delete fails with "You only have read access to that doc." So they see an empty folder they cannot delete, for a reason they can neither see nor fix. Any member can also drop a private doc into any collection and permanently block its deletion for everyone except an admin.
The issue asked for Option 1 as "refuse the whole delete and name the documents in the way", and the naming half is what makes it survivable. Please collect the blocking docs instead of throwing on the first one, then raise an error that names the ones the caller can actually read and counts the ones they cannot. Something like "2 pages in this folder are not yours to move: Runbook, Protocol, and 1 more you cannot see."
There is a related consistency point. loadReadableDoc deliberately throws notFound rather than forbidden for a doc the caller cannot read, specifically so the response does not confirm that hidden content exists. This path throws forbidden for exactly that case. Counting the invisible ones rather than naming them keeps that intent intact while still being useful.
2. Say what the real blast radius is, and cover it in a test. isRestricted is private || team, not just private. I confirmed that a team visibility doc authored by another member blocks the delete with the same message. Team docs are ordinary collaborative content, so any collection holding one becomes undeletable for everyone outside that team. That is a much bigger behaviour change than the PR describes, and it needs to be a deliberate call rather than a side effect. Please add a test for the team visibility case alongside the private one.
3. Use DOC_COLUMNS, and batch the grant lookup. The preflight uses a bare .select(), which pulls every column including full content bodies and the generated searchVector tsvector. DOC_COLUMNS exists precisely to exclude searchVector, and every other query in this file uses it. assertDocWritable only needs id, authorId, visibility and organizationId.
Separately, the loop runs one writeGrantedDocIds query per restricted doc, sequentially, inside a transaction that is now holding an exclusive lock on the collection. grantedDocIds already batches exactly this shape, so a single lookup up front would replace N round trips.
4. Drop the redundant parameter. emptyCollection now takes both organizationId and principal, and the only call site passes principal.organizationId and principal. Take just the principal.
5. Update the MCP tool description. delete_doc_collection still says "The documents inside are never deleted: they move to reassignTo, or become unfiled when you leave it out." For an agent that description is the whole contract, so it needs to say the call is refused when the folder holds a doc you cannot write.
6. Tidy the diff and the history. There are six blank lines added inside emptyCollection that are unrelated to the change. And commit fb82ec55 narrows the UPDATE to inArray(checkedIds), an approach that aa6edeb4 then reverts, so please squash those two together.
Smaller notes, not blockers
- Please put the reason the
FOR UPDATEworks into the commit message. The guarantee rests entirely on that foreign key existing and being non-deferrable, there is no test pinning it, and the no-comments rule means nothing in the file can explain it. If someone later defers or drops that constraint the protection disappears silently. - Two people simultaneously deleting collection X into Y and Y into X now deadlock. I reproduced it, one side gets a raw
40P01and it is not mapped to a domain error. Before this change the same race threw a raw foreign key violation instead, so it is a changed error class rather than a new failure, and I am not asking you to solve it here. Worth knowing it exists.
Out of scope, I will track it separately
moveDoc still has the same hole this PR closes. I verified that one member can move a parent doc into another collection and adoptDescendants drags another member's private child along with it, with no authorization check at all. So after this lands you cannot delete a collection containing someone's private doc, but you can still relocate that doc by moving its parent. Not yours to fix in this PR, I will open a separate issue for it.
aa6edeb to
a8cc78b
Compare
979d2c5 to
04de568
Compare
imshashank
left a comment
There was a problem hiding this comment.
Thanks for turning this around so quickly. Five of the six asks landed cleanly, and the commit message explaining why the FOR UPDATE works is exactly the durable record I was hoping for. That reasoning is correct.
Landed and good:
DOC_COLUMNSinstead of the bareselect()- The grant lookup is batched, so N sequential queries became 2
- The redundant
organizationIdparameter is gone - The MCP tool description is updated and accurate
- Squashed to one commit with the concurrency note in the body
The problem is in the new assertDocsMovable. It reimplements the authorization decision inline rather than reusing the existing policy, and it has already drifted from the canonical version in two places. That drift produces three regressions.
CI is red
Unit and integration tests fails, on the test this PR adds:
(fail) collections > refuses deletion if the collection contains a team document the deleter cannot write
ZodError: expected array, received undefined at ["grants"]
The checklist says bun run verify is green, so it is worth re-running it locally before the next push. More on that test below.
(The Playwright failure is e2e/filters.spec.ts:81, goForward: net::ERR_ABORTED, an unrelated navigation flake. The Vercel failure is the standard fork authorization gate. Neither is yours.)
Three regressions, one root cause
assertDocsMovable decides with isOwner || isWorkspace || writeGrants.has(doc.id). Compare docAccessLevel, which is the canonical version:
if (!can(principal, 'doc:write')) return 'read';
if (principal.role === 'admin') return 'write';
if (doc.authorId === principal.userId) return 'write';
if (!isRestricted(doc.visibility)) return 'write';
return granted ? 'write' : 'read';Two differences:
- There is no
principal.role === 'admin'branch. doc.visibility !== 'workspace'stands in for!isRestricted(doc.visibility).isRestrictedisprivate || team, so!== 'workspace'also catchespublicandlink.
I probed each case against a live database:
admin deleting a collection holding a member's private doc -> forbidden
a public doc authored by another member -> forbidden
a link-shared doc authored by another member -> forbidden
an ordinary workspace doc by another member -> deletes, correct
A. Admins can no longer delete a collection. Any member's private doc now blocks an admin. This worked on main and in your previous revision, so it is a straight regression.
B. Publishing a doc makes its collection undeletable. A public or link doc blocks everyone except its author. This also contradicts your own commit message, which scopes the refusal to documents "(private or team)".
C. The message tells people they cannot see documents they can see. The read classification has the same two differences, so an admin, and anyone looking at a public doc, gets "You cannot see it" about a document canReadDoc says they can read.
Worth knowing why the tests did not catch A and B: the private-doc test asserts only code: 'forbidden', and the existing happy-path collection test passes the admin as the document's author, so it exercises isOwner and never the admin branch.
The suggested fix
Keep the batched lookup, it is the right shape. Just stop re-deriving the rules. Build the two grant sets as you do now, then classify each document through the existing predicates: canReadDoc(principal, doc, readGrants) for readability, and the same ladder as docAccessLevel (admin, then author, then !isRestricted, then grant) for writability. That fixes all three at once and stops the next drift.
While you are in there, batchedWriteGrantedDocIds is a near-verbatim copy of writeGrantedDocIds, the same predicate with inArray for eq. Either express the singular one in terms of the batched one, or have a single query return { docId, level } so you make one round trip instead of two.
The new team test needs two fixes, not one
First, setDocAccess takes { grants: [...] }, not a bare grant object. That is the ZodError.
Second, and this is the one that will bite you: fixing the shape is not enough. member1 is never added to the Design team, so they hold no grant at all, so the document is classified invisible and the message never names it. I ran both variants:
your test, zod shape corrected: "1 page in this folder are not yours to move. You cannot see it."
contains "Design Specs": false
member1 given a read grant: "1 page in this folder are not yours to move: Design Specs."
passes
For stringContaining('Design Specs') to mean anything, member1 needs read but not write on that document.
Also, addMember already takes { teamIds: [team.id] }, so the raw db.insert(schema.teamMember) with a hardcoded id: 'test-team-member-1' can go.
Please also add a test that an admin can still delete a collection holding another member's private document, and one for a published document. Those are the two cases that regressed.
Minor
- "1 page in this folder are not yours to move" should be "is". You handled page and pages but not the verb.
- This revision removes three pre-existing blank lines that are unrelated to the change. Same note as last time, opposite direction.
On the newest Greptile finding
Its "permission changes bypass collection lock" note is real in theory, but every other write path in this file has the same shape: updateDoc, moveDoc and archiveDoc all call assertDocWritable and then update without locking the document row or its access rows. Holding this PR to a stricter standard than its siblings would be inconsistent, so I am not asking you to solve it here.
This PR has precedence, and there is something to take from #319Heads up that #319 is an independent fix for the same issue, opened about eleven hours after you opened this one. You picked it up first, so we are consolidating on this PR and #319 will not be merged. Nothing for you to do about that, but it is worth reading, because it solves two things better than this branch currently does and I would like you to adopt both. 1. Stop re-deriving the authorization rules. This fixes all three regressions at once.#319 does the whole check with the existing I verified every row of that against a live database. Your The fix is to keep your batched grant lookup, which is a genuine improvement over #319's per-document loop, and feed it into the existing predicates rather than a hand-written condition: 2. Assert the rollback in your tests#319's test checks that the collection still exists and that the document's What this branch already does betterKeep both of these, #319 has neither:
Still outstanding from my last review
Take your time with it. The direction is right and the concurrency work on this branch is the part nobody else got to. |
|
Checking in: this has gone quiet since my last review, the one asking you to route through the canonical Labeling this |
|
Hey Shashank, Thanks for taking the time to review this and for bearing with me. I appreciate your efforts in code review. I'm working through the feedback now. I'll get a fresh commit up shortly that addresses all of this. Thanks again for the guidance, |
Updates emptyCollection to require the user's Principal and batches authorization checks for all nested documents before deletion. Refuses the deletion if the collection contains documents (private or team) that the caller lacks write access to. The error message explicitly names blocking documents the caller can read and counts the ones they cannot. Concurrency Note: We serialize placement with deletion by acquiring a FOR UPDATE lock on the collection row prior to fetching the documents. Because doc.collection_id has a foreign key to doc_collection.id (ON DELETE SET NULL), Postgres takes a FOR KEY SHARE lock on the collection row for any concurrent insert/update. This conflicts with our FOR UPDATE lock, ensuring concurrent inserts safely block until our transaction commits, removing the TOCTOU race condition.
04de568 to
ff6a15e
Compare
|
Status check on this one since it has gone a day without a commit. The branch is still on You said a fresh commit was coming, no rush, just keeping the queue accurate. Leaving this labeled |
|
Hey @imshashank, Thanks for the ping! Just to clarify, the commit currently on the branch (ff6a15e pushed yesterday) is the fresh commit containing all the requested fixes. I force-pushed it right after your second review round, so it already includes: Removing the hand-rolled assertDocsMovable logic and replacing it with the canonical docAccessLevel / canReadDoc ladder to prevent the regressions. Fixing the Zod shape for setDocAccess to { grants: [...] }. Adding the level: 'read' grant for member1 so the team-visibility test successfully evaluates the name of the document. Adding both regression tests (admin deleting a private doc, and a member deleting a public doc). Asserting the rollback in the tests by verifying the collectionId remains unchanged. Fixing the batchedWriteGrantedDocIds query and the "is/are" grammar. Let me know if that commit looks good to you, or if there is anything else you'd like me to tweak before we merge! |
|
You're right and I was wrong, sorry about that. I read I went through the branch properly this time. The Two things left, one of which is me correcting myself again. 1. The lock does not close the race, and I said it didThat was too generous on my part. The problem is that the final statement re-scans rather than using the set you authorized: .update(schema.doc)
.set({ collectionId: reassignToId, updatedAt: new Date(), syncId })
.where(
and(eq(schema.doc.organizationId, organizationId), eq(schema.doc.collectionId, collectionId)),
)So a document inserted between your preflight and that update gets moved having never been checked, which is the exact bug this PR exists to fix. The fix is small: constrain the update to the ids you already checked, 2.
|
…policy - Constrains the final document UPDATE query to strictly use inArray(doc.id, docIds) instead of the broad collectionId. This guarantees we only relocate the exact documents that passed the authorization preflight, closing a TOCTOU race condition involving concurrent inserts. - Extracts the synchronous logic from docAccessLevel into evaluateDocAccessLevel and applies it within assertDocsMovable. This replaces the hand-rolled permission ladder, ensuring the canonical doc:write policy is respected and eliminating code drift.
2ab86c9 to
5f24c4f
Compare
|
This is merged, so nothing here needs action from you. Posting it anyway because I got something wrong twice on this PR and you were right twice, and that should be on the record rather than buried in a merged thread. On the lock. I told you Your instinct was right and my correction of it was wrong. Worth keeping the On the fresh commit. Earlier I read On the refactor itself. Extracting One thing that is not yours to fix but worth flagging since you were in this file: Thanks for the patience across three review rounds, and for pushing back instead of just doing what the review said. That is the more useful behaviour and it caught me out twice here. |
What this changes
Updates
emptyCollectionto require the user'sPrincipal, queries all nested documents in the collection, and runsassertDocWritableon each document before theUPDATEoperation executes.Why
Closes #245
A member could previously delete a collection containing private documents created by other users because
emptyCollectionexecuted a bulk SQLUPDATEwithout checking row-level permissions on the individual documents being moved to the root level.How you know it works
Added an isolated test case in
doc-service.test.tswhere a member attempts to delete a collection containing another member's private document. Verified that the test correctly throws aforbiddenerror, causing the database transaction to rollback successfully.Checklist
bun run verifyis green, all four checksany, no non-null assertions@orbit/sharedpackages/shared/src/policy, not only in the UIbun run db:releaseandbun run db:check-driftpassed against the target database before this shipsAnything reviewers should know
I chose Option 1 from the issue description (refusing the deletion entirely rather than skipping un-editable documents) as it provides a clearer failure state and prevents unexpected folder restructuring for other users.
Greptile Summary
The PR adds per-document write authorization before deleting a document collection and limits reassignment to the authorized snapshot.
Confidence Score: 2/5
The PR is not yet safe to merge because permission changes can bypass the authorization snapshot and concurrent move-outs can still cause false forbidden responses.
The collection lock blocks new documents from entering through the foreign-key relationship, but it does not serialize document moves, visibility changes, or grant mutations. Authorization and mutation can therefore operate on different document placement or permission states.
Files Needing Attention: packages/core/src/content/doc-service.ts
Important Files Changed
Sequence Diagram
sequenceDiagram participant C as Caller participant S as Doc service participant DB as PostgreSQL C->>S: Delete collection S->>DB: Lock collection row S->>DB: Select contained documents and grants S->>S: Evaluate write access alt Any document is not writable S-->>C: Forbidden else All documents are writable S->>DB: Reassign matching snapshotted documents S->>DB: Delete collection S-->>C: Collection and document actions endReviews (9): Last reviewed commit: "fix(docs): constrain collection update s..." | Re-trigger Greptile
Context used: