capgo icon indicating copy to clipboard operation
capgo copied to clipboard

Block deleted bundle reads from cache

Open slashdevcorpse opened this issue 6 months ago โ€ข 8 comments

Summary

  • Block app-scoped attachment reads when the requested path matches a soft-deleted app_versions.r2_path or a persisted manifest asset path.
  • Run the deleted-bundle check before cache reads and cache-to-R2 restore logic.
  • Keep private download links from resolving deleted bundles.
  • Add indexes for deleted bundle path lookups and persisted manifest path lookups.
  • Add regression coverage for deleted bundle paths, persisted manifest asset paths, and non-deleted cached bundle reads.

/claim #1667

Test plan

  • [x] GitHub CI passed on head 0374e6c.
  • [x] bunx vitest run tests/files-app-read-guard.unit.test.ts
  • [x] bunx vitest run tests/files-app-read-guard.unit.test.ts tests/files-local-read-proxy.unit.test.ts tests/download-link-deleted-bundle.unit.test.ts
  • [x] bunx eslint supabase/functions/_backend/files/files.ts supabase/functions/_backend/private/download_link.ts tests/files-app-read-guard.unit.test.ts tests/files-local-read-proxy.unit.test.ts tests/download-link-deleted-bundle.unit.test.ts
  • [x] git diff --check

Screenshots

Not applicable; backend-only change.

Checklist

  • [x] My code follows the code style of this project and passes the targeted lint checks listed above.
  • [ ] My change requires a change to the documentation.
  • [ ] I have updated the documentation accordingly.
  • [ ] My change has adequate E2E test coverage.
  • [x] I have tested my code manually, and I have provided steps how to reproduce my tests.

slashdevcorpse avatar May 11 '26 01:05 slashdevcorpse

๐Ÿ“ Walkthrough

Walkthrough

Adds a DB-backed soft-deletion guard for app-scoped attachments (checks app_versions/manifest and returns 404), tightens download_link to exclude deleted app_versions, adds indexes, and updates/introduces unit tests plus a shared pgClient mock.

Changes

Soft-Deleted Bundle Read Prevention

Layer / File(s) Summary
Deletion Check Implementation
supabase/functions/_backend/files/files.ts
assertReadableAppScopedAttachment queries public.app_versions (with EXISTS(manifest)) for the requested fileId and throws 404 not_found when a deleted = true match exists.
Download Link Filter
supabase/functions/_backend/private/download_link.ts
app_versions query now requires deleted = false so deleted app versions are excluded from manifest/bundle URL generation.
DB Indexes Migration
supabase/migrations/20260511012637_add_app_versions_deleted_r2_path_index.sql
Adds partial index idx_app_versions_deleted_r2_path on (owner_org, app_id, r2_path) for deleted = true and index idx_manifest_app_version_id_s3_path on manifest(app_version_id, s3_path).
Test Mock Infrastructure
tests/files-app-read-guard.unit.test.ts, tests/files-local-read-proxy.unit.test.ts
Introduces a shared pgClientMock with query = vi.fn() and sets default resolution { rows: [] } in beforeEach.
Files Read Guard Tests
tests/files-app-read-guard.unit.test.ts
New tests assert 404 for soft-deleted .zip and manifest asset paths (verifying queries include FROM public.app_versions or FROM public.manifest and bucketPut is not called), and a case that cached bytes are served for non-deleted bundles.
Download Link Deleted-Bundle Test
tests/download-link-deleted-bundle.unit.test.ts
New test mounts download_link, posts a request, asserts a 400 cannot_get_bundle, verifies deleted = false was applied to the DB filter, and confirms no bundle URL generation occurred.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant assertReadableAppScopedAttachment
  participant PostgreSQL
  participant AttachmentCache
  Client->>assertReadableAppScopedAttachment: GET app-scoped attachment (fileId)
  assertReadableAppScopedAttachment->>PostgreSQL: SELECT FROM public.app_versions / EXISTS(public.manifest) with (owner_org, app_id, fileId)
  alt deleted match found
    PostgreSQL-->>assertReadableAppScopedAttachment: deleted row found
    assertReadableAppScopedAttachment-->>Client: 404 not_found
  else no deleted match
    PostgreSQL-->>assertReadableAppScopedAttachment: no deleted row
    assertReadableAppScopedAttachment->>AttachmentCache: request cached bytes or fallback read
    AttachmentCache-->>Client: 200 + bytes
  end

Estimated Code Review Effort

๐ŸŽฏ 3 (Moderate) | โฑ๏ธ ~20 minutes

Possibly Related PRs

  • Cap-go/capgo#1964: Related changes that add DB checks to files-serving/read guards for deleted app versions and manifests.
  • Cap-go/capgo#2037: Also touches files.ts and app_versions r2_path checks; related guard logic for attachment operations.
  • Cap-go/capgo#2057: Hardens attachment/download-read behavior with DB-level checks similar to this PR.

Poem

๐Ÿฐ A little rabbit hops and peeks the log,
Guards the bundles by the Postgres bog,
If a version's soft-deleted, it won't run free,
"Not found" it says โ€” safe bytes wait patiently. ๐Ÿฅ•โœจ

๐Ÿšฅ Pre-merge checks | โœ… 4 | โŒ 1

โŒ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage โš ๏ธ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
โœ… Passed checks (4 passed)
Check name Status Explanation
Title check โœ… Passed The title accurately summarizes the main change: blocking deleted bundle reads from cache, which is the primary objective across all modified files.
Linked Issues check โœ… Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check โœ… Passed Check skipped because no linked issues were found for this pull request.
Description check โœ… Passed The PR description includes all required sections: Summary, Test plan with specific command verification steps, Screenshots (marked N/A for backend), and a complete Checklist with most items checked as applicable.

โœ๏ธ Tip: You can configure your own custom pre-merge checks in the settings.

โœจ Finishing Touches
๐Ÿงช Generate unit tests (beta)
  • [ ] Create PR with unit tests

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 and usage tips.

coderabbitai[bot] avatar May 11 '26 01:05 coderabbitai[bot]

Merging this PR will not alter performance

โœ… 43 untouched benchmarks
โฉ 2 skipped benchmarks[^skipped]


Comparing slashdevcorpse:codex/capgo-deleted-bundle-read-guard (0374e6c) with main (38e5856)[^unexpected-base]

Open in CodSpeed

[^skipped]: 2 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. [^unexpected-base]: No successful run was found on main (3d184f8) during the generation of this report, so 38e5856 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report.

codspeed[bot] avatar May 11 '26 01:05 codspeed[bot]

Addressed the index and coverage feedback.

Current head cec23dc now:

  • checks deleted r2_path and stored manifest asset paths before cache reads or cache-to-R2 restore
  • filters deleted bundles in /private/download_link
  • adds the partial deleted-path index plus regression coverage for deleted zip paths, deleted manifest asset paths, non-deleted cached reads, and private download links

CI is green on the current head.

slashdevcorpse avatar May 11 '26 02:05 slashdevcorpse

Pushed 0374e6c to address the read-guard review feedback.

Changes:

  • The deleted-asset guard now checks persisted public.manifest rows instead of the cleared app_versions.manifest array.
  • Added idx_manifest_app_version_id_s3_path alongside the deleted app_versions.r2_path partial index.
  • Updated the regression to cover persisted manifest asset paths and keep the positive cached-read case.

Validation:

  • bunx vitest run tests/files-app-read-guard.unit.test.ts
  • git diff --check

slashdevcorpse avatar May 11 '26 02:05 slashdevcorpse

The manifest-file cache guard still has a hole after the normal deleted-version cleanup runs. assertReadableAppScopedAttachment() only blocks a delta object when it can join the requested s3_path back through public.manifest to a deleted app_versions row. But the existing delete path calls deleteManifest() when a version is soft-deleted, and that deletes the manifest rows before/while deleting the R2 objects. If a delta object was already in the edge cache, the later /files/read/attachments/orgs/.../delta/... request no longer has any manifest row to match, so the new query returns empty and the handler can still serve the stale cached object.

The new tests cover the direct bundle r2_path case, but not this manifest-row-removed case. To actually close deleted partial reads, the guard needs a durable tombstone/path index that survives manifest row cleanup, or the delete flow needs to preserve enough path metadata until caches are guaranteed cold. A regression should seed/cache a manifest attachment path, soft-delete the version so its manifest row is removed, then assert the cached /delta/... read is still blocked.

digzrow-coder avatar May 13 '26 18:05 digzrow-coder

The DB-side guard work here looks solid -- the manifest persistence concern @digzrow-coder and @KCDaemon raised is the biggest miss to address before merging. Two additional gaps worth considering since they sit upstream of this guard and aren't covered by the new tests.

1. Edge / CDN caching can serve deleted bundle bytes despite the DB guard

assertReadableAppScopedAttachment runs inside the files worker, which is great for first-fetch paths. But two upstream layers can return a cached copy without invoking the worker:

  • Cloudflare R2 + the worker's own cache.match() paths. If the same fileId was successfully fetched before deletion, Workers Cache (and any CDN sitting in front) may have a 200 response keyed on the URL. assertReadableAppScopedAttachment only protects the slow path. A client hitting the cached path won't run this check at all.
  • Pre-existing browser caches, especially when the underlying R2 object was served with a long Cache-Control: public, max-age=... and no per-org ETag/varying header. The browser revalidates against the URL, not against the DB.

For SaaS billing/customer-data bundles this is the exact "deleted but still accessible" scenario the PR is trying to close. Suggested follow-ups:

  • After app_versions.deleted = true, enqueue caches.default.delete(<canonical url>) for every variant URL that targets the deleted r2_path and persisted manifest.s3_path.
  • Add a Cache-Control: private, must-revalidate (or short max-age) to app-scoped attachment responses so the browser doesn't keep a long-lived copy past deletion.
  • Add a regression test that primes the worker cache for a path, soft-deletes, and asserts the next request returns 404 -- not the cached 200.

2. Signed download links already issued continue to resolve after deletion

download_link.ts now adds .eq('deleted', false) so new signed URLs can't be minted for a deleted bundle. But signed URLs minted before deletion keep working for the remainder of their TTL because the resolver they point to doesn't recheck app_versions.deleted.

If TTLs are short (minutes) the exposure window is small; if TTLs are hour/day-scale (common for big bundle downloads) the deletion is essentially advisory until expiry.

Two options, low to high effort:

  • Cheap: keep the new check, but also wire the soft-delete write to bump a per-app/per-version signing_epoch column and include it in the signed payload, then have the resolver reject if epoch < app_version.signing_epoch.
  • Cheaper still: shorten TTL on download_link issuance and document the window.

A test that issues a signed URL, soft-deletes the version, and asserts the URL returns 404 would make either fix verifiable.


Neither blocks the direct-fetch fix that's the meat of this PR, but both undercut the security claim if left out. Happy to send a follow-up PR with the cache-invalidate path + a regression test if there's interest.

austin33133-maker avatar May 15 '26 02:05 austin33133-maker

I could not push to the original slashdevcorpse/capgo PR branch from this GitHub account, so I rebased the fix onto current main and pushed it here:

  • Branch: https://github.com/digzrow-coder/capgo/tree/codex/capgo-deleted-bundle-read-guard
  • Fork PR with exact diff: https://github.com/digzrow-coder/capgo/pull/1
  • Head commit: f64ebc3b7 (Persist deleted manifest path tombstones)

This addresses the remaining blocker from @KCDaemon: the guard no longer depends only on a live public.manifest row. Before deleteManifest() removes manifest rows, it writes durable deleted_app_version_manifest_paths tombstones keyed by (app_version_id, s3_path), and the attachment read guard checks those tombstones before cache/R2 reads. That keeps cached manifest/delta asset requests blocked after the normal manifest cleanup path has removed the original rows.

Validation on the rebased branch:

  • bun x vitest run tests/files-app-read-guard.unit.test.ts tests/files-local-read-proxy.unit.test.ts tests/download-link-deleted-bundle.unit.test.ts tests/on-version-update-cleanup.unit.test.ts -> 4 files / 13 tests passed
  • bun x eslint supabase/functions/_backend/files/files.ts supabase/functions/_backend/triggers/on_version_update.ts supabase/functions/_backend/private/download_link.ts tests/download-link-deleted-bundle.unit.test.ts tests/files-app-read-guard.unit.test.ts tests/files-local-read-proxy.unit.test.ts tests/on-version-update-cleanup.unit.test.ts
  • git diff --check

I also tried opening a replacement PR from digzrow-coder/capgo to Cap-go/capgo, but GitHub returned digzrow-coder does not have the correct permissions to execute CreatePullRequest. If a maintainer can either allow a PR from that fork or apply/cherry-pick f64ebc3b7, this should remove the stale-cache blocker and the merge conflict at the same time.

digzrow-coder avatar May 15 '26 05:05 digzrow-coder