Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(storage): verify streamed bytes before publishing; never truncate or replace a stored object on refusal
garrytan0f41fc9389a5
diff --git a/src/commands/files.ts b/src/commands/files.tsindex 9f62be4d10..74d799984c 100644--- a/src/commands/files.ts+++ b/src/commands/files.ts@@ -202,7 +202,7 @@ async function uploadFile(engine: BrainEngine, args: string[]) {const method = stat.size >= SIZE_THRESHOLD ? 'TUS resumable' : 'standard';console.log(`Uploading ${humanSize(stat.size)} via ${method}...`);- await uploadUnchangedFile(storage, storagePath, filePath, stat, mimeType || undefined);+ await uploadUnchangedFile(storage, storagePath, filePath, hash, mimeType || undefined);// files.metadata is JSONB — bind a real object via executeRawJsonb instead// of casting a string into ::jsonb (the #2339 double-encode class).@@ -347,7 +347,7 @@ async function uploadRaw(engine: BrainEngine, args: string[]) {const method = stat.size >= SIZE_THRESHOLD ? 'TUS resumable' : 'standard';console.error(`Uploading ${humanSize(stat.size)} via ${method}...`);- await uploadUnchangedFile(storage, storagePath, filePath, stat, mimeType || undefined);+ await uploadUnchangedFile(storage, storagePath, filePath, hash, mimeType || undefined);// Create .redirect.yaml pointer in the brain repolet pointerPath: string | null = null;@@ -467,7 +467,7 @@ async function syncFiles(engine: BrainEngine, dir?: string) {const pageSlug = pathParts.length > 1 ? pathParts.slice(0, -1).join('/') : null;// Actually put the bytes in storage before recording them as stored.- await uploadUnchangedFile(storage, storagePath, filePath, stat, mimeType || undefined);+ await uploadUnchangedFile(storage, storagePath, filePath, hash, mimeType || undefined);// files.metadata is JSONB — bind a real object via executeRawJsonb instead// of casting a string into ::jsonb (the #2339 double-encode class).diff --git a/src/core/ops/files.ts b/src/core/ops/files.tsindex 032a1906ac..0a23b88d79 100644--- a/src/core/ops/files.ts+++ b/src/core/ops/files.ts@@ -127,7 +127,7 @@ const file_upload: Operation = {}try {- await uploadUnchangedFile(storage, storagePath, filePath, stat, mimeType || undefined);+ await uploadUnchangedFile(storage, storagePath, filePath, hash, mimeType || undefined);} catch (uploadErr) {throw opError('storage_error', `Upload failed: ${uploadErr instanceof Error ? uploadErr.message : String(uploadErr)}`,'Nothing was recorded. Check the storage backend (credentials, bucket, disk) with `gbrain doctor --json`, then upload again; the upload is keyed by content hash, so repeating it is safe.');diff --git a/src/core/storage.ts b/src/core/storage.tsindex b5c6acd09c..facb0acd80 100644--- a/src/core/storage.ts+++ b/src/core/storage.ts@@ -1,4 +1,4 @@-import { closeSync, openSync, readSync, statSync, type Stats } from 'fs';+import { closeSync, openSync, readSync } from 'fs';import type { FileHandle } from 'fs/promises';import { createHash } from 'crypto';@@ -11,8 +11,11 @@ import { createHash } from 'crypto';export interface StorageBackend {upload(path: string, data: Buffer, mime?: string): Promise<void>;- /** Upload a file from disk with memory bounded independently of its size (#7427). */- uploadFile(path: string, filePath: string, mime?: string): Promise<void>;+ /**+ * Upload a file from disk with memory bounded independently of its size (#7427). With `sha256`, bytes that differ+ * from it are refused before anything is published, so a stored object is never replaced by them.+ */+ uploadFile(path: string, filePath: string, mime?: string, sha256?: string): Promise<void>;download(path: string): Promise<Buffer>;delete(path: string): Promise<void>;exists(path: string): Promise<boolean>;@@ -73,15 +76,36 @@ export function hashStorageFile(filePath: string): string {}}+/** Upload a file under the hash the caller recorded; a file that changed since then is refused before it is published. */+export async function uploadUnchangedFile(storage: StorageBackend, path: string, filePath: string, sha256: string, mime?: string): Promise<void> {+ await storage.uploadFile(path, filePath, mime, sha256);+}++export function fileChangedDuringUpload(filePath: string): Error {+ return Object.assign(new Error(`${filePath} changed during the upload, so its bytes no longer match the hash taken before it; nothing was stored or recorded. Upload it again once it stops changing.`), { code: 'file_changed_during_upload' });+}+/**- * Upload a file whose hash the caller already computed, then refuse when the file changed since `before` was taken,- * so a row is never recorded under a hash the stored bytes may not match.+ * Hashes the bytes a backend reads from a file in order (re-reads of a retried range count once), so the backend can+ * refuse before its publishing step when they differ from the hash the caller recorded.*/-export async function uploadUnchangedFile(storage: StorageBackend, path: string, filePath: string, before: Stats, mime?: string): Promise<void> {- await storage.uploadFile(path, filePath, mime);- const after = statSync(filePath);- if (after.size !== before.size || after.mtimeMs !== before.mtimeMs) {- throw new Error(`${filePath} changed during the upload, so its hash may not match the stored bytes; nothing was recorded. Upload it again once it stops changing.`);+export class FileDigest {+ private readonly hash = createHash('sha256');+ private hashed = 0;++ constructor(private readonly filePath: string, private readonly expected?: string) {}++ async read(file: FileHandle, buffer: Buffer, length: number, position: number): Promise<Buffer> {+ const bytes = await readFileRange(file, buffer, length, position);+ if (position <= this.hashed && position + length > this.hashed) {+ this.hash.update(bytes.subarray(this.hashed - position));+ this.hashed = position + length;+ }+ return bytes;+ }++ assertMatches(size: number): void {+ if (this.expected !== undefined && (this.hashed !== size || this.hash.copy().digest('hex') !== this.expected)) throw fileChangedDuringUpload(this.filePath);}}diff --git a/src/core/storage/local.ts b/src/core/storage/local.tsindex cb0ffc82b2..b309fc75e5 100644--- a/src/core/storage/local.ts+++ b/src/core/storage/local.ts@@ -1,7 +1,8 @@-import { createReadStream, createWriteStream, readFileSync, writeFileSync, unlinkSync, existsSync, mkdirSync, readdirSync, realpathSync } from 'fs';+import { chmodSync, createReadStream, createWriteStream, readFileSync, statSync, writeFileSync, unlinkSync, existsSync, mkdirSync, readdirSync, realpathSync, renameSync, rmSync } from 'fs';import { pipeline } from 'stream/promises';-import { join, dirname, resolve } from 'path';-import type { StorageBackend } from '../storage.ts';+import { join, dirname, resolve, basename } from 'path';+import { createHash, randomBytes } from 'crypto';+import { fileChangedDuringUpload, type StorageBackend } from '../storage.ts';/*** Local filesystem storage — for testing and development.@@ -29,10 +30,20 @@ export class LocalStorage implements StorageBackend {writeFileSync(full, data);}- async uploadFile(path: string, filePath: string, _mime?: string): Promise<void> {+ /** Streams into a sibling temporary file and renames it over the key, so a source that is the stored object itself is never truncated and a refused upload leaves the stored object as it was; an existing object keeps its mode, as a plain write would. */+ async uploadFile(path: string, filePath: string, _mime?: string, sha256?: string): Promise<void> {const full = this.contained(path);mkdirSync(dirname(full), { recursive: true });- await pipeline(createReadStream(filePath), createWriteStream(full));+ const partial = join(dirname(full), `.${basename(full)}.${randomBytes(6).toString('hex')}.partial`);+ const hash = createHash('sha256');+ try {+ await pipeline(createReadStream(filePath).on('data', chunk => hash.update(chunk)), createWriteStream(partial, { flags: 'wx' }));+ if (sha256 !== undefined && hash.digest('hex') !== sha256) throw fileChangedDuringUpload(filePath);+ if (existsSync(full)) chmodSync(partial, statSync(full).mode & 0o7777);+ renameSync(partial, full);+ } finally {+ rmSync(partial, { force: true });+ }}async download(path: string): Promise<Buffer> {diff --git a/src/core/storage/s3.ts b/src/core/storage/s3.tsindex 6d4e2c2212..19fe90d9c0 100644--- a/src/core/storage/s3.ts+++ b/src/core/storage/s3.ts@@ -11,7 +11,7 @@ import {HeadObjectCommand,ListObjectsV2Command,} from '@aws-sdk/client-s3';-import { readFileRange, type StorageBackend, type StorageConfig } from '../storage.ts';+import { FileDigest, type StorageBackend, type StorageConfig } from '../storage.ts';const MIN_PART_SIZE = 16 * 1024 * 1024;const MAX_PART_SIZE = 5 * 1024 * 1024 * 1024;@@ -75,8 +75,9 @@ export class S3Storage implements StorageBackend {* bounded by the part size, not the file size (#7427). A file that fits in* one part is a single PutObject.*/- async uploadFile(path: string, filePath: string, mime?: string): Promise<void> {+ async uploadFile(path: string, filePath: string, mime?: string, sha256?: string): Promise<void> {const file = await open(filePath, 'r');+ const digest = new FileDigest(filePath, sha256);const target = { Bucket: this.bucket, Key: path };let uploadId: string | undefined;try {@@ -84,7 +85,9 @@ export class S3Storage implements StorageBackend {const partSize = multipartPartSize(size);const buffer = Buffer.allocUnsafe(Math.min(size, partSize));if (size <= partSize) {- await this.upload(path, await readFileRange(file, buffer, size, 0), mime);+ const data = await digest.read(file, buffer, size, 0);+ digest.assertMatches(size);+ await this.upload(path, data, mime);return;}const created = await this.client.send(new CreateMultipartUploadCommand({@@ -98,12 +101,13 @@ export class S3Storage implements StorageBackend {const PartNumber = parts.length + 1;const result = await this.client.send(new UploadPartCommand({...target, UploadId: uploadId, PartNumber,- Body: await readFileRange(file, buffer, length, offset), ContentLength: length,+ Body: await digest.read(file, buffer, length, offset), ContentLength: length,}));if (!result.ETag) throw new Error(`S3 multipart part ${PartNumber} returned no ETag`);parts.push({ PartNumber, ETag: result.ETag });offset += length;}+ digest.assertMatches(size);await this.client.send(new CompleteMultipartUploadCommand({...target, UploadId: uploadId, MultipartUpload: { Parts: parts },}));diff --git a/src/core/storage/supabase.ts b/src/core/storage/supabase.tsindex 6051444bfc..53babf7c78 100644--- a/src/core/storage/supabase.ts+++ b/src/core/storage/supabase.ts@@ -1,5 +1,5 @@import { open } from 'fs/promises';-import { readFileRange, type StorageBackend, type StorageConfig } from '../storage.ts';+import { FileDigest, type StorageBackend, type StorageConfig } from '../storage.ts';/** Size thresholds for upload method selection */const TUS_THRESHOLD = 100 * 1024 * 1024; // 100 MB — use TUS resumable above this@@ -53,16 +53,23 @@ export class SupabaseStorage implements StorageBackend {}/** Upload from disk: TUS reads each chunk from the file, so memory is bounded by the chunk size (#7427). */- async uploadFile(path: string, filePath: string, mime?: string): Promise<void> {+ async uploadFile(path: string, filePath: string, mime?: string, sha256?: string): Promise<void> {const file = await open(filePath, 'r');+ const digest = new FileDigest(filePath, sha256);try {const { size } = await file.stat();if (size < TUS_THRESHOLD) {- await this.uploadStandard(path, await readFileRange(file, Buffer.allocUnsafe(size), size, 0), mime);+ const data = await digest.read(file, Buffer.allocUnsafe(size), size, 0);+ digest.assertMatches(size);+ await this.uploadStandard(path, data, mime);return;}const chunk = Buffer.allocUnsafe(TUS_CHUNK_SIZE);- await this.uploadTus(path, size, (offset, length) => readFileRange(file, chunk, length, offset), mime);+ await this.uploadTus(path, size, async (offset, length) => {+ const bytes = await digest.read(file, chunk, length, offset);+ if (offset + length === size) digest.assertMatches(size);+ return bytes;+ }, mime);} finally {await file.close();}diff --git a/test/storage-upload-file.test.ts b/test/storage-upload-file.test.tsindex d5f2269019..53ef9f1c9f 100644--- a/test/storage-upload-file.test.ts+++ b/test/storage-upload-file.test.ts@@ -311,9 +311,9 @@ describe('upload callers hash and upload from disk (#7427)', () => {sourceId: 'default',} as never;const original = LocalStorage.prototype.uploadFile;- const spy = spyOn(LocalStorage.prototype, 'uploadFile').mockImplementation(async function (this: LocalStorage, path: string, filePath: string, mime?: string) {- fs.appendFileSync(filePath, 'edited while uploading');- return original.call(this, path, filePath, mime);+ const spy = spyOn(LocalStorage.prototype, 'uploadFile').mockImplementation(async function (this: LocalStorage, ...args: Parameters<LocalStorage['uploadFile']>) {+ fs.appendFileSync(args[1], 'edited while uploading');+ return original.apply(this, args);});try {await expect(operationsByName['file_upload'].handler(ctx, { path: src, page_slug: 'media/changing-example' }))@@ -367,3 +367,106 @@ describe('upload callers hash and upload from disk (#7427)', () => {rmSync(storageDir, { recursive: true, force: true });});});++describe('a refused upload never replaces stored bytes (#7427 review)', () => {+ test('local: re-uploading a stored object onto its own key keeps its bytes', async () => {+ const storageDir = mkdtempSync(join(tmpdir(), 'gb-7427-self-'));+ const storage = new LocalStorage(storageDir);+ const src = join(workDir, 'self-src.bin');+ writePatterned(src, 2 * MiB + 9);+ const expected = sha256Of(src);+ await storage.uploadFile('media/self/clip.bin', src);+ const stored = join(storageDir, 'media/self/clip.bin');+ await storage.uploadFile('media/self/clip.bin', stored, undefined, expected);+ expect(sha256Of(stored)).toBe(expected);+ fs.linkSync(stored, join(storageDir, 'media/self/alias.bin'));+ await storage.uploadFile('media/self/clip.bin', join(storageDir, 'media/self/alias.bin'));+ expect(sha256Of(stored)).toBe(expected);+ expect(fs.readdirSync(join(storageDir, 'media/self')).sort()).toEqual(['alias.bin', 'clip.bin']);+ rmSync(storageDir, { recursive: true, force: true });+ });++ test('file_upload: a changed re-upload keeps the existing attachment bytes and row', async () => {+ const storageDir = mkdtempSync(join(tmpdir(), 'gb-7427-keep-'));+ const src = join(workDir, 'keep-original.mp4');+ writePatterned(src, MiB + 21);+ const firstHash = sha256Of(src);+ const ctx = {+ engine,+ config: { engine: 'pglite', storage: { backend: 'local', bucket: 'b', localPath: storageDir } },+ logger: { info() {}, warn() {}, error() {} },+ dryRun: false,+ remote: false,+ sourceId: 'default',+ } as never;+ const first = await operationsByName['file_upload'].handler(ctx, { path: src, page_slug: 'media/keep-example' }) as { storage_path: string };+ fs.appendFileSync(src, 'second version');+ const original = LocalStorage.prototype.uploadFile;+ const spy = spyOn(LocalStorage.prototype, 'uploadFile').mockImplementation(async function (this: LocalStorage, ...args: Parameters<LocalStorage['uploadFile']>) {+ fs.appendFileSync(args[1], 'edited while uploading');+ return original.apply(this, args);+ });+ try {+ await expect(operationsByName['file_upload'].handler(ctx, { path: src, page_slug: 'media/keep-example' }))+ .rejects.toThrow(/changed during the upload/);+ } finally {+ spy.mockRestore();+ }+ expect(sha256Of(join(storageDir, first.storage_path))).toBe(firstHash);+ const rows = await engine.executeRaw<{ content_hash: string }>('SELECT content_hash FROM files WHERE storage_path = $1', [first.storage_path]);+ expect(rows.map(r => r.content_hash)).toEqual([firstHash]);+ expect(fs.readdirSync(join(storageDir, 'media/keep-example'))).toEqual(['keep-original.mp4']);+ rmSync(storageDir, { recursive: true, force: true });+ });++ test('S3: bytes that differ from the recorded hash abort the multipart upload before it completes', async () => {+ const src = join(workDir, 's3-changing.bin');+ writePatterned(src, 2 * S3_PART + 5);+ const expected = sha256Of(src);+ const { client, sent } = s3Stub((command) => {+ if (command instanceof CreateMultipartUploadCommand) return { UploadId: 'upload-c' };+ if (command instanceof UploadPartCommand) {+ if (command.input.PartNumber === 1) { const fd = openSync(src, 'r+'); writeSync(fd, Buffer.from('edited'), 0, 6, S3_PART + 1); closeSync(fd); }+ return { ETag: '"e' + command.input.PartNumber + '"' };+ }+ return {};+ });+ await expect(new S3Storage({ backend: 's3', bucket: 'originals' }, client).uploadFile('media/s3-changing.bin', src, undefined, expected))+ .rejects.toThrow(/changed during the upload/);+ expect(sent.some(c => c instanceof CompleteMultipartUploadCommand)).toBe(false);+ expect(sent.at(-1)).toBeInstanceOf(AbortMultipartUploadCommand);+ });++ test('S3: a single-part file whose bytes differ from the recorded hash is never put', async () => {+ const src = join(workDir, 's3-small-changed.txt');+ writeFileSync(src, 'first version');+ const expected = sha256Of(src);+ writeFileSync(src, 'second version');+ const { client, sent } = s3Stub(() => ({}));+ await expect(new S3Storage({ backend: 's3', bucket: 'originals' }, client).uploadFile('notes/small.txt', src, 'text/plain', expected))+ .rejects.toThrow(/changed during the upload/);+ expect(sent).toEqual([]);+ });++ test('Supabase: a TUS upload whose bytes differ from the recorded hash never sends its final chunk', async () => {+ const src = join(workDir, 'supabase-changing.bin');+ const size = 100 * MiB + 2 * MiB + 3;+ writeFileSync(src, '');+ truncateSync(src, size);+ const expected = sha256Of(src);+ let patched = 0;+ const fetchImpl = async (_url: string, init: RequestInit) => {+ const headers = init.headers as Record<string, string>;+ if (init.method === 'POST') return new Response(null, { status: 201, headers: { Location: 'https://example.test/tus/2' } });+ if (init.method === 'HEAD') return new Response(null, { status: 200, headers: { 'Upload-Offset': String(patched) } });+ const body = init.body as Uint8Array;+ if (patched === 0) { const fd = openSync(src, 'r+'); writeSync(fd, Buffer.from('edited'), 0, 6, 50 * MiB); closeSync(fd); }+ patched += body.byteLength;+ return new Response(null, { status: 204, headers: { 'Upload-Offset': String(Number(headers['Upload-Offset']) + body.byteLength) } });+ };+ const storage = new SupabaseStorage({ backend: 'supabase', bucket: 'b', projectUrl: 'https://example.test', serviceRoleKey: 'k' }, fetchImpl);+ await expect(storage.uploadFile('media/supabase-changing.bin', src, undefined, expected)).rejects.toThrow(/changed during the upload/);+ expect(patched).toBeLessThan(size);+ }, 30_000);+});+