From 5f6f3799fb420cea1442314e73139a52120f1bf7 Mon Sep 17 00:00:00 2001 From: Yiling-J Date: Mon, 23 Nov 2026 19:35:40 +0800 Subject: [PATCH] feat(storage): align local presigned URL expiry with env vars and float hours (#543) --- docs/configuration/env-variables.mdx | 20 +- docs/getting-started/s3-storage.mdx | 20 +- docs/zh/configuration/env-variables.mdx | 20 +- docs/zh/getting-started/s3-storage.mdx | 20 +- eslint.config.js | 2 +- packages/api/src/upload.test.ts | 62 ++++++ packages/api/src/upload.ts | 6 +- packages/core/src/s3/s3.test.ts | 247 +++++++++++++++++++++++- packages/core/src/s3/s3.ts | 93 +++++---- packages/dtos/src/upload.ts | 1 + 10 files changed, 410 insertions(+), 81 deletions(-) diff --git a/docs/configuration/env-variables.mdx b/docs/configuration/env-variables.mdx index 5bbe4f2d..a9a50d64 100644 --- a/docs/configuration/env-variables.mdx +++ b/docs/configuration/env-variables.mdx @@ -38,16 +38,16 @@ Shumai is configured via environment variables. You can define these variables i Shumai supports storing files locally or on S3-compatible endpoints. -| Variable | Description | Example / Default | -| :-------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------------------------------ | -| `STORAGE_BACKEND` | Storage type. Use `local` for local file system storage, or `s3` for S3-compatible cloud storage. | `local` (default) or `s3` | -| `AWS_ENDPOINT_URL_S3` | Endpoint for S3 storage or local storage. Used by the browser to build file upload URLs. Must include port if deploying remotely or using custom ports. | `http://localhost:3000` (respects `SHUMAI_SERVER_PORT` fallback if unset) | -| `S3_BUCKET` | S3 bucket name. | `shumai` (default) | -| `S3_ACCESS_KEY_ID` | Access key credentials for S3. | `minioadmin` (default) | -| `S3_SECRET_ACCESS_KEY` | Secret key credentials for S3. | `minioadmin` (default) | -| `S3_REGION` | S3 storage region. | `auto` (default) | -| `PRESIGNED_URL_EXPIRES_IN` | Number of hours for which generated presigned download links are valid. | `5` (default) | -| `PRESIGNED_UPLOAD_URL_EXPIRES_IN` | Number of hours for which generated presigned upload links are valid. Falls back to `PRESIGNED_URL_EXPIRES_IN` if unset. | `12` (default) | +| Variable | Description | Example / Default | +| :-------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------ | +| `STORAGE_BACKEND` | Storage type. Use `local` for local file system storage, or `s3` for S3-compatible cloud storage. | `local` (default) or `s3` | +| `AWS_ENDPOINT_URL_S3` | Endpoint for S3 storage or local storage. Used by the browser to build file upload URLs. Must include port if deploying remotely or using custom ports. | `http://localhost:3000` (respects `SHUMAI_SERVER_PORT` fallback if unset) | +| `S3_BUCKET` | S3 bucket name. | `shumai` (default) | +| `S3_ACCESS_KEY_ID` | Access key credentials for S3. | `minioadmin` (default) | +| `S3_SECRET_ACCESS_KEY` | Secret key credentials for S3. | `minioadmin` (default) | +| `S3_REGION` | S3 storage region. | `auto` (default) | +| `PRESIGNED_URL_EXPIRES_IN` | Number of hours (decimals supported, e.g. `0.5`) for which generated presigned download links are valid. Applies to both local and S3 storage. | `12` (default) | +| `PRESIGNED_UPLOAD_URL_EXPIRES_IN` | Number of hours (decimals supported, e.g. `0.5`) for which generated presigned upload links are valid. Falls back to `PRESIGNED_URL_EXPIRES_IN` if unset. Applies to both local and S3. | `12` (default) | ### Local Storage Port Configuration diff --git a/docs/getting-started/s3-storage.mdx b/docs/getting-started/s3-storage.mdx index bb335896..fdc8acec 100644 --- a/docs/getting-started/s3-storage.mdx +++ b/docs/getting-started/s3-storage.mdx @@ -13,16 +13,16 @@ Using external S3 storage is highly recommended for production teams. It allows To enable S3-compatible storage, update the following environment variables in your `.env` file or Docker Compose configuration: -| Variable | Description | Required | Default / Example | -| :-------------------------------- | :------------------------------------------------------------------------------------------------------------------ | :------- | :----------------------------------- | -| `STORAGE_BACKEND` | Set to `s3` to enable S3 compatible storage. | Yes | `s3` | -| `S3_BUCKET` | The name of the S3 bucket where files will be stored. | Yes | `shumai-bucket` | -| `S3_REGION` | The region of your S3 bucket. | No | `auto` | -| `S3_ACCESS_KEY_ID` | The access key ID for your storage service. | Yes | `your-access-key-id` | -| `S3_SECRET_ACCESS_KEY` | The secret access key for your storage service. | Yes | `your-secret-access-key` | -| `AWS_ENDPOINT_URL_S3` | The endpoint URL of your S3 compatible storage provider. | Yes | `https://s3.us-east-1.amazonaws.com` | -| `PRESIGNED_URL_EXPIRES_IN` | Duration in hours before generated presigned download URLs expire. | No | `5` | -| `PRESIGNED_UPLOAD_URL_EXPIRES_IN` | Duration in hours before generated presigned upload URLs expire. Falls back to `PRESIGNED_URL_EXPIRES_IN` if unset. | No | `12` | +| Variable | Description | Required | Default / Example | +| :-------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------- | :------- | :----------------------------------- | +| `STORAGE_BACKEND` | Set to `s3` to enable S3 compatible storage. | Yes | `s3` | +| `S3_BUCKET` | The name of the S3 bucket where files will be stored. | Yes | `shumai-bucket` | +| `S3_REGION` | The region of your S3 bucket. | No | `auto` | +| `S3_ACCESS_KEY_ID` | The access key ID for your storage service. | Yes | `your-access-key-id` | +| `S3_SECRET_ACCESS_KEY` | The secret access key for your storage service. | Yes | `your-secret-access-key` | +| `AWS_ENDPOINT_URL_S3` | The endpoint URL of your S3 compatible storage provider. | Yes | `https://s3.us-east-1.amazonaws.com` | +| `PRESIGNED_URL_EXPIRES_IN` | Duration in hours (decimals supported, e.g. `0.5`) before generated presigned download URLs expire. | No | `12` | +| `PRESIGNED_UPLOAD_URL_EXPIRES_IN` | Duration in hours (decimals supported, e.g. `0.5`) before generated presigned upload URLs expire. Falls back to `PRESIGNED_URL_EXPIRES_IN` if unset. | No | `12` | --- diff --git a/docs/zh/configuration/env-variables.mdx b/docs/zh/configuration/env-variables.mdx index 3b356892..de6ae32e 100644 --- a/docs/zh/configuration/env-variables.mdx +++ b/docs/zh/configuration/env-variables.mdx @@ -38,16 +38,16 @@ Shumai 通过环境变量配置。可以在应用工作区根目录的 `.env` Shumai 支持将文件存储在本地文件系统或兼容 S3 的对象存储中。 -| 变量 | 说明 | 示例 / 默认值 | -| :-------------------------------- | :------------------------------------------------------------------------------------------------------ | :------------------------------------------------------------- | -| `STORAGE_BACKEND` | 存储类型。使用 `local` 表示本地文件系统存储,使用 `s3` 表示兼容 S3 的云对象存储。 | `local`(默认)或 `s3` | -| `AWS_ENDPOINT_URL_S3` | S3 存储或本地存储的服务端点。浏览器据此生成文件上传链接。在远程部署或使用自定义端口时,必须包含端口号。 | `http://localhost:3000`(未设置时回退至 `SHUMAI_SERVER_PORT`) | -| `S3_BUCKET` | S3 存储桶名称。 | `shumai`(默认) | -| `S3_ACCESS_KEY_ID` | S3 访问凭据 Access Key ID。 | `minioadmin`(默认) | -| `S3_SECRET_ACCESS_KEY` | S3 访问凭据 Secret Access Key。 | `minioadmin`(默认) | -| `S3_REGION` | S3 存储区域。 | `auto`(默认) | -| `PRESIGNED_URL_EXPIRES_IN` | 生成的预签名下载链接的有效时长(单位:小时)。 | `5`(默认) | -| `PRESIGNED_UPLOAD_URL_EXPIRES_IN` | 生成的预签名上传链接的有效时长(单位:小时)。未设置时回退至 `PRESIGNED_URL_EXPIRES_IN`。 | `12`(默认) | +| 变量 | 说明 | 示例 / 默认值 | +| :-------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------------------- | +| `STORAGE_BACKEND` | 存储类型。使用 `local` 表示本地文件系统存储,使用 `s3` 表示兼容 S3 的云对象存储。 | `local`(默认)或 `s3` | +| `AWS_ENDPOINT_URL_S3` | S3 存储或本地存储的服务端点。浏览器据此生成文件上传链接。在远程部署或使用自定义端口时,必须包含端口号。 | `http://localhost:3000`(未设置时回退至 `SHUMAI_SERVER_PORT`) | +| `S3_BUCKET` | S3 存储桶名称。 | `shumai`(默认) | +| `S3_ACCESS_KEY_ID` | S3 访问凭据 Access Key ID。 | `minioadmin`(默认) | +| `S3_SECRET_ACCESS_KEY` | S3 访问凭据 Secret Access Key。 | `minioadmin`(默认) | +| `S3_REGION` | S3 存储区域。 | `auto`(默认) | +| `PRESIGNED_URL_EXPIRES_IN` | 生成的预签名下载链接的有效时长(单位:小时,支持小数如 `0.5`),同时适用于本地与 S3 存储。 | `12`(默认) | +| `PRESIGNED_UPLOAD_URL_EXPIRES_IN` | 生成的预签名上传链接的有效时长(单位:小时,支持小数如 `0.5`)。未设置时回退至 `PRESIGNED_URL_EXPIRES_IN`,同时适用于本地与 S3 存储。 | `12`(默认) | ### 本地存储端口配置 diff --git a/docs/zh/getting-started/s3-storage.mdx b/docs/zh/getting-started/s3-storage.mdx index e9a33e9f..1d852c10 100644 --- a/docs/zh/getting-started/s3-storage.mdx +++ b/docs/zh/getting-started/s3-storage.mdx @@ -13,16 +13,16 @@ Shumai 采用 Bun 原生高性能 S3 客户端存储与分发创意资产。借 若要启用兼容 S3 的存储,请在 `.env` 文件或 Docker Compose 配置中更新以下环境变量: -| 变量名 | 说明 | 必填 | 默认值 / 示例 | -| :-------------------------------- | :------------------------------------------------------------------------------------------ | :--- | :----------------------------------- | -| `STORAGE_BACKEND` | 设为 `s3` 以启用兼容 S3 的存储后端。 | 是 | `s3` | -| `S3_BUCKET` | 存放文件的 S3 存储桶名称。 | 是 | `shumai-bucket` | -| `S3_REGION` | S3 存储桶所在地域(Region)。 | 否 | `auto` | -| `S3_ACCESS_KEY_ID` | 存储服务的访问密钥 ID(Access Key ID)。 | 是 | `your-access-key-id` | -| `S3_SECRET_ACCESS_KEY` | 存储服务的私有访问密钥(Secret Access Key)。 | 是 | `your-secret-access-key` | -| `AWS_ENDPOINT_URL_S3` | 兼容 S3 的存储服务端点 URL。 | 是 | `https://s3.us-east-1.amazonaws.com` | -| `PRESIGNED_URL_EXPIRES_IN` | 生成的预签名下载链接有效期(单位:小时)。 | 否 | `5` | -| `PRESIGNED_UPLOAD_URL_EXPIRES_IN` | 生成的预签名上传链接有效期(单位:小时)。若未指定,则回退继承 `PRESIGNED_URL_EXPIRES_IN`。 | 否 | `12` | +| 变量名 | 说明 | 必填 | 默认值 / 示例 | +| :-------------------------------- | :------------------------------------------------------------------------------------------------------------ | :--- | :----------------------------------- | +| `STORAGE_BACKEND` | 设为 `s3` 以启用兼容 S3 的存储后端。 | 是 | `s3` | +| `S3_BUCKET` | 存放文件的 S3 存储桶名称。 | 是 | `shumai-bucket` | +| `S3_REGION` | S3 存储桶所在地域(Region)。 | 否 | `auto` | +| `S3_ACCESS_KEY_ID` | 存储服务的访问密钥 ID(Access Key ID)。 | 是 | `your-access-key-id` | +| `S3_SECRET_ACCESS_KEY` | 存储服务的私有访问密钥(Secret Access Key)。 | 是 | `your-secret-access-key` | +| `AWS_ENDPOINT_URL_S3` | 兼容 S3 的存储服务端点 URL。 | 是 | `https://s3.us-east-1.amazonaws.com` | +| `PRESIGNED_URL_EXPIRES_IN` | 生成的预签名下载链接有效期(单位:小时,支持小数如 `0.5`)。 | 否 | `12` | +| `PRESIGNED_UPLOAD_URL_EXPIRES_IN` | 生成的预签名上传链接有效期(单位:小时,支持小数如 `0.5`)。若未指定,则回退继承 `PRESIGNED_URL_EXPIRES_IN`。 | 否 | `12` | --- diff --git a/eslint.config.js b/eslint.config.js index 010772d4..7cb26f5b 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -22,7 +22,7 @@ const baseNamingConvention = [ filter: { // Allow CSS variables, common HTTP headers, library-specific names, paths, and hyphenated/numeric keys regex: - '^(Authorization|Content-Type|Accept|--.*|string_contains|disableCSRFCheck|X-Frameio-.*|/.*|field-.*|class-name|icon-.*|[0-9]+|@typescript-eslint/.*|Variables|Read|Edit|Admin|Bucket|Key|Body|ContentLength|ContentType|Prefix|ContinuationToken|Signature|CopySource|Delete|Objects|Quiet|ResponseContentDisposition|UploadId|PartNumber)$', + '^(Authorization|Content-Type|Accept|--.*|string_contains|disableCSRFCheck|X-Frameio-.*|/.*|field-.*|class-name|icon-.*|[0-9]+|@typescript-eslint/.*|Variables|Read|Edit|Admin|Bucket|Key|Body|ContentLength|ContentType|Prefix|ContinuationToken|Signature|Expires|CopySource|Delete|Objects|Quiet|ResponseContentDisposition|UploadId|PartNumber)$', match: false, }, }, diff --git a/packages/api/src/upload.test.ts b/packages/api/src/upload.test.ts index 09c81b43..cdfc3999 100644 --- a/packages/api/src/upload.test.ts +++ b/packages/api/src/upload.test.ts @@ -254,5 +254,67 @@ describe('Upload API', () => { }) expect(res.status).toBe(404) }) + + it('accepts a valid signed local upload URL', async () => { + vi.spyOn(s3Module, 'getStorageBackend').mockReturnValue('local') + const putObjectSpy = vi.spyOn(s3Module.s3Service, 'putObject').mockResolvedValue(undefined) + const signedPath = s3Module.signLocalUrl('test-bucket', 'files/test.txt') + const localPath = signedPath.replace(/^\/api/, '') + const localApp = new Hono().route('/', localUploadRoute) + + const res = await localApp.request(localPath, { + method: 'PUT', + headers: { 'Content-Type': 'text/plain', 'Content-Length': '5' }, + body: 'hello', + }) + + expect(res.status).toBe(200) + expect(await res.json()).toEqual({ success: true }) + expect(putObjectSpy).toHaveBeenCalledWith( + 'test-bucket', + 'files/test.txt', + expect.anything(), + 5, + 'text/plain', + ) + }) + + it('returns 403 when local upload URL signature is expired', async () => { + vi.spyOn(s3Module, 'getStorageBackend').mockReturnValue('local') + const putObjectSpy = vi.spyOn(s3Module.s3Service, 'putObject').mockResolvedValue(undefined) + const signedPath = s3Module.signLocalUrl('test-bucket', 'files/test.txt', -10) + const localPath = signedPath.replace(/^\/api/, '') + const localApp = new Hono().route('/', localUploadRoute) + + const res = await localApp.request(localPath, { + method: 'PUT', + body: 'hello', + }) + + expect(res.status).toBe(403) + expect(putObjectSpy).not.toHaveBeenCalled() + }) + + it('returns 403 when Expires query param is missing or invalid', async () => { + vi.spyOn(s3Module, 'getStorageBackend').mockReturnValue('local') + const putObjectSpy = vi.spyOn(s3Module.s3Service, 'putObject').mockResolvedValue(undefined) + const localApp = new Hono().route('/', localUploadRoute) + + const missingRes = await localApp.request('/upload/local?bucket=b&key=k&Signature=sig', { + method: 'PUT', + body: 'hello', + }) + expect(missingRes.status).toBe(403) + + const invalidRes = await localApp.request( + '/upload/local?bucket=b&key=k&Signature=sig&Expires=not-a-number', + { + method: 'PUT', + body: 'hello', + }, + ) + expect(invalidRes.status).toBe(403) + expect(putObjectSpy).not.toHaveBeenCalled() + }) }) }) diff --git a/packages/api/src/upload.ts b/packages/api/src/upload.ts index 2ff4968d..84c1a080 100644 --- a/packages/api/src/upload.ts +++ b/packages/api/src/upload.ts @@ -27,10 +27,10 @@ export const localUploadRoute = new Hono().put( return c.text('Not found', 404) } - const { bucket, key, Signature } = c.req.valid('query') + const { bucket, key, Signature, Expires } = c.req.valid('query') - if (!verifyLocalUrlSignature(bucket, key, Signature)) { - return c.text('Invalid signature', 403) + if (!verifyLocalUrlSignature(bucket, key, Signature, Expires)) { + return c.text('Invalid or expired signature', 403) } const contentType = c.req.header('Content-Type') diff --git a/packages/core/src/s3/s3.test.ts b/packages/core/src/s3/s3.test.ts index c3144ee3..c6cf4a40 100644 --- a/packages/core/src/s3/s3.test.ts +++ b/packages/core/src/s3/s3.test.ts @@ -12,10 +12,13 @@ import { } from '@aws-sdk/client-s3' import { buildContentDisposition, + getPresignedUrlExpirySeconds, LocalStorageService, S3StorageService, signLocalGetUrl, + signLocalUrl, verifyLocalGetUrlSignature, + verifyLocalUrlSignature, } from './s3' const s3ClientConstructorSpy = vi.fn() @@ -82,7 +85,7 @@ describe('S3Service implementations', () => { expect(getSignedUrlSpy).toHaveBeenCalledWith( expect.anything(), expect.any(GetObjectCommand), - expect.objectContaining({ expiresIn: 18000 }), + expect.objectContaining({ expiresIn: 43200 }), ) }) @@ -116,14 +119,14 @@ describe('S3Service implementations', () => { const url1 = await s3.presign('bucket', 'key', 'GET') expect(url1).toBe('http://presigned-url-1') - // Default GET lifetime is 5h; before 2.5h the cached URL should still be reused - const almostHalfMs = 2.5 * 3600 * 1000 - 1_000 + // Default GET lifetime is 12h; before 6h the cached URL should still be reused + const almostHalfMs = 6 * 3600 * 1000 - 1_000 wallNow += almostHalfMs perfNow += almostHalfMs expect(await s3.presign('bucket', 'key', 'GET')).toBe('http://presigned-url-1') expect(getSignedUrlSpy).toHaveBeenCalledTimes(1) - // Past 2.5h (half of the 5h lifetime), the cache must expire so callers never get nearly expired URLs + // Past 6h (half of the 12h lifetime), the cache must expire so callers never get nearly expired URLs wallNow += 2_000 perfNow += 2_000 expect(await s3.presign('bucket', 'key', 'GET')).toBe('http://presigned-url-2') @@ -301,6 +304,43 @@ describe('S3Service implementations', () => { delete process.env.PRESIGNED_URL_EXPIRES_IN }) + it('should support float values for PRESIGNED_URL_EXPIRES_IN and PRESIGNED_UPLOAD_URL_EXPIRES_IN', async () => { + process.env.PRESIGNED_URL_EXPIRES_IN = '0.1' + process.env.PRESIGNED_UPLOAD_URL_EXPIRES_IN = '1.5' + const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket') + + getSignedUrlSpy.mockClear() + await s3.presign('bucket', 'key', 'GET') + expect(getSignedUrlSpy).toHaveBeenCalledWith( + expect.anything(), + expect.any(GetObjectCommand), + expect.objectContaining({ expiresIn: 360 }), + ) + + getSignedUrlSpy.mockClear() + await s3.presign('bucket', 'key', 'PUT') + expect(getSignedUrlSpy).toHaveBeenCalledWith( + expect.anything(), + expect.any(PutObjectCommand), + expect.objectContaining({ expiresIn: 5400 }), + ) + + getSignedUrlSpy.mockClear() + await s3.presignMultipart('bucket', 'key', { + method: 'PUT', + key: 'key', + fileId: 'file-1', + }) + expect(getSignedUrlSpy).toHaveBeenCalledWith( + expect.anything(), + expect.any(PutObjectCommand), + expect.objectContaining({ expiresIn: 5400 }), + ) + + delete process.env.PRESIGNED_URL_EXPIRES_IN + delete process.env.PRESIGNED_UPLOAD_URL_EXPIRES_IN + }) + it('should not set contentDisposition for normal GET presign', async () => { const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket') await s3.presign('bucket', 'key', 'GET') @@ -920,6 +960,102 @@ describe('S3Service implementations', () => { await expect(localS3.presign('b', 'k', 'POST')).rejects.toThrow() }) + it('should default local GET and PUT presign expiry to 12 hours', async () => { + const fixedNow = 1_700_000_000_000 + const dateNowSpy = vi.spyOn(Date, 'now').mockReturnValue(fixedNow) + try { + const expectedExpires = String(Math.floor(fixedNow / 1000) + 12 * 3600) + + const getUrl = new URL(await localS3.presign('my-bucket', 'dir/default.txt', 'GET')) + expect(getUrl.searchParams.get('Expires')).toBe(expectedExpires) + + const putUrl = new URL(await localS3.presign('my-bucket', 'dir/default.txt', 'PUT')) + expect(putUrl.pathname).toBe('/api/upload/local') + expect(putUrl.searchParams.get('Expires')).toBe(expectedExpires) + expect( + verifyLocalUrlSignature( + 'my-bucket', + 'dir/default.txt', + putUrl.searchParams.get('Signature'), + putUrl.searchParams.get('Expires'), + ), + ).toBe(true) + } finally { + dateNowSpy.mockRestore() + } + }) + + it('should respect PRESIGNED_URL_EXPIRES_IN (including floats) for local GET and PUT fallback', async () => { + const fixedNow = 1_700_000_000_000 + const dateNowSpy = vi.spyOn(Date, 'now').mockReturnValue(fixedNow) + process.env.PRESIGNED_URL_EXPIRES_IN = '0.1' + try { + const expectedExpires = String(Math.floor(fixedNow / 1000) + 360) + + const getUrl = new URL(await localS3.presign('my-bucket', 'dir/float.txt', 'GET')) + expect(getUrl.searchParams.get('Expires')).toBe(expectedExpires) + + const putUrl = new URL(await localS3.presign('my-bucket', 'dir/float.txt', 'PUT')) + expect(putUrl.searchParams.get('Expires')).toBe(expectedExpires) + } finally { + dateNowSpy.mockRestore() + delete process.env.PRESIGNED_URL_EXPIRES_IN + } + }) + + it('should respect PRESIGNED_UPLOAD_URL_EXPIRES_IN (including floats) for local PUT and presignMultipart', async () => { + const fixedNow = 1_700_000_000_000 + const dateNowSpy = vi.spyOn(Date, 'now').mockReturnValue(fixedNow) + process.env.PRESIGNED_URL_EXPIRES_IN = '2' + process.env.PRESIGNED_UPLOAD_URL_EXPIRES_IN = '1.5' + try { + const expectedGetExpires = String(Math.floor(fixedNow / 1000) + 2 * 3600) + const expectedPutExpires = String(Math.floor(fixedNow / 1000) + 5400) + + const getUrl = new URL(await localS3.presign('my-bucket', 'dir/upload-env.txt', 'GET')) + expect(getUrl.searchParams.get('Expires')).toBe(expectedGetExpires) + + const putUrl = new URL(await localS3.presign('my-bucket', 'dir/upload-env.txt', 'PUT')) + expect(putUrl.searchParams.get('Expires')).toBe(expectedPutExpires) + + const { url: multipartUrlStr } = await localS3.presignMultipart( + 'my-bucket', + 'dir/upload-env.txt', + { + method: 'PUT', + key: 'dir/upload-env.txt', + fileId: 'file-1', + }, + ) + const multipartUrl = new URL(multipartUrlStr) + expect(multipartUrl.searchParams.get('Expires')).toBe(expectedPutExpires) + } finally { + dateNowSpy.mockRestore() + delete process.env.PRESIGNED_URL_EXPIRES_IN + delete process.env.PRESIGNED_UPLOAD_URL_EXPIRES_IN + } + }) + + it('should respect explicit expiresInSeconds override for local GET and PUT', async () => { + const fixedNow = 1_700_000_000_000 + const dateNowSpy = vi.spyOn(Date, 'now').mockReturnValue(fixedNow) + try { + const expectedExpires = String(Math.floor(fixedNow / 1000) + 600) + + const getUrl = new URL( + await localS3.presign('my-bucket', 'dir/custom.txt', 'GET', false, undefined, false, 600), + ) + expect(getUrl.searchParams.get('Expires')).toBe(expectedExpires) + + const putUrl = new URL( + await localS3.presign('my-bucket', 'dir/custom.txt', 'PUT', false, undefined, false, 600), + ) + expect(putUrl.searchParams.get('Expires')).toBe(expectedExpires) + } finally { + dateNowSpy.mockRestore() + } + }) + it('should resolveInput to local file path if file exists on disk', async () => { await localS3.putObject('my-bucket', 'video.mp4', 'dummy content', 13) const input = await localS3.resolveInput('my-bucket', 'video.mp4') @@ -1079,4 +1215,107 @@ describe('S3Service implementations', () => { ).toBe(false) }) }) + + describe('getPresignedUrlExpirySeconds', () => { + it('supports float hours and falls back to 12 hours for invalid values', () => { + expect(getPresignedUrlExpirySeconds('GET')).toBe(12 * 3600) + expect(getPresignedUrlExpirySeconds('PUT')).toBe(12 * 3600) + + process.env.PRESIGNED_URL_EXPIRES_IN = '0.1' + expect(getPresignedUrlExpirySeconds('GET')).toBe(360) + expect(getPresignedUrlExpirySeconds('PUT')).toBe(360) + + process.env.PRESIGNED_URL_EXPIRES_IN = '0.0001' + expect(getPresignedUrlExpirySeconds('GET')).toBe(1) + + for (const invalid of ['0', '-1', 'abc', 'Infinity', 'NaN', ' ']) { + process.env.PRESIGNED_URL_EXPIRES_IN = invalid + expect(getPresignedUrlExpirySeconds('GET')).toBe(12 * 3600) + expect(getPresignedUrlExpirySeconds('PUT')).toBe(12 * 3600) + } + + expect(getPresignedUrlExpirySeconds('GET', 120)).toBe(120) + expect(getPresignedUrlExpirySeconds('PUT', -10)).toBe(-10) + }) + }) + + describe('signLocalUrl and verifyLocalUrlSignature', () => { + it('signs and verifies valid local PUT url', () => { + const signed = signLocalUrl('my-bucket', 'files/123/file.mp4') + const parsed = new URL(`http://localhost:3000${signed}`) + const signature = parsed.searchParams.get('Signature') + const expires = parsed.searchParams.get('Expires') + + expect(signature).toBeTruthy() + expect(Number(expires)).toBeGreaterThan(Math.floor(Date.now() / 1000)) + expect(verifyLocalUrlSignature('my-bucket', 'files/123/file.mp4', signature, expires)).toBe( + true, + ) + }) + + it('rejects expired local PUT url signature', () => { + const signed = signLocalUrl('my-bucket', 'files/123/file.mp4', -10) + const parsed = new URL(`http://localhost:3000${signed}`) + expect( + verifyLocalUrlSignature( + 'my-bucket', + 'files/123/file.mp4', + parsed.searchParams.get('Signature'), + parsed.searchParams.get('Expires'), + ), + ).toBe(false) + }) + + it('rejects tampered bucket, key, or malformed params', () => { + const signed = signLocalUrl('my-bucket', 'files/123/file.mp4') + const parsed = new URL(`http://localhost:3000${signed}`) + const signature = parsed.searchParams.get('Signature') + const expires = parsed.searchParams.get('Expires') + + expect( + verifyLocalUrlSignature('other-bucket', 'files/123/file.mp4', signature, expires), + ).toBe(false) + expect(verifyLocalUrlSignature('my-bucket', 'files/999/other.mp4', signature, expires)).toBe( + false, + ) + expect( + verifyLocalUrlSignature( + 'my-bucket', + 'files/123/file.mp4', + signature, + String(Number(expires) + 60), + ), + ).toBe(false) + expect(verifyLocalUrlSignature('my-bucket', 'files/123/file.mp4', undefined, expires)).toBe( + false, + ) + expect(verifyLocalUrlSignature('my-bucket', 'files/123/file.mp4', signature, undefined)).toBe( + false, + ) + expect( + verifyLocalUrlSignature('my-bucket', 'files/123/file.mp4', signature, `${expires}abc`), + ).toBe(false) + }) + + it('rejects reusing a GET signature for PUT and vice versa', () => { + const { signature: getSig, expires: getExp } = signLocalGetUrl( + 'my-bucket', + 'files/123/file.mp4', + ) + expect( + verifyLocalUrlSignature('my-bucket', 'files/123/file.mp4', getSig, String(getExp)), + ).toBe(false) + + const signedPut = signLocalUrl('my-bucket', 'files/123/file.mp4') + const parsedPut = new URL(`http://localhost:3000${signedPut}`) + expect( + verifyLocalGetUrlSignature( + 'my-bucket', + 'files/123/file.mp4', + parsedPut.searchParams.get('Signature'), + parsedPut.searchParams.get('Expires'), + ), + ).toBe(false) + }) + }) }) diff --git a/packages/core/src/s3/s3.ts b/packages/core/src/s3/s3.ts index 56788e10..8e852cd5 100644 --- a/packages/core/src/s3/s3.ts +++ b/packages/core/src/s3/s3.ts @@ -26,34 +26,73 @@ import { ulid } from 'ulid' import { LruTtlCache } from '../cache/lru-ttl-cache' import { detectSupportedMimeType } from '../utils/mime' -export function signLocalUrl(bucket: string, key: string): string { - const secret = process.env.BETTER_AUTH_SECRET || 'shumai-local-storage-secret' - const hmac = crypto.createHmac('sha256', secret) - hmac.update(`${bucket}/${key}`) - const signature = hmac.digest('hex') - return `/api/upload/local?bucket=${encodeURIComponent(bucket)}&key=${encodeURIComponent(key)}&Signature=${signature}` +export const DEFAULT_PRESIGNED_URL_EXPIRY_HOURS = 12 + +export function getPresignedUrlExpirySeconds(method: string, expiresInSeconds?: number): number { + if (expiresInSeconds !== undefined) { + return expiresInSeconds + } + const raw = + method === 'PUT' + ? process.env.PRESIGNED_UPLOAD_URL_EXPIRES_IN?.trim() || + process.env.PRESIGNED_URL_EXPIRES_IN?.trim() + : process.env.PRESIGNED_URL_EXPIRES_IN?.trim() + + if (raw) { + const hours = Number(raw) + if (Number.isFinite(hours) && hours > 0) { + return Math.max(1, Math.round(hours * 3600)) + } + } + + return DEFAULT_PRESIGNED_URL_EXPIRY_HOURS * 3600 } -export function verifyLocalUrlSignature(bucket: string, key: string, signature: string): boolean { +export function signLocalUrl(bucket: string, key: string, expiresInSeconds?: number): string { + const lifetimeSeconds = getPresignedUrlExpirySeconds('PUT', expiresInSeconds) + const expires = Math.floor(Date.now() / 1000) + lifetimeSeconds const secret = process.env.BETTER_AUTH_SECRET || 'shumai-local-storage-secret' const hmac = crypto.createHmac('sha256', secret) - hmac.update(`${bucket}/${key}`) + hmac.update(`PUT:${bucket}/${key}:${expires}`) + const signature = hmac.digest('hex') + return `/api/upload/local?bucket=${encodeURIComponent(bucket)}&key=${encodeURIComponent(key)}&Signature=${signature}&Expires=${expires}` +} + +export function verifyLocalUrlSignature( + bucket: string, + key: string, + signature: string | undefined | null, + expiresStr: string | undefined | null, +): boolean { + if (!signature || !expiresStr) return false + if (!/^-?\d+$/.test(expiresStr)) return false + const expires = parseInt(expiresStr, 10) + if (isNaN(expires)) return false + + const now = Math.floor(Date.now() / 1000) + if (now > expires) return false + + const secret = process.env.BETTER_AUTH_SECRET || 'shumai-local-storage-secret' + const hmac = crypto.createHmac('sha256', secret) + hmac.update(`PUT:${bucket}/${key}:${expires}`) const expected = hmac.digest('hex') try { - return crypto.timingSafeEqual(Buffer.from(signature, 'hex'), Buffer.from(expected, 'hex')) + const sigBuf = Buffer.from(signature, 'hex') + const expBuf = Buffer.from(expected, 'hex') + if (sigBuf.length !== expBuf.length) return false + return crypto.timingSafeEqual(sigBuf, expBuf) } catch { return false } } -export const DEFAULT_LOCAL_GET_EXPIRY_SECONDS = 12 * 3600 - export function signLocalGetUrl( bucket: string, key: string, - expiresInSeconds: number = DEFAULT_LOCAL_GET_EXPIRY_SECONDS, + expiresInSeconds?: number, ): { signature: string; expires: number } { - const expires = Math.floor(Date.now() / 1000) + expiresInSeconds + const lifetimeSeconds = getPresignedUrlExpirySeconds('GET', expiresInSeconds) + const expires = Math.floor(Date.now() / 1000) + lifetimeSeconds const secret = process.env.BETTER_AUTH_SECRET || 'shumai-local-storage-secret' const hmac = crypto.createHmac('sha256', secret) hmac.update(`GET:${bucket}/${key}:${expires}`) @@ -68,6 +107,7 @@ export function verifyLocalGetUrlSignature( expiresStr: string | undefined | null, ): boolean { if (!signature || !expiresStr) return false + if (!/^-?\d+$/.test(expiresStr)) return false const expires = parseInt(expiresStr, 10) if (isNaN(expires)) return false @@ -392,7 +432,7 @@ export interface S3Service { download?: boolean, filename?: string, internal?: boolean, - /** URL lifetime; defaults to PRESIGNED_UPLOAD_URL_EXPIRES_IN (12h) for PUT, or PRESIGNED_URL_EXPIRES_IN (5h) for GET, or DEFAULT_LOCAL_GET_EXPIRY_SECONDS (12h) for local. */ + /** URL lifetime; defaults to PRESIGNED_UPLOAD_URL_EXPIRES_IN (12h, fallback PRESIGNED_URL_EXPIRES_IN) for PUT, or PRESIGNED_URL_EXPIRES_IN (12h) for GET and other methods. */ expiresInSeconds?: number, ) => Promise presignMultipart: ( @@ -664,21 +704,12 @@ export class S3StorageService implements S3Service { internal?: boolean, expiresInSeconds?: number, ): Promise { - const defaultExpireHours = - method === 'PUT' - ? parseInt( - process.env.PRESIGNED_UPLOAD_URL_EXPIRES_IN || - process.env.PRESIGNED_URL_EXPIRES_IN || - '12', - 10, - ) - : parseInt(process.env.PRESIGNED_URL_EXPIRES_IN || '5', 10) - const lifetimeSeconds = expiresInSeconds ?? defaultExpireHours * 3600 + const lifetimeSeconds = getPresignedUrlExpirySeconds(method, expiresInSeconds) // Only reuse a cached URL while it has at least half of its lifetime left, so callers // never receive a nearly expired link. const cacheTtlMs = (lifetimeSeconds * 1000) / 2 - const cacheKey = `${bucket}/${key}?download=${download || false}&filename=${filename || ''}&internal=${internal || false}&expires=${expiresInSeconds ?? 'default'}` + const cacheKey = `${bucket}/${key}?download=${download || false}&filename=${filename || ''}&internal=${internal || false}&expires=${lifetimeSeconds}` if (method === 'GET' && !download) { const cached = this.presignCache.get(cacheKey) if (cached) { @@ -724,11 +755,7 @@ export class S3StorageService implements S3Service { key: string, request: S3SignRequest, ): Promise<{ url: string }> { - const expireHours = parseInt( - process.env.PRESIGNED_UPLOAD_URL_EXPIRES_IN || process.env.PRESIGNED_URL_EXPIRES_IN || '12', - 10, - ) - const expiresInSeconds = expireHours * 3600 + const expiresInSeconds = getPresignedUrlExpirySeconds('PUT') let url: string @@ -1094,12 +1121,12 @@ export class LocalStorageService implements S3Service { throw new Error(`Invalid method: ${method}`) } if (method === 'PUT') { - return `${this.endpoint}${signLocalUrl(bucket, key)}` + return `${this.endpoint}${signLocalUrl(bucket, key, expiresInSeconds)}` } - const lifetimeSeconds = expiresInSeconds ?? DEFAULT_LOCAL_GET_EXPIRY_SECONDS + const lifetimeSeconds = getPresignedUrlExpirySeconds('GET', expiresInSeconds) const cacheTtlMs = (lifetimeSeconds * 1000) / 2 - const cacheKey = `${bucket}/${key}?download=${download || false}&filename=${filename || ''}&expires=${expiresInSeconds ?? 'default'}` + const cacheKey = `${bucket}/${key}?download=${download || false}&filename=${filename || ''}&expires=${lifetimeSeconds}` if (method === 'GET' && !download) { const cached = this.presignCache.get(cacheKey) diff --git a/packages/dtos/src/upload.ts b/packages/dtos/src/upload.ts index 3b3f204d..944a3f19 100644 --- a/packages/dtos/src/upload.ts +++ b/packages/dtos/src/upload.ts @@ -100,6 +100,7 @@ export const localUploadQuerySchema = z.object({ bucket: z.string(), key: z.string(), Signature: z.string(), + Expires: z.string().optional(), }) export type LocalUploadQuery = z.infer