import { Hono } from 'hono' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { parseDeleteObjectsResult, s3 } from '../supabase/functions/_backend/utils/s3.ts' import { sha256Hex, signV4 } from '../supabase/functions/_backend/utils/s3_sign.ts' const fetchMock = vi.fn<(input: RequestInfo | URL, init?: RequestInit) => Promise>() async function runInContext(fn: (c: any) => Promise): Promise { let result: T | undefined let failure: unknown const app = new Hono<{ Bindings: Record }>() app.post('/', async (c) => { try { result = await fn(c) } catch (error) { failure = error } return c.text('ok') }) await app.request('http://127.0.0.1/', { method: 'POST' }, { S3_ENDPOINT: 'https://account.r2.cloudflarestorage.com', S3_BUCKET: 'capgo', S3_REGION: 'auto', S3_ACCESS_KEY_ID: 'id', S3_SECRET_ACCESS_KEY: 'secret', }) if (failure) throw failure return result as T } const result = (body: string) => `${body}` const keys = ['orgs/o/apps/a/delta/a.js', 'orgs/o/apps/a/delta/b&c.js', 'orgs/o/apps/a/delta/d.js'] describe('signV4', () => { it('matches the AWS S3 header-signing example (GET object)', async () => { const headers = new Headers({ range: 'bytes=0-9' }) await signV4({ method: 'GET', url: new URL('https://examplebucket.s3.amazonaws.com/test.txt'), headers, payloadHash: await sha256Hex(''), accessKey: 'AKIAIOSFODNN7EXAMPLE', secretKey: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY', region: 'us-east-1', date: new Date('2013-05-24T00:00:00Z'), }) expect(headers.get('authorization')).toBe('AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/s3/aws4_request, SignedHeaders=host;range;x-amz-content-sha256;x-amz-date, Signature=f0e8bdb87c964420e857bd35b5d6ed310bd44f0170aba48dd91039c6036bdb41') }) it('signs a DeleteObjects request exactly like s3-lite-client', async () => { // Not exported by the package: loaded by path for the comparison only. const liteSigningPath = '../node_modules/@bradenmacdonald/s3-lite-client/signing.js' const lite = await import(/* @vite-ignore */ liteSigningPath) as { signV4: (request: { headers: Headers, method: string, path: string, accessKey: string, secretKey: string, region: string, date: Date }) => Promise } const date = new Date('2026-12-01T10:20:30Z') const payloadHash = await sha256Hex('') const extra = { 'content-type': 'application/xml', 'x-amz-checksum-sha256': 'abc=', 'x-amz-sdk-checksum-algorithm': 'SHA256' } const ours = new Headers(extra) await signV4({ method: 'POST', url: new URL('https://account.r2.cloudflarestorage.com/capgo?delete'), headers: ours, payloadHash, accessKey: 'id', secretKey: 'secret', region: 'auto', date }) const theirs = new Headers({ ...extra, 'host': 'account.r2.cloudflarestorage.com', 'x-amz-date': '20261201T102030Z', 'x-amz-content-sha256': payloadHash }) const expected = await lite.signV4({ headers: theirs, method: 'POST', path: '/capgo?delete=', accessKey: 'id', secretKey: 'secret', region: 'auto', date }) expect(ours.get('authorization')).toBe(expected) }) }) describe('parseDeleteObjectsResult', () => { it('reads error keys, counts NoSuchKey as deleted and refuses unreadable bodies', () => { expect(parseDeleteObjectsResult('')).toEqual([]) expect(parseDeleteObjectsResult(result('a&bAccessDeniedcNoSuchKey'))).toEqual(['a&b']) expect(parseDeleteObjectsResult('')).toBeNull() expect(parseDeleteObjectsResult('a')).toBeNull() expect(parseDeleteObjectsResult(result('InternalError'))).toBeNull() }) }) describe('deleteObjectKeysBounded', () => { beforeEach(() => { fetchMock.mockReset() vi.stubGlobal('fetch', fetchMock) // Bindings are the env only on the Workers runtime (hono's env()). vi.stubGlobal('navigator', { userAgent: 'Cloudflare-Workers' }) }) afterEach(() => { vi.unstubAllGlobals() }) it('sends one signed DeleteObjects request with a body checksum', async () => { fetchMock.mockResolvedValue(new Response(result(''), { status: 200 })) const outcome = await runInContext(c => s3.deleteObjectKeysBounded(c, keys, { startBy: Date.now() + 1_000, timeoutMs: 800 })) expect(outcome).toEqual({ failed: [] }) expect(fetchMock).toHaveBeenCalledOnce() const [url, init] = fetchMock.mock.calls[0] expect(String(url)).toBe('https://account.r2.cloudflarestorage.com/capgo?delete') expect(init?.method).toBe('POST') expect(init?.signal).toBeInstanceOf(AbortSignal) const headers = new Headers(init?.headers) const body = new TextDecoder().decode(init?.body as Uint8Array) expect([...body.matchAll(/(.*?)<\/Key>/g)].map(match => match[1])).toEqual(['orgs/o/apps/a/delta/a.js', 'orgs/o/apps/a/delta/b&c.js', 'orgs/o/apps/a/delta/d.js']) const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(body))) expect(headers.get('x-amz-checksum-sha256')).toBe(btoa(String.fromCodePoint(...digest))) expect(headers.get('x-amz-content-sha256')).toBe(await sha256Hex(body)) expect(headers.get('authorization')).toMatch(/^AWS4-HMAC-SHA256 Credential=id\/\d{8}\/auto\/s3\/aws4_request, SignedHeaders=host;x-amz-checksum-sha256;x-amz-content-sha256;x-amz-date;x-amz-sdk-checksum-algorithm, Signature=[0-9a-f]{64}$/) }) it('reports the keys of the error entries only', async () => { fetchMock.mockResolvedValue(new Response(result('orgs/o/apps/a/delta/b&c.jsInternalErrororgs/o/apps/a/delta/d.jsNoSuchKey'), { status: 200 })) const outcome = await runInContext(c => s3.deleteObjectKeysBounded(c, keys, { startBy: Date.now() + 1_000, timeoutMs: 800 })) expect(outcome).toEqual({ failed: ['orgs/o/apps/a/delta/b&c.js'] }) }) it('returns an unknown outcome without falling back to single deletes', async () => { fetchMock.mockResolvedValue(new Response('NotImplemented', { status: 501 })) expect(await runInContext(c => s3.deleteObjectKeysBounded(c, keys, { startBy: Date.now() + 1_000, timeoutMs: 800 }))).toBeNull() expect(fetchMock).toHaveBeenCalledOnce() fetchMock.mockClear() fetchMock.mockResolvedValue(new Response('proxy error', { status: 200 })) expect(await runInContext(c => s3.deleteObjectKeysBounded(c, keys, { startBy: Date.now() + 1_000, timeoutMs: 800 }))).toBeNull() fetchMock.mockClear() fetchMock.mockRejectedValue(new Error('network')) expect(await runInContext(c => s3.deleteObjectKeysBounded(c, keys, { startBy: Date.now() + 1_000, timeoutMs: 800 }))).toBeNull() expect(fetchMock).toHaveBeenCalledOnce() }) it('does not start after the start window', async () => { expect(await runInContext(c => s3.deleteObjectKeysBounded(c, keys, { startBy: Date.now() - 1, timeoutMs: 800 }))).toBeNull() expect(fetchMock).not.toHaveBeenCalled() }) it('aborts the request after the timeout and confirms nothing', async () => { let signal: AbortSignal | undefined // Headers arrive, then the body stalls, as a stuck R2 request would. fetchMock.mockImplementation(async (_url, init) => { signal = init?.signal ?? undefined return new Response(new ReadableStream({ start() {} }), { status: 200 }) }) const startedAt = Date.now() const outcome = await runInContext(c => s3.deleteObjectKeysBounded(c, keys, { startBy: Date.now() + 1_000, timeoutMs: 50 })) expect(outcome).toBeNull() expect(signal?.aborted).toBe(true) expect(Date.now() - startedAt).toBeLessThan(1_000) }) })