Skip to content
16 changes: 11 additions & 5 deletions examples/site-deploy-ssg/__tests__/mock-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ interface ReleaseRow {
export interface MockServer {
api: GraphQLExecutor;
putObject: PutObject;
/** CAS keys whose bytes the bucket holds. */
/** Managed object keys whose bytes the bucket holds. */
storedKeys: string[];
/** Hashes the bucket holds, as dedupe sees them. */
storedHashes: Set<string>;
Expand All @@ -47,7 +47,7 @@ export function createMockServer(): MockServer {
assertSignedHeaders(url, headers);
const hash = url.slice(url.lastIndexOf('/') + 1);
hashes.add(hash);
server.storedKeys.push(`cas/sha256/${hash}`);
server.storedKeys.push(`originals/${hash}`);
void body;
void contentType;
},
Expand All @@ -56,15 +56,21 @@ export function createMockServer(): MockServer {
function handle(operation: string, variables: Record<string, unknown>) {
const input = (variables.input ?? {}) as Record<string, any>;
switch (operation) {
case 'uploadFiles':
case 'uploadSiteFiles':
return {
uploadFiles: {
uploadSiteFiles: {
files: (input.files as any[]).map((file) => {
const deduplicated = hashes.has(file.contentHash);
const logicalKey = `cas/sha256/${file.contentHash}`;
if (input.checkOnly && !deduplicated) {
return { logicalKey, key: null as string | null, deduplicated: false, pending: false };
}
return {
fileId: `file-${file.contentHash.slice(0, 8)}`,
key: file.key as string,
key: `originals/${file.contentHash}`,
logicalKey,
deduplicated,
pending: false,
uploadUrl: deduplicated ? null : `https://s3.test/put/${file.contentHash}`,
uploadHeaders: deduplicated ? null : signedHeaders(file),
};
Expand Down
15 changes: 13 additions & 2 deletions examples/site-deploy-ssg/__tests__/ssg-deploy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,21 @@ const deployOptions = (server: ReturnType<typeof createMockServer>) => ({
putObject: server.putObject,
siteId: 'site-1',
databaseId: 'db-1',
bucketKey: 'site-example',
source: dist,
});

test('the mock reports an absent release asset without issuing a PUT URL', async () => {
const server = createMockServer();
const contentHash = 'a'.repeat(64);
const result = await server.api('mutation { uploadSiteFiles(input: $input) { files { key } } }', {
input: { checkOnly: true, files: [{ contentHash }] },
});

expect(result.uploadSiteFiles).toEqual({
files: [{ logicalKey: `cas/sha256/${contentHash}`, key: null, deduplicated: false, pending: false }],
});
});

test('builds every page, the stylesheet and a 404', async () => {
const files = await buildSite(content, dist);
expect(files).toEqual([
Expand Down Expand Up @@ -82,7 +93,7 @@ test('deploys the build to a play preview without touching production', async ()

// Bytes are addressed by content, and the manifest carries served types.
expect(server.storedKeys).toHaveLength(5);
for (const key of server.storedKeys) expect(key).toMatch(/^cas\/sha256\/[0-9a-f]{64}$/);
for (const key of server.storedKeys) expect(key).toMatch(/^originals\/[0-9a-f]{64}$/);
expect(result.manifest.files['assets/site.css'].content_type).toBe('text/css; charset=utf-8');
expect(result.manifest.files['index.html'].content_type).toBe('text/html; charset=utf-8');
});
Expand Down
6 changes: 1 addition & 5 deletions examples/site-deploy-ssg/src/deploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* ```bash
* CONSTRUCTIVE_API_URL=https://api.example.com/graphql \
* CONSTRUCTIVE_TOKEN=$TOKEN \
* SITE_ID=... DATABASE_ID=... BUCKET_KEY=site-example \
* SITE_ID=... DATABASE_ID=... \
* PREVIEW=play pnpm deploy
* ```
*
Expand Down Expand Up @@ -81,12 +81,8 @@ async function main(): Promise<void> {
const api = fetchExecutor(required('CONSTRUCTIVE_API_URL'), process.env.CONSTRUCTIVE_TOKEN);
const result = await deploySite({
api,
storage: process.env.CONSTRUCTIVE_STORAGE_URL
? fetchExecutor(process.env.CONSTRUCTIVE_STORAGE_URL, process.env.CONSTRUCTIVE_TOKEN)
: undefined,
siteId: required('SITE_ID'),
databaseId: process.env.DATABASE_ID,
bucketKey: required('BUCKET_KEY'),
source: dist,
preview: process.env.PREVIEW,
previewApex: process.env.PREVIEW_APEX,
Expand Down
22 changes: 21 additions & 1 deletion graphile/graphile-presigned-url-plugin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ Presigned URL upload plugin for PostGraphile v5.
- Per-files-table `upload<FilesType>` mutations — generate presigned PUT URLs for direct client-to-S3 upload; use `createStorageClient` from `@constructive-io/graphql-query` with `storageTransport` from `@constructive-io/upload-client` for client orchestration
- `downloadUrl` computed field — presigned GET URLs for private files, public URLs for public files
- `maxBulkFiles` field on bucket types — the most files one bulk-upload call accepts (`storage_module.max_bulk_files`, default 100)
- Content-hash based S3 keys (SHA-256) with automatic deduplication — only against rows whose bytes are in S3, so a retry of a never-completed upload gets a fresh URL
- Independent server-allocated object keys (`originals/<UUID>`), with SHA-256 integrity and deduplication of confirmed content in the same logical slot
- Per-bucket MIME type and file size validation

## Usage
Expand All @@ -44,3 +44,23 @@ const preset = {
],
};
```

## Upload identity and retries

The optional upload input `key` names a **logical slot** (`files.logical_key`);
without it the logical slot is the SHA-256 content hash. It never chooses an S3
location. The generated recorder allocates a fresh `originals/<UUID>` for each
new request and returns it as `files.key`. The response `key`, projection `key`,
PUT signature and downloads all use that physical key.

A confirmed (`uploaded`/`processed`) row with the same bucket, logical key and
checksum is reused, without issuing a PUT URL. Pending or rejected attempts do
not deduplicate: a new request gets a new object and confirm job, and leaves the
older attempt to its existing lifecycle. Repeating a PUT with the same URL is a
retry of that same object; checksum and upload-id must still match its signature.

This requires the matching constructive-db storage generator with `logical_key`
and a server-allocated recorder result. Deploy the generator and pinned package
together; there is no fallback to signing the caller's logical key. Successful
logical replacement retains the existing database authorization policy; UUIDs
are object identities, not access control.
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
*/

import { processSingleFile } from '../src/plugin';
import { generatePresignedPutUrl } from '../src/s3-signer';
import type { BucketConfig, PresignedUrlPluginOptions, S3Config, StorageModuleConfig } from '../src/types';

jest.mock('../src/s3-signer', () => ({
Expand All @@ -21,6 +22,8 @@ const BUCKET_ID = '33333333-3333-3333-3333-333333333333';
const OLD_FILE_ID = '44444444-4444-4444-4444-444444444444';
const NEW_FILE_ID = '55555555-5555-5555-5555-555555555555';
const KEY = 'index.html';
const OLD_KEY = `originals/${OLD_FILE_ID}`;
const NEW_KEY = `originals/${NEW_FILE_ID}`;

function storageConfig(overrides: Partial<StorageModuleConfig> = {}): StorageModuleConfig {
return {
Expand Down Expand Up @@ -60,15 +63,17 @@ function fakeTx(existingHash: string, deletable = true, existingStatus = 'upload
const txClient = {
async query(opts: { text: string; values: unknown[] }) {
queries.push(opts);
if (/^SELECT id, status/.test(opts.text)) {
if (/^SELECT id, (?:key|status)/.test(opts.text) && !/record_file\(/.test(opts.text)) {
// The probe is by (key, bucket, hash): a row carrying other bytes is not seen.
const probedHash = opts.values[2];
return { rows: probedHash === existingHash ? [{ id: OLD_FILE_ID, status: existingStatus }] : [] };
const confirmedOnly = opts.text.includes("status IN ('uploaded', 'processed')");
return { rows: probedHash === existingHash && (!confirmedOnly || ['uploaded', 'processed'].includes(existingStatus))
? [{ id: OLD_FILE_ID, key: OLD_KEY, status: existingStatus, mime_type: 'text/html', size: '16', filename: KEY }] : [] };
}
if (/^DELETE FROM storage_public\.app_files/.test(opts.text)) {
return { rows: deletable ? [{ id: OLD_FILE_ID }] : [] };
}
if (/record_file\(/.test(opts.text)) return { rows: [{ id: NEW_FILE_ID }] };
if (/record_file\(/.test(opts.text)) return { rows: [{ id: NEW_FILE_ID, key: NEW_KEY }] };
throw new Error(`unexpected query: ${opts.text}`);
},
};
Expand Down Expand Up @@ -96,7 +101,7 @@ describe('custom-key upload of changed bytes', () => {

expect(result).toMatchObject({
fileId: NEW_FILE_ID,
key: KEY,
key: NEW_KEY,
deduplicated: false,
uploadUrl: 'https://s3.example.com/put',
});
Expand All @@ -116,23 +121,29 @@ describe('custom-key upload of changed bytes', () => {
const result = await upload(storageConfig(), txClient);

expect(result).toMatchObject({ fileId: NEW_FILE_ID, deduplicated: false });
expect(queries.map((q) => q.text.trim().split(/\s+/)[0])).toEqual(['SELECT', 'DELETE', 'SELECT']);
expect(queries[1].values).toEqual([OLD_FILE_ID]);
expect(queries.map((q) => q.text.trim().split(/\s+/)[0])).toEqual(['SELECT', 'SELECT']);
expect(result.key).toBe(NEW_KEY);
expect(queries.some((q) => /^DELETE/.test(q.text))).toBe(false);
});

it('refuses to restart a row the caller cannot delete', async () => {
it('retries independently even when the caller cannot delete an earlier attempt', async () => {
const { txClient, queries } = fakeTx('b'.repeat(64), false, 'requested');

const refused = upload(storageConfig(), txClient);
await expect(refused).rejects.toThrow(
`FILE_NOT_REPLACEABLE: file ${OLD_FILE_ID} at key ${KEY}`,
);
// A named error carries its code, so the server passes it through
// instead of masking it as INTERNAL_SERVER_ERROR.
await expect(refused).rejects.toMatchObject({ code: 'FILE_NOT_REPLACEABLE', errorClass: 'public' });
expect(queries.some((q) => /record_file\(/.test(q.text))).toBe(false);
await expect(upload(storageConfig(), txClient)).resolves.toMatchObject({ key: NEW_KEY, deduplicated: false });
expect(queries.some((q) => /^DELETE/.test(q.text))).toBe(false);
});

it.each(['a'.repeat(64), OLD_KEY, `derived/${OLD_KEY}/thumb.webp`])(
'never signs the attacker-selected logical key %s', async (logicalKey) => {
const { txClient } = fakeTx('a'.repeat(64));
const result = await processSingleFile(options, txClient, storageConfig(), 'db', bucket, s3, {
contentHash: 'b'.repeat(64), contentType: 'text/html', size: 16, key: logicalKey,
});
expect(result.key).toBe(NEW_KEY);
expect(result.file.key).toBe(NEW_KEY);
expect(generatePresignedPutUrl).toHaveBeenLastCalledWith(s3, NEW_KEY, 'text/html', 16, 900, 'b'.repeat(64), NEW_FILE_ID);
},
);

it('deduplicates identical bytes at the key without touching the row', async () => {
const { txClient, queries } = fakeTx('b'.repeat(64));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,8 @@ describe('validateCustomKey', () => {
expect(validateCustomKey(key)).toMatch(/^INVALID_KEY:/);
});

// A file's rendered versions live under `<key>.versions/` and are served to
// whoever can read that file, so no file of its own may be stored there.
// The legacy `.versions/` suffix remains reserved in logical-key syntax;
// physical storage isolation no longer depends on this validation.
it.each(['photo.png.versions/secret.webp', 'a/b.versions/c/d.txt'])('rejects %s: the versions prefix is reserved', (key) => {
expect(validateCustomKey(key)).toMatch(/reserved/);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ jest.mock('../src/s3-signer', () => ({
import { HeadObjectCommand } from '@aws-sdk/client-s3';

import { processSingleFile } from '../src/plugin';
import { generatePresignedPutUrl } from '../src/s3-signer';
import type { BucketConfig, PresignedUrlPluginOptions, S3Config, StorageModuleConfig } from '../src/types';

const BUCKET_ID = '33333333-3333-3333-3333-333333333333';
Expand Down Expand Up @@ -82,14 +83,17 @@ const options: PresignedUrlPluginOptions = { credentials: { accessKeyId: 'test',
* resolver probes by key (the custom key, or the hash's own key), so the row is
* found only when the probed key is its own.
*/
function fakeTx(rowKey: string, status: string) {
function fakeTx(rowKey: string, status: string, retired = false) {
const queries: Array<{ text: string; values: unknown[] }> = [];
const txClient = {
async query(opts: { text: string; values: unknown[] }) {
queries.push(opts);
if (/record_file\(/.test(opts.text)) return { rows: [{ id: NEW_FILE_ID }] };
if (/record_file\(/.test(opts.text)) return { rows: [{ id: NEW_FILE_ID, key: `originals/${NEW_FILE_ID}` }] };
if (/^SELECT id/.test(opts.text)) {
return { rows: opts.values[0] === rowKey ? [{ id: OLD_FILE_ID, status }] : [] };
if (retired && /AND NOT logical_key_retired/.test(opts.text)) return { rows: [] };
const confirmedOnly = opts.text.includes("status IN ('uploaded', 'processed')");
return { rows: opts.values[0] === rowKey && (!confirmedOnly || ['uploaded', 'processed'].includes(status))
? [{ id: OLD_FILE_ID, key: `originals/${OLD_FILE_ID}`, mime_type: 'text/plain', size: '32', filename: 'original.txt' }] : [] };
}
if (/^DELETE FROM storage_public\.app_files/.test(opts.text)) return { rows: [{ id: OLD_FILE_ID }] };
throw new Error(`unexpected query: ${opts.text}`);
Expand Down Expand Up @@ -127,7 +131,7 @@ describe.each([
expect(result.file).not.toHaveProperty('url');
expect(heads(s3)).toEqual([]);
const del = queries.find((q) => /^DELETE/.test(q.text));
expect(del?.values).toEqual([OLD_FILE_ID]);
expect(del).toBeUndefined();
},
);

Expand All @@ -138,11 +142,19 @@ describe.each([
const result = await upload(txClient, s3, customKey);

expect(result).toMatchObject({ fileId: OLD_FILE_ID, deduplicated: true, uploadUrl: null });
expect(result.file).toMatchObject({ mime: 'text/plain', size: 32, filename: 'original.txt' });
expect(heads(s3)).toEqual([]);
expect(result.file).not.toHaveProperty('url');
expect(queries).toHaveLength(1);
expect(queries[0].text).toContain('status');
});

it('does not deduplicate against a retired but still readable row', async () => {
const { txClient } = fakeTx(rowKey, 'uploaded', true);
const result = await upload(txClient, fakeS3(), customKey);

expect(result).toMatchObject({ fileId: NEW_FILE_ID, deduplicated: false });
});
});

describe('content-addressed upload whose hash a custom-key row carries', () => {
Expand All @@ -155,8 +167,102 @@ describe('content-addressed upload whose hash a custom-key row carries', () => {

const result = await upload(txClient, s3);

expect(result).toMatchObject({ fileId: NEW_FILE_ID, deduplicated: false, key: HASH });
expect(queries[0].values).toEqual([HASH, BUCKET_ID]);
expect(result).toMatchObject({ fileId: NEW_FILE_ID, deduplicated: false, key: `originals/${NEW_FILE_ID}` });
expect(queries[0].values).toEqual([HASH, BUCKET_ID, HASH]);
expect(queries.some((q) => /^DELETE/.test(q.text))).toBe(false);
});
});

describe('site release requested before the deploy was canceled', () => {
const retry = async (checkOnly: boolean, ageSeconds = 60) => {
const key = `originals/${OLD_FILE_ID}`;
const txClient = {
query: jest.fn().mockResolvedValueOnce({
rows: [{ id: OLD_FILE_ID, key, status: 'requested', mime_type: 'text/html', size: '16',
created_at: new Date(Date.now() - ageSeconds * 1000) }],
}),
};
const s3 = fakeS3();
const result = await processSingleFile(options, txClient, storageConfig(), 'db', bucket, s3,
{ contentHash: HASH, contentType: 'text/html', size: 16, filename: SITE_KEY },
{ release: true, checkOnly });
expect(txClient.query).toHaveBeenCalledTimes(1);
expect(heads(s3)).toEqual([]);
return { result, key, s3 };
};

beforeEach(() => jest.mocked(generatePresignedPutUrl).mockClear());

it('reissues a PUT for the same managed row and only for its remaining lifetime', async () => {
const { result, key, s3 } = await retry(false);
expect(result).toMatchObject({ fileId: OLD_FILE_ID, key, deduplicated: false, uploadUrl: 'https://s3.example.com/put' });
expect(result.pending).not.toBe(true);
expect(result.uploadHeaders).toMatchObject({ 'x-amz-meta-upload-id': OLD_FILE_ID, 'Content-Type': 'text/html' });
const ttl = jest.mocked(generatePresignedPutUrl).mock.calls[0][4]!;
expect(ttl).toBeGreaterThanOrEqual(839);
expect(ttl).toBeLessThanOrEqual(840);
expect(generatePresignedPutUrl).toHaveBeenCalledWith(s3, key, 'text/html', 16, ttl, HASH, OLD_FILE_ID);
});

it('does not sign during a confirmation-only poll', async () => {
const { result } = await retry(true);
expect(result).toMatchObject({ fileId: OLD_FILE_ID, pending: true, uploadUrl: null });
expect(generatePresignedPutUrl).not.toHaveBeenCalled();
});

it('uses the confirmed release row metadata when reusing a slot', async () => {
const key = `originals/${OLD_FILE_ID}`;
const txClient = {
query: jest.fn().mockResolvedValueOnce({
rows: [{ id: OLD_FILE_ID, key, status: 'uploaded', mime_type: 'text/plain',
size: '32', filename: 'original.txt' }],
}),
};

const result = await processSingleFile(options, txClient, storageConfig(), 'db', bucket, fakeS3(),
{ contentHash: HASH, contentType: 'text/html', size: 16, filename: SITE_KEY },
{ release: true, checkOnly: false });

expect(result).toMatchObject({ deduplicated: true, uploadUrl: null,
file: { id: OLD_FILE_ID, key, mime: 'text/plain', size: 32, filename: 'original.txt' } });
expect(generatePresignedPutUrl).not.toHaveBeenCalled();
});

it('signs both copies of the same asset in a batch with a one-second lifetime', async () => {
const createdAt = new Date('2026-01-01T00:00:00.000Z');
const clock = jest.spyOn(Date, 'now').mockReturnValue(createdAt.getTime());
const key = `originals/${NEW_FILE_ID}`;
const txClient = {
query: jest.fn()
.mockResolvedValueOnce({ rows: [] })
.mockResolvedValueOnce({ rows: [] })
.mockResolvedValueOnce({ rows: [{ id: NEW_FILE_ID, key }] })
.mockResolvedValueOnce({
rows: [{ id: NEW_FILE_ID, key, status: 'requested', mime_type: 'text/html', size: '16',
filename: 'index.html', created_at: createdAt }],
}),
};
const config = storageConfig({ uploadUrlExpirySeconds: 1 });
const s3 = fakeS3();
const request = (filename: string) => processSingleFile(options, txClient, config, 'db', bucket, s3,
{ contentHash: HASH, contentType: 'text/html', size: 16, filename },
{ release: true, checkOnly: false });
try {
const first = await request('index.html');
clock.mockReturnValue(createdAt.getTime() + 50);
const second = await request('copy.html');

expect(first).toMatchObject({ fileId: NEW_FILE_ID, key, uploadUrl: 'https://s3.example.com/put' });
expect(second).toMatchObject({ fileId: NEW_FILE_ID, key, uploadUrl: first.uploadUrl, expiresAt: first.expiresAt });
expect(txClient.query).toHaveBeenCalledTimes(4);
expect(generatePresignedPutUrl).toHaveBeenNthCalledWith(2, s3, key, 'text/html', 16, 1, HASH, NEW_FILE_ID);
} finally {
clock.mockRestore();
}
});

it('does not reissue a PUT after the original confirmation deadline', async () => {
await expect(retry(false, 900)).rejects.toThrow('SITE_RELEASE_UPLOAD_EXPIRED');
expect(generatePresignedPutUrl).not.toHaveBeenCalled();
});
});
Loading
Loading