Skip to content

fix(core): protect docs when deleting collections - #319

Closed
mikemikimike wants to merge 1 commit into
Noveum:mainfrom
mikemikimike:fix/protect-doc-collection-delete
Closed

mikemikimike wants to merge 1 commit into
Noveum:mainfrom
mikemikimike:fix/protect-doc-collection-delete

Conversation

@mikemikimike

@mikemikimike mikemikimike commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

What this changes

Preflight every document in a collection with assertDocWritable before 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:write could previously delete a collection and move documents they were not allowed to edit. Closes #245

How 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.14
  • bun run --filter '@orbit/core' typecheck: passed
  • bunx biome lint packages/core/src/content/doc-service.ts packages/core/tests/content/doc-service.test.ts: passed
  • git diff --check: passed
  • The focused database test was attempted after starting Docker and running bun run db:push and bun 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 verify is green, all four checks
  • Tests added or updated, and they fail without the change
  • No comments added to code, and no em-dash characters anywhere
  • No any, no non-null assertions
  • External input is parsed with a Zod schema from @orbit/shared
  • Authorization is enforced on the server through packages/shared/src/policy, not only in the UI
  • Docs updated if behaviour, configuration or setup changed
  • bun run db:release and bun run db:check-drift passed against the target database before this ships

Anything 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.

@vercel

vercel Bot commented Aug 15, 2026

Copy link
Copy Markdown

@mikemikimike is attempting to deploy a commit to the MagicAPI Team on Vercel.

A member of the Team first needs to authorize it.

@github-actions github-actions Bot added the tests Test coverage and test infrastructure label Aug 15, 2026
@coderabbitai

coderabbitai Bot commented Aug 15, 2026

Copy link
Copy Markdown

Important

Review available on request

  • 🔍 Trigger review

Reviews should be triggered manually for repositories with fewer than 10 stars. Select Trigger review above or comment @coderabbitai review to review the latest changes. For a full review, comment @coderabbitai full review.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: db2bdadf-debd-44a9-b46b-805fee59ceb5


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions

Copy link
Copy Markdown

Thanks for your first pull request to Orbit.

Two things that will save you a review round: bun run verify runs the
same four checks CI does, and the repo has no comments in code by policy,
so bun run check-comments will flag any you added out of habit.

A maintainer will review this shortly. Ask anything on the thread.

Comment on lines +1554 to +1564
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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 security 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.

Fix in Claude Code

Comment on lines +1562 to +1564
);
for (const doc of docs) {
await assertDocWritable(tx, principal, doc);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 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!

Fix in Claude Code

@imshashank imshashank left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 rejects assertion would not.
  • The preflight covers exactly the rows emptyCollection later updates, nested descendants included, because they inherit collection_id.
  • DOC_COLUMNS rather than a bare select(), 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.

@imshashank

Copy link
Copy Markdown
Contributor

Decision on this one

We 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 assertDocWritable instead of re-deriving the rules inline, and I verified that this is exactly why yours keeps the admin bypass working and correctly lets public and link documents through, while the other implementation currently breaks both. Your test asserting that the collection survives and the document placement is unchanged is also the better test, because it proves the rollback rather than just the rejection.

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 time

Please 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 instead

Both are unclaimed, and I have checked that neither has an open PR against it:

  • The audit log table is never written to #194, the audit log table is never written to. Security, area: database, p1. audit_log ships on every deployment with a well designed set of columns and nothing has ever written a row to it, so an admin reading the schema concludes there is an audit trail that does not exist. This is the closest match to what you just demonstrated: service layer work, drizzle, transactions, and getting the authorization-adjacent details right. It is the larger of the two.
  • Send personal notifications as a Slack DM, not to a channel #191, send personal notifications as a Slack DM rather than to a channel. Marked ready, p1, three points, and the routing rule is spelled out in the issue, so there is no design question waiting on me.

If you would rather have something smaller to land first, #183 and #175 are both small and marked ready.

One caution learned from #245: if an issue carries the needs design label, please ask me to make the call in the issue before writing code. #245 had it, and the ambiguity in that label is a direct cause of this collision. Neither #194 nor #191 has it.

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.

@imshashank imshashank added the duplicate Already tracked somewhere else label Aug 16, 2026 — with Claude

imshashank commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Status update: per the decision above, this stays open only as a record. #316 is the PR carrying #245 forward, with your assertDocWritable routing and the rollback-style test folded in. Labeling this duplicate, no further action needed here.

Thanks again for the work, and I hope to see you on #194 or #191.

@imshashank imshashank added bug Something is broken area: policy Roles, permissions and authorization area: docs-feature The docs product and its editor labels Aug 16, 2026
@imshashank

Copy link
Copy Markdown
Contributor

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 collectionId is unchanged after the refusal, instead of only asserting that the call threw. That is the assertion that actually proves the transaction rolled back, and I asked #316 to adopt it, which it has. The verb agreement fix in the error message came across too.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: docs-feature The docs product and its editor area: policy Roles, permissions and authorization bug Something is broken duplicate Already tracked somewhere else tests Test coverage and test infrastructure

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Deleting a doc collection relocates pages the deleter cannot write

2 participants