diff --git a/src/http/routes/s3/commands/get-object.ts b/src/http/routes/s3/commands/get-object.ts index 338d32e51..346731e4a 100644 --- a/src/http/routes/s3/commands/get-object.ts +++ b/src/http/routes/s3/commands/get-object.ts @@ -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: { @@ -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())) { @@ -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'], @@ -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'], diff --git a/src/http/routes/s3/error-handler.test.ts b/src/http/routes/s3/error-handler.test.ts index 80d5bed9a..36c5e800a 100644 --- a/src/http/routes/s3/error-handler.test.ts +++ b/src/http/routes/s3/error-handler.test.ts @@ -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' @@ -24,6 +26,49 @@ describe('formatS3ErrorResponse resource normalization', () => { }) describe('s3ErrorHandler', () => { + it.each([ + [ + 'the upstream XML code', + 412, + 'PreconditionFailedETag changed', + '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) diff --git a/src/http/routes/s3/error-handler.ts b/src/http/routes/s3/error-handler.ts index 8153e3113..c2c96afb8 100644 --- a/src/http/routes/s3/error-handler.ts +++ b/src/http/routes/s3/error-handler.ts @@ -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 ) } diff --git a/src/http/routes/s3/router.test.ts b/src/http/routes/s3/router.test.ts index 1cd933413..bcee19779 100644 --- a/src/http/routes/s3/router.test.ts +++ b/src/http/routes/s3/router.test.ts @@ -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') + }) }) }) diff --git a/src/internal/errors/codes.ts b/src/internal/errors/codes.ts index e7b725c10..21bd4e67f 100644 --- a/src/internal/errors/codes.ts +++ b/src/internal/errors/codes.ts @@ -45,6 +45,7 @@ export enum ErrorCode { InvalidUploadSignature = 'InvalidUploadSignature', LockTimeout = 'LockTimeout', S3Error = 'S3Error', + PreconditionFailed = 'PreconditionFailed', S3InvalidAccessKeyId = 'InvalidAccessKeyId', S3MaximumCredentialsLimit = 'MaximumCredentialsLimit', InvalidChecksum = 'InvalidChecksum', diff --git a/src/internal/monitoring/logger.ts b/src/internal/monitoring/logger.ts index dc5473d1c..f01aa6a5a 100644 --- a/src/internal/monitoring/logger.ts +++ b/src/internal/monitoring/logger.ts @@ -254,6 +254,8 @@ const allowlistedHeaderKeys = new Map( 'content-type', 'if-none-match', 'if-modified-since', + 'if-match', + 'if-unmodified-since', 'upload-metadata', 'upload-length', 'upload-offset', diff --git a/src/storage/backend/adapter.ts b/src/storage/backend/adapter.ts index bd10fdd2d..9e68fef85 100644 --- a/src/storage/backend/adapter.ts +++ b/src/storage/backend/adapter.ts @@ -6,8 +6,10 @@ import { getConfig } from '../../config' * Browser cache headers */ export interface BrowserCacheHeaders { + ifMatch?: string ifModifiedSince?: string ifNoneMatch?: string + ifUnmodifiedSince?: string range?: string } diff --git a/src/storage/backend/file.test.ts b/src/storage/backend/file.test.ts index e9113ac4a..e329f5647 100644 --- a/src/storage/backend/file.test.ts +++ b/src/storage/backend/file.test.ts @@ -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', () => ({ @@ -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() @@ -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', () => { @@ -853,6 +920,7 @@ describe('FileBackend copy source preconditions', () => { async function expectPreconditionFailed(conditions: Parameters[0]) { await expect(copy(conditions)).rejects.toMatchObject({ httpStatusCode: 412, + code: 'PreconditionFailed', message: 'PreconditionFailed', }) await expect(fsp.stat(filePath('destination.txt'))).rejects.toMatchObject({ code: 'ENOENT' }) diff --git a/src/storage/backend/file.ts b/src/storage/backend/file.ts index af86579cc..32639ef23 100644 --- a/src/storage/backend/file.ts +++ b/src/storage/backend/file.ts @@ -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)) || @@ -772,7 +788,7 @@ function assertCopySourcePreconditions( if (failed) { throw StorageBackendError.withStatusCode(412, { error: 'PreconditionFailed', - code: ErrorCode.S3Error, + code: ErrorCode.PreconditionFailed, httpStatusCode: 412, message: 'PreconditionFailed', }) diff --git a/src/storage/backend/s3/adapter.test.ts b/src/storage/backend/s3/adapter.test.ts index d941bc05b..74f5eb55f 100644 --- a/src/storage/backend/s3/adapter.test.ts +++ b/src/storage/backend/s3/adapter.test.ts @@ -253,6 +253,34 @@ describe('S3Backend', () => { }) describe('getObject', () => { + test('forwards conditional range headers and cancellation to S3', async () => { + mockSend.mockResolvedValue({ $metadata: { httpStatusCode: 206 } }) + const backend = createBackend() + const signal = new AbortController().signal + const date = new Date('2026-01-01T00:00:00Z') + + await backend.getObject( + 'test-bucket', + 'test-key', + 'version', + { + ifMatch: '"expected-etag"', + ifUnmodifiedSince: date.toISOString(), + range: 'bytes=0-1', + }, + signal + ) + + expect(mockSend).toHaveBeenCalledWith(expect.any(GetObjectCommand), { abortSignal: signal }) + expect(mockSend.mock.calls[0][0].input).toMatchObject({ + Bucket: 'test-bucket', + Key: withOptionalVersion('test-key', 'version'), + IfMatch: '"expected-etag"', + IfUnmodifiedSince: date, + Range: 'bytes=0-1', + }) + }) + test('should return correct default MIME type when S3 returns no ContentType', async () => { mockSend.mockResolvedValue({ Body: Readable.from(['test content']), @@ -826,6 +854,19 @@ describe('S3Backend', () => { }) describe('copyObject', () => { + test.each([ + ['PreconditionFailed', 412, ErrorCode.PreconditionFailed], + ['AccessDenied', 403, ErrorCode.S3Error], + ])('reports an upstream %s as %i with its error code', async (name, httpStatusCode, code) => { + mockSend.mockRejectedValue( + Object.assign(new Error('upstream'), { name, $metadata: { httpStatusCode } }) + ) + + await expect( + createBackend().copyObject('test-bucket', 'source', 'v1', 'destination', 'v2') + ).rejects.toMatchObject({ code, httpStatusCode, message: name }) + }) + test('uses REPLACE metadata directive when metadata should be overwritten', async () => { mockSend.mockResolvedValue({ CopyObjectResult: { diff --git a/src/storage/backend/s3/adapter.ts b/src/storage/backend/s3/adapter.ts index 89efaf7dc..b963ee274 100644 --- a/src/storage/backend/s3/adapter.ts +++ b/src/storage/backend/s3/adapter.ts @@ -20,7 +20,7 @@ import { } from '@aws-sdk/client-s3' import { Progress, Upload } from '@aws-sdk/lib-storage' import { getSignedUrl } from '@aws-sdk/s3-request-presigner' -import { ERRORS, isS3Error, StorageBackendError } from '@internal/errors' +import { ERRORS, ErrorCode, isS3Error, StorageBackendError } from '@internal/errors' import { createAgent, InstrumentedAgent } from '@internal/http' import { monitorStream } from '@internal/streams' import { NodeHttpHandler } from '@smithy/node-http-handler' @@ -122,6 +122,7 @@ export class S3Backend implements StorageBackendAdapter { ): Promise { const input: GetObjectCommandInput = { Bucket: bucketName, + IfMatch: headers?.ifMatch, IfNoneMatch: headers?.ifNoneMatch, Key: withOptionalVersion(key, version), Range: headers?.range, @@ -129,6 +130,9 @@ export class S3Backend implements StorageBackendAdapter { if (headers?.ifModifiedSince) { input.IfModifiedSince = new Date(headers.ifModifiedSince) } + if (headers?.ifUnmodifiedSince) { + input.IfUnmodifiedSince = new Date(headers.ifUnmodifiedSince) + } const command = new GetObjectCommand(input) const data = await this.client.send(command, { abortSignal: signal, @@ -388,7 +392,11 @@ export class S3Backend implements StorageBackendAdapter { lastModified: data.CopyObjectResult?.LastModified, } } catch (e) { - throw StorageBackendError.fromError(e) + const error = StorageBackendError.fromError(e) + if (isS3Error(e) && e.name === 'PreconditionFailed') { + error.code = ErrorCode.PreconditionFailed + } + throw error } } diff --git a/src/storage/protocols/s3/s3-handler.test.ts b/src/storage/protocols/s3/s3-handler.test.ts index 488ac9c29..844e9ba5e 100644 --- a/src/storage/protocols/s3/s3-handler.test.ts +++ b/src/storage/protocols/s3/s3-handler.test.ts @@ -1,3 +1,4 @@ +import { GetObjectCommand, S3Client } from '@aws-sdk/client-s3' import { ERRORS, ErrorCode } from '@internal/errors' import { MAX_HEADER_NAME_LENGTH } from '@internal/http/header' import { S3ProtocolHandler } from '@storage/protocols/s3/s3-handler' @@ -152,6 +153,73 @@ describe('S3ProtocolHandler.dbHeadObject', () => { }) describe('S3ProtocolHandler.getObject', () => { + it('returns an upstream S3 304 as a not-modified response with its validators', async () => { + const sdkError = async ( + statusCode: number, + headers: Record, + body: string[], + input: { IfNoneMatch: string } + ) => { + const client = new S3Client({ + region: 'us-east-1', + credentials: { accessKeyId: 'test', secretAccessKey: 'test' }, + requestHandler: { + handle: async () => ({ response: { statusCode, headers, body: Readable.from(body) } }), + }, + }) + try { + return await client + .send(new GetObjectCommand({ Bucket: 'b', Key: 'k', ...input })) + .catch((e) => e) + } finally { + client.destroy() + } + } + const notModified = await sdkError( + 304, + { + etag: '"current-etag"', + 'last-modified': 'Thu, 01 Jan 2026 00:00:00 GMT', + 'cache-control': 'max-age=60', + }, + [], + { IfNoneMatch: '"current-etag"' } + ) + const preconditionFailed = await sdkError( + 412, + { 'content-type': 'application/xml' }, + ['PreconditionFailedm'], + { IfNoneMatch: '"current-etag"' } + ) + const backendGetObject = vi + .fn() + .mockRejectedValueOnce(notModified) + .mockRejectedValueOnce(preconditionFailed) + const storage = { + backend: { getObject: backendGetObject }, + from: vi.fn(() => ({ + findObject: vi.fn().mockResolvedValue({ user_metadata: null, version: 'object-version' }), + })), + location: { + getKeyLocation: vi.fn(() => 'tenant-id/bucket/object.txt'), + getRootLocation: vi.fn(() => 'root-bucket'), + }, + } + const handler = new S3ProtocolHandler(storage as never, 'tenant-id') + const command = { Bucket: 'bucket', Key: 'object.txt', IfNoneMatch: '"current-etag"' } + + await expect(handler.getObject(command)).resolves.toEqual({ + statusCode: 304, + responseBody: undefined, + headers: { + 'cache-control': 'max-age=60', + etag: '"current-etag"', + 'last-modified': 'Thu, 01 Jan 2026 00:00:00 GMT', + }, + }) + await expect(handler.getObject(command)).rejects.toBe(preconditionFailed) + }) + it('preserves backend not-modified responses for cache validators', async () => { const backendGetObject = vi.fn().mockResolvedValue({ body: undefined, diff --git a/src/storage/protocols/s3/s3-handler.ts b/src/storage/protocols/s3/s3-handler.ts index cff8a238e..5aa0ceed8 100644 --- a/src/storage/protocols/s3/s3-handler.ts +++ b/src/storage/protocols/s3/s3-handler.ts @@ -24,6 +24,7 @@ import { logger, logSchema } from '@internal/monitoring' import { PassThrough, Readable } from 'stream' import stream from 'stream/promises' import { getConfig } from '../../../config' +import type { ObjectResponse } from '../../backend' import { assertLifecycleApiEnabled, assertLifecycleWriteReady, @@ -1062,21 +1063,38 @@ export class S3ProtocolHandler { userMetadata = object.user_metadata } - const response = await this.storage.backend.getObject( - this.storage.location.getRootLocation(), - this.storage.location.getKeyLocation({ - bucketId: bucket, - objectName: key, - tenantId: this.tenantId, - }), - version, - { - ifModifiedSince: command.IfModifiedSince?.toISOString(), - ifNoneMatch: command.IfNoneMatch, - range: command.Range, - }, - options?.signal - ) + let response: ObjectResponse + try { + response = await this.storage.backend.getObject( + this.storage.location.getRootLocation(), + this.storage.location.getKeyLocation({ + bucketId: bucket, + objectName: key, + tenantId: this.tenantId, + }), + version, + { + ifMatch: command.IfMatch, + ifModifiedSince: command.IfModifiedSince?.toISOString(), + ifNoneMatch: command.IfNoneMatch, + ifUnmodifiedSince: command.IfUnmodifiedSince?.toISOString(), + range: command.Range, + }, + options?.signal + ) + } catch (error) { + // The S3 SDK rejects on a 304; the file backend returns it as a value. + if (isS3Error(error) && error.$metadata.httpStatusCode === 304) { + const upstream = error.$response?.headers + const headers: Record = { + 'cache-control': upstream?.['cache-control'] || '', + etag: upstream?.etag || '', + 'last-modified': upstream?.['last-modified'] || '', + } + return { headers, responseBody: undefined, statusCode: 304 } + } + throw error + } let metadataHeaders: Record = {} diff --git a/src/test/s3-protocol.test.ts b/src/test/s3-protocol.test.ts index d901018d6..17cbeb0e6 100644 --- a/src/test/s3-protocol.test.ts +++ b/src/test/s3-protocol.test.ts @@ -2374,6 +2374,76 @@ describe('S3 Protocol', () => { expect(data).toBeTruthy() expect(resp.ETag).toBeTruthy() }) + + it('rejects a read with 412 when If-Match does not match the current ETag', async () => { + const bucketName = await createBucket(client) + const key = 'test-1.jpg' + await uploadFile(client, bucketName, key, 1) + + const head = await client.send(new HeadObjectCommand({ Bucket: bucketName, Key: key })) + + const matching = await client.send( + new GetObjectCommand({ Bucket: bucketName, Key: key, IfMatch: head.ETag }) + ) + await matching.Body?.transformToByteArray() + expect(matching.$metadata.httpStatusCode).toEqual(200) + + await expect( + client.send( + new GetObjectCommand({ + Bucket: bucketName, + Key: key, + IfMatch: '"not-the-current-etag"', + Range: 'bytes=0-100', + }) + ) + ).rejects.toMatchObject({ name: 'PreconditionFailed', $metadata: { httpStatusCode: 412 } }) + }) + + it('returns 304 with the ETag and no error document when If-None-Match matches', async () => { + const bucketName = await createBucket(client) + const key = 'test-1.jpg' + await uploadFile(client, bucketName, key, 1) + + const head = await client.send(new HeadObjectCommand({ Bucket: bucketName, Key: key })) + + const error = (await client + .send(new GetObjectCommand({ Bucket: bucketName, Key: key, IfNoneMatch: head.ETag })) + .catch((e) => e)) as S3ServiceException + + expect(error.$metadata.httpStatusCode).toBe(304) + expect(error.$response?.headers.etag).toBe(head.ETag) + expect(error.$response?.headers['content-type'] ?? '').not.toMatch(/xml/) + }) + + it('rejects a read with 412 when the object changed after If-Unmodified-Since', async () => { + const bucketName = await createBucket(client) + const key = 'test-1.jpg' + await uploadFile(client, bucketName, key, 1) + + const head = await client.send(new HeadObjectCommand({ Bucket: bucketName, Key: key })) + const lastModified = head.LastModified as Date + + const unchanged = await client.send( + new GetObjectCommand({ + Bucket: bucketName, + Key: key, + IfUnmodifiedSince: new Date(lastModified.getTime() + 60_000), + }) + ) + await unchanged.Body?.transformToByteArray() + expect(unchanged.$metadata.httpStatusCode).toEqual(200) + + await expect( + client.send( + new GetObjectCommand({ + Bucket: bucketName, + Key: key, + IfUnmodifiedSince: new Date(lastModified.getTime() - 60_000), + }) + ) + ).rejects.toMatchObject({ name: 'PreconditionFailed', $metadata: { httpStatusCode: 412 } }) + }) }) describe('DeleteObjectCommand', () => {