Repository navigation
fix(core): protect docs when deleting collections - #319
mikemikimike wants to merge 1 commit into
Conversation
|
@mikemikimike 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 |
|
Thanks for your first pull request to Orbit. Two things that will save you a review round: A maintainer will review this shortly. Ask anything on the thread. |
| const docs = await tx | ||
| .select(DOC_COLUMNS) | ||
| .from(schema.doc) | ||
| .where( | ||
| and( | ||
| eq(schema.doc.organizationId, principal.organizationId), | ||
| eq(schema.doc.collectionId, collectionId), | ||
| ), | ||
| ); | ||
| for (const doc of docs) { | ||
| await assertDocWritable(tx, principal, doc); |
There was a problem hiding this comment.
Preflight snapshot leaves race
If document placement operations overlap collection deletion, a document committed after this query is absent from the authorization loop but included by emptyCollection's later predicate-based update, causing a document the caller cannot write to be reassigned. How this was verified: The preflight and update are separate READ COMMITTED statements, while concurrent create and move paths can change collectionId without locking the target collection.
Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/core/src/content/doc-service.ts
Line: 1554-1564
Comment:
**Preflight snapshot leaves race**
If document placement operations overlap collection deletion, a document committed after this query is absent from the authorization loop but included by `emptyCollection`'s later predicate-based update, causing a document the caller cannot write to be reassigned. **How this was verified:** The preflight and update are separate READ COMMITTED statements, while concurrent create and move paths can change `collectionId` without locking the target collection.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.| ); | ||
| for (const doc of docs) { | ||
| await assertDocWritable(tx, principal, doc); |
There was a problem hiding this comment.
Serial checks create N+1 queries
For a large collection of restricted documents authored by other users, this loop awaits a separate access query for each document. Deletion latency and transaction connection occupancy therefore grow linearly with collection size; use a bulk access check instead.
Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/core/src/content/doc-service.ts
Line: 1562-1564
Comment:
**Serial checks create N+1 queries**
For a large collection of restricted documents authored by other users, this loop awaits a separate access query for each document. Deletion latency and transaction connection occupancy therefore grow linearly with collection size; use a bulk access check instead.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
imshashank
left a comment
There was a problem hiding this comment.
Thanks for this, and for being straight in the description about not having got the test to run. I checked it out and ran it, and I want to lead with what you got right, because the central decision here is a good one.
Verified working
You route the decision through assertDocWritable rather than re-deriving the rules, which is what packages/shared/src/policy exists for. That matters more than it might look. I probed every visibility case against a live database:
admin deleting a collection holding a member's private doc -> deletes, correct
a published (public) doc authored by another member -> deletes, correct
a link shared doc authored by another member -> deletes, correct
a team doc authored by another member -> refused, correct
a private doc authored by another member -> refused, correct
a nested private child of another member -> refused, correct
an ordinary workspace doc by another member -> deletes, correct
Every one of those is right, including the ones that are easy to get wrong: the admin bypass survives, and public and link documents correctly do not block, because isRestricted is private || team. Reusing the existing predicate is what buys you that.
Also confirmed:
- Your test genuinely fails without the change. I reverted the source file and it fails as expected.
- Asserting that the collection survives and the document placement is unchanged is a good instinct. It proves the transaction actually rolled back, which a bare
rejectsassertion would not. - The preflight covers exactly the rows
emptyCollectionlater updates, nested descendants included, because they inheritcollection_id. DOC_COLUMNSrather than a bareselect(), correct.- Full suites pass locally: 929 in
@orbit/core, 193 in@orbit/mcp-server. Comment policy, biome and whitespace are all clean. CI has since gone green on unit and integration too, so you can tick that checklist box.
Please fix before merge
1. The refusal needs to tell the user something they can act on.
Right now the blocking document is completely invisible to the person deleting. I confirmed that 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 document into any collection and permanently block its deletion for everyone except an admin.
Issue #245 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 gather the blocking documents rather than 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 consistency point worth knowing here. loadReadableDoc deliberately throws notFound rather than forbidden for a document 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. The race Greptile flagged is real. I reproduced it.
I replayed your statement sequence against Postgres with two connections:
preflight saw 0 docs, so the authorization loop passes trivially
a private doc was committed into the collection by another transaction
the delete path reassigned 1 docs
the unchecked private doc was reassigned: true
So a document committed into the collection after the preflight gets reassigned having never been authorized, which is the original bug narrowed to a race window.
The fix is one statement. Take a lock on the collection row before the preflight:
await tx
.select({ id: schema.docCollection.id })
.from(schema.docCollection)
.where(and(
eq(schema.docCollection.organizationId, principal.organizationId),
eq(schema.docCollection.id, collectionId),
))
.for('update');That genuinely closes it, and the reason is worth putting in your commit message because no comment can carry it: doc.collection_id has a foreign key to doc_collection.id, so Postgres takes a FOR KEY SHARE lock on the collection row for any insert or update that places a document in it, and that conflicts with FOR UPDATE. I verified the block empirically, a concurrent insert waits for the whole transaction and only lands after commit.
3. Batch the access check. Greptile's P2 is fair. The loop runs one writeGrantedDocIds query per restricted document, sequentially, inside the transaction. grantedDocIds already batches exactly this shape, so a single lookup up front replaces N round trips. While you are there, DOC_COLUMNS pulls every document's full content body for a check that only needs id, authorId, visibility and organizationId.
4. Put the guard inside emptyCollection. The bulk UPDATE lives in emptyCollection, but the authorization lives in its caller. That is correct today because there is exactly one caller, but the invariant is not local to the function that does the damage, so the next caller reopens the hole silently. Moving the preflight and the lock into emptyCollection makes it hold for anyone who calls it.
5. Pin the cases that must keep working. Your test covers the refusal. Please also add one that an admin can still delete a collection holding another member's private document, and one that a published document does not block. Your implementation gets both right, but nothing currently fails if a future change breaks them, and they are exactly the ones that break quietly.
Minor
- The test is named "refuses to move a doc the caller cannot write", but it deletes a collection. Worth renaming to match.
One thing you should know
PR #316 is an independent attempt at this same issue, opened earlier and also targeting #245. The two touch the same region and conflict, so a maintainer will need to pick one rather than both landing. That is not a reflection on your work, and I would rather tell you now than after another round of changes. Your choice to go through assertDocWritable instead of re-implementing the rules is the better call of the two, for what it is worth.
Decision on this oneWe are consolidating #245 onto #316, which was opened about eleven hours before this PR for the same issue. Two people should not be spending evenings on the same bug, so I want to be direct rather than leave this sitting: this PR will not be merged. That is a call about who picked the work up first, not about the quality of what you wrote. To be accurate about it: of the two implementations, yours is the better one in the way that matters most. You routed the decision through So this is not wasted. I am asking #316 to adopt both of those things by name, with a pointer back here. The failure is ours: #245 was never assigned, and there was no note on it saying somebody had started. I have no way to give you those hours back, and I am sorry for them. To avoid this next timePlease comment on an issue to claim it before you start, and we will assign it to you. If an issue already has a comment claiming it, or a linked PR, treat it as taken. We will do a better job of keeping that state visible. Two things worth your time insteadBoth are unclaimed, and I have checked that neither has an open PR against it:
If you would rather have something smaller to land first, #183 and #175 are both small and marked One caution learned from #245: if an issue carries the The detailed technical review I left on this PR still stands and is worth reading, since the same points are going to land in #316. Thank you for the work, and I hope you will pick up one of the above. |
|
Status update: per the decision above, this stays open only as a record. #316 is the PR carrying #245 forward, with your Thanks again for the work, and I hope to see you on #194 or #191. |
|
Closing this as a duplicate of #316, which came in first and has since landed the same fix with batched grant lookups instead of a query per document, a lock against concurrent deletes, and an error that names which pages are blocking. #316's CI is green and it is one round from approval, so consolidating there rather than carrying two branches for the same issue. Not wasted work though, and I want to be specific about that rather than vague. Your test shape was better than what #316 had: asserting that the collection still exists and the document's Two things for next time, since the same pattern shows up in #321 and #323 as well:
Thanks for the quick turnaround on this one. If you want something else in the same area, #324 is open and unclaimed, and it happens to be the piece that unblocks your own Slack work on #321 and #323. |
What this changes
Preflight every document in a collection with
assertDocWritablebefore deleting the collection and reassigning its documents. If any document is not writable by the caller, the whole operation is rejected before any rows are changed.Why
A member with collection-level
doc:writecould previously delete a collection and move documents they were not allowed to edit. Closes #245How you know it works
Added a regression test proving a member cannot delete a collection containing a private document owned by another user, and that both the collection and document placement remain unchanged.
bun --version: 1.3.14bun run --filter '@orbit/core' typecheck: passedbunx biome lint packages/core/src/content/doc-service.ts packages/core/tests/content/doc-service.test.ts: passedgit diff --check: passedbun run db:pushandbun run db:test-setup. The test database lane hung while cloning/resetting and timed out, so no passing test result is claimed.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
The chosen behavior is the issue's option 1: fail the entire collection deletion when any contained document is not writable. The preflight runs in the existing transaction, so no partial reassignment is committed.