Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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-current-version-deletion.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
---

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.
1 change: 1 addition & 0 deletions packages/bb-file-bucket/DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,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

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 @@ -257,6 +257,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):
Expand Down
161 changes: 161 additions & 0 deletions packages/bb-file-bucket/src/current-version-deletion.test.ts
Original file line number Diff line number Diff line change
@@ -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), []);
});
24 changes: 24 additions & 0 deletions packages/bb-file-bucket/src/file-server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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' });
Expand Down
79 changes: 52 additions & 27 deletions packages/bb-file-bucket/src/index.mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
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 } 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 {
Expand Down Expand Up @@ -220,9 +222,28 @@ export class FileBucket<O extends FileBucketOptions = FileBucketOptions> 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));
Comment thread
xyos marked this conversation as resolved.
Resolved
} else {
try { unlinkSync(contentPath(this.dataDir, path)); } catch {}
try { unlinkSync(metaPath(this.dataDir, path)); } catch {}
}
return;
}
if (this.versioned) {
Expand Down Expand Up @@ -439,30 +460,7 @@ export class FileBucket<O extends FileBucketOptions = FileBucketOptions> extends
*/
async listVersions(path: string): Promise<FileVersionInfo[]> {
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);
}

/**
Expand Down Expand Up @@ -513,6 +511,33 @@ export class FileBucket<O extends FileBucketOptions = FileBucketOptions> 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 assertPresignedUploadSupported(): void {
if (this.objectLocked) {
throw blocksError(FileBucketErrors.PresignedUploadUnsupported, presignedUploadUnsupportedMessage(this.fullId));
Expand Down
42 changes: 42 additions & 0 deletions test-apps/comprehensive/test/file-bucket.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,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();
Expand Down