Block deleted bundle reads from cache
Summary
- Block app-scoped attachment reads when the requested path matches a soft-deleted
app_versions.r2_pathor 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.
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. Soft-Deleted Bundle Read Prevention ๐ฏ 3 (Moderate) | โฑ๏ธ ~20 minutes ๐ฐ A little rabbit hops and peeks the log, โ๏ธ Tip: You can configure your own custom pre-merge checks in the settings.๐ Walkthrough
Walkthrough
Changes
Layer / File(s)
Summary
Deletion Check Implementation
supabase/functions/_backend/files/files.tsassertReadableAppScopedAttachment 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.tsapp_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.sqlAdds 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.tsIntroduces 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.tsNew 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.tsNew 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
Possibly Related PRs
files.ts and app_versions r2_path checks; related guard logic for attachment operations.Poem
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.
โจ Finishing Touches
๐งช Generate unit tests (beta)
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 @coderabbitai help to get the list of available commands and usage tips.
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]
[^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.
Addressed the index and coverage feedback.
Current head cec23dc now:
- checks deleted
r2_pathand 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.
Pushed 0374e6c to address the read-guard review feedback.
Changes:
- The deleted-asset guard now checks persisted
public.manifestrows instead of the clearedapp_versions.manifestarray. - Added
idx_manifest_app_version_id_s3_pathalongside the deletedapp_versions.r2_pathpartial 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.tsgit diff --check
Quality Gate passed
Issues
0 New issues
0 Accepted issues
Measures
0 Security Hotspots
0.0% Coverage on New Code
0.0% Duplication on New Code
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.
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 samefileIdwas successfully fetched before deletion, Workers Cache (and any CDN sitting in front) may have a 200 response keyed on the URL.assertReadableAppScopedAttachmentonly 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, enqueuecaches.default.delete(<canonical url>)for every variant URL that targets the deletedr2_pathand persistedmanifest.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_epochcolumn and include it in the signed payload, then have the resolver reject ifepoch < app_version.signing_epoch. - Cheaper still: shorten TTL on
download_linkissuance 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.
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 passedbun 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.tsgit 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.