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
14 changes: 10 additions & 4 deletions src/http/routes/s3/commands/get-object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,10 @@ const GetObjectInput = {
type: 'object',
properties: {
range: { type: 'string' },
'if-match': { type: 'string' },
'if-none-match': { type: 'string' },
'if-modified-since': { type: 'string' },
'if-unmodified-since': { type: 'string' },
},
},
Querystring: {
Expand Down Expand Up @@ -63,8 +65,8 @@ function parseDateHeader(input?: string) {
}
}

// RFC 9110 13.1.3: an invalid If-Modified-Since date is ignored
function parseIfModifiedSince(input?: string) {
// RFC 9110 13.1.3 and 13.1.4: an invalid If-Modified-Since or If-Unmodified-Since date is ignored
function parseConditionalDate(input?: string) {
if (input) {
const parsedDate = new Date(input)
if (!isNaN(parsedDate.getTime())) {
Expand Down Expand Up @@ -100,8 +102,10 @@ export default function GetObject(s3Router: S3Router) {
Bucket: icebergBucket,
Key: req.Params['*'],
Range: req.Headers?.['range'],
IfMatch: req.Headers?.['if-match'],
IfNoneMatch: req.Headers?.['if-none-match'],
IfModifiedSince: parseIfModifiedSince(req.Headers?.['if-modified-since']),
IfModifiedSince: parseConditionalDate(req.Headers?.['if-modified-since']),
IfUnmodifiedSince: parseConditionalDate(req.Headers?.['if-unmodified-since']),
ResponseContentDisposition: req.Querystring?.['response-content-disposition'],
ResponseContentType: req.Querystring?.['response-content-type'],
ResponseCacheControl: req.Querystring?.['response-cache-control'],
Expand Down Expand Up @@ -129,8 +133,10 @@ export default function GetObject(s3Router: S3Router) {
Bucket: req.Params.Bucket,
Key: req.Params['*'],
Range: req.Headers?.['range'],
IfMatch: req.Headers?.['if-match'],
IfNoneMatch: req.Headers?.['if-none-match'],
IfModifiedSince: parseIfModifiedSince(req.Headers?.['if-modified-since']),
IfModifiedSince: parseConditionalDate(req.Headers?.['if-modified-since']),
IfUnmodifiedSince: parseConditionalDate(req.Headers?.['if-unmodified-since']),
ResponseContentDisposition: req.Querystring?.['response-content-disposition'],
ResponseContentType: req.Querystring?.['response-content-type'],
ResponseCacheControl: req.Querystring?.['response-cache-control'],
Expand Down
45 changes: 45 additions & 0 deletions src/http/routes/s3/error-handler.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { IncomingMessage, ServerResponse } from 'node:http'
import { Socket } from 'node:net'
import { Readable } from 'node:stream'
import { GetObjectCommand, S3Client, S3ServiceException } from '@aws-sdk/client-s3'
import { ERRORS, ErrorCode } from '@internal/errors'
import { DBError } from '@storage/database/errors'
import type { FastifyReply, FastifyRequest } from 'fastify'
Expand All @@ -24,6 +26,49 @@ describe('formatS3ErrorResponse resource normalization', () => {
})

describe('s3ErrorHandler', () => {
it.each([
[
'the upstream XML code',
412,
'<Error><Code>PreconditionFailed</Code><Message>ETag changed</Message></Error>',
'PreconditionFailed',
'ETag changed',
],
['S3Error when the upstream response has no XML code', 403, '', 'S3Error', 'UnknownError'],
])('reports %s for an S3 SDK error', async (_name, statusCode, body, Code, Message) => {
const client = new S3Client({
region: 'us-east-1',
credentials: { accessKeyId: 'test', secretAccessKey: 'test' },
requestHandler: {
handle: async () => ({
response: {
statusCode,
headers: { 'content-type': 'application/xml' },
body: Readable.from(body ? [body] : []),
},
}),
},
})
const request = createRequest('/s3/public/object')
const reply = createReply(request)

try {
const error = await client
.send(new GetObjectCommand({ Bucket: 'public', Key: 'object', IfMatch: '"stale"' }))
.catch((error: unknown) => error)
expect(error).toBeInstanceOf(S3ServiceException)
s3ErrorHandler(error as S3ServiceException, request, reply)

expect(reply.status).toHaveBeenCalledWith(statusCode)
expect(reply.send).toHaveBeenCalledWith({
Error: { Resource: 'public/object', Code, Message },
})
} finally {
client.destroy()
request.raw.destroy()
}
})

it('retains explicit-close errors for the response hook', () => {
const request = createRequest('/s3/public/object')
const reply = createReply(request)
Expand Down
2 changes: 1 addition & 1 deletion src/http/routes/s3/error-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export const s3ErrorHandler = (
reply,
request,
error.$metadata.httpStatusCode || 500,
error.$response?.body.Code || ErrorCode.S3Error,
(error as { Code?: string }).Code || ErrorCode.S3Error,
error.message
)
}
Expand Down
113 changes: 63 additions & 50 deletions src/http/routes/s3/router.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -872,61 +872,74 @@ describe('S3 route handler matching', () => {
expect(getObject).toHaveBeenCalled()
})

it.each([
['not a date', undefined],
['Thu, 01 Jan 2026 00:00:00 GMT', '2026-01-01T00:00:00.000Z'],
])('passes if-modified-since %s to the backend as %s', async (header, expected) => {
const getObject = vi.fn().mockResolvedValue({
body: new Blob(['stored']),
httpStatusCode: 200,
metadata: {
cacheControl: 'no-cache',
contentLength: 6,
eTag: '"etag"',
mimetype: 'text/plain',
},
})

await withMockedS3App(
async (app) => {
const response = await app.inject({
method: 'GET',
url: '/bucket/object.txt',
headers: {
'if-modified-since': header,
},
})
describe.each([false, true])('conditional reads (iceberg: %s)', (isIcebergBucket) => {
it.each([
['not a date', undefined, undefined],
['Thu, 01 Jan 2026 00:00:00 GMT', '2026-01-01T00:00:00.000Z', '2026-01-02T00:00:00.000Z'],
])('passes conditional headers with date %s to the backend as %s', async (header, expected, expectedUnmodified) => {
const getObject = vi.fn().mockResolvedValue({
body: new Blob(['stored']),
httpStatusCode: 200,
metadata: {
cacheControl: 'no-cache',
contentLength: 6,
eTag: '"etag"',
mimetype: 'text/plain',
},
})

expect(response.statusCode).toBe(200)
},
{
configureRequest: (request) => {
Object.assign(request, {
owner: 'owner-id',
signals: {
body: new AbortController(),
response: new AbortController(),
},
storage: {
backend: { getObject },
from: vi.fn(() => ({
findObject: vi.fn().mockResolvedValue({
user_metadata: null,
version: 'version',
}),
})),
location: {
getKeyLocation: vi.fn().mockReturnValue('tenant-id/bucket/object.txt'),
getRootLocation: vi.fn().mockReturnValue('root'),
},
await withMockedS3App(
async (app) => {
const response = await app.inject({
method: 'GET',
url: '/bucket/object.txt',
headers: {
'if-match': '"expected-etag"',
'if-modified-since': header,
'if-unmodified-since': expectedUnmodified ? 'Fri, 02 Jan 2026 00:00:00 GMT' : header,
range: 'bytes=0-1',
},
tenantId: 'tenant-id',
})

expect(response.statusCode).toBe(200)
},
}
)
{
configureRequest: (request) => {
Object.assign(request, {
owner: 'owner-id',
isIcebergBucket,
internalIcebergBucketName: 'internal-bucket',
signals: {
body: new AbortController(),
response: new AbortController(),
},
storage: {
backend: { getObject },
from: vi.fn(() => ({
findObject: vi.fn().mockResolvedValue({
user_metadata: null,
version: 'version',
}),
})),
location: {
getKeyLocation: vi.fn().mockReturnValue('tenant-id/bucket/object.txt'),
getRootLocation: vi.fn().mockReturnValue('root'),
},
},
tenantId: 'tenant-id',
})
},
}
)

expect(getObject.mock.calls[0][3].ifModifiedSince).toBe(expected)
expect(getObject.mock.calls[0][3]).toMatchObject({
ifMatch: '"expected-etag"',
ifModifiedSince: expected,
ifUnmodifiedSince: expectedUnmodified,
range: 'bytes=0-1',
})
expect(getObject.mock.calls[0][2]).toBe(isIcebergBucket ? undefined : 'version')
})
})
})

Expand Down
1 change: 1 addition & 0 deletions src/internal/errors/codes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ export enum ErrorCode {
InvalidUploadSignature = 'InvalidUploadSignature',
LockTimeout = 'LockTimeout',
S3Error = 'S3Error',
PreconditionFailed = 'PreconditionFailed',
S3InvalidAccessKeyId = 'InvalidAccessKeyId',
S3MaximumCredentialsLimit = 'MaximumCredentialsLimit',
InvalidChecksum = 'InvalidChecksum',
Expand Down
2 changes: 2 additions & 0 deletions src/internal/monitoring/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,8 @@ const allowlistedHeaderKeys = new Map<string, string>(
'content-type',
'if-none-match',
'if-modified-since',
'if-match',
'if-unmodified-since',
'upload-metadata',
'upload-length',
'upload-offset',
Expand Down
2 changes: 2 additions & 0 deletions src/storage/backend/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@ import { getConfig } from '../../config'
* Browser cache headers
*/
export interface BrowserCacheHeaders {
ifMatch?: string
ifModifiedSince?: string
ifNoneMatch?: string
ifUnmodifiedSince?: string
range?: string
}

Expand Down
72 changes: 70 additions & 2 deletions src/storage/backend/file.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { Readable } from 'stream'
import { text } from 'stream/consumers'
import { type Mock, vi } from 'vitest'
import { getConfig } from '../../config'
import { withOptionalVersion } from './adapter'
import { type BrowserCacheHeaders, withOptionalVersion } from './adapter'
import { FileBackend } from './file'

vi.mock('fs-xattr', () => ({
Expand Down Expand Up @@ -683,7 +683,7 @@ describe('FileBackend conditional reads', () => {
await fsp.utimes(filePath, mtime, mtime)
})

async function statusFor(headers: { ifNoneMatch?: string; ifModifiedSince?: string }) {
async function statusFor(headers: BrowserCacheHeaders) {
const response = await ctx.backend.getObject(bucket, key, version, headers)
if (response.body instanceof Readable) {
response.body.destroy()
Expand Down Expand Up @@ -755,6 +755,73 @@ describe('FileBackend conditional reads', () => {
])('ignores if-modified-since %s when if-none-match is empty', async (ifModifiedSince) => {
await expect(statusFor({ ifNoneMatch: '', ifModifiedSince })).resolves.toBe(200)
})

it('returns 200 when if-match matches the etag', async () => {
const head = await ctx.backend.headObject(bucket, key, version)
await expect(statusFor({ ifMatch: head.eTag })).resolves.toBe(200)
})

it.each([
['a stale weak tag', (_eTag: string) => 'W/"stale-etag"'],
['a quoted wildcard', () => '"stale,*,etag"'],
])('rejects if-match with %s before range and cache checks', async (_name, toHeader) => {
const head = await ctx.backend.headObject(bucket, key, version)
await expect(
statusFor({ ifMatch: toHeader(head.eTag), range: 'bytes=0-1' })
).rejects.toMatchObject({ httpStatusCode: 412, code: 'PreconditionFailed' })
await expect(
statusFor({ ifMatch: toHeader(head.eTag), ifNoneMatch: head.eTag })
).rejects.toMatchObject({ httpStatusCode: 412, code: 'PreconditionFailed' })
})

it.each([
['a wildcard', () => '*'],
['a match in a list', (eTag: string) => `W/"stale-etag", ${eTag}`],
['an unquoted tag', (eTag: string) => eTag.slice(1, -1)],
['a weak tag', (eTag: string) => `W/${eTag}`],
['a weak tag in a list', (eTag: string) => `"stale-etag", W/${eTag}`],
])('allows a range when if-match has %s', async (_name, toHeader) => {
const head = await ctx.backend.headObject(bucket, key, version)
await expect(statusFor({ ifMatch: toHeader(head.eTag), range: 'bytes=0-1' })).resolves.toBe(206)
})

it('rejects with 412 when if-match does not match the etag', async () => {
await expect(statusFor({ ifMatch: '"stale-etag"' })).rejects.toMatchObject({
httpStatusCode: 412,
code: 'PreconditionFailed',
message: 'PreconditionFailed',
})
})

it('rejects an empty if-match even when if-unmodified-since passes', async () => {
await expect(
statusFor({ ifMatch: '', ifUnmodifiedSince: lastModifiedHeader })
).rejects.toMatchObject({ httpStatusCode: 412, code: 'PreconditionFailed' })
})

it('returns 200 when the object was not modified after if-unmodified-since', async () => {
await expect(statusFor({ ifUnmodifiedSince: lastModifiedHeader })).resolves.toBe(200)
})

it('rejects with 412 when the object changed after if-unmodified-since', async () => {
await expect(
statusFor({ ifUnmodifiedSince: new Date(mtime.getTime() - 1_000).toUTCString() })
).rejects.toMatchObject({ httpStatusCode: 412, code: 'PreconditionFailed' })
})

it('ignores an invalid if-unmodified-since date', async () => {
await expect(statusFor({ ifUnmodifiedSince: 'not a date' })).resolves.toBe(200)
})

it('ignores if-unmodified-since when if-match matches', async () => {
const head = await ctx.backend.headObject(bucket, key, version)
await expect(
statusFor({
ifMatch: head.eTag,
ifUnmodifiedSince: new Date(mtime.getTime() - 1_000).toUTCString(),
})
).resolves.toBe(200)
})
})

describe('FileBackend range reads', () => {
Expand Down Expand Up @@ -853,6 +920,7 @@ describe('FileBackend copy source preconditions', () => {
async function expectPreconditionFailed(conditions: Parameters<typeof copy>[0]) {
await expect(copy(conditions)).rejects.toMatchObject({
httpStatusCode: 412,
code: 'PreconditionFailed',
message: 'PreconditionFailed',
})
await expect(fsp.stat(filePath('destination.txt'))).rejects.toMatchObject({ code: 'ENOENT' })
Expand Down
18 changes: 17 additions & 1 deletion src/storage/backend/file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,22 @@ export class FileBackend implements StorageBackendAdapter {
const { cacheControl, mimetype } = await this.getFileMetadata(file)
const lastModified = data.mtime

// RFC 9110 13.1.4: If-Unmodified-Since is ignored when If-Match is present.
const preconditionFailed =
headers?.ifMatch !== undefined
? !matchesETag(headers.ifMatch, eTag)
: headers?.ifUnmodifiedSince !== undefined &&
toSeconds(lastModified) > toSeconds(new Date(headers.ifUnmodifiedSince))

if (preconditionFailed) {
throw StorageBackendError.withStatusCode(412, {
error: 'PreconditionFailed',
code: ErrorCode.PreconditionFailed,
httpStatusCode: 412,
message: 'PreconditionFailed',
})
}

// RFC 9110 13.1.3: If-Modified-Since is ignored when If-None-Match is present.
const notModified =
(headers?.ifNoneMatch && matchesETag(headers.ifNoneMatch, eTag)) ||
Expand Down Expand Up @@ -772,7 +788,7 @@ function assertCopySourcePreconditions(
if (failed) {
throw StorageBackendError.withStatusCode(412, {
error: 'PreconditionFailed',
code: ErrorCode.S3Error,
code: ErrorCode.PreconditionFailed,
httpStatusCode: 412,
message: 'PreconditionFailed',
})
Expand Down
Loading