Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
157 changes: 157 additions & 0 deletions packages/worker/src/dr/backup-s3.node.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
import { expect, test, vi } from 'vitest'
import {
createDrBackupS3Client,
DrBackupPreconditionFailedError,
isTransientDrBackupHttpStatus,
readDrBackupS3Config,
} from './backup-s3.ts'

const config = {
accountId: 'acct',
bucketName: 'backups',
accessKeyId: 'key',
secretAccessKey: 'secret',
}

function jsonResponse(
status: number,
body = '',
headers: Record<string, string> = {},
) {
return new Response(body, { status, headers })
}

test('isTransientDrBackupHttpStatus matches platform blips only', () => {
expect(isTransientDrBackupHttpStatus(429)).toBe(true)
expect(isTransientDrBackupHttpStatus(500)).toBe(true)
expect(isTransientDrBackupHttpStatus(502)).toBe(true)
expect(isTransientDrBackupHttpStatus(503)).toBe(true)
expect(isTransientDrBackupHttpStatus(504)).toBe(true)
expect(isTransientDrBackupHttpStatus(400)).toBe(false)
expect(isTransientDrBackupHttpStatus(403)).toBe(false)
expect(isTransientDrBackupHttpStatus(404)).toBe(false)
expect(isTransientDrBackupHttpStatus(412)).toBe(false)
expect(isTransientDrBackupHttpStatus(200)).toBe(false)
})

test('put retries transient HTTP 500 then succeeds', async () => {
const fetchImpl = vi
.fn()
.mockResolvedValueOnce(jsonResponse(500, 'blip'))
.mockResolvedValueOnce(jsonResponse(200, '', { etag: '"etag-1"' }))

const client = createDrBackupS3Client(config, fetchImpl as typeof fetch, {
maxAttempts: 3,
baseDelayMs: 1,
})
await expect(
client.put('staging/day/exporter/progress.json', '{}', {
contentType: 'application/json',
ifMatch: '"prev"',
}),
).resolves.toEqual({ etag: '"etag-1"' })
expect(fetchImpl).toHaveBeenCalledTimes(2)
const secondInit = fetchImpl.mock.calls[1]?.[0] as Request
expect(secondInit.method).toBe('PUT')
expect(secondInit.headers.get('If-Match')).toBe('"prev"')
})

test('put does not retry precondition failures', async () => {
const fetchImpl = vi.fn().mockResolvedValue(jsonResponse(412, 'conflict'))
const client = createDrBackupS3Client(config, fetchImpl as typeof fetch, {
maxAttempts: 4,
baseDelayMs: 1,
})
await expect(
client.put('staging/day/exporter/progress.json', '{}', {
ifMatch: '"prev"',
}),
).rejects.toBeInstanceOf(DrBackupPreconditionFailedError)
expect(fetchImpl).toHaveBeenCalledTimes(1)
})

test('put retries transport errors then surfaces exhausted failures', async () => {
const fetchImpl = vi
.fn()
.mockRejectedValueOnce(new TypeError('network down'))
.mockResolvedValueOnce(jsonResponse(500, 'still bad'))
.mockResolvedValueOnce(jsonResponse(500, 'still bad'))

const client = createDrBackupS3Client(config, fetchImpl as typeof fetch, {
maxAttempts: 3,
baseDelayMs: 1,
})
await expect(client.put('key', 'body')).rejects.toThrow(
'DR backup PUT failed for key: HTTP 500',
)
expect(fetchImpl).toHaveBeenCalledTimes(3)
})

test('head, getText, and getBytes retry transient 503 responses', async () => {
const headFetch = vi
.fn()
.mockResolvedValueOnce(jsonResponse(503))
.mockResolvedValueOnce(jsonResponse(200, '', { etag: '"h"' }))
const headClient = createDrBackupS3Client(config, headFetch as typeof fetch, {
maxAttempts: 2,
baseDelayMs: 1,
})
await expect(headClient.head('blob')).resolves.toEqual({
exists: true,
status: 200,
etag: '"h"',
})
expect(headFetch).toHaveBeenCalledTimes(2)

const getFetch = vi
.fn()
.mockResolvedValueOnce(jsonResponse(503, 'busy'))
.mockResolvedValueOnce(jsonResponse(200, '{"ok":true}', { etag: '"g"' }))
const getClient = createDrBackupS3Client(config, getFetch as typeof fetch, {
maxAttempts: 2,
baseDelayMs: 1,
})
await expect(getClient.getText('progress.json')).resolves.toEqual({
text: '{"ok":true}',
etag: '"g"',
})
expect(getFetch).toHaveBeenCalledTimes(2)

const bytesFetch = vi
.fn()
.mockResolvedValueOnce(jsonResponse(503, 'busy'))
.mockResolvedValueOnce(jsonResponse(200, 'abc', { etag: '"b"' }))
const bytesClient = createDrBackupS3Client(
config,
bytesFetch as typeof fetch,
{ maxAttempts: 2, baseDelayMs: 1 },
)
await expect(bytesClient.getBytes('blob.bin')).resolves.toEqual(
new Uint8Array([97, 98, 99]),
)
expect(bytesFetch).toHaveBeenCalledTimes(2)
})

test('readDrBackupS3Config requires all fields', () => {
expect(
readDrBackupS3Config({
DR_BACKUP_ACCOUNT_ID: 'a',
DR_BACKUP_BUCKET_NAME: 'b',
DR_BACKUP_ACCESS_KEY_ID: 'c',
DR_BACKUP_SECRET_ACCESS_KEY: 'd',
}),
).toEqual({
accountId: 'a',
bucketName: 'b',
accessKeyId: 'c',
secretAccessKey: 'd',
})
expect(
readDrBackupS3Config({
DR_BACKUP_ACCOUNT_ID: 'a',
DR_BACKUP_BUCKET_NAME: '',
DR_BACKUP_ACCESS_KEY_ID: 'c',
DR_BACKUP_SECRET_ACCESS_KEY: 'd',
}),
).toBeNull()
})
70 changes: 66 additions & 4 deletions packages/worker/src/dr/backup-s3.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,28 @@ export type DrBackupS3Client = {
) => Promise<{ etag: string | null }>
}

/** R2/S3 platform blips observed on PutObject (and siblings) during cron ticks. */
export const drBackupS3RetryMaxAttempts = 4
export const drBackupS3RetryBaseDelayMs = 150

function sleep(ms: number) {
return new Promise<void>((resolve) => setTimeout(resolve, ms))
}

/**
* Transient R2/S3 HTTP statuses worth retrying. 412 stays non-retryable so
* conditional progress.json ownership conflicts surface immediately.
*/
export function isTransientDrBackupHttpStatus(status: number) {
return (
status === 429 ||
status === 500 ||
status === 502 ||
status === 503 ||
status === 504
)
}

function objectUrl(config: DrBackupS3Config, key: string) {
const encodedKey = key
.split('/')
Expand All @@ -55,25 +77,65 @@ function readEtag(response: Response): string | null {
return etag && etag.length > 0 ? etag : null
}

async function drainResponseBody(response: Response) {
try {
await response.arrayBuffer()
} catch {
// Best-effort: free the connection before the next attempt.
}
}

export function createDrBackupS3Client(
config: DrBackupS3Config,
fetchImpl: typeof fetch = fetch,
options?: {
maxAttempts?: number
baseDelayMs?: number
},
): DrBackupS3Client {
const aws = new AwsClient({
accessKeyId: config.accessKeyId,
secretAccessKey: config.secretAccessKey,
service: 's3',
region: 'auto',
})
const maxAttempts = options?.maxAttempts ?? drBackupS3RetryMaxAttempts
const baseDelayMs = options?.baseDelayMs ?? drBackupS3RetryBaseDelayMs

async function signedFetch(key: string, init?: RequestInit) {
const request = await aws.sign(objectUrl(config, key), init)
return fetchImpl(request)
}
Comment on lines 105 to 108

@coderabbitai coderabbitai Bot Jul 31, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

Namespace DR backup object access by userId.

The client signs the caller-provided key directly, and its API has no userId. HEAD, GET, and PUT therefore access one shared bucket keyspace without tenant isolation.

  • packages/worker/src/dr/backup-s3.ts#L105-L108: require a validated userId at the client or operation boundary and derive the object key from that namespace before signing.
  • packages/worker/src/dr/backup-s3.node.test.ts#L9-L14: update the fixture and add assertions that distinct user IDs produce isolated object keys.

As per coding guidelines, “every read and write path must be scoped by userId.”

📍 Affects 2 files
  • packages/worker/src/dr/backup-s3.ts#L105-L108 (this comment)
  • packages/worker/src/dr/backup-s3.node.test.ts#L9-L14
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/worker/src/dr/backup-s3.ts` around lines 105 - 108, Namespace every
backup-s3 read and write operation by a validated userId before signing
requests: update the client or operation boundary around signedFetch and its
HEAD, GET, and PUT callers to derive user-scoped object keys rather than signing
the raw key. In packages/worker/src/dr/backup-s3.ts lines 105-108, apply this
requirement to signedFetch and all paths using it; in
packages/worker/src/dr/backup-s3.node.test.ts lines 9-14, update the fixture and
assert distinct user IDs generate isolated object keys.

Source: Coding guidelines

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not applicable here: this client is the platform disaster-recovery backup path (backup-control-plane), which intentionally writes a shared staging/sealed backup keyspace for the whole deployment. Per-user isolation applies to user-owned storage/MCP paths, not this operator backup bucket. Adding userId namespacing would break the exporter/restore contract.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Skipped: comment is from another GitHub bot.


/**
* Retry transport / platform blips. Conditional headers are preserved on
* each attempt: a phantom success that still 412s on retry is handled by
* callers as `DrBackupPreconditionFailedError` (safe skip / resume).
*/
async function signedFetchWithRetry(key: string, init?: RequestInit) {
let lastError: unknown
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
const response = await signedFetch(key, init)
if (
!isTransientDrBackupHttpStatus(response.status) ||
attempt === maxAttempts
) {
return response
}
await drainResponseBody(response)
} catch (error) {
lastError = error
if (attempt === maxAttempts) throw error
}
await sleep(baseDelayMs * 2 ** (attempt - 1))
}
throw lastError ?? new Error('DR backup request failed after retries')
}

return {
async head(key) {
const response = await signedFetch(key, { method: 'HEAD' })
const response = await signedFetchWithRetry(key, { method: 'HEAD' })
if (response.status === 404) {
return { exists: false, status: response.status, etag: null }
}
Expand All @@ -89,7 +151,7 @@ export function createDrBackupS3Client(
}
},
async getText(key) {
const response = await signedFetch(key, { method: 'GET' })
const response = await signedFetchWithRetry(key, { method: 'GET' })
if (response.status === 404) return null
if (!response.ok) {
throw new Error(
Expand All @@ -102,7 +164,7 @@ export function createDrBackupS3Client(
}
},
async getBytes(key) {
const response = await signedFetch(key, { method: 'GET' })
const response = await signedFetchWithRetry(key, { method: 'GET' })
if (response.status === 404) return null
if (!response.ok) {
throw new Error(
Expand All @@ -121,7 +183,7 @@ export function createDrBackupS3Client(
if (options.ifNoneMatch) {
headers['If-None-Match'] = options.ifNoneMatch
}
const response = await signedFetch(key, {
const response = await signedFetchWithRetry(key, {
method: 'PUT',
headers,
body: body as BodyInit,
Expand Down
Loading