From 017b18dff4c1ac963cf53c75c356124db49a6341 Mon Sep 17 00:00:00 2001 From: Kento Ikeda Date: Mon, 5 Oct 2026 08:40:27 +0900 Subject: [PATCH 1/3] fix(bb-file-bucket): reconcile current files after version deletion --- .../file-bucket-current-version-deletion.md | 6 + packages/bb-file-bucket/DESIGN.md | 1 + packages/bb-file-bucket/README.md | 2 + .../src/current-version-deletion.test.ts | 161 ++++++++++++++++++ .../bb-file-bucket/src/file-server.test.ts | 24 +++ packages/bb-file-bucket/src/index.mock.ts | 79 ++++++--- .../comprehensive/test/file-bucket.test.ts | 42 +++++ 7 files changed, 288 insertions(+), 27 deletions(-) create mode 100644 .changeset/file-bucket-current-version-deletion.md create mode 100644 packages/bb-file-bucket/src/current-version-deletion.test.ts diff --git a/.changeset/file-bucket-current-version-deletion.md b/.changeset/file-bucket-current-version-deletion.md new file mode 100644 index 0000000000..ecab7cfb92 --- /dev/null +++ b/.changeset/file-bucket-current-version-deletion.md @@ -0,0 +1,6 @@ +--- +'@aws-blocks/bb-file-bucket': patch +'@aws-blocks/blocks': patch +--- + +Fix local FileBucket version deletion so removing the current version promotes the next stored version, including its metadata, for reads, scans, and downloads. Removing the last stored version now removes the current file instead of leaving deleted content accessible. Existing delete markers and older-version deletion behavior are preserved. diff --git a/packages/bb-file-bucket/DESIGN.md b/packages/bb-file-bucket/DESIGN.md index bc3e80f450..b592e36061 100644 --- a/packages/bb-file-bucket/DESIGN.md +++ b/packages/bb-file-bucket/DESIGN.md @@ -108,6 +108,7 @@ Creates a single S3 bucket (plus a dedicated log bucket when `accessLogging` is - Key length validated against S3's 1,024-byte limit (warns, does not reject). - Object keys are validated identically on the mock and the AWS runtime via the shared, filesystem-independent `assertValidKey` (`validation.ts`), called from every key-accepting method on both layers. It rejects (`ValidationFailed`) an empty/non-string key, a leading slash, an empty path segment (interior `a//b` or trailing `a/`, which the mock's `path.join` would otherwise collapse while S3 keeps literal), ASCII control characters, and a `..`/`.` path segment. The mock additionally applies a filesystem realpath/symlink containment guard (`assertContainedPath`) as local-only defense. `deleteBatch` validates every key up front on both layers, so a mixed valid/invalid batch deletes nothing. - Versioning fully supported: each `put` writes to `versions/{key}/v{n}`, delete without `versionId` places a `__deleted__` sentinel, `listVersions` reads the versions directory, `restoreVersion` copies an old version via `put`. +- Deleting the newest stored version updates the current `content/` and `meta/` copies from the next version, including its original modification time, without creating a new version or removing a delete marker. Deleting the last stored version removes the current copies. Deleting older or unknown versions leaves the current copies unchanged. The synchronous version reader is shared with `listVersions()`, so selection follows the same newest-first ordering and deletion does not yield between reading and reconciling the version history. ### Mock vs AWS Behavior Differences diff --git a/packages/bb-file-bucket/README.md b/packages/bb-file-bucket/README.md index 6bdf3cc319..dd7aec3a7c 100644 --- a/packages/bb-file-bucket/README.md +++ b/packages/bb-file-bucket/README.md @@ -216,6 +216,8 @@ export const api = new ApiNamespace(scope, 'api', (context) => ({ })); ``` +On a versioned bucket, `delete(path)` creates a delete marker without removing stored versions; `get()` returns `null` and `scan()` omits the file. `delete(path, { versionId })` permanently removes that specific version. Deleting the current version makes the newest remaining version current, unless a delete marker still hides it from these reads. Deleting the last stored version leaves no file to retrieve or list in `scan()`. The local mock follows S3's version-deletion behavior without creating a replacement version. + ### Access Logging Opt in to S3 server access logging. A dedicated, locked-down log bucket is provisioned and access logs expire automatically after the stack posture's `logRetention` (`ONE_WEEK` in sandbox, `ONE_YEAR` in production): diff --git a/packages/bb-file-bucket/src/current-version-deletion.test.ts b/packages/bb-file-bucket/src/current-version-deletion.test.ts new file mode 100644 index 0000000000..50fa2eaf32 --- /dev/null +++ b/packages/bb-file-bucket/src/current-version-deletion.test.ts @@ -0,0 +1,161 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { test, beforeEach, afterEach } from 'node:test'; +import assert from 'node:assert/strict'; +import { existsSync, readFileSync, rmSync, statSync, utimesSync } from 'node:fs'; +import { join } from 'node:path'; +import { Scope } from '@aws-blocks/core'; +import { FileBucket } from './index.mock.js'; +import { contentPath, metaPath, deleteMarkerPath, versionContentPath } from './paths.js'; + +const scope = new Scope('version-delete'); +const bucketId = 'files'; +const dataDir = join(process.cwd(), '.bb-data', `${scope.fullId}-${bucketId}`); +const key = 'reports/document.txt'; + +beforeEach(() => rmSync(dataDir, { recursive: true, force: true })); +afterEach(() => rmSync(dataDir, { recursive: true, force: true })); + +async function scanFiles(bucket: FileBucket) { + const files = []; + for await (const file of bucket.scan()) files.push(file); + return files; +} + +async function putVersions(bucket: FileBucket) { + await bucket.put(key, 'old', { + contentType: 'text/plain', + metadata: { revision: 'old' }, + cacheControl: 'max-age=60', + }); + await bucket.put(key, 'new content', { + contentType: 'text/csv', + metadata: { revision: 'new' }, + cacheControl: 'no-cache', + }); + return bucket.listVersions(key); +} + +test('deleting the current version promotes the previous body and metadata without a new version', async () => { + const bucket = new FileBucket(scope, bucketId); + const [latest, previous] = await putVersions(bucket); + const timestamp = new Date('2020-01-01T00:00:00.000Z'); + utimesSync(versionContentPath(dataDir, key, previous.versionId), timestamp, timestamp); + await bucket.delete(key, { versionId: latest.versionId }); + const file = await bucket.get(key); + assert.ok(file); + assert.equal(file.body.toString(), 'old'); + assert.equal(file.contentType, 'text/plain'); + assert.deepEqual(file.metadata, { revision: 'old' }); + assert.equal(file.size, 3); + assert.equal(JSON.parse(readFileSync(metaPath(dataDir, key), 'utf8')).cacheControl, 'max-age=60'); + assert.equal(await bucket.get(key, { versionId: latest.versionId }), null); + const versions = await bucket.listVersions(key); + assert.equal(versions.length, 1); + assert.equal(versions[0].versionId, previous.versionId); + assert.equal(versions[0].isCurrent, true); + const files = await scanFiles(bucket); + assert.equal(files.length, 1); + assert.equal(files[0].size, 3); + assert.equal(files[0].lastModified.getTime(), timestamp.getTime()); + const reopened = new FileBucket(scope, bucketId); + assert.equal((await reopened.get(key))?.body.toString(), 'old'); + assert.deepEqual((await reopened.get(key))?.metadata, { revision: 'old' }); +}); + +test('equal version timestamps use the same numeric ordering as listVersions', async () => { + const bucket = new FileBucket(scope, bucketId); + await bucket.put(key, 'first'); + await bucket.put(key, 'second'); + await bucket.put(key, 'third'); + const timestamp = new Date('2020-01-01T00:00:00.000Z'); + for (const version of await bucket.listVersions(key)) { + utimesSync(versionContentPath(dataDir, key, version.versionId), timestamp, timestamp); + } + const [latest, previous] = await bucket.listVersions(key); + await bucket.delete(key, { versionId: latest.versionId }); + assert.equal((await bucket.get(key))?.body.toString(), 'second'); + assert.equal((await bucket.listVersions(key))[0].versionId, previous.versionId); +}); + +test('deleting the only version removes the current body and sidecar', async () => { + const bucket = new FileBucket(scope, bucketId); + await bucket.put(key, 'only'); + const [version] = await bucket.listVersions(key); + await bucket.delete(key, { versionId: version.versionId }); + assert.equal(await bucket.get(key), null); + assert.deepEqual(await scanFiles(bucket), []); + assert.deepEqual(await bucket.listVersions(key), []); + assert.equal(existsSync(contentPath(dataDir, key)), false); + assert.equal(existsSync(metaPath(dataDir, key)), false); +}); + +test('repeated newest-first deletion promotes each remaining version and then removes the file', async () => { + const bucket = new FileBucket(scope, bucketId); + await bucket.put(key, 'first'); + await bucket.put(key, 'second'); + await bucket.put(key, 'third'); + for (const expected of ['second', 'first', null]) { + const [current] = await bucket.listVersions(key); + await bucket.delete(key, { versionId: current.versionId }); + assert.equal((await bucket.get(key))?.body.toString() ?? null, expected); + } + assert.deepEqual(await scanFiles(bucket), []); +}); + +test('deleting an older version leaves current content, metadata, and modification time unchanged', async () => { + const bucket = new FileBucket(scope, bucketId); + const [latest, previous] = await putVersions(bucket); + const before = statSync(contentPath(dataDir, key)).mtimeMs; + await bucket.delete(key, { versionId: previous.versionId }); + assert.equal((await bucket.get(key))?.body.toString(), 'new content'); + assert.deepEqual((await bucket.get(key))?.metadata, { revision: 'new' }); + assert.equal(statSync(contentPath(dataDir, key)).mtimeMs, before); + assert.equal((await bucket.listVersions(key))[0].versionId, latest.versionId); +}); + +test('deleting an unknown version is a no-op for existing and missing objects', async () => { + const bucket = new FileBucket(scope, bucketId); + const versions = await putVersions(bucket); + const before = statSync(contentPath(dataDir, key)).mtimeMs; + await bucket.delete(key, { versionId: 'v999' }); + await bucket.delete('missing.txt', { versionId: 'v999' }); + assert.equal((await bucket.get(key))?.body.toString(), 'new content'); + assert.equal(statSync(contentPath(dataDir, key)).mtimeMs, before); + assert.deepEqual(await bucket.listVersions(key), versions); + assert.equal(await bucket.get('missing.txt'), null); +}); + +test('deleting versions does not remove an existing delete marker or resurrect the object', async () => { + const bucket = new FileBucket(scope, bucketId); + const versions = await putVersions(bucket); + await bucket.delete(key); + for (const version of versions) { + await bucket.delete(key, { versionId: version.versionId }); + assert.equal(await bucket.get(key), null); + assert.deepEqual(await scanFiles(bucket), []); + assert.equal(existsSync(deleteMarkerPath(dataDir, key)), true); + assert.ok((await bucket.listVersions(key)).every((remaining) => !remaining.isCurrent)); + } + assert.equal(existsSync(contentPath(dataDir, key)), false); + await bucket.put(key, 'uploaded again'); + assert.equal((await bucket.get(key))?.body.toString(), 'uploaded again'); +}); + +test('concurrent version deletions do not retain a stale current copy', async () => { + const bucket = new FileBucket(scope, bucketId); + const versions = await putVersions(bucket); + await Promise.all(versions.map((version) => bucket.delete(key, { versionId: version.versionId }))); + assert.equal(await bucket.get(key), null); + assert.deepEqual(await bucket.listVersions(key), []); + assert.deepEqual(await scanFiles(bucket), []); +}); + +test('non-versioned deletion still removes the object', async () => { + const bucket = new FileBucket(scope, bucketId, { versioned: false }); + await bucket.put(key, 'data'); + await bucket.delete(key); + assert.equal(await bucket.get(key), null); + assert.deepEqual(await scanFiles(bucket), []); +}); diff --git a/packages/bb-file-bucket/src/file-server.test.ts b/packages/bb-file-bucket/src/file-server.test.ts index 91f5ab0871..bbf3cd53bb 100644 --- a/packages/bb-file-bucket/src/file-server.test.ts +++ b/packages/bb-file-bucket/src/file-server.test.ts @@ -347,6 +347,30 @@ describe('file-server: URL-encoded paths', () => { // ── Versioning integration ────────────────────────────────────────────────── describe('file-server: versioning', () => { + test('current download serves the previous version after deleting the latest version', async () => { + const bucket = new FileBucket(scope, 'fs-delete-current'); + await bucket.put('doc.txt', 'old', { contentType: 'text/plain' }); + await bucket.put('doc.txt', 'new content', { contentType: 'text/csv' }); + const [latest] = await bucket.listVersions('doc.txt'); + const url = (await bucket.getUrl('doc.txt')).replace(/localhost:\d+/, `localhost:${port}`); + await bucket.delete('doc.txt', { versionId: latest.versionId }); + const res = await fetch(url); + assert.strictEqual(res.status, 200); + assert.strictEqual(res.headers.get('content-type'), 'text/plain'); + assert.strictEqual(await res.text(), 'old'); + }); + + test('current download returns 404 after permanently deleting all versions', async () => { + const bucket = new FileBucket(scope, 'fs-delete-all'); + await bucket.put('doc.txt', 'only'); + const [version] = await bucket.listVersions('doc.txt'); + const url = (await bucket.getUrl('doc.txt')).replace(/localhost:\d+/, `localhost:${port}`); + await bucket.delete('doc.txt', { versionId: version.versionId }); + const res = await fetch(url); + assert.strictEqual(res.status, 404); + await res.text(); + }); + test('PUT via presigned URL creates a new version', async () => { const bucket = new FileBucket(scope, 'fs-ver1', { versioned: true }); await bucket.put('doc.txt', 'v1-api', { contentType: 'text/plain' }); diff --git a/packages/bb-file-bucket/src/index.mock.ts b/packages/bb-file-bucket/src/index.mock.ts index 6009986932..3e1875ec9d 100644 --- a/packages/bb-file-bucket/src/index.mock.ts +++ b/packages/bb-file-bucket/src/index.mock.ts @@ -4,7 +4,9 @@ import { Scope, blocksError, registerSdkIdentifiers } from '@aws-blocks/core'; import { getMockDataDir } from '@aws-blocks/core/bb-utils'; import type { ScopeParent } from '@aws-blocks/core'; -import { existsSync, mkdirSync, readFileSync, writeFileSync, unlinkSync, readdirSync, statSync } from 'node:fs'; +import { + existsSync, mkdirSync, readFileSync, writeFileSync, unlinkSync, readdirSync, statSync, copyFileSync, utimesSync, +} from 'node:fs'; import { dirname, join, relative } from 'node:path'; import { assertContainedPath } from './mock-utils.js'; import { @@ -212,9 +214,28 @@ export class FileBucket extends this.validateKey(path); const versionId = (options as any)?.versionId as string | undefined; if (this.versioned && versionId) { - // Permanently delete a specific version - try { unlinkSync(versionContentPath(this.dataDir, path, versionId)); } catch {} + const versions = this.readVersions(path); + if (!versions.some(version => version.versionId === versionId)) return; + unlinkSync(versionContentPath(this.dataDir, path, versionId)); try { unlinkSync(versionMetaPath(this.dataDir, path, versionId)); } catch {} + if (versions[0].versionId !== versionId) return; + + // The current copy is also read by scan() and the dev file-server. + // Promote the next version without put(), which would create a new version + // and remove any existing delete marker. + const next = versions[1]; + if (next) { + const filePath = contentPath(this.dataDir, path); + const source = versionContentPath(this.dataDir, path, next.versionId); + const stat = statSync(source); + mkdirSync(dirname(filePath), { recursive: true }); + copyFileSync(source, filePath); + utimesSync(filePath, stat.atime, stat.mtime); + this.writeMeta(path, this.readVersionMeta(path, next.versionId)); + } else { + try { unlinkSync(contentPath(this.dataDir, path)); } catch {} + try { unlinkSync(metaPath(this.dataDir, path)); } catch {} + } return; } if (this.versioned) { @@ -429,30 +450,7 @@ export class FileBucket extends */ async listVersions(path: string): Promise { this.validateKey(path); - const versionsDir = versionsDirFor(this.dataDir, path); - if (!existsSync(versionsDir)) return []; - const entries = readdirSync(versionsDir).filter(isVersionEntry); - if (entries.length === 0) return []; - - const hasDeleteMarker = existsSync(deleteMarkerPath(this.dataDir, path)); - const versions: FileVersionInfo[] = entries.map(versionId => { - const vPath = versionContentPath(this.dataDir, path, versionId); - const stat = statSync(vPath); - return { versionId, lastModified: stat.mtime, size: stat.size, isCurrent: false }; - }); - // Sort newest first; break ties by version number (descending) for deterministic ordering - versions.sort((a, b) => { - const timeDiff = b.lastModified.getTime() - a.lastModified.getTime(); - if (timeDiff !== 0) return timeDiff; - const aNum = parseInt(a.versionId.slice(1), 10); - const bNum = parseInt(b.versionId.slice(1), 10); - return bNum - aNum; - }); - // Mark the newest as current (unless there's a delete marker) - if (versions.length > 0 && !hasDeleteMarker) { - versions[0].isCurrent = true; - } - return versions; + return this.readVersions(path); } /** @@ -492,6 +490,33 @@ export class FileBucket extends // ── Internal helpers ────────────────────────────────────────────────── + private readVersions(path: string): FileVersionInfo[] { + const versionsDir = versionsDirFor(this.dataDir, path); + if (!existsSync(versionsDir)) return []; + const entries = readdirSync(versionsDir).filter(isVersionEntry); + if (entries.length === 0) return []; + + const hasDeleteMarker = existsSync(deleteMarkerPath(this.dataDir, path)); + const versions: FileVersionInfo[] = entries.map(versionId => { + const vPath = versionContentPath(this.dataDir, path, versionId); + const stat = statSync(vPath); + return { versionId, lastModified: stat.mtime, size: stat.size, isCurrent: false }; + }); + // Sort newest first; break ties by version number (descending) for deterministic ordering + versions.sort((a, b) => { + const timeDiff = b.lastModified.getTime() - a.lastModified.getTime(); + if (timeDiff !== 0) return timeDiff; + const aNum = parseInt(a.versionId.slice(1), 10); + const bNum = parseInt(b.versionId.slice(1), 10); + return bNum - aNum; + }); + // Mark the newest as current (unless there's a delete marker) + if (versions.length > 0 && !hasDeleteMarker) { + versions[0].isCurrent = true; + } + return versions; + } + private validateKey(key: string): void { // Portable, filesystem-independent key rules shared with the AWS runtime, // so a key rejected here is rejected identically on AWS (and vice versa). diff --git a/test-apps/comprehensive/test/file-bucket.test.ts b/test-apps/comprehensive/test/file-bucket.test.ts index fa0af472a7..2c539db92d 100644 --- a/test-apps/comprehensive/test/file-bucket.test.ts +++ b/test-apps/comprehensive/test/file-bucket.test.ts @@ -250,6 +250,48 @@ export function fileBucketTests(getApi: () => typeof apiType) { // ── Versioned FileBucket ────────────────────────────────────────────── describe('Versioned', () => { + test('deleting the current version promotes the previous version through the API', async () => { + const api = getApi(); + const path = `v/delete-current-${crypto.randomUUID()}.txt`; + try { + await api.vFilePut(path, 'old', 'text/plain'); + await api.vFilePut(path, 'new content', 'text/csv'); + const [latest, previous] = await api.vFileListVersions(path); + await api.vFileDelete(path, latest.versionId); + const file = await api.vFileGet(path); + assert.ok(file); + assert.strictEqual(file.body, 'old'); + assert.strictEqual(file.contentType, 'text/plain'); + assert.strictEqual(file.size, 3); + assert.strictEqual(await api.vFileGet(path, latest.versionId), null); + const remaining = await api.vFileListVersions(path); + assert.strictEqual(remaining.length, 1); + assert.strictEqual(remaining[0].versionId, previous.versionId); + assert.strictEqual(remaining[0].isCurrent, true); + const files = await api.vFileScan(path); + assert.strictEqual(files.length, 1); + assert.strictEqual(files[0].size, 3); + } finally { + await api.vFilePurge(path); + } + }); + + test('permanently deleting every version removes the object from reads and scans', async () => { + const api = getApi(); + const path = `v/delete-all-${crypto.randomUUID()}.txt`; + try { + await api.vFilePut(path, 'old'); + await api.vFilePut(path, 'new content'); + const versions = await api.vFileListVersions(path); + for (const version of versions) await api.vFileDelete(path, version.versionId); + assert.deepStrictEqual(await api.vFileListVersions(path), []); + assert.strictEqual(await api.vFileGet(path), null); + assert.deepStrictEqual(await api.vFileScan(path), []); + } finally { + await api.vFilePurge(path); + } + }); + // Clean up any leftover versions from previous runs test.before(async () => { const api = getApi(); From a4f3d602587ad084a3c6ea31f4dc303529b3a54a Mon Sep 17 00:00:00 2001 From: Kento Ikeda Date: Sat, 31 Oct 2026 06:24:56 +0900 Subject: [PATCH 2/3] docs(file-bucket): clarify historical delete-marker limitation --- .../file-bucket-current-version-deletion.md | 2 +- packages/bb-file-bucket/DESIGN.md | 10 ++++---- packages/bb-file-bucket/README.md | 23 +++++++++++++++++-- 3 files changed, 28 insertions(+), 7 deletions(-) diff --git a/.changeset/file-bucket-current-version-deletion.md b/.changeset/file-bucket-current-version-deletion.md index ecab7cfb92..de0d0ccfe0 100644 --- a/.changeset/file-bucket-current-version-deletion.md +++ b/.changeset/file-bucket-current-version-deletion.md @@ -3,4 +3,4 @@ '@aws-blocks/blocks': patch --- -Fix local FileBucket version deletion so removing the current version promotes the next stored version, including its metadata, for reads, scans, and downloads. Removing the last stored version now removes the current file instead of leaving deleted content accessible. Existing delete markers and older-version deletion behavior are preserved. +Fix local FileBucket version deletion so removing the newest stored data version updates the current body and metadata from the next stored data version, or removes the current copies when none remain. Active delete-marker flags and older-version deletion behavior are preserved. Document that historical delete markers discarded by a subsequent upload are not reconstructed, so deletion across re-uploads still differs from S3. diff --git a/packages/bb-file-bucket/DESIGN.md b/packages/bb-file-bucket/DESIGN.md index 6cd0d9a43a..fb202654e6 100644 --- a/packages/bb-file-bucket/DESIGN.md +++ b/packages/bb-file-bucket/DESIGN.md @@ -21,7 +21,7 @@ versions/{key}/{versionId} version body versions/{key}/{versionId}.json version metadata versions/{key}/__deleted__ delete marker (sentinel) ``` -**Rationale:** Keeps file content byte-identical (no wrapping format) while guaranteeing internal bookkeeping can never collide with user keys. An earlier design co-located metadata as `{path}.__meta__.json` next to each file and relied on marker substrings, which meant a user key like `data.__meta__.json` or a directory named `x.__versions__/` could be silently hidden or shadowed by `scan()`. Because user content now lives only under `content/`, `scan()` walks that one root and yields everything with no marker-based filtering — arbitrary keys are supported, matching S3 semantics. +**Rationale:** Keeps file content byte-identical (no wrapping format) while guaranteeing internal bookkeeping can never collide with user keys. An earlier design co-located metadata as `{path}.__meta__.json` next to each file and relied on marker substrings, which meant a user key like `data.__meta__.json` or a directory named `x.__versions__/` could be silently hidden or shadowed by `scan()`. Because user content now lives only under `content/`, `scan()` walks that root without filtering by bookkeeping-like filenames. On versioned buckets it separately omits keys with an active delete-marker flag. **D-FB-3: deleteBatch chunks at 1,000** **Decision:** `deleteBatch()` internally chunks into groups of 1,000 and issues separate `DeleteObjects` calls. @@ -43,6 +43,7 @@ versions/{key}/__deleted__ delete marker (sentinel) **D-FB-7: Mock versioning uses filesystem directories** **Decision:** Versioned mock stores each version in `versions/{key}/v{n}` with monotonic IDs. Delete markers are `versions/{key}/__deleted__` sentinel files. **Rationale:** Simple, inspectable, and matches the S3 semantics closely enough for local development. Monotonic IDs (`v1`, `v2`, ...) are deterministic and easy to reason about in tests, unlike S3's opaque version IDs. Version history lives under the segregated `versions/` root (see D-FB-2), so it never appears in `scan()` or collides with a user key. +**Limitation:** The sentinel represents only the active deleted state. `put()` removes it rather than retaining a historical delete-marker entry. Deleting a later upload therefore cannot make an earlier marker current again, unlike S3. See "Historical delete markers are not retained" below. **D-FB-8: Bucket name validated at synth — error, never truncate/hash** **Decision:** The derived bucket name (`scope.fullId`) is validated against S3's naming rules (`bucket-name.ts`) before the bucket is constructed. An invalid name throws a `ValidationFailed` error with an actionable message. The same validator runs in the mock constructor so local dev (`bb dev`) fails identically — parity. `FileBucket.fromExisting(...)` skips validation since the name is externally owned. @@ -121,17 +122,18 @@ 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. -- `scan()` recursively walks only the `content/` root and yields every file it finds — no marker-based filtering — so user keys are unrestricted. +- `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). - Object keys are validated identically on the mock and the AWS runtime via the shared, filesystem-independent `assertValidKey` (`validation.ts`), called from every key-accepting method on both layers. It rejects (`ValidationFailed`) an empty/non-string key, a leading slash, an empty path segment (interior `a//b` or trailing `a/`, which the mock's `path.join` would otherwise collapse while S3 keeps literal), ASCII control characters, and a `..`/`.` path segment. The mock additionally applies a filesystem realpath/symlink containment guard (`assertContainedPath`) as local-only defense. `deleteBatch` validates every key up front on both layers, so a mixed valid/invalid batch deletes nothing. -- Versioning fully supported: each `put` writes to `versions/{key}/v{n}`, delete without `versionId` places a `__deleted__` sentinel, `listVersions` reads the versions directory, `restoreVersion` copies an old version via `put`. -- Deleting the newest stored version updates the current `content/` and `meta/` copies from the next version, including its original modification time, without creating a new version or removing a delete marker. Deleting the last stored version removes the current copies. Deleting older or unknown versions leaves the current copies unchanged. The synchronous version reader is shared with `listVersions()`, so selection follows the same newest-first ordering and deletion does not yield between reading and reconciling the version history. +- Basic versioning: each `put` writes to `versions/{key}/v{n}` and removes any active `__deleted__` sentinel; delete without `versionId` places that sentinel, `listVersions` reads stored data versions, and `restoreVersion` copies an old version via `put`. Historical delete markers are not retained. +- Deleting the newest stored data version updates the current `content/` and `meta/` copies from the next stored data version, including its original modification time, without creating a new version or removing an active delete-marker flag. Deleting the last stored data version removes the current copies. Deleting older or unknown versions leaves the current copies unchanged. The synchronous version reader is shared with `listVersions()`, so selection follows the same newest-first ordering and deletion does not yield between reading and reconciling the version history. This reconciles current copies with the data versions the mock retains; it does not reconstruct discarded delete-marker history. ### Mock vs AWS Behavior Differences | Behavior Difference | Impact | Mitigation | |------------|--------|------------| +| Historical delete markers are not retained | The mock has one `__deleted__` flag, removed by the next `put()`, rather than delete markers ordered among data versions. For `put(old)` → `delete()` → `put(replacement)` → permanent deletion of the replacement version, the mock exposes `old`, includes the key in `scan()`, and marks the older data version current in `listVersions()`. S3 instead makes the earlier delete marker current, so a read without a version ID treats the key as deleted. | Do not use the local mock to assert S3 deletion-history behavior across re-uploads; exercise that case in a sandbox. Correct historical promotion needs a model that retains ordered delete markers and defines compatibility with existing local data. Current-copy reconciliation alone does not address it. | | No lifecycle rules | Objects never expire or transition locally | No mitigation — lifecycle rules are a background S3 process | | No CORS enforcement | Browser requests succeed regardless of origin locally; a missing `corsRules` only fails after deploy | CORS is enforced by the browser + S3, not the mock. The README's "Browser Uploads and Downloads (CORS)" section documents that `corsRules` is required for deployed browser access | | No storage classes | Transition rules have no effect locally | No mitigation — storage classes are a cost optimization | diff --git a/packages/bb-file-bucket/README.md b/packages/bb-file-bucket/README.md index de31526d97..d563071bd1 100644 --- a/packages/bb-file-bucket/README.md +++ b/packages/bb-file-bucket/README.md @@ -261,7 +261,26 @@ export const api = new ApiNamespace(scope, 'api', (context) => ({ })); ``` -On a versioned bucket, `delete(path)` creates a delete marker without removing stored versions; `get()` returns `null` and `scan()` omits the file. `delete(path, { versionId })` permanently removes that specific version. Deleting the current version makes the newest remaining version current, unless a delete marker still hides it from these reads. Deleting the last stored version leaves no file to retrieve or list in `scan()`. The local mock follows S3's version-deletion behavior without creating a replacement version. +On a versioned bucket, `delete(path)` creates a delete marker without removing +stored data versions; `get()` returns `null` and `scan()` omits the file. +`delete(path, { versionId })` permanently removes that specific data version. +On S3, deleting the current data version exposes the next entry in the version +history, which may be another data version or a delete marker. + +The local mock reconciles its current body and metadata with the next stored +data version when the newest data version is permanently deleted, or removes +the current copies when none remain. This creates no replacement version and +does not remove an active delete-marker flag; `get()` and `scan()` still honor +that flag. + +**Local limitation:** the mock keeps only an active delete-marker flag, not +delete markers ordered within the version history. A subsequent `put()` removes +the flag. Consequently, `put(old)` → `delete()` → `put(replacement)` → permanent +deletion of the replacement can expose `old` locally, whereas S3 would make the +earlier delete marker current and treat the key as deleted. This case is not +fixed by current-copy reconciliation. See +[Mock vs AWS Behavior Differences](./DESIGN.md#mock-vs-aws-behavior-differences) +and use a sandbox when testing deletion history across re-uploads. ### Access Logging @@ -336,6 +355,6 @@ Object Lock can only be turned on when the bucket is first deployed, and can't b ## Local Development -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=...`. Versioning is fully supported locally. 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)). +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)). From 46fdd5acf869b0f48da0bf22909f39132f2b010c Mon Sep 17 00:00:00 2001 From: Kento Ikeda Date: Tue, 3 Nov 2026 04:53:02 +0900 Subject: [PATCH 3/3] fix(file-bucket): keep version deletions retryable --- .../file-bucket-current-version-deletion.md | 2 + packages/bb-file-bucket/DESIGN.md | 2 + .../src/current-version-deletion.test.ts | 100 +++++++++++++++++- packages/bb-file-bucket/src/index.mock.ts | 46 ++++---- .../comprehensive/test/file-bucket.test.ts | 17 +++ 5 files changed, 144 insertions(+), 23 deletions(-) diff --git a/.changeset/file-bucket-current-version-deletion.md b/.changeset/file-bucket-current-version-deletion.md index de0d0ccfe0..0038954a71 100644 --- a/.changeset/file-bucket-current-version-deletion.md +++ b/.changeset/file-bucket-current-version-deletion.md @@ -4,3 +4,5 @@ --- Fix local FileBucket version deletion so removing the newest stored data version updates the current body and metadata from the next stored data version, or removes the current copies when none remain. Active delete-marker flags and older-version deletion behavior are preserved. Document that historical delete markers discarded by a subsequent upload are not reconstructed, so deletion across re-uploads still differs from S3. + +Ignore nested-key directories when reading version history. Retain the target version body until current-copy reconciliation and version-sidecar removal succeed, allowing filesystem failures to be retried with the same version ID. diff --git a/packages/bb-file-bucket/DESIGN.md b/packages/bb-file-bucket/DESIGN.md index fb202654e6..659f0bc9de 100644 --- a/packages/bb-file-bucket/DESIGN.md +++ b/packages/bb-file-bucket/DESIGN.md @@ -128,12 +128,14 @@ Creates a single S3 bucket (plus a dedicated log bucket when `accessLogging` is - Object keys are validated identically on the mock and the AWS runtime via the shared, filesystem-independent `assertValidKey` (`validation.ts`), called from every key-accepting method on both layers. It rejects (`ValidationFailed`) an empty/non-string key, a leading slash, an empty path segment (interior `a//b` or trailing `a/`, which the mock's `path.join` would otherwise collapse while S3 keeps literal), ASCII control characters, and a `..`/`.` path segment. The mock additionally applies a filesystem realpath/symlink containment guard (`assertContainedPath`) as local-only defense. `deleteBatch` validates every key up front on both layers, so a mixed valid/invalid batch deletes nothing. - Basic versioning: each `put` writes to `versions/{key}/v{n}` and removes any active `__deleted__` sentinel; delete without `versionId` places that sentinel, `listVersions` reads stored data versions, and `restoreVersion` copies an old version via `put`. Historical delete markers are not retained. - Deleting the newest stored data version updates the current `content/` and `meta/` copies from the next stored data version, including its original modification time, without creating a new version or removing an active delete-marker flag. Deleting the last stored data version removes the current copies. Deleting older or unknown versions leaves the current copies unchanged. The synchronous version reader is shared with `listVersions()`, so selection follows the same newest-first ordering and deletion does not yield between reading and reconciling the version history. This reconciles current copies with the data versions the mock retains; it does not reconstruct discarded delete-marker history. +- The shared version reader considers only regular files, excluding directories that belong to nested object keys. Current-copy updates or removal complete before the target version is unlinked; missing copies and sidecars are tolerated, but other filesystem errors propagate so callers can retry the same deletion. The version body is removed last, after its metadata sidecar. ### Mock vs AWS Behavior Differences | Behavior Difference | Impact | Mitigation | |------------|--------|------------| | Historical delete markers are not retained | The mock has one `__deleted__` flag, removed by the next `put()`, rather than delete markers ordered among data versions. For `put(old)` → `delete()` → `put(replacement)` → permanent deletion of the replacement version, the mock exposes `old`, includes the key in `scan()`, and marks the older data version current in `listVersions()`. S3 instead makes the earlier delete marker current, so a read without a version ID treats the key as deleted. | Do not use the local mock to assert S3 deletion-history behavior across re-uploads; exercise that case in a sandbox. Correct historical promotion needs a model that retains ordered delete markers and defines compatibility with existing local data. Current-copy reconciliation alone does not address it. | +| Non-atomic version deletion | Current body, metadata, and version history are separate filesystem writes. An I/O failure or process interruption can leave partially updated current copies until deletion is retried; this is not an atomic S3 operation or a rollback guarantee. | The target version body remains until current-copy reconciliation and version-sidecar removal succeed. After resolving the I/O error, retry deletion with the same version ID to finish reconciliation. | | No lifecycle rules | Objects never expire or transition locally | No mitigation — lifecycle rules are a background S3 process | | No CORS enforcement | Browser requests succeed regardless of origin locally; a missing `corsRules` only fails after deploy | CORS is enforced by the browser + S3, not the mock. The README's "Browser Uploads and Downloads (CORS)" section documents that `corsRules` is required for deployed browser access | | No storage classes | Transition rules have no effect locally | No mitigation — storage classes are a cost optimization | diff --git a/packages/bb-file-bucket/src/current-version-deletion.test.ts b/packages/bb-file-bucket/src/current-version-deletion.test.ts index 50fa2eaf32..37c00effd6 100644 --- a/packages/bb-file-bucket/src/current-version-deletion.test.ts +++ b/packages/bb-file-bucket/src/current-version-deletion.test.ts @@ -3,11 +3,11 @@ import { test, beforeEach, afterEach } from 'node:test'; import assert from 'node:assert/strict'; -import { existsSync, readFileSync, rmSync, statSync, utimesSync } from 'node:fs'; +import { existsSync, mkdirSync, readFileSync, rmSync, statSync, utimesSync } from 'node:fs'; import { join } from 'node:path'; import { Scope } from '@aws-blocks/core'; import { FileBucket } from './index.mock.js'; -import { contentPath, metaPath, deleteMarkerPath, versionContentPath } from './paths.js'; +import { contentPath, metaPath, deleteMarkerPath, versionContentPath, versionMetaPath } from './paths.js'; const scope = new Scope('version-delete'); const bucketId = 'files'; @@ -159,3 +159,99 @@ test('non-versioned deletion still removes the object', async () => { assert.equal(await bucket.get(key), null); assert.deepEqual(await scanFiles(bucket), []); }); + +test('version history ignores directories belonging to nested keys', async () => { + const bucket = new FileBucket(scope, bucketId); + await bucket.put('docs/readme.txt', 'nested'); + await bucket.put('docs/v999', 'numeric-looking key'); + assert.deepEqual(await bucket.listVersions('docs'), []); + assert.equal((await bucket.listVersions('docs/readme.txt')).length, 1); + assert.equal((await bucket.listVersions('docs/v999')).length, 1); +}); + +test('deleting a directory-shaped version ID leaves nested keys untouched', async () => { + const bucket = new FileBucket(scope, bucketId); + for (const child of ['readme.txt', 'v999']) { + await bucket.put(`docs/${child}`, 'nested'); + await bucket.delete('docs', { versionId: child }); + assert.equal((await bucket.get(`docs/${child}`))?.body.toString(), 'nested'); + assert.equal((await bucket.listVersions(`docs/${child}`)).length, 1); + } +}); + +for (const [name, pathFor] of [['body', contentPath], ['metadata', metaPath]] as const) { + test(`failed promotion ${name} write preserves version history for a retry`, async () => { + const bucket = new FileBucket(scope, bucketId); + const [latest, previous] = await putVersions(bucket); + const obstruction = pathFor(dataDir, key); + rmSync(obstruction); + mkdirSync(obstruction); + + await assert.rejects(bucket.delete(key, { versionId: latest.versionId })); + assert.equal(existsSync(versionContentPath(dataDir, key, latest.versionId)), true); + assert.equal(existsSync(versionMetaPath(dataDir, key, latest.versionId)), true); + assert.deepEqual((await bucket.listVersions(key)).map(version => version.versionId), [ + latest.versionId, previous.versionId, + ]); + + rmSync(obstruction, { recursive: true }); + const reopened = new FileBucket(scope, bucketId); + await reopened.delete(key, { versionId: latest.versionId }); + const file = await reopened.get(key); + assert.equal(file?.body.toString(), 'old'); + assert.equal(file?.contentType, 'text/plain'); + assert.deepEqual(file?.metadata, { revision: 'old' }); + assert.equal(JSON.parse(readFileSync(metaPath(dataDir, key), 'utf8')).cacheControl, 'max-age=60'); + assert.equal(await reopened.get(key, { versionId: latest.versionId }), null); + assert.equal((await reopened.listVersions(key))[0].versionId, previous.versionId); + }); + + test(`failed last-version ${name} cleanup preserves the version for a retry`, async () => { + const bucket = new FileBucket(scope, bucketId); + await bucket.put(key, 'only'); + const [latest] = await bucket.listVersions(key); + const obstruction = pathFor(dataDir, key); + rmSync(obstruction); + mkdirSync(obstruction); + + await assert.rejects(bucket.delete(key, { versionId: latest.versionId })); + assert.equal(existsSync(versionContentPath(dataDir, key, latest.versionId)), true); + assert.equal(existsSync(versionMetaPath(dataDir, key, latest.versionId)), true); + rmSync(obstruction, { recursive: true }); + + await bucket.delete(key, { versionId: latest.versionId }); + assert.equal(await bucket.get(key), null); + assert.deepEqual(await bucket.listVersions(key), []); + assert.deepEqual(await scanFiles(bucket), []); + assert.equal(existsSync(contentPath(dataDir, key)), false); + assert.equal(existsSync(metaPath(dataDir, key)), false); + }); +} + +test('failed version metadata cleanup preserves its body for a retry', async () => { + const bucket = new FileBucket(scope, bucketId); + const [latest, previous] = await putVersions(bucket); + const obstruction = versionMetaPath(dataDir, key, latest.versionId); + rmSync(obstruction); + mkdirSync(obstruction); + + await assert.rejects(bucket.delete(key, { versionId: latest.versionId })); + assert.equal(existsSync(versionContentPath(dataDir, key, latest.versionId)), true); + rmSync(obstruction, { recursive: true }); + await bucket.delete(key, { versionId: latest.versionId }); + assert.equal((await bucket.get(key))?.body.toString(), 'old'); + assert.equal((await bucket.get(key))?.contentType, 'text/plain'); + assert.equal((await bucket.listVersions(key))[0].versionId, previous.versionId); +}); + +test('deleting the last version tolerates missing current copies and version metadata', async () => { + const bucket = new FileBucket(scope, bucketId); + await bucket.put(key, 'only'); + const [latest] = await bucket.listVersions(key); + for (const file of [contentPath(dataDir, key), metaPath(dataDir, key), versionMetaPath(dataDir, key, latest.versionId)]) { + rmSync(file); + } + await bucket.delete(key, { versionId: latest.versionId }); + assert.equal(await bucket.get(key), null); + assert.deepEqual(await bucket.listVersions(key), []); +}); diff --git a/packages/bb-file-bucket/src/index.mock.ts b/packages/bb-file-bucket/src/index.mock.ts index 153ed133b4..e77ce3e524 100644 --- a/packages/bb-file-bucket/src/index.mock.ts +++ b/packages/bb-file-bucket/src/index.mock.ts @@ -5,7 +5,7 @@ import { Scope, blocksError, registerSdkIdentifiers } from '@aws-blocks/core'; import { getMockDataDir, assertNotMockInDeployedEnv } from '@aws-blocks/core/bb-utils'; import type { ScopeParent } from '@aws-blocks/core'; import { - existsSync, mkdirSync, readFileSync, writeFileSync, unlinkSync, readdirSync, statSync, copyFileSync, utimesSync, + existsSync, mkdirSync, readFileSync, writeFileSync, unlinkSync, readdirSync, statSync, copyFileSync, utimesSync, rmSync, } from 'node:fs'; import { dirname, join, relative } from 'node:path'; import { assertContainedPath } from './mock-utils.js'; @@ -207,6 +207,8 @@ export class FileBucket extends * On non-versioned buckets, permanently removes the file. * On versioned buckets without `versionId`, places a delete marker (file appears deleted * but previous versions are preserved). With `versionId`, permanently removes that version. + * Deleting the newest stored data version promotes the next stored data version, if any, + * without creating a new version. An active local delete marker continues to hide the key. * * No-op if the file does not exist (matches S3 behavior). * @@ -224,26 +226,26 @@ export class FileBucket extends if (this.versioned && versionId) { const versions = this.readVersions(path); if (!versions.some(version => version.versionId === versionId)) return; - unlinkSync(versionContentPath(this.dataDir, path, versionId)); - try { unlinkSync(versionMetaPath(this.dataDir, path, versionId)); } catch {} - if (versions[0].versionId !== versionId) return; - - // The current copy is also read by scan() and the dev file-server. - // Promote the next version without put(), which would create a new version - // and remove any existing delete marker. - const next = versions[1]; - if (next) { - const filePath = contentPath(this.dataDir, path); - const source = versionContentPath(this.dataDir, path, next.versionId); - const stat = statSync(source); - mkdirSync(dirname(filePath), { recursive: true }); - copyFileSync(source, filePath); - utimesSync(filePath, stat.atime, stat.mtime); - this.writeMeta(path, this.readVersionMeta(path, next.versionId)); - } else { - try { unlinkSync(contentPath(this.dataDir, path)); } catch {} - try { unlinkSync(metaPath(this.dataDir, path)); } catch {} + if (versions[0].versionId === versionId) { + // The current copy is also read by scan() and the dev file-server. + // Promote without put(), which would create a version and clear the marker. + // Keep the target version until reconciliation succeeds so failures are retryable. + const next = versions[1]; + if (next) { + const filePath = contentPath(this.dataDir, path); + const source = versionContentPath(this.dataDir, path, next.versionId); + const stat = statSync(source); + mkdirSync(dirname(filePath), { recursive: true }); + copyFileSync(source, filePath); + utimesSync(filePath, stat.atime, stat.mtime); + this.writeMeta(path, this.readVersionMeta(path, next.versionId)); + } else { + rmSync(contentPath(this.dataDir, path), { force: true }); + rmSync(metaPath(this.dataDir, path), { force: true }); + } } + rmSync(versionMetaPath(this.dataDir, path, versionId), { force: true }); + unlinkSync(versionContentPath(this.dataDir, path, versionId)); return; } if (this.versioned) { @@ -514,7 +516,9 @@ export class FileBucket extends private readVersions(path: string): FileVersionInfo[] { const versionsDir = versionsDirFor(this.dataDir, path); if (!existsSync(versionsDir)) return []; - const entries = readdirSync(versionsDir).filter(isVersionEntry); + const entries = readdirSync(versionsDir, { withFileTypes: true }) + .filter(entry => entry.isFile() && isVersionEntry(entry.name)) + .map(entry => entry.name); if (entries.length === 0) return []; const hasDeleteMarker = existsSync(deleteMarkerPath(this.dataDir, path)); diff --git a/test-apps/comprehensive/test/file-bucket.test.ts b/test-apps/comprehensive/test/file-bucket.test.ts index d6d2c81adb..75bd4008c6 100644 --- a/test-apps/comprehensive/test/file-bucket.test.ts +++ b/test-apps/comprehensive/test/file-bucket.test.ts @@ -248,6 +248,23 @@ export function fileBucketTests(getApi: () => typeof apiType) { // ── Versioned FileBucket ────────────────────────────────────────────── describe('Versioned', () => { + test('deleting a version of a prefix key does not delete nested objects', async () => { + const api = getApi(); + const prefix = `v/prefix-delete-${crypto.randomUUID()}`; + const children = ['readme.txt', 'v999']; + try { + for (const child of children) { + await api.vFilePut(`${prefix}/${child}`, 'nested'); + await api.vFileDelete(prefix, child); + assert.strictEqual((await api.vFileGet(`${prefix}/${child}`))?.body, 'nested'); + assert.strictEqual((await api.vFileListVersions(`${prefix}/${child}`)).length, 1); + } + assert.deepStrictEqual(await api.vFileListVersions(prefix), []); + } finally { + for (const child of children) await api.vFilePurge(`${prefix}/${child}`); + } + }); + test('deleting the current version promotes the previous version through the API', async () => { const api = getApi(); const path = `v/delete-current-${crypto.randomUUID()}.txt`;