Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/file-bucket-missing-version-download.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@aws-blocks/bb-file-bucket": patch
"@aws-blocks/blocks": patch
---

Return HTTP 404 for local presigned downloads of unknown or permanently deleted file versions instead of serving the current file's content.
1 change: 1 addition & 0 deletions packages/bb-file-bucket/DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ Creates a single S3 bucket (plus a dedicated log bucket when `accessLogging` is
- Data persists across dev server restarts. Customers can wipe with `rm -rf .bb-data`.
- Presigned URLs are served by the dev file-server at `/.bb-file-bucket/{scope.fullId}/{path}?token=...`. The path segments are URL-encoded; the server decodes them and validates an HMAC token scoped to method, path, and expiry. The HMAC secret (`LOCAL_FILE_SECRET` in `tokens.ts`) is a **per-process random value** — the token-minting mock and the validating dev file-server share the same in-process module instance, so tokens are unforgeable without being a hardcoded, source-visible literal.
- Downloads are served with `X-Content-Type-Options: nosniff` and `Content-Disposition: attachment`. The stored body and its `Content-Type` are caller-controlled, so serving them inline would make the dev file-server a stored-XSS vector (an uploaded `text/html`/SVG payload executing in the app origin). Forcing a download + disabling MIME sniffing is dev-server hardening only; deployed content is served via S3 presigned URLs, where the stored `Content-Type` is caller-chosen and no equivalent `Content-Disposition`/`nosniff` is applied — do not assume this dev-server behavior reflects the deployed path.
- A download with an explicit `versionId` resolves its body and metadata only from that version. A missing version uses the existing HTTP 404 response, without falling back to the current object. Downloads without `versionId` retain their current-object resolution.
- `scan()` recursively walks only the `content/` root, without hiding user keys based on bookkeeping-like filenames. It omits keys with an active delete-marker flag on versioned buckets.
- The dev file-server's PUT handler delegates to the registered `FileBucket` instance (via a process-global registry) so uploads get versioning, key validation, and metadata. There is no direct-write fallback; an unregistered bucket fails loud with a 500.
- Key length validated against S3's 1,024-byte limit (warns, does not reject).
Expand Down
2 changes: 2 additions & 0 deletions packages/bb-file-bucket/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -357,4 +357,6 @@ Object Lock can only be turned on when the bucket is first deployed, and can't b

Mock data persists to disk at `.bb-data/{fullId}/` across dev server restarts. Internal data is segregated into sibling roots so it never collides with your keys: file bodies live under `content/`, metadata under `meta/`, and version history under `versions/`. Wipe with `rm -rf .bb-data`. Presigned URLs are served by the dev server at `/.bb-file-bucket/{fullId}/{path}?token=...`. Version-aware operations are available locally, with the historical delete-marker limitation described under [Versioned Bucket](#versioned-bucket). Lifecycle rules and `corsRules` have no effect locally — the dev file-server accepts browser requests from any origin, so a missing or wrong `corsRules` only shows up after deploy (see [Browser Uploads and Downloads (CORS)](#browser-uploads-and-downloads-cors)).

When a local download URL specifies a `versionId`, only that version is served. An unknown or permanently deleted version returns HTTP 404; it never falls back to the current file. URLs without `versionId` continue to select the current file.


40 changes: 40 additions & 0 deletions packages/bb-file-bucket/src/file-server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,7 @@
await bucket.put('文件/数据.txt', 'unicode content', { contentType: 'text/plain' });

const token = mintFileToken('fsrv-fs-enc4', '文件/数据.txt', 'GET', 3600, LOCAL_FILE_SECRET);
const encodedPath = encodeURIComponent('文件') + '/' + encodeURIComponent('数据.txt');

Check notice on line 319 in packages/bb-file-bucket/src/file-server.test.ts

View workflow job for this annotation

GitHub Actions / Local Build and Checks

lint/style/useTemplate

Template literals are preferred over string concatenation.
const url = `http://localhost:${port}/.bb-file-bucket/fsrv-fs-enc4/${encodedPath}?token=${token}`;

const res = await fetch(url);
Expand Down Expand Up @@ -415,6 +415,46 @@
assert.strictEqual(await res.text(), 'v1');
});

test('GET with an unknown versionId returns 404 instead of the current file', async () => {
const bucket = new FileBucket(scope, 'fs-ver-missing');
await bucket.put('doc.txt', 'current content', { contentType: 'text/plain' });
assert.strictEqual(await bucket.get('doc.txt', { versionId: 'v999' }), null);

const url = (await bucket.getUrl('doc.txt', { versionId: 'v999' }))
.replace(/localhost:\d+/, `localhost:${port}`);
const res = await fetch(url);
assert.strictEqual(res.status, 404);
assert.deepStrictEqual(await res.json(), { error: 'NoSuchKey' });
});

test('GET for a permanently deleted version returns 404 without changing current downloads', async () => {
const bucket = new FileBucket(scope, 'fs-ver-deleted');
await bucket.put('doc.txt', 'old content', { contentType: 'text/csv' });
await bucket.put('doc.txt', 'current content', { contentType: 'text/plain' });
const [current, old] = await bucket.listVersions('doc.txt');
const url = (await bucket.getUrl('doc.txt', { versionId: old.versionId }))
.replace(/localhost:\d+/, `localhost:${port}`);
const before = await fetch(url);
assert.strictEqual(before.status, 200);
assert.strictEqual(before.headers.get('content-type'), 'text/csv');
assert.strictEqual(await before.text(), 'old content');

await bucket.delete('doc.txt', { versionId: old.versionId });
assert.strictEqual(await bucket.get('doc.txt', { versionId: old.versionId }), null);
const deleted = await fetch(url);
assert.strictEqual(deleted.status, 404);
assert.deepStrictEqual(await deleted.json(), { error: 'NoSuchKey' });

for (const options of [undefined, { versionId: current.versionId }]) {
const currentUrl = (await bucket.getUrl('doc.txt', options))
.replace(/localhost:\d+/, `localhost:${port}`);
const res = await fetch(currentUrl);
assert.strictEqual(res.status, 200);
assert.strictEqual(res.headers.get('content-type'), 'text/plain');
assert.strictEqual(await res.text(), 'current content');
}
});

test('rejects a traversal versionId (path-traversal guard)', async () => {
const bucket = new FileBucket(scope, 'fs-ver-traversal', { versioned: true });
await bucket.put('doc.txt', 'secret-contents', { contentType: 'text/plain' });
Expand Down
7 changes: 2 additions & 5 deletions packages/bb-file-bucket/src/file-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,11 +129,8 @@ export function attach(httpServer: Server) {
let readPath = contentPath(dataDir, path);
let metaFilePath = metaPath(dataDir, path);
if (versionId) {
const vPath = versionContentPath(dataDir, path, versionId);
if (existsSync(vPath)) {
readPath = vPath;
metaFilePath = versionMetaPath(dataDir, path, versionId);
}
readPath = versionContentPath(dataDir, path, versionId);
metaFilePath = versionMetaPath(dataDir, path, versionId);
}

if (!existsSync(readPath)) {
Expand Down
4 changes: 4 additions & 0 deletions test-apps/comprehensive/aws-blocks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2320,6 +2320,10 @@ export const api = new ApiNamespace(scope, 'api', (context) => ({
return await versionedBucket.listVersions(path);
},

async vFileGetUrl(path: string, versionId?: string) {
return await versionedBucket.getUrl(path, versionId ? { versionId } : undefined);
},

async vFileRestoreVersion(path: string, versionId: string) {
await versionedBucket.restoreVersion(path, versionId);
return { success: true };
Expand Down
24 changes: 24 additions & 0 deletions test-apps/comprehensive/test/file-bucket.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,30 @@ export function fileBucketTests(getApi: () => typeof apiType) {
assert.strictEqual(file.body, 'original');
});

test('a presigned URL returns 404 after its version is permanently deleted', async () => {
const api = getApi();
const key = `v/deleted-download-${Date.now()}.txt`;
await api.vFilePut(key, 'old content', 'text/csv');
await api.vFilePut(key, 'current content', 'text/plain');
const versions = await api.vFileListVersions(key);
const old = versions[versions.length - 1];
const url = await api.vFileGetUrl(key, old.versionId);
const before = await fetch(url);
assert.strictEqual(before.status, 200);
assert.strictEqual(await before.text(), 'old content');

await api.vFileDelete(key, old.versionId);
assert.strictEqual(await api.vFileGet(key, old.versionId), null);
const deleted = await fetch(url);
assert.strictEqual(deleted.status, 404);
await deleted.text();

const current = await fetch(await api.vFileGetUrl(key));
assert.strictEqual(current.status, 200);
assert.strictEqual(current.headers.get('content-type'), 'text/plain');
assert.strictEqual(await current.text(), 'current content');
});

test('scan skips deleted files', async () => {
const api = getApi();
await api.vFilePut('v/scan-a.txt', 'a');
Expand Down
Loading