Skip to content

CASCADE delete must abort when the subtree contains nodes the actor cannot read #1736

Closed

Description

@malibio

Overview

Deleting a node removes its entire has_child subtree in one transaction, version-checking only the delete target. That OCC scoping is correct for concurrency — a teammate's concurrent edit to a descendant must not abort your delete. But it confers no authorization, and today nothing checks whether the actor may read the descendants being destroyed.

Once per-node access exists, a user with access to an open parent can CASCADE-delete restricted descendants they cannot read. Because deletes win over concurrent edits via tombstones, that destruction then propagates to every device and every member of the restricted collection. It is both destructive and fail-open.

Problem Statement

delete_subtree_atomic collects all descendants via a WITH RECURSIVE walk over has_child edges and issues a single DELETE FROM node WHERE id IN (target + descendants). FK ON DELETE CASCADE removes the edge and embedding rows. No step consults the actor's access to any descendant.

Under the collection access model an open parent can legitimately hold restricted descendants:

Project "Platform Migration"        (open — team-visible)
  └── has_child → Task "Contractor rate renegotiation"
                    └── member_of → Collection "Compensation"  (restrictedToMembers = true)

A teammate who can see the project deletes it. The restricted task — which they cannot read, and whose existence they should not learn from the delete — is destroyed for everyone, including the collection's members. Delete-wins tombstoning makes the destruction authoritative across devices, so there is no version conflict to save it and no natural recovery path.

Two things are conflated in the current design and must be separated explicitly: "OCC guards only the target" is a statement about concurrency, not a grant of authority over descendants. Both concerns touch descendants, which is why the distinction is easy to lose.

Proposed Solution

Add an access gate before the delete transaction. The OCC semantics inside the transaction are unchanged.

  • Walk the subtree and determine whether it contains any node the actor cannot read.
  • If it does, abort the whole delete — no node is removed — and report a count only: "This contains N items you don't have access to." The count is the minimum disclosure needed to explain the refusal; names, types, and locations are not disclosed.
  • If it does not, proceed exactly as today.

Silently skipping inaccessible descendants is explicitly rejected. A partial delete leaves orphaned descendants under a deleted parent, reports success for an operation that did not complete, and discloses the same existence information while also destroying data. Failing loudly is both safer and more honest.

The gate must live on the same authority as the rest of access enforcement — the Pro tenant schema — because a client-side or daemon-side check is advisory only and can be bypassed by any client that writes directly. The local daemon check is for UX (surfacing the count before the user commits to the action); the server-side check is the guarantee.

Note the interaction with the existing confirmation flow: the frontend already fetches a descendant count to show "Delete node and N descendants?". That count is computed from the actor's own visible graph, so on a Pro install it may already differ from the true subtree size — which is itself the signal that inaccessible descendants exist.

Architecture Impact

  • ADR-041 (../nodespace-docs/decisions/041-node-deletion-strategy.md) has been amended with a "CASCADE requires read access across the whole subtree" section. This issue implements that amendment. It does not weaken ADR-041's OCC-scoped-to-target decision — the amendment states explicitly that OCC scoping and access checking are separate concerns.
  • ADR-042 (../nodespace-docs/decisions/042-delete-wins-conflict-resolution.md) is what makes the exposure durable rather than recoverable: delete-wins tombstones propagate the destruction.
  • ADR-059 (../nodespace-docs/decisions/059-access-classification-not-outline-position.md) establishes that an open parent can hold restricted descendants — the access boundary and the atomicity/OCC boundary are independent partitions that do not coincide.
  • architecture/tenant-isolation-rls.md records this as load-bearing security property P7.
  • The companion nodespace-docs changes are already committed; no further docs work is required.

Acceptance Criteria

  • A delete whose subtree contains nodes the actor cannot read is rejected, and no node in the subtree is removed
  • The rejection reports a count of inaccessible items and no identifying information about them
  • A delete whose subtree is fully readable by the actor succeeds unchanged
  • The gate is enforced server-side in the tenant schema, not only in the daemon or frontend
  • OCC behavior is unchanged: a concurrent edit to a readable descendant still does not abort the delete, and a target version mismatch still yields a version conflict with an intact subtree
  • Adversarial test: a user deletes an open parent holding a restricted descendant they are not a member of — the restricted node survives and the parent is not deleted
  • Adversarial test: partial deletion is not reachable by any path (no orphaned descendants under a deleted parent)
  • Tests pass (bun run test:all)
  • Code passes bun run quality:fix

Technical Specifications

Reference Files

  • Delete implementation: packages/core/src/db/ — SqliteStore::delete_subtree_atomic(node_id, expected_version, source)
  • Service layer: NodeService::delete_node(node_id, expected_version) — returns DeleteResult { existed, deleted_count }
  • Frontend confirmation: packages/desktop-app/src/lib/services/delete-confirmation.svelte.ts and delete-confirmation-modal.svelte
  • Tenant schema: db/tenant-schema.sql in nodespace-cloud — nodes_delete policy, user_can_write_node, has_restricted_ancestor
  • Security properties: ../nodespace-docs/architecture/tenant-isolation-rls.md — P7

Implementation Details

  • The existing subtree collection is a WITH RECURSIVE walk over has_child; the access check needs the same node set, so compute it once rather than walking twice.
  • The daemon-side check runs before the transaction opens. Do not perform it inside the transaction and roll back — the count is needed for the user-facing message, and a rollback-based check does wasted work on the common path.
  • DeleteResult and the deleted_count proto field are unchanged for the success path. The rejection is a distinct error carrying the inaccessible count, not a deleted_count of zero — callers must be able to distinguish "refused" from "nothing to delete" (the idempotent absent-target case already returns existed: false).
  • The confirmation modal copy needs a second state for the refusal. The existing state resolves immediately when the descendant count is zero; the refusal state is terminal (no Delete button) rather than a confirm prompt.

Dependencies

Related Issues

Activity

  1. mstomar125 commented on Jul 31, 2026

    @mstomar125
    Contributor

    Design scoped (2026-07-31) — this is a cross-layer build, not a server-side-only trigger; capturing the key finding before it's picked up.

    Why a BEFORE-DELETE trigger doesn't satisfy the AC. The cloud nodes_delete policy is per-row RLS USING (user_can_write_node AND (has_restricted_ancestor OR created_by = auth.uid())). RLS silently filters rows the actor can't delete — so a subtree delete that includes an unreadable/unwritable descendant doesn't error; it just skips that row, producing exactly the partial delete + orphaned descendant this issue rejects. A per-row BEFORE DELETE trigger can't fix it either: RLS has already filtered those rows out, so the trigger never sees them and cannot abort. RLS fundamentally can't express abort-all-if-any-unreadable.

    The server-side guarantee therefore needs a SECURITY DEFINER delete RPC (sibling to insert_node_with_member_of): the daemon hands it the intended subtree id set; the RPC checks each id against user_can_access_node(id, auth.uid()) (exempting is_service_context() for the sync service), and — if any is unreadable — RAISEs with the count and deletes nothing; otherwise deletes the whole set (bypassing per-row RLS via SECURITY DEFINER). This is the only way to get loud-abort + count + no-partial.

    Cross-layer scope (≈ #1741-scale):

    • cloud: the delete RPC in db/tenant-schema.sql + a dated migration + pinning test.
    • daemon/core: route delete_subtree_atomic through the RPC instead of a raw DELETE … WHERE id IN (…); surface the returned count as the confirmation-flow UX (the daemon-side advisory the issue mentions).
    • sync: verify the delete-apply / delete-wins tombstone path is unaffected.
    • Adversarial ACs ('restricted descendant survives', 'no partial deletion reachable by any path') need a live delete-flow / 2-device check — deferred to a Mac session.

    Status: parked as the next focused build (needs its own session; not decision-gated — ADR-041 amendment stands). Not started here to avoid rushing a security-critical delete path at the tail of a long autonomous run.

  2. malibio commented on Jul 31, 2026

    @malibio
    CollaboratorAuthor

    Scoping finding: this issue is blocked on cloud-side work that doesn't exist yet

    Traced the full path (nodespace-core, nodespace-cloud, nodespace-sync) before implementing. Summary:

    nodespace-core has zero access-control concept today. delete_subtree_atomic (packages/core/src/db/sqlite_store/nodes.rs:517) walks has_child and hard-deletes unconditionally in one local transaction. There's no actor/current_user notion anywhere in this repo — the daemon serves whoever is on localhost.

    nodespace-cloud has per-row RLS (nodes_update/nodes_delete in db/tenant-schema.sql), but no subtree-scoped check. user_can_write_node/has_restricted_ancestor are single-node functions only.

    nodespace-sync is where local deletes actually propagate: SupabasePushConsumer turns each locally-deleted node into an independent PATCH .../nodes?id=eq.<id> (is_deleted: true soft-delete), one per node, in a loop — no batching, no subtree grouping. A row an RLS policy rejects returns WriteOutcome::NotApplied, which the code treats identically to "already gone" (explicitly documented, not accidental) — no error, no abort of sibling deletes still in flight. So today, deleting an open parent with a restricted descendant silently soft-deletes everything the actor can write and silently no-ops the rest — exactly the partial-delete failure mode ADR-041 forbids, just distributed across N independent PATCHes instead of one bulk statement.

    By the time events reach nodespace-sync, the local hard-delete has already committed (ADR-041's transaction already closed) and decomposed into N ungrouped NodeDeleted events — there's no "this was one cascade" envelope left to abort as a unit. So a pre-delete gate can only work if it runs before delete_subtree_atomic commits locally, which per ADR-041 means the daemon must synchronously ask the Pro tenant (cloud) "can this actor read every node in this subtree?" before proceeding. That RPC doesn't exist in nodespace-cloud today, and there's no call site for it in pro_client.rs (which today only does tier/status probing) or nodespace-sync.

    No companion issue exists in nodespace-cloud or nodespace-sync for this.

    Recommendation

    Split the work along the repo boundary rather than trying to land a self-contained PR here:

    1. This issue (CASCADE delete must abort when the subtree contains nodes the actor cannot read #1736, nodespace-core): scope to the daemon-side plumbing only —

      • A pluggable pre-delete access-check hook point in NodeService::delete_node / ahead of delete_subtree_atomic, reusing the already-computed subtree ID set (per the issue's own note: "compute it once rather than walking twice").
      • A distinct refusal error (NodeServiceError::InaccessibleDescendants { count } or similar) propagated through OpsError → gRPC status (parallel to the existing VersionConflict x-metadata pattern) → Tauri CommandError → frontend.
      • Frontend: second modal state in delete-confirmation-modal.svelte/delete-confirmation.svelte.ts for the refusal (terminal, no Delete button, per the issue spec).
      • For local-only/non-Pro installs (no tenant, no restricted collections possible): the hook is a no-op / always-allow, matching today's behavior exactly. It only does real work when a Pro tenant binding is active.
      • The gate's actual predicate is injected via ProClient (or equivalent) calling out to cloud — stubbed against a trait/interface so it's testable in isolation here, with the real backing RPC landing in nodespace-cloud separately.
    2. New companion issue in nodespace-cloud: a subtree-scoped read-check RPC (e.g. user_can_read_subtree(node_ids UUID[], for_user_id UUID) RETURNS TABLE(id UUID, readable BOOLEAN) or a count-only variant returning just the inaccessible count, matching the "count only, no identifying info" disclosure rule) exposed over the Pro gRPC surface, plus the nodespace-sync/pro_client.rs call site that invokes it synchronously before the local daemon's delete_subtree_atomic runs.

    Proceeding on (1) — the nodespace-core-scoped plumbing, with the gate behind a trait so it's real and tested here, wired to a stub/no-op predicate for local installs — and will open the companion cloud-side issue as part of this work, unless redirected.

  3. malibio commented on Jul 31, 2026

    @malibio
    CollaboratorAuthor

    Opened companion cloud-side issue: NodeSpaceAI/nodespace-cloud#103 (subtree read-check RPC). Proceeding here with the nodespace-core-scoped plumbing per the recommendation above.

  4. malibio commented on Jul 31, 2026

    @malibio
    CollaboratorAuthor

    Frontend baseline: 171 test files passed, 4113 tests passed (46.48s).

  5. self-assigned this
    on Jul 31, 2026
  6. malibio commented on Aug 1, 2026

    @malibio
    CollaboratorAuthor

    Follow-up scoping decision: on reflection this PR put Pro-only error/gRPC/frontend plumbing into the community codebase for a refusal state nothing can currently produce. Split the remaining work:

    • core#1870: pare nodespace-core back to just the generic SubtreeAccessGate trait + injection point (keep), remove the InaccessibleDescendants error/gRPC/modal chain (defer) until there's a real gate to test it against.
    • nodespace-cloud#103: updated to own the full wire-up (RPC + core's error/gRPC/frontend chain) as one coordinated cross-repo change once it lands.

    Checked ADR-041 and tenant-isolation-rls.md (P7) — both describe the design as a requirement/intent, not an implementation-status claim, so no doc changes needed; this is purely an implementation-sequencing decision that belongs in issues.

  7. added a commit that references this issue on Aug 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions