diff --git a/.changeset/storage-upload-bound-built-in-default.md b/.changeset/storage-upload-bound-built-in-default.md new file mode 100644 index 00000000000..45f636042d6 --- /dev/null +++ b/.changeset/storage-upload-bound-built-in-default.md @@ -0,0 +1,37 @@ +--- +'@objectstack/service-storage': patch +--- + +fix(service-storage)!: every upload bound resolves by one precedence, and unset never means unlimited + +Clause-②: no (narrowing) +Metadata-protocol: none + + + +**BREAKING** for a host whose storage doors had no upload bound because nothing set one. Each such host now enforces 100 MB per upload. + +**The rule.** The three storage Limits keys (`presigned_ttl`, `session_ttl`, `max_upload_mb`) resolve by one precedence, highest first: a saved setting (an admin save or an env override), the host's option, the settings manifest's default, the built-in default. Unset never means unlimited. + +- **Built-in default.** `max_upload_mb`'s built-in default is 100 MB (counted as MiB), the number the settings manifest declares. A drift pin holds the two equal. +- **Host option.** `maxUploadMb` on the `StorageServicePlugin` constructor, on `mountStorageRoutes` and on `registerStorageRoutes` is the host layer, exactly like `presignedTtl` and `sessionTtl`. It takes a positive number of MB, or `'unlimited'` for no bound. Any other value (`0`, a negative or non-finite number, a numeric string, any other string) refuses construction or the mount. +- **Failure paths.** A settings read that fails, and a saved value that is present but not a positive number, take the host option or else the built-in default, never no bound. +- **Coverage.** The bound applies wherever an upload is judged: the byte doors (the chunk `PUT`, the presigned local raw `PUT`, the upload-link `PUT` and its several-file form), the declared-size doors (presign, chunked start), and the server-side file verbs (`field-files`, `file-attachments` and the upload link's several-file spend). +- **Boot line.** Each host door says, once at boot or mount, the bound in force and the layer it came from: the plugin through its logger, `mountStorageRoutes` and `registerStorageRoutes` through the `logger` they are given. With an explicit `'unlimited'` the line is a `warn`, and it is said even when no logger was passed, on `console.warn`. + +**Who moves.** Each of these moves from no upload bound to 100 MB: + +- a DevPlugin-composed server; +- `--preset minimal` with storage; +- a `mountStorageRoutes` host over a bare adapter or over a plugin bound to no settings; +- an embedder that passes `bindToSettings: false`; +- a settings-bound host while its settings read fails; +- a host whose saved or env-sourced `max_upload_mb` is present but not a positive number (it was dropped, and nothing stood in its place). + +Remedies: + +- **A host that constructs the plugin** (`bindToSettings: false` embedders, `--preset minimal`, settings-fault hosts): one option, `new StorageServicePlugin({ maxUploadMb: 500 })` for another bound, or `maxUploadMb: 'unlimited'` to keep accepting uploads of any size (boot then says so at `warn`). A `mountStorageRoutes` or `registerStorageRoutes` host passes the same option for that mount's doors. +- **A DevPlugin-composed server**: DevPlugin constructs the storage plugin with no options, so turn its storage toggle off and mount the plugin yourself: `new DevPlugin({ services: { storage: false }, extraPlugins: [new StorageServicePlugin({ maxUploadMb: 500 })] })`, or list the `StorageServicePlugin` instance in the stack's own `plugins`, where an explicit instance wins. +- **A host with an invalid saved value**: correct the saved `max_upload_mb` (Setup's File Storage settings, or the env override) to a positive number. The saved layer cannot spell "no bound"; to accept any size, remove the saved value and pass the host option `maxUploadMb: 'unlimited'`. + +**Unchanged.** A settings-bound host with nothing saved, which is the default `os serve`, already enforced the manifest's 100 MB and still does. A saved `max_upload_mb` still wins over every host option. The 18.5.0 note "with `max_upload_mb` unset a byte door states no bound and reads the whole body" no longer holds: with `max_upload_mb` unset a byte door states the host's bound or else the built-in 100 MB, and it states no bound only under an explicit host `'unlimited'`. diff --git a/content/docs/api/error-catalog.mdx b/content/docs/api/error-catalog.mdx index 0f89bc7c8cb..fe2eb256600 100644 --- a/content/docs/api/error-catalog.mdx +++ b/content/docs/api/error-catalog.mdx @@ -611,11 +611,14 @@ The standard catalog names no `413` member. - **An upload over the File Storage settings' `max_upload_mb`.** The presigned-upload door (the declared `size`), the chunked-upload start (the declared `totalSize`), the local adapter's raw upload (the body) and the chunk door (the bytes the upload already holds plus the chunk) refuse - it before anything is stored. The message names the size, the limit and the setting. + it before anything is stored. The message names the size, the limit and the setting. With no + saved value, the bound is the storage plugin's `maxUploadMb` option, then the setting's declared + default, then the built-in 100 MB: an upload bound is never unset. - **An import over its route's row ceiling** — 5,000 rows on the synchronous route, 50,000 on the job route ([size limits](/docs/data-modeling/import-mappings#size-limits)). -**Fix:** Raise the setting or send a smaller file; split the import across requests. Resending +**Fix:** Raise the setting (or, with nothing saved, the host's `maxUploadMb`) or send a smaller +file; split the import across requests. Resending the same request cannot succeed. **Retry:** `no_retry` diff --git a/packages/qa/dogfood/test/request-body-limit-upload-doors.dogfood.test.ts b/packages/qa/dogfood/test/request-body-limit-upload-doors.dogfood.test.ts index dfcc1523cea..d2e043baf3f 100644 --- a/packages/qa/dogfood/test/request-body-limit-upload-doors.dogfood.test.ts +++ b/packages/qa/dogfood/test/request-body-limit-upload-doors.dogfood.test.ts @@ -43,9 +43,10 @@ describe('the request-body limit leaves each upload door its own bound, over a r const rootDir = mkdtempSync(join(tmpdir(), 'body-limit-upload-doors-')); stack = await bootStack(attachmentsFixtureStack as never, { security: attachmentsFixtureSecurity(), - // `bindToSettings:false` keeps the constructor rootDir and leaves - // `max_upload_mb` unset, so each door's own bound is none at all: what - // is measured here is that the transport limit does not stand in for it. + // `bindToSettings:false` keeps the constructor rootDir and reads no + // `max_upload_mb`, so each door's own bound is the built-in 100 MB, far + // above the transport's 10 MiB: what is measured here is that the + // transport limit does not stand in for it. extraPlugins: [ new StorageServicePlugin({ adapter: 'local', local: { rootDir }, bindToSettings: false }), new MCPServerPlugin(), diff --git a/packages/services/service-storage/README.md b/packages/services/service-storage/README.md index 386ce4d1392..99ce2193ce7 100644 --- a/packages/services/service-storage/README.md +++ b/packages/services/service-storage/README.md @@ -110,17 +110,43 @@ doors whenever the plugin is bound to settings (the default): | Setting | Default | Applies to | |:---|:---|:---| -| `max_upload_mb` | 100 (MB, counted as MiB) | Every upload door: the presigned upload's declared `size`, the chunked upload's declared `totalSize`, the local raw PUT body and each chunk's running total. Over it ⇒ `413` with code `PAYLOAD_TOO_LARGE`, before anything is stored. | +| `max_upload_mb` | 100 (MB, counted as MiB) | Every upload door: the presigned upload's declared `size`, the chunked upload's declared `totalSize`, the local raw PUT body, each chunk's running total, the upload-link PUT (and each file of its several-file form), and the server-side file verbs. Over it ⇒ `413` with code `PAYLOAD_TOO_LARGE`, before anything is stored. | | `presigned_ttl` | 3600 s | Presigned upload URLs and non-gated download URLs issued from then on. | | `session_ttl` | 86400 s | Chunked upload sessions started from then on. | -Per key, a saved value (an admin save or an env override) wins over the -constructor's `presignedTtl` / `sessionTtl`, and those win over the namespace's -declared default. A save reaches the doors without a restart; URLs and sessions -already issued keep their lifetime. With no settings namespace bound -(`bindToSettings: false`, or no settings service) the constructor TTLs apply and -no upload size limit is enforced. On the S3 adapter a presigned upload is judged -by its declared size — the bytes go straight to the bucket. +All three keys resolve by one precedence, highest first: a saved value (an +admin save or an env override), then the host's option on the plugin's +constructor (or on `mountStorageRoutes`) — `presignedTtl`, `sessionTtl`, +`maxUploadMb` — then the namespace's declared default, then the built-in +default (3600 s, 86400 s, 100 MB). A save reaches the doors without a restart; +URLs and sessions already issued keep their lifetime. + +**The upload bound is never unset.** With no settings namespace bound +(`bindToSettings: false`, no settings service, a settings read that failed, +or `mountStorageRoutes` over a bare adapter) and no host option, every upload +door enforces the built-in 100 MB — the number the manifest declares. No limit +is an explicit host choice: + +```typescript +new StorageServicePlugin({ maxUploadMb: 500 }); // the host's bound, in MB +new StorageServicePlugin({ maxUploadMb: 'unlimited' }); // no bound, announced at warn on boot +``` + +Anything else (`0`, a negative or non-finite number, a number too small to +bound one byte, a numeric string, any other string) refuses construction. Each +host door — the plugin, `mountStorageRoutes`, `registerStorageRoutes` — says once +the bound in force and the layer it came from; an explicit `'unlimited'` is said +at `warn`, on `console.warn` when the door was given no logger. + +Who moved from no bound to 100 MB, and the remedy: + +| Host | Remedy | +|:---|:---| +| Constructs the plugin with no settings bound (`bindToSettings: false`, `--preset minimal`), or its settings read fails | `maxUploadMb: 500` or `'unlimited'` on the plugin | +| `mountStorageRoutes` / `registerStorageRoutes` over a bare adapter or an unbound plugin | the same option on that call | +| DevPlugin-composed server (DevPlugin builds the plugin with no options) | `new DevPlugin({ services: { storage: false }, extraPlugins: [new StorageServicePlugin({ maxUploadMb: 500 })] })`, or list the instance in the stack's `plugins` | +| A saved or env-sourced `max_upload_mb` that is not a positive number | correct the saved value; the saved layer cannot spell "no bound", so to accept any size remove it and pass `maxUploadMb: 'unlimited'` | On the S3 adapter a presigned upload is judged by +its declared size — the bytes go straight to the bucket. ## REST API Endpoints diff --git a/packages/services/service-storage/package.json b/packages/services/service-storage/package.json index 833c83157b2..dad4f36b56b 100644 --- a/packages/services/service-storage/package.json +++ b/packages/services/service-storage/package.json @@ -49,6 +49,7 @@ "@objectstack/objectql": "workspace:*", "@objectstack/driver-sql": "workspace:*", "@objectstack/plugin-audit": "workspace:*", + "@objectstack/service-settings": "workspace:*", "@types/node": "^26.6.5", "tsx": "^4.23.15", "typescript": "^6.0.3", diff --git a/packages/services/service-storage/src/field-file-service.ts b/packages/services/service-storage/src/field-file-service.ts index c3940884a4b..ccd29e23822 100644 --- a/packages/services/service-storage/src/field-file-service.ts +++ b/packages/services/service-storage/src/field-file-service.ts @@ -24,10 +24,12 @@ import { // The upload doors' own size verdict and refusal, asked here rather than // restated. import { + parseHostMaxUploadMb, resolveStorageLimits, uploadSizeRefusal, UPLOAD_TOO_LARGE_CODE, UPLOAD_TOO_LARGE_STATUS, + type HostMaxUploadMb, type StorageLimitsSnapshot, } from './storage-limits.js'; // The upload doors' own storage-key layout. @@ -81,6 +83,12 @@ export interface FieldFileServiceDeps { getStorage(): IStorageService | null; /** The `storage` namespace's Limits group as last read — the upload doors' own source. */ getLimitsSnapshot(): StorageLimitsSnapshot | undefined; + /** + * The host's upload bound (the plugin's `maxUploadMb`, already validated) — + * the host layer of the doors' own precedence; absent ⇒ the namespace + * default, else the built-in 100 MB. + */ + hostMaxUploadMb?: HostMaxUploadMb; logger: FileReferenceLogger; } @@ -178,7 +186,10 @@ function isSlot(owner: FieldFileSlot | null, slot: FieldFileSlot): boolean { } export class FieldFileService implements IFieldFileService { - constructor(private readonly deps: FieldFileServiceDeps) {} + constructor(private readonly deps: FieldFileServiceDeps) { + // The host bound is judged where the verb is built, as at every host door. + parseHostMaxUploadMb(deps.hostMaxUploadMb, 'FieldFileService'); + } async storeFile(input: StoreFieldFileInput): Promise { const request = validateStoreInput(input); @@ -190,7 +201,7 @@ export class FieldFileService implements IFieldFileService { const size = request.data.byteLength; const tooLarge = uploadSizeRefusal( size, - resolveStorageLimits(this.deps.getLimitsSnapshot()).maxUploadBytes, + resolveStorageLimits(this.deps.getLimitsSnapshot(), { maxUploadMb: this.deps.hostMaxUploadMb }).maxUploadBytes, (n) => `The file ${request.filename} is ${n} bytes`, ); if (tooLarge !== null) refuse(UPLOAD_TOO_LARGE_CODE, UPLOAD_TOO_LARGE_STATUS, tooLarge); diff --git a/packages/services/service-storage/src/file-attachment-service.ts b/packages/services/service-storage/src/file-attachment-service.ts index 698cc2943fb..4b0448dc0ba 100644 --- a/packages/services/service-storage/src/file-attachment-service.ts +++ b/packages/services/service-storage/src/file-attachment-service.ts @@ -35,10 +35,12 @@ import { createWallOrganizationResolver } from './backfill-sys-file-organization // The upload doors' own size verdict and refusal, asked here rather than // restated. import { + parseHostMaxUploadMb, resolveStorageLimits, uploadSizeRefusal, UPLOAD_TOO_LARGE_CODE, UPLOAD_TOO_LARGE_STATUS, + type HostMaxUploadMb, type StorageLimitsSnapshot, } from './storage-limits.js'; // The upload doors' own storage-key layout, and the commit door's question @@ -140,6 +142,12 @@ export interface FileAttachmentServiceDeps { getStorage(): IStorageService | null; /** The `storage` namespace's Limits group as last read — the upload doors' own source. */ getLimitsSnapshot(): StorageLimitsSnapshot | undefined; + /** + * The host's upload bound (the plugin's `maxUploadMb`, already validated) — + * the host layer of the doors' own precedence; absent ⇒ the namespace + * default, else the built-in 100 MB. + */ + hostMaxUploadMb?: HostMaxUploadMb; logger: { warn(message: string): void; debug?(message: string): void }; /** The sharing service, for the attach rule's verdict ({@link FileAttachmentService.assertMayAttach}). */ getSharing?(): AttachmentSharingLike | null | undefined; @@ -315,6 +323,8 @@ export class FileAttachmentService private readonly recordFiles: RecordFileAccess | null; constructor(private readonly deps: FileAttachmentServiceDeps) { + // The host bound is judged where the verb is built, as at every host door. + parseHostMaxUploadMb(deps.hostMaxUploadMb, 'FileAttachmentService'); const bound = deps.recordFiles; this.recordFiles = bound ? new RecordFileAccess({ @@ -322,6 +332,7 @@ export class FileAttachmentService getEngine: () => deps.getEngine(), getStorage: () => deps.getStorage(), getLimitsSnapshot: () => deps.getLimitsSnapshot(), + hostMaxUploadMb: deps.hostMaxUploadMb, attachments: this, getSharing: () => deps.getSharing?.(), getSecurity: () => deps.getSecurity?.(), @@ -594,7 +605,7 @@ export class FileAttachmentService const size = request.data.byteLength; const tooLarge = uploadSizeRefusal( size, - resolveStorageLimits(this.deps.getLimitsSnapshot()).maxUploadBytes, + resolveStorageLimits(this.deps.getLimitsSnapshot(), { maxUploadMb: this.deps.hostMaxUploadMb }).maxUploadBytes, (n) => `The file is ${n} bytes`, ); if (tooLarge !== null) refuse(UPLOAD_TOO_LARGE_CODE, UPLOAD_TOO_LARGE_STATUS, tooLarge); diff --git a/packages/services/service-storage/src/index.ts b/packages/services/service-storage/src/index.ts index 29414ed2f68..29aaefd7e99 100644 --- a/packages/services/service-storage/src/index.ts +++ b/packages/services/service-storage/src/index.ts @@ -25,6 +25,11 @@ export type { // group as last read. Types only — the reading and the resolution stay inside // the package, so the precedence has one definition. export type { StorageLimitsSnapshot, StorageLimitReading } from './storage-limits.js'; +// The host's upload bound (`maxUploadMb` on the plugin, `mountStorageRoutes` and +// `registerStorageRoutes`): its type, so a host can type the option, and the +// refusal a malformed one boots into, so a host can recognise it by class. +export type { HostMaxUploadMb } from './storage-limits.js'; +export { InvalidMaxUploadMbError } from './storage-limits.js'; // [#15169] The host door: the storage routes composed from a kernel and // mounted on an HTTP surface the host owns — for kernels with no `http-server` // service (cloud's per-environment tenant kernels). Published as ONE entry diff --git a/packages/services/service-storage/src/mount-storage-routes.ts b/packages/services/service-storage/src/mount-storage-routes.ts index 85e70a0d2a1..e96c03bb6fb 100644 --- a/packages/services/service-storage/src/mount-storage-routes.ts +++ b/packages/services/service-storage/src/mount-storage-routes.ts @@ -28,7 +28,7 @@ * consumer gets is the door; what it never gets is a handle on any gate: * * - {@link MountStorageRoutesOptions} carries the wire knobs only (`basePath`, - * the three TTLs, a logger). It has no `resolveSession`, no + * the three TTLs, the upload bound, a logger). It has no `resolveSession`, no * `authorizeFileRead`, no `resolveFileHolder` — the three option keys of * `registerStorageRoutes` this door exists to keep off the host's side. * An object literal naming one of them is a type error, and a widened @@ -56,6 +56,13 @@ */ import type { IHttpServer, IDataEngine, IStorageService } from '@objectstack/spec/contracts'; +import { + parseHostMaxUploadMb, + announceUploadBound, + resolveStorageLimits, + type HostMaxUploadMb, + type StorageLimitsSnapshot, +} from './storage-limits.js'; import { composeStorageRoutes, toGateRegistry, @@ -80,14 +87,30 @@ export interface MountStorageRoutesOptions { * and that plugin is bound to the `storage` settings namespace, a SAVED * `presigned_ttl` wins over this option, and this option wins over the * namespace default — the same precedence the plugin's own mount applies. - * The saved `max_upload_mb` reaches this door the same way. */ presignedTtl?: number; /** Default chunked upload session TTL in seconds; a SAVED `session_ttl` wins over it. @default 86400 */ sessionTtl?: number; + /** + * Upload size bound in MB (counted as MiB), or `'unlimited'` to accept + * uploads of any size — the host layer, exactly like the TTLs: a SAVED + * `max_upload_mb` wins over it, it wins over the namespace default, and + * left out the namespace default or else the built-in 100 MB applies (a + * bare adapter, an unbound plugin). Never unset by omission. Anything but a + * positive number or `'unlimited'` throws before a route is mounted. + * + * Bounds THIS mount's doors. The server-side file verbs on the kernel take + * the storage plugin's own `maxUploadMb`. + * @default 100 (via the storage settings, else built in) + */ + maxUploadMb?: HostMaxUploadMb; /** TTL of the signed URL minted on a GATED download. @default 300 */ downloadTtl?: number; - /** Receives the door's one-time notices (open upload mode, unbound gates). */ + /** + * Receives the door's one-time notices (the upload bound in force, open + * upload mode, unbound gates). Without one, an explicit `maxUploadMb: + * 'unlimited'` is still announced, on `console.warn`. + */ logger?: { info(msg: string): void; warn(msg: string): void }; } @@ -106,12 +129,14 @@ export interface MountStorageRoutesOptions { * against. * * @throws when `kernel` has no `storage` service — there is nothing to mount. + * @throws when `opts.maxUploadMb` is neither a positive number nor `'unlimited'`. */ export function mountStorageRoutes( http: IHttpServer, kernel: StorageRouteKernel, opts: MountStorageRoutesOptions = {}, ): StorageRoutesMountReport { + const maxUploadMb = parseHostMaxUploadMb(opts.maxUploadMb, 'mountStorageRoutes'); let storage: IStorageService | undefined; try { storage = kernel.getService('storage'); @@ -141,10 +166,23 @@ export function mountStorageRoutes( basePath: opts.basePath, presignedTtl: opts.presignedTtl, sessionTtl: opts.sessionTtl, + maxUploadMb, downloadTtl: opts.downloadTtl, logger: opts.logger, }); + // The upload bound this mount's doors meet now, and the layer it came from: + // the kernel has bootstrapped, so a bound plugin's settings are read. + // No bound is said at `warn` whether or not the host passed a logger. + const carrier = storage as { getLimitsSnapshot?: () => StorageLimitsSnapshot | undefined }; + announceUploadBound( + 'mountStorageRoutes', + resolveStorageLimits(typeof carrier.getLimitsSnapshot === 'function' ? carrier.getLimitsSnapshot() : undefined, { + maxUploadMb, + }), + opts.logger, + ); + const unbound: string[] = []; if (!report.sessionResolver) { unbound.push('upload routes accept anonymous requests (no `auth` service on the kernel)'); diff --git a/packages/services/service-storage/src/record-file-access.integration.test.ts b/packages/services/service-storage/src/record-file-access.integration.test.ts index f585f4db5ee..0d6e8a8b094 100644 --- a/packages/services/service-storage/src/record-file-access.integration.test.ts +++ b/packages/services/service-storage/src/record-file-access.integration.test.ts @@ -2163,25 +2163,52 @@ describe('#30892 — a record\'s files for a resolved caller: read one, attach o } }); - it('with no max_upload_mb, a host size refusal is not taken as the door\'s own: it is relayed with its own words, as before', async () => { + it('with no max_upload_mb the door states the built-in 100 MB bound, so a read refused past it is the door\'s own 413, the link unspent', async () => { const grant = await files.createUploadLinkAs('claim', await newClaim('bound-host'), { field: 'policy' }, OWNER as never); const token = tokenOf(grant.path); - const hostSizeRefusal = vi.fn(async () => { - throw Object.assign(new Error('the host refused this body for size'), { status: 413, code: 'PAYLOAD_TOO_LARGE' }); + const asked: Array = []; + const refusedPastBound = vi.fn(async (options?: { maxBytes?: number }) => { + asked.push(options?.maxBytes); + throw Object.assign(new Error('refused past the bound'), { status: 413, code: 'PAYLOAD_TOO_LARGE' }); }); - const answer = await putLink(token, hostSizeRefusal); + const answer = await putLink(token, refusedPastBound); expect(answer._status, JSON.stringify(answer._json)).toBe(413); expect(answer._json.error.code).toBe('PAYLOAD_TOO_LARGE'); - expect(answer._json.error.message).toBe('the host refused this body for size'); + expect(answer._json.error.message).toBe(uploadSizeRefusal(100 * MIB + 1, 100 * MIB, () => `The upload body is more than ${100 * MIB} bytes`)); + expect(asked).toEqual([100 * MIB]); // CONTROL — the link was not spent. expect((await putLink(token, boundedRawBody(Buffer.from('%PDF-1.4 after host')).rawBody))._status).toBe(200); }); - it('CONTROL · with no max_upload_mb the door states no bound and reads the whole body, as before', async () => { + it('with no max_upload_mb a body within the built-in bound is read whole under it', async () => { const grant = await files.createUploadLinkAs('claim', await newClaim('bound-none'), { field: 'policy' }, OWNER as never); - const read = boundedRawBody(Buffer.from('%PDF-1.4 unbounded')); + const read = boundedRawBody(Buffer.from('%PDF-1.4 within')); expect((await putLink(tokenOf(grant.path), read.rawBody))._status).toBe(200); - expect(read.asked).toEqual([undefined]); + expect(read.asked).toEqual([100 * MIB]); + }); + + it('with no max_upload_mb a 101 MB file inside a several-file form within its form limit is refused by the link verb, the link unspent', async () => { + const id = await newClaim('bound-form-file'); + const grant = await files.createUploadLinkAs('claim', id, { field: 'scans' }, OWNER as never); + const token = tokenOf(grant.path); + const big = new ArrayBuffer(101 * MIB); + const answer = await call('PUT', `${BASE}/upload-links/:token`, { + params: { token }, + headers: { 'content-type': 'multipart/form-data; boundary=----os', 'x-upload-link-form': 'several', ...sessionOf(OWNER.userId) }, + body: { count: '1', file0: { name: 'big.pdf', type: 'application/pdf', arrayBuffer: async () => big } }, + rawBody: async () => Buffer.from('------os--\r\n'), + }); + expect(answer._status, JSON.stringify(answer._json)).toBe(413); + expect(answer._json.error.code).toBe('PAYLOAD_TOO_LARGE'); + // CONTROL — the link was not spent: a small file lands through it. + const small = new File([new Uint8Array(Buffer.from('%PDF-1.4 small'))], 'small.pdf', { type: 'application/pdf' }); + const landed = await call('PUT', `${BASE}/upload-links/:token`, { + params: { token }, + headers: { 'content-type': 'multipart/form-data; boundary=----os', 'x-upload-link-form': 'several', ...sessionOf(OWNER.userId) }, + body: { count: '1', file0: small }, + rawBody: async () => Buffer.from('------os--\r\n'), + }); + expect(landed._status, JSON.stringify(landed._json)).toBe(200); }); }); }); diff --git a/packages/services/service-storage/src/record-file-access.ts b/packages/services/service-storage/src/record-file-access.ts index 9a7a0a8006b..3d1e64f8bd5 100644 --- a/packages/services/service-storage/src/record-file-access.ts +++ b/packages/services/service-storage/src/record-file-access.ts @@ -36,10 +36,12 @@ import { // The upload doors' own size verdict and refusal, asked here rather than // restated. import { + parseHostMaxUploadMb, resolveStorageLimits, uploadSizeRefusal, UPLOAD_TOO_LARGE_CODE, UPLOAD_TOO_LARGE_STATUS, + type HostMaxUploadMb, type StorageLimitsSnapshot, } from './storage-limits.js'; // The upload doors' own storage-key layout, and the download doors' link. @@ -459,6 +461,12 @@ export interface RecordFileAccessDeps { getEngine(): RecordFileEngine | null; getStorage(): IStorageService | null; getLimitsSnapshot(): StorageLimitsSnapshot | undefined; + /** + * The host's upload bound (the plugin's `maxUploadMb`, already validated) — + * the host layer of the doors' own precedence; absent ⇒ the namespace + * default, else the built-in 100 MB. + */ + hostMaxUploadMb?: HostMaxUploadMb; /** The caller-scoped attach verbs (`FileAttachmentService`). */ attachments: { attachFileAs(input: AttachFileInput, context: ExecutionContext): Promise; @@ -757,7 +765,10 @@ function describe(file: FileRecord): Pick range.max) refuseFileCount(range, uploads.length); - const maxUploadBytes = resolveStorageLimits(this.deps.getLimitsSnapshot()).maxUploadBytes; + const maxUploadBytes = resolveStorageLimits(this.deps.getLimitsSnapshot(), { + maxUploadMb: this.deps.hostMaxUploadMb, + }).maxUploadBytes; for (const upload of uploads) { if (!nonEmptyString(upload?.filename)) refuse('VALIDATION_ERROR', 400, 'The upload names no file.'); if (!Buffer.isBuffer(upload.data)) refuse('VALIDATION_ERROR', 400, 'The upload carries no bytes.'); diff --git a/packages/services/service-storage/src/storage-limits.test.ts b/packages/services/service-storage/src/storage-limits.test.ts index 699e8440096..ebfa51f9113 100644 --- a/packages/services/service-storage/src/storage-limits.test.ts +++ b/packages/services/service-storage/src/storage-limits.test.ts @@ -15,16 +15,22 @@ * - **§2 the TTLs and the precedence.** A saved TTL is what a presigned URL * and a new session carry; a saved value beats the host's option, the host's * option beats the namespace default, and with no namespace bound the - * built-in defaults and NO size limit stand (the pre-#22283 behaviour). + * built-in defaults stand — the upload bound's included. * - **§3 the plugin wiring, end to end through `applySettings`.** Nothing * saved ⇒ the declared defaults (100 MB, 3600 s, 86400 s) hold; a save after * boot reaches the next request, while a session already issued keeps the - * lifetime it was issued with; `bindToSettings: false` keeps the old doors. + * lifetime it was issued with; `bindToSettings: false` keeps the + * constructor TTLs and the built-in upload bound. * - **§4 the host door** (`mountStorageRoutes`) honours the same snapshot, * because it rides the `storage` service both mounts are composed over. + * - **§5 the upload bound: one precedence, and unset never means unlimited.** + * Every path that sets nothing lands on the built-in 100 MB; the host + * option is a layer like the TTLs'; no limit is an explicit, announced host + * choice; a malformed host option refuses the boot; a saved setting still + * wins; the built-in default is the manifest's. */ -import { describe, it, expect, vi, afterEach } from 'vitest'; +import { describe, it, expect, vi, afterEach, afterAll } from 'vitest'; import { promises as fs } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; @@ -36,7 +42,18 @@ import { registerStorageRoutes, type StorageRoutesOptions } from './storage-rout import { StorageServicePlugin } from './storage-service-plugin.js'; import { SwappableStorageService } from './swappable-storage-service.js'; import { mountStorageRoutes } from './mount-storage-routes.js'; -import { readStorageLimits, resolveStorageLimits, type StorageLimitsSnapshot } from './storage-limits.js'; +import { + DEFAULT_MAX_UPLOAD_MB, + InvalidMaxUploadMbError, + readStorageLimits, + resolveStorageLimits, + type StorageLimitsSnapshot, +} from './storage-limits.js'; +import { registerStorageFamily } from './storage-routes.js'; +import { FieldFileService } from './field-file-service.js'; +import { FileAttachmentService } from './file-attachment-service.js'; +import type { UploadLinkDoor } from './record-file-access.js'; +import { storageSettingsManifest } from '@objectstack/service-settings'; const BASE = '/api/v1/storage'; const MIB = 1024 * 1024; @@ -345,14 +362,21 @@ describe('[#22283] §1 · the upload doors refuse a file over max_upload_mb, bef expect(rawBody).not.toHaveBeenCalled(); }); - it('CONTROL · no settings namespace bound: no size limit at any door (the pre-#22283 behaviour)', async () => { + it('no settings namespace bound: the built-in 100 MB bounds the declared-size doors, never no limit', async () => { const { routes } = await mountDoors(undefined); + expectTooLarge(await call(routes, 'POST', `${BASE}/upload/presigned`, { + body: { filename: 'huge.bin', mimeType: 'application/octet-stream', size: 101 * MIB }, + })); + expectTooLarge(await call(routes, 'POST', `${BASE}/upload/chunked`, { + body: { filename: 'huge.bin', mimeType: 'application/octet-stream', totalSize: 101 * MIB }, + })); + // CONTROL — exactly the built-in bound is accepted at both. const presigned = await call(routes, 'POST', `${BASE}/upload/presigned`, { - body: { filename: 'huge.bin', mimeType: 'application/octet-stream', size: 1024 * MIB }, + body: { filename: 'at.bin', mimeType: 'application/octet-stream', size: 100 * MIB }, }); expect(presigned.status).toBe(200); const started = await call(routes, 'POST', `${BASE}/upload/chunked`, { - body: { filename: 'huge.bin', mimeType: 'application/octet-stream', totalSize: 1024 * MIB }, + body: { filename: 'at.bin', mimeType: 'application/octet-stream', totalSize: 100 * MIB }, }); expect(started.status).toBe(200); }); @@ -440,8 +464,8 @@ describe('a byte door holds a body with no declared length to its own bound, as throw Object.assign(new Error('the host refused this body for size'), { status: 413, code: 'PAYLOAD_TOO_LARGE' }); }); - it('with no max_upload_mb, a host size refusal on the local raw PUT is not taken as the door\'s own: the door answers, as before', async () => { - const { adapter, routes } = await mountDoors(undefined); + it('with no bound (the host chose unlimited), a host size refusal on the local raw PUT is not taken as the door\'s own', async () => { + const { adapter, routes } = await mountDoors(undefined, { maxUploadMb: 'unlimited' }); const presigned = await call(routes, 'POST', `${BASE}/upload/presigned`, { body: { filename: 'h.bin', mimeType: 'application/octet-stream', size: 10 }, }); @@ -455,8 +479,8 @@ describe('a byte door holds a body with no declared length to its own bound, as expect(upload).not.toHaveBeenCalled(); }); - it('with no max_upload_mb, a host size refusal on the chunk PUT is not taken as the door\'s own: the door answers, as before', async () => { - const { adapter, routes } = await mountDoors(undefined); + it('with no bound (the host chose unlimited), a host size refusal on the chunk PUT is not taken as the door\'s own', async () => { + const { adapter, routes } = await mountDoors(undefined, { maxUploadMb: 'unlimited' }); const started = await call(routes, 'POST', `${BASE}/upload/chunked`, { body: { filename: 'h.bin', mimeType: 'application/octet-stream', totalSize: MIB }, }); @@ -474,15 +498,25 @@ describe('a byte door holds a body with no declared length to its own bound, as expect(uploadChunk).not.toHaveBeenCalled(); }); - it('CONTROL · with no max_upload_mb the doors state no bound, and read the whole body as before', async () => { - const { routes } = await mountDoors(undefined); - const presigned = await call(routes, 'POST', `${BASE}/upload/presigned`, { - body: { filename: 'n.bin', mimeType: 'application/octet-stream', size: 10 }, - }); - const token = String(presigned.body.data.uploadUrl).split('/_local/raw/')[1]!; - const read = boundedRawBody(2 * MIB); - expect((await call(routes, 'PUT', `${BASE}/_local/raw/:token`, { params: { token }, rawBody: read.rawBody })).status).toBe(200); - expect(read.asked).toEqual([undefined]); + it('with no max_upload_mb the doors state the built-in 100 MB bound; only an explicit host unlimited states none', async () => { + const tokenFrom = async (routes: Map) => { + const presigned = await call(routes, 'POST', `${BASE}/upload/presigned`, { + body: { filename: 'n.bin', mimeType: 'application/octet-stream', size: 10 }, + }); + return String(presigned.body.data.uploadUrl).split('/_local/raw/')[1]!; + }; + const unset = await mountDoors(undefined); + const bounded = boundedRawBody(2 * MIB); + const token = await tokenFrom(unset.routes); + expect((await call(unset.routes, 'PUT', `${BASE}/_local/raw/:token`, { params: { token }, rawBody: bounded.rawBody })).status).toBe(200); + expect(bounded.asked).toEqual([100 * MIB]); + + // CONTROL — the explicit host choice reads the whole body, stating no bound. + const unlimited = await mountDoors(undefined, { maxUploadMb: 'unlimited' }); + const whole = boundedRawBody(2 * MIB); + const open = await tokenFrom(unlimited.routes); + expect((await call(unlimited.routes, 'PUT', `${BASE}/_local/raw/:token`, { params: { token: open }, rawBody: whole.rawBody })).status).toBe(200); + expect(whole.asked).toEqual([undefined]); }); }); @@ -528,14 +562,20 @@ describe('[#22283] §2 · the saved TTLs reach issuance; saved > host option > n expect(resolveStorageLimits({ sessionTtl: dflt(86400) }, { sessionTtl: 900 }).sessionTtl).toBe(900); // The namespace default applies when the host said nothing. expect(resolveStorageLimits({ sessionTtl: dflt(7200) }, {}).sessionTtl).toBe(7200); - // No namespace: the host's option, else the built-in defaults, and no size limit. + // No namespace: the host's option, else the built-in defaults — the upload bound's included. expect(resolveStorageLimits(undefined, { presignedTtl: 600 })).toEqual({ presignedTtl: 600, sessionTtl: 86400, - maxUploadBytes: undefined, + maxUploadBytes: 100 * MIB, + maxUploadLayer: 'built-in default', }); - expect(resolveStorageLimits(undefined)).toEqual({ presignedTtl: 3600, sessionTtl: 86400, maxUploadBytes: undefined }); - // The size limit comes from the namespace alone — its default included. + expect(resolveStorageLimits(undefined)).toEqual({ + presignedTtl: 3600, + sessionTtl: 86400, + maxUploadBytes: 100 * MIB, + maxUploadLayer: 'built-in default', + }); + // The size limit: the namespace default, a saved value (MB counted as MiB). expect(resolveStorageLimits({ maxUploadMb: dflt(100) }).maxUploadBytes).toBe(100 * MIB); expect(resolveStorageLimits({ maxUploadMb: saved(2.5) }).maxUploadBytes).toBe(Math.floor(2.5 * MIB)); }); @@ -586,15 +626,16 @@ function fakeSettings(values: Record, sources: Record | null, - options: { presignedTtl?: number; sessionTtl?: number; bindToSettings?: boolean } = {}, + options: { presignedTtl?: number; sessionTtl?: number; maxUploadMb?: number | 'unlimited'; bindToSettings?: boolean } = {}, ) { const { http, routes } = routeCollector(); const services = new Map([['http-server', http]]); if (settings) services.set('settings', settings); const hooks: Array<() => Promise | void> = []; const infos: string[] = []; + const warns: string[] = []; const ctx = { - logger: { info: (m: string) => { infos.push(m); }, warn: () => {}, error: () => {}, debug: () => {} }, + logger: { info: (m: string) => { infos.push(m); }, warn: (m: string) => { warns.push(m); }, error: () => {}, debug: () => {} }, registerService: (name: string, svc: unknown) => { services.set(name, svc); }, getService: (name: string) => { if (!services.has(name)) throw new Error(`service '${name}' not registered`); @@ -610,7 +651,7 @@ async function bootPlugin( await plugin.init(ctx as never); await plugin.start(ctx as never); for (const h of hooks) await h(); - return { routes, infos }; + return { routes, infos, warns, services }; } /** Let a `void applySettings()` fired by a settings change settle. */ @@ -704,16 +745,20 @@ describe('[#22283] §3 · StorageServicePlugin reads the Limits group and its do expect(b.body.data.expiresIn).toBe(1200); }); - it('CONTROL · bindToSettings: false keeps the constructor doors — no size limit, built-in TTLs', async () => { + it('bindToSettings: false keeps the constructor doors — built-in TTLs and the built-in 100 MB bound, the saved 1 MB unread', async () => { const { routes } = await bootPlugin( fakeSettings({ ...MANIFEST_DEFAULTS, max_upload_mb: 1 }, { max_upload_mb: 'global' }), { bindToSettings: false }, ); - const huge = await call(routes, 'POST', `${BASE}/upload/presigned`, { - body: { filename: 'huge.bin', mimeType: 'application/octet-stream', size: 1024 * MIB }, + expectTooLarge(await call(routes, 'POST', `${BASE}/upload/presigned`, { + body: { filename: 'huge.bin', mimeType: 'application/octet-stream', size: 101 * MIB }, + })); + // CONTROL — the saved 1 MB is not read: 2 MiB is under the built-in bound. + const within = await call(routes, 'POST', `${BASE}/upload/presigned`, { + body: { filename: 'two.bin', mimeType: 'application/octet-stream', size: 2 * MIB }, }); - expect(huge.status).toBe(200); - expect(huge.body.data.expiresIn).toBe(3600); + expect(within.status).toBe(200); + expect(within.body.data.expiresIn).toBe(3600); }); }); @@ -745,3 +790,461 @@ describe('[#22283] §4 · mountStorageRoutes honours the Limits group the kernel expect(ok.body.data.expiresIn).toBe(300); }); }); + +// --------------------------------------------------------------------------- +// §5 — the upload bound: one precedence, and unset never means unlimited +// --------------------------------------------------------------------------- + +/** One MB over the built-in bound. */ +const OVER = 101 * MIB; +const BUILT_IN = 100 * MIB; + +/** A link door that takes whatever it is handed: what the routes need to reach the upload-link byte door. */ +function acceptingLinkDoor(filesMax: number) { + const consumeUploadLink = vi.fn(async (_token: string, upload: { data: Buffer }) => ({ fileId: 'f-link', size: upload.data.byteLength })); + const consumeUploadLinkFiles = vi.fn(async () => ({ files: [] })); + const door = { + inspectUploadLink: async () => ({ + expiresAt: new Date(Date.now() + 60_000).toISOString(), + target: 'attachments', + files: { min: 1, max: filesMax }, + }), + consumeUploadLink, + consumeUploadLinkFiles, + } as unknown as UploadLinkDoor; + return { door, consumeUploadLink, consumeUploadLinkFiles }; +} + +/** The upload-link door over a composition with no settings bound, signed in. */ +async function mountLinkDoor(filesMax: number, opts: StorageRoutesOptions = {}) { + const adapter = new LocalStorageAdapter({ rootDir: await tmpRoot(), signingSecret: 'test-secret-bound' }); + const { http, routes } = routeCollector(); + const link = acceptingLinkDoor(filesMax); + registerStorageFamily( + http, + adapter, + new StorageMetadataStore(null), + { basePath: BASE, resolveSession: async () => ({ userId: 'u_link' }), ...opts } as StorageRoutesOptions, + undefined, + undefined, + () => link.door, + ); + return { routes, ...link }; +} + +/** The several-file form as a transport hands it once its request-body limit refused `req.body`. */ +async function putTakenOverForm( + routes: Map, + rawBody: (options?: { maxBytes?: number }) => Promise, + headers: Record = {}, +): Promise { + const handler = routes.get(`PUT:${BASE}/upload-links/:token`)!; + const answer: Answer = { status: 200, body: undefined }; + const res = { + json(data: unknown) { answer.body = data; return res; }, + send() { return res; }, + status(code: number) { answer.status = code; return res; }, + header() { return res; }, + }; + const req: Record = { + params: { token: 'link.token' }, + query: {}, + headers: { 'content-type': 'multipart/form-data; boundary=----os', 'x-upload-link-form': 'several', ...headers }, + method: 'PUT', + path: `${BASE}/upload-links/:token`, + rawBody, + }; + Object.defineProperty(req, 'body', { + get() { + throw Object.assign(new Error('over the request-body limit'), { status: 413, code: 'PAYLOAD_TOO_LARGE' }); + }, + }); + await handler(req as unknown as IHttpRequest, res as unknown as IHttpResponse); + return answer; +} + +/** An engine or store no call may reach before the size verdict: reaching it is the proof the verdict passed. */ +const unreachable = () => + new Proxy({}, { + get() { + throw new Error('reached past the size verdict'); + }, + }); + +/** A refusal as a thrown ADR-0112 error carries it. */ +const refusalOf = (p: Promise) => + p.then( + () => null, + (e: any) => ({ code: e?.code as string | undefined, status: e?.status as number | undefined, message: String(e?.message) }), + ); + +describe('the upload bound resolves by one precedence — saved > host > manifest default > built-in — and unset is never unlimited', () => { + const saved = (value: number) => ({ value, authored: true }); + const dflt = (value: number) => ({ value, authored: false }); + + it('every layer, by resolution: built-in when nothing is set, host over the manifest default, saved over the host', () => { + expect(resolveStorageLimits(undefined)).toMatchObject({ maxUploadBytes: BUILT_IN, maxUploadLayer: 'built-in default' }); + expect(resolveStorageLimits({})).toMatchObject({ maxUploadBytes: BUILT_IN, maxUploadLayer: 'built-in default' }); + expect(resolveStorageLimits({ maxUploadMb: dflt(100) })).toMatchObject({ maxUploadBytes: BUILT_IN, maxUploadLayer: 'manifest default' }); + expect(resolveStorageLimits(undefined, { maxUploadMb: 5 })).toMatchObject({ maxUploadBytes: 5 * MIB, maxUploadLayer: 'host option' }); + expect(resolveStorageLimits({ maxUploadMb: dflt(100) }, { maxUploadMb: 200 })).toMatchObject({ + maxUploadBytes: 200 * MIB, + maxUploadLayer: 'host option', + }); + expect(resolveStorageLimits(undefined, { maxUploadMb: 'unlimited' })).toMatchObject({ + maxUploadBytes: undefined, + maxUploadLayer: 'host option', + }); + // A saved setting wins over every host choice, an explicit unlimited included. + expect(resolveStorageLimits({ maxUploadMb: saved(2) }, { maxUploadMb: 'unlimited' })).toMatchObject({ + maxUploadBytes: 2 * MIB, + maxUploadLayer: 'saved setting', + }); + expect(resolveStorageLimits({ maxUploadMb: saved(2) }, { maxUploadMb: 200 }).maxUploadBytes).toBe(2 * MIB); + }); + + it('the built-in default is the settings manifest\'s declared max_upload_mb default', () => { + const declared = (storageSettingsManifest.specifiers as Array<{ key?: string; default?: unknown }>).find( + (s) => s.key === 'max_upload_mb', + ); + expect(declared?.default).toBe(DEFAULT_MAX_UPLOAD_MB); + expect(DEFAULT_MAX_UPLOAD_MB * MIB).toBe(BUILT_IN); + }); + + describe('each unset path resolves to the built-in 100 MB', () => { + it('a plugin with no settings service: 101 MB refused, 100 MB accepted, and the boot line names the built-in default', async () => { + const { routes, infos, warns } = await bootPlugin(null); + expectTooLarge(await call(routes, 'POST', `${BASE}/upload/presigned`, { + body: { filename: 'over.bin', mimeType: 'application/octet-stream', size: OVER }, + })); + expect((await call(routes, 'POST', `${BASE}/upload/presigned`, { + body: { filename: 'at.bin', mimeType: 'application/octet-stream', size: BUILT_IN }, + })).status).toBe(200); + const line = infos.filter((m) => m.includes(`(${BUILT_IN} bytes)`)); + expect(line).toHaveLength(1); + expect(line[0]).toContain('built-in default'); + expect(warns.filter((m) => m.includes('UNLIMITED'))).toEqual([]); + }); + + it('a settings-bound plugin whose settings read fails takes the built-in bound, not no limit', async () => { + const settings = fakeSettings({ ...MANIFEST_DEFAULTS }, {}); + settings.getNamespace = async () => { throw new Error('settings store unreachable'); }; + const { routes, infos } = await bootPlugin(settings); + expectTooLarge(await call(routes, 'POST', `${BASE}/upload/presigned`, { + body: { filename: 'over.bin', mimeType: 'application/octet-stream', size: OVER }, + })); + expect(infos.find((m) => m.includes(`(${BUILT_IN} bytes)`))).toContain('built-in default'); + }); + + it('a saved value that is not a positive number is dropped to the host option, else the built-in bound — never to no limit', async () => { + const bad = () => fakeSettings({ ...MANIFEST_DEFAULTS, max_upload_mb: 'lots' }, { max_upload_mb: 'global' }); + const builtIn = await bootPlugin(bad()); + expectTooLarge(await call(builtIn.routes, 'POST', `${BASE}/upload/presigned`, { + body: { filename: 'over.bin', mimeType: 'application/octet-stream', size: OVER }, + })); + expect(builtIn.warns.some((m) => m.includes("'max_upload_mb'"))).toBe(true); + + const host = await bootPlugin(bad(), { maxUploadMb: 5 }); + expectTooLarge(await call(host.routes, 'POST', `${BASE}/upload/presigned`, { + body: { filename: 'over.bin', mimeType: 'application/octet-stream', size: 5 * MIB + 1 }, + })); + }); + + it('mountStorageRoutes over a bare adapter, and over an unbound plugin\'s service, refuses 101 MB', async () => { + for (const storage of [ + new LocalStorageAdapter({ rootDir: await tmpRoot(), signingSecret: 'test-secret-bound' }), + new SwappableStorageService(new LocalStorageAdapter({ rootDir: await tmpRoot(), signingSecret: 'test-secret-bound' })), + ]) { + const kernel = new ObjectKernel({ skipSystemValidation: true, gracefulShutdown: false } as never); + kernel.registerService('storage', storage); + const { http, routes } = routeCollector(); + const infos: string[] = []; + mountStorageRoutes(http, kernel, { basePath: BASE, logger: { info: (m) => { infos.push(m); }, warn: () => {} } }); + expectTooLarge(await call(routes, 'POST', `${BASE}/upload/presigned`, { + body: { filename: 'over.bin', mimeType: 'application/octet-stream', size: OVER }, + })); + expect(infos.find((m) => m.includes(`(${BUILT_IN} bytes)`))).toContain('built-in default'); + } + }); + }); + + describe('the host option is a layer, exactly like the TTLs', () => { + it('on the plugin it overrides the manifest default, and a saved setting still wins over it', async () => { + const unsaved = await bootPlugin(fakeSettings({ ...MANIFEST_DEFAULTS }, {}), { maxUploadMb: 200 }); + expect((await call(unsaved.routes, 'POST', `${BASE}/upload/presigned`, { + body: { filename: 'big.bin', mimeType: 'application/octet-stream', size: 150 * MIB }, + })).status).toBe(200); + expectTooLarge(await call(unsaved.routes, 'POST', `${BASE}/upload/presigned`, { + body: { filename: 'over.bin', mimeType: 'application/octet-stream', size: 200 * MIB + 1 }, + })); + expect(unsaved.infos.find((m) => m.includes(`(${200 * MIB} bytes)`))).toContain('host option'); + + const savedWins = await bootPlugin( + fakeSettings({ ...MANIFEST_DEFAULTS, max_upload_mb: 1 }, { max_upload_mb: 'global' }), + { maxUploadMb: 'unlimited' }, + ); + expectTooLarge(await call(savedWins.routes, 'POST', `${BASE}/upload/presigned`, { + body: { filename: 'a.bin', mimeType: 'application/octet-stream', size: MIB + 1 }, + })); + expect(savedWins.infos.find((m) => m.includes(`(${MIB} bytes)`))).toContain('saved setting'); + expect(savedWins.warns.filter((m) => m.includes('UNLIMITED'))).toEqual([]); + }); + + it('on mountStorageRoutes it bounds that mount\'s doors', async () => { + const kernel = new ObjectKernel({ skipSystemValidation: true, gracefulShutdown: false } as never); + kernel.registerService('storage', new LocalStorageAdapter({ rootDir: await tmpRoot(), signingSecret: 'test-secret-bound' })); + const { http, routes } = routeCollector(); + mountStorageRoutes(http, kernel, { basePath: BASE, maxUploadMb: 1, logger: { info: () => {}, warn: () => {} } }); + expectTooLarge(await call(routes, 'POST', `${BASE}/upload/presigned`, { + body: { filename: 'a.bin', mimeType: 'application/octet-stream', size: MIB + 1 }, + })); + expect((await call(routes, 'POST', `${BASE}/upload/presigned`, { + body: { filename: 'a.bin', mimeType: 'application/octet-stream', size: MIB }, + })).status).toBe(200); + }); + }); + + describe('no limit is an explicit host choice, honoured and announced', () => { + it('mountStorageRoutes with no logger still announces \'unlimited\' at warn, on console', async () => { + const kernel = new ObjectKernel({ skipSystemValidation: true, gracefulShutdown: false } as never); + kernel.registerService('storage', new LocalStorageAdapter({ rootDir: await tmpRoot(), signingSecret: 'test-secret-bound' })); + const consoleWarn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + mountStorageRoutes(routeCollector().http, kernel, { basePath: BASE, maxUploadMb: 'unlimited' }); + expect(consoleWarn.mock.calls.filter(([m]) => String(m).includes('UNLIMITED'))).toHaveLength(1); + // CONTROL — a bounded mount with no logger says nothing on console.warn. + consoleWarn.mockClear(); + mountStorageRoutes(routeCollector().http, kernel, { basePath: BASE }); + expect(consoleWarn).not.toHaveBeenCalled(); + }); + + it('registerStorageRoutes announces the bound in force: \'unlimited\' at warn, with a logger or, without one, on console', async () => { + const adapter = new LocalStorageAdapter({ rootDir: await tmpRoot(), signingSecret: 'test-secret-bound' }); + const warns: string[] = []; + const infos: string[] = []; + const logger = { info: (m: string) => { infos.push(m); }, warn: (m: string) => { warns.push(m); } }; + registerStorageRoutes(routeCollector().http, adapter, new StorageMetadataStore(null), { maxUploadMb: 'unlimited', logger }); + expect(warns.filter((m) => m.includes('UNLIMITED'))).toHaveLength(1); + + const consoleWarn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + registerStorageRoutes(routeCollector().http, adapter, new StorageMetadataStore(null), { maxUploadMb: 'unlimited' }); + expect(consoleWarn.mock.calls.filter(([m]) => String(m).includes('UNLIMITED'))).toHaveLength(1); + + // CONTROL — a bounded registration names its bound and layer to the logger, and nothing goes to console.warn. + consoleWarn.mockClear(); + registerStorageRoutes(routeCollector().http, adapter, new StorageMetadataStore(null), { logger }); + registerStorageRoutes(routeCollector().http, adapter, new StorageMetadataStore(null)); + expect(infos.find((m) => m.includes(`(${BUILT_IN} bytes)`))).toContain('built-in default'); + expect(consoleWarn).not.toHaveBeenCalled(); + }); + + it('the plugin: maxUploadMb \'unlimited\' accepts any size, and boot says so at warn', async () => { + const { routes, warns, infos } = await bootPlugin(null, { maxUploadMb: 'unlimited' }); + expect((await call(routes, 'POST', `${BASE}/upload/presigned`, { + body: { filename: 'huge.bin', mimeType: 'application/octet-stream', size: 1024 * MIB }, + })).status).toBe(200); + const announced = warns.filter((m) => m.includes('UNLIMITED')); + expect(announced).toHaveLength(1); + expect(announced[0]).toContain("'unlimited'"); + expect(infos.filter((m) => m.includes('upload size bound'))).toEqual([]); + }); + + it('mountStorageRoutes: maxUploadMb \'unlimited\' is announced at warn by the mount', async () => { + const kernel = new ObjectKernel({ skipSystemValidation: true, gracefulShutdown: false } as never); + kernel.registerService('storage', new LocalStorageAdapter({ rootDir: await tmpRoot(), signingSecret: 'test-secret-bound' })); + const { http, routes } = routeCollector(); + const warns: string[] = []; + mountStorageRoutes(http, kernel, { + basePath: BASE, + maxUploadMb: 'unlimited', + logger: { info: () => {}, warn: (m) => { warns.push(m); } }, + }); + expect(warns.filter((m) => m.includes('UNLIMITED'))).toHaveLength(1); + expect((await call(routes, 'POST', `${BASE}/upload/presigned`, { + body: { filename: 'huge.bin', mimeType: 'application/octet-stream', size: 1024 * MIB }, + })).status).toBe(200); + }); + }); + + it('a malformed host option refuses the boot — the plugin, the host mount and the route registrar alike', async () => { + // The numeric arm's two edges: too small to bound one byte, and too large to be a finite byte bound. + const malformed: unknown[] = [ + 0, -1, Number.NaN, Number.POSITIVE_INFINITY, 1e-9, Number.MAX_VALUE, '100', 'Unlimited', 'none', null, true, {}, + ]; + const kernel = new ObjectKernel({ skipSystemValidation: true, gracefulShutdown: false } as never); + kernel.registerService('storage', new LocalStorageAdapter({ rootDir: await tmpRoot(), signingSecret: 'test-secret-bound' })); + for (const bad of malformed) { + expect(() => new StorageServicePlugin({ maxUploadMb: bad as never }), String(bad)).toThrow(InvalidMaxUploadMbError); + const host = routeCollector(); + expect(() => mountStorageRoutes(host.http, kernel, { maxUploadMb: bad as never }), String(bad)).toThrow(InvalidMaxUploadMbError); + expect(host.routes.size).toBe(0); + const direct = routeCollector(); + expect( + () => registerStorageRoutes(direct.http, new LocalStorageAdapter({ rootDir: tmpdir(), signingSecret: 's' }), new StorageMetadataStore(null), { + maxUploadMb: bad as never, + }), + String(bad), + ).toThrow(InvalidMaxUploadMbError); + expect(direct.routes.size).toBe(0); + } + // The file verbs judge a host bound handed to them directly, too. + for (const bad of [0, 1e-9, Number.MAX_VALUE, '100']) { + const deps = { + getEngine: () => null, + getStorage: () => null, + getLimitsSnapshot: () => undefined, + hostMaxUploadMb: bad as never, + logger: { warn: () => {}, info: () => {}, error: () => {}, debug: () => {} } as never, + }; + expect(() => new FieldFileService(deps as never), String(bad)).toThrow(InvalidMaxUploadMbError); + expect(() => new FileAttachmentService(deps as never), String(bad)).toThrow(InvalidMaxUploadMbError); + } + // CONTROL — the well-formed spellings construct, down to a bound of exactly one byte. + expect(() => new StorageServicePlugin({ maxUploadMb: 0.5 })).not.toThrow(); + expect(() => new StorageServicePlugin({ maxUploadMb: 1 / MIB })).not.toThrow(); + expect(resolveStorageLimits(undefined, { maxUploadMb: 1 / MIB }).maxUploadBytes).toBe(1); + expect(() => new StorageServicePlugin({ maxUploadMb: 'unlimited' })).not.toThrow(); + }); +}); + +describe('with no settings bound, a 101 MB body is refused at every byte door, declared or not', () => { + it('local raw PUT: a declared 101 MB is refused unread; an undeclared one is read under the built-in bound and refused', async () => { + const { adapter, routes } = await mountDoors(undefined); + const presigned = await call(routes, 'POST', `${BASE}/upload/presigned`, { + body: { filename: 'r.bin', mimeType: 'application/octet-stream', size: 10 }, + }); + const token = String(presigned.body.data.uploadUrl).split('/_local/raw/')[1]!; + const upload = vi.spyOn(adapter, 'upload'); + const unread = vi.fn(async () => Buffer.alloc(10)); + expectTooLarge(await call(routes, 'PUT', `${BASE}/_local/raw/:token`, { + params: { token }, + headers: { 'content-length': String(OVER) }, + rawBody: unread, + })); + expect(unread).not.toHaveBeenCalled(); + const undeclared = boundedRawBody(OVER); + expectTooLarge(await call(routes, 'PUT', `${BASE}/_local/raw/:token`, { params: { token }, rawBody: undeclared.rawBody })); + expect(undeclared.asked).toEqual([BUILT_IN]); + expect(upload).not.toHaveBeenCalled(); + }); + + it('chunk PUT: a declared 101 MB chunk is refused unread; an undeclared one is read under the built-in bound and refused', async () => { + const { adapter, store, routes } = await mountDoors(undefined); + const started = await call(routes, 'POST', `${BASE}/upload/chunked`, { + body: { filename: 'c.bin', mimeType: 'application/octet-stream', totalSize: BUILT_IN }, + }); + expect(started.status).toBe(200); + const { uploadId, resumeToken } = started.body.data; + const uploadChunk = vi.spyOn(adapter, 'uploadChunk'); + const chunk = (rawBody: (o?: { maxBytes?: number }) => Promise, headers: Record = {}) => + call(routes, 'PUT', `${BASE}/upload/chunked/:uploadId/chunk/:chunkIndex`, { + params: { uploadId, chunkIndex: '0' }, + headers: { 'x-resume-token': resumeToken, ...headers }, + rawBody, + }); + const unread = vi.fn(async () => Buffer.alloc(10)); + expectTooLarge(await chunk(unread, { 'content-length': String(OVER) })); + expect(unread).not.toHaveBeenCalled(); + const undeclared = boundedRawBody(OVER); + expectTooLarge(await chunk(undeclared.rawBody)); + expect(undeclared.asked).toEqual([BUILT_IN]); + expect(uploadChunk).not.toHaveBeenCalled(); + expect((await store.getSession(uploadId))?.uploaded_size ?? 0).toBe(0); + }); + + it('upload-link PUT, one file: a declared 101 MB is refused unread; an undeclared one is read under the built-in bound and refused', async () => { + const { routes, consumeUploadLink } = await mountLinkDoor(1); + const put = (rawBody: (o?: { maxBytes?: number }) => Promise, headers: Record = {}) => + call(routes, 'PUT', `${BASE}/upload-links/:token`, { + params: { token: 'link.token' }, + headers: { 'content-type': 'application/pdf', 'x-file-name': 'scan.pdf', ...headers }, + rawBody, + }); + const unread = vi.fn(async () => Buffer.alloc(10)); + expectTooLarge(await put(unread, { 'content-length': String(OVER) })); + expect(unread).not.toHaveBeenCalled(); + const undeclared = boundedRawBody(OVER); + expectTooLarge(await put(undeclared.rawBody)); + expect(undeclared.asked).toEqual([BUILT_IN]); + expect(consumeUploadLink).not.toHaveBeenCalled(); + // CONTROL — a body within the bound reaches the link. + expect((await put(boundedRawBody(10).rawBody)).status).toBe(200); + expect(consumeUploadLink).toHaveBeenCalledTimes(1); + }); + + it('upload-link PUT, the several-file form: over its form limit (each file within the built-in bound) is refused, declared or not', async () => { + const { routes, consumeUploadLinkFiles } = await mountLinkDoor(2); + const formLimit = BUILT_IN * 2 + 64 * 1024; + /** The form's refusal names its form limit, not the setting: status and code are the claim. */ + const expectFormTooLarge = (answer: Answer) => { + expect(answer.status).toBe(413); + expect(answer.body?.error?.code).toBe('PAYLOAD_TOO_LARGE'); + }; + const unread = vi.fn(async () => Buffer.alloc(10)); + expectFormTooLarge(await putTakenOverForm(routes, unread, { 'content-length': String(formLimit + 1) })); + expect(unread).not.toHaveBeenCalled(); + const undeclared = boundedRawBody(formLimit + 1); + expectFormTooLarge(await putTakenOverForm(routes, undeclared.rawBody)); + expect(undeclared.asked).toEqual([formLimit]); + expect(consumeUploadLinkFiles).not.toHaveBeenCalled(); + }); + + it('CONTROL · with the host\'s explicit unlimited, the upload-link door relays a host size refusal in its own words', async () => { + const { routes } = await mountLinkDoor(1, { maxUploadMb: 'unlimited' }); + const hostRefusal = boundedRawBody(OVER); + const host = vi.fn(async (options?: { maxBytes?: number }) => { + hostRefusal.asked.push(options?.maxBytes); + throw Object.assign(new Error('the host refused this body for size'), { status: 413, code: 'PAYLOAD_TOO_LARGE' }); + }); + const answer = await call(routes, 'PUT', `${BASE}/upload-links/:token`, { + params: { token: 'link.token' }, + headers: { 'content-type': 'application/pdf', 'x-file-name': 'scan.pdf' }, + rawBody: host, + }); + expect(answer.status).toBe(413); + expect(answer.body?.error?.code).toBe('PAYLOAD_TOO_LARGE'); + expect(answer.body?.error?.message).toBe('the host refused this body for size'); + expect(hostRefusal.asked).toEqual([undefined]); + }); +}); + +describe('with no settings bound, the server-side file verbs refuse a 101 MB file at the built-in bound', () => { + let file: Buffer | undefined; + const overFile = () => (file ??= Buffer.alloc(OVER)); + afterAll(() => { file = undefined; }); + + it('field-files storeFile: 413 PAYLOAD_TOO_LARGE before the engine or the store is reached; the host\'s unlimited lets it through', async () => { + const verb = (hostMaxUploadMb?: 'unlimited') => + new FieldFileService({ + getEngine: () => unreachable() as never, + getStorage: () => unreachable() as never, + getLimitsSnapshot: () => undefined, + hostMaxUploadMb, + logger: { warn: () => {}, info: () => {}, error: () => {}, debug: () => {} } as never, + }); + const input = { organizationId: 'org_a', filename: 'big.pdf', mimeType: 'application/pdf', data: overFile() }; + expect(await refusalOf(verb().storeFile(input))).toMatchObject({ code: 'PAYLOAD_TOO_LARGE', status: 413 }); + // CONTROL — past the size verdict, the verb reaches the engine. + expect((await refusalOf(verb('unlimited').storeFile(input)))?.message).toContain('reached past the size verdict'); + }); + + it('file-attachments attachFile: 413 PAYLOAD_TOO_LARGE before the engine or the store is reached; the host\'s unlimited lets it through', async () => { + const verb = (hostMaxUploadMb?: 'unlimited') => + new FileAttachmentService({ + getEngine: () => unreachable() as never, + getStorage: () => unreachable() as never, + getLimitsSnapshot: () => undefined, + hostMaxUploadMb, + logger: { warn: () => {} }, + }); + const input = { + parentObject: 'att_case', + parentId: 'case_a', + organizationId: 'org_a', + filename: 'big.eml', + mimeType: 'message/rfc822', + data: overFile(), + }; + expect(await refusalOf(verb().attachFile(input))).toMatchObject({ code: 'PAYLOAD_TOO_LARGE', status: 413 }); + expect((await refusalOf(verb('unlimited').attachFile(input)))?.message).toContain('reached past the size verdict'); + }); +}); diff --git a/packages/services/service-storage/src/storage-limits.ts b/packages/services/service-storage/src/storage-limits.ts index 8c3629eca62..9ffe93f2716 100644 --- a/packages/services/service-storage/src/storage-limits.ts +++ b/packages/services/service-storage/src/storage-limits.ts @@ -13,17 +13,18 @@ * plugin's mount and a host's `mountStorageRoutes` mount cannot answer the * same question two ways. * - * ## Precedence — measured from this plugin's adapter keys, and followed + * ## Precedence — one order, the same for all three keys * * Per key, highest first: * * 1. an AUTHORED value — an admin save or an env override (any `source` * other than `'default'`); - * 2. the HOST's option (`presignedTtl` / `sessionTtl` on the plugin's - * constructor, or on `mountStorageRoutes`); + * 2. the HOST's option (`presignedTtl` / `sessionTtl` / `maxUploadMb` on the + * plugin's constructor, or on `mountStorageRoutes`); * 3. the cascade's DEFAULT (the manifest default, `source: 'default'`); * 4. the built-in default below — what a mount with no settings namespace - * bound (a bare kernel, `bindToSettings: false`) has always used. + * bound (a bare kernel, `bindToSettings: false`, a settings read that + * failed) uses. * * That is exactly how the adapter keys already behave: an authored save * rebuilds the adapter over the constructor's (`buildAdapterFromValues`), while @@ -31,10 +32,15 @@ * nobody chose does not override a host decision; a decision an admin made * does. * - * `max_upload_mb` has no host option, so its layers are 1, 3 and 4 — and layer - * 4 is NO limit. A mount bound to the settings namespace therefore enforces the - * declared default (100 MB) when nothing is saved; a mount with no namespace - * bound keeps accepting any size, as it always did. + * ## The upload bound is never unset + * + * `max_upload_mb` follows the same four layers, and layer 4 is + * {@link DEFAULT_MAX_UPLOAD_MB} — the number the manifest declares, so a mount + * with no settings bound enforces what a settings-bound mount enforces when + * nothing is saved. Unset never means unlimited: a dropped value, a settings + * read that failed and a mount with no namespace all land on a bound. No + * limit is something only a host can ask for, by name + * (`maxUploadMb: 'unlimited'`), and the boot line says so at `warn`. * * ## Read when used, never frozen * @@ -79,14 +85,30 @@ export interface ResolvedStorageLimits { presignedTtl: number; /** Chunked upload session lifetime, in seconds. */ sessionTtl: number; - /** Largest upload accepted, in bytes; `undefined` ⇒ no limit (no settings namespace bound). */ + /** + * Largest upload accepted, in bytes; `undefined` ⇒ no limit, which only an + * explicit host `maxUploadMb: 'unlimited'` (under no saved value) resolves to. + */ maxUploadBytes: number | undefined; + /** Which layer the upload bound came from — named by the boot line. */ + maxUploadLayer: StorageLimitLayer; } +/** The four layers of the precedence, as the boot line names them. */ +export type StorageLimitLayer = 'saved setting' | 'host option' | 'manifest default' | 'built-in default'; + +/** The one spelling a host uses to ask for no upload bound. */ +export const UNLIMITED_UPLOAD = 'unlimited'; + +/** A host's upload bound: a positive number of MB (MiB), or {@link UNLIMITED_UPLOAD}. */ +export type HostMaxUploadMb = number | typeof UNLIMITED_UPLOAD; + /** The host-side layer: the options a mount was composed with. */ export interface StorageLimitHostOptions { presignedTtl?: number; sessionTtl?: number; + /** Validated by {@link parseHostMaxUploadMb} before it reaches here. */ + maxUploadMb?: HostMaxUploadMb; } /** Built-in presigned URL TTL (seconds) — the manifest default carries the same number. */ @@ -94,9 +116,58 @@ export const DEFAULT_PRESIGNED_TTL = 3600; /** Built-in upload session TTL (seconds) — the manifest default carries the same number. */ export const DEFAULT_SESSION_TTL = 86400; +/** + * Built-in upload bound (MB) — the manifest's declared `max_upload_mb` default, + * held equal to it by a drift pin (`storage-limits.test.ts`). + */ +export const DEFAULT_MAX_UPLOAD_MB = 100; + /** Bytes in one MB of `max_upload_mb`. */ export const BYTES_PER_UPLOAD_MB = 1024 * 1024; +/** A host's `maxUploadMb` that is neither a positive number nor {@link UNLIMITED_UPLOAD}. */ +export class InvalidMaxUploadMbError extends Error { + constructor(where: string, raw: unknown) { + super( + `${where}: \`maxUploadMb\` is ${describeRaw(raw)}, which is not an upload bound. Pass a positive ` + + `number of MB (counted as MiB), or '${UNLIMITED_UPLOAD}' to accept uploads of any size. Leave it ` + + `out to take the storage setting, or else the built-in ${DEFAULT_MAX_UPLOAD_MB} MB.`, + ); + this.name = 'InvalidMaxUploadMbError'; + } +} + +function describeRaw(raw: unknown): string { + if (typeof raw === 'number') return String(raw); + try { + return JSON.stringify(raw) ?? String(raw); + } catch { + return String(raw); + } +} + +/** + * A host's `maxUploadMb`, strictly: absent, a positive NUMBER whose bound in + * bytes is finite and at least one byte, or exactly {@link UNLIMITED_UPLOAD}. + * Anything else throws {@link InvalidMaxUploadMbError} — the boot is refused + * rather than a bound guessed. A numeric string is refused too: a host option + * is code, not a form post. The byte edge is judged on the floored byte count + * the doors enforce, so a number too small to bound one byte, or too large to + * be a finite bound, is refused rather than read as "refuse everything" or as + * an unannounced "no bound". + */ +export function parseHostMaxUploadMb(raw: unknown, where: string): HostMaxUploadMb | undefined { + if (raw === undefined) return undefined; + if (raw === UNLIMITED_UPLOAD) return UNLIMITED_UPLOAD; + if (typeof raw === 'number' && raw > 0 && isByteBound(Math.floor(raw * BYTES_PER_UPLOAD_MB))) return raw; + throw new InvalidMaxUploadMbError(where, raw); +} + +/** A bound the doors can enforce: a finite whole number of bytes, at least one. */ +function isByteBound(bytes: number): boolean { + return Number.isFinite(bytes) && bytes >= 1; +} + /** The three keys, their snapshot field, and the unit a warning names. */ const LIMIT_KEYS = [ { key: 'presigned_ttl', field: 'presignedTtl', unit: 'seconds', whole: true }, @@ -155,26 +226,85 @@ export function readStorageLimits( return snapshot; } -function pickTtl(reading: StorageLimitReading | undefined, host: number | undefined, builtIn: number): number { - if (reading?.authored) return reading.value; - if (host !== undefined) return host; - if (reading) return reading.value; - return builtIn; +/** One key through the four layers: the value, and the layer it came from. */ +function pickLayer( + reading: StorageLimitReading | undefined, + host: T | undefined, + builtIn: number, +): { value: number | T; layer: StorageLimitLayer } { + if (reading?.authored) return { value: reading.value, layer: 'saved setting' }; + if (host !== undefined) return { value: host, layer: 'host option' }; + if (reading) return { value: reading.value, layer: 'manifest default' }; + return { value: builtIn, layer: 'built-in default' }; } -/** Resolve the limits a request is served under — see the module header for the precedence. */ +/** + * Resolve the limits a request is served under — see the module header for the + * precedence. `host.maxUploadMb` is taken as given: every door that accepts + * one from a host (the plugin, `mountStorageRoutes`, `registerStorageRoutes`, + * the file verbs) has passed it through {@link parseHostMaxUploadMb} first. + */ export function resolveStorageLimits( snapshot: StorageLimitsSnapshot | undefined, host: StorageLimitHostOptions = {}, ): ResolvedStorageLimits { - const maxMb = snapshot?.maxUploadMb?.value; + const upload = pickLayer(snapshot?.maxUploadMb, host.maxUploadMb, DEFAULT_MAX_UPLOAD_MB); return { - presignedTtl: pickTtl(snapshot?.presignedTtl, host.presignedTtl, DEFAULT_PRESIGNED_TTL), - sessionTtl: pickTtl(snapshot?.sessionTtl, host.sessionTtl, DEFAULT_SESSION_TTL), - maxUploadBytes: maxMb === undefined ? undefined : Math.floor(maxMb * BYTES_PER_UPLOAD_MB), + presignedTtl: pickLayer(snapshot?.presignedTtl, host.presignedTtl, DEFAULT_PRESIGNED_TTL).value, + sessionTtl: pickLayer(snapshot?.sessionTtl, host.sessionTtl, DEFAULT_SESSION_TTL).value, + maxUploadBytes: + upload.value === UNLIMITED_UPLOAD ? undefined : Math.floor(upload.value * BYTES_PER_UPLOAD_MB), + maxUploadLayer: upload.layer, }; } +/** + * The boot line naming the upload bound in force and the layer it came from. + * `warn` when there is no bound — only an explicit host choice gets there — + * so a deployment that accepts any size says so where it is read. + */ +export function uploadBoundBootLine( + who: string, + limits: ResolvedStorageLimits, +): { level: 'info' | 'warn'; message: string } { + if (limits.maxUploadBytes === undefined) { + return { + level: 'warn', + message: + `${who}: uploads are UNLIMITED — the host passed \`maxUploadMb: '${UNLIMITED_UPLOAD}'\`, so no upload ` + + 'door bounds the size of a file. Pass a number of MB to bound them, or save `max_upload_mb` in the ' + + 'File Storage settings, which wins over the host option.', + }; + } + const mb = Math.round((limits.maxUploadBytes / BYTES_PER_UPLOAD_MB) * 100) / 100; + return { + level: 'info', + message: `${who}: upload size bound is ${mb} MB (${limits.maxUploadBytes} bytes), from the ${limits.maxUploadLayer}.`, + }; +} + +/** + * Say the boot line through a host door's logger. The `warn` for no bound + * never depends on that optional argument: with no logger it goes to + * `console`, the sink the platform's other boot notices fall back to, so an + * explicit `'unlimited'` is announced at every door that accepts it. The + * bounded `info` line goes to the logger when there is one. Called on the + * sink, never as a detached function, so a class-based logger keeps `this`. + */ +export function announceUploadBound( + who: string, + limits: ResolvedStorageLimits, + logger: { info(msg: string): void; warn(msg: string): void } | undefined, +): void { + const line = uploadBoundBootLine(who, limits); + if (line.level === 'warn') { + const sink = logger ?? console; + sink.warn(line.message); + } else { + logger?.info(line.message); + } +} + /** * [#22283] The answer every door that accepts bytes gives a file over the * resolved `max_upload_mb` — before the backend stores a byte and before any @@ -205,7 +335,8 @@ function uploadTooLargeMessage(measured: string, maxUploadBytes: number): string return ( `${measured}, over the maximum upload size of ${mb} MB (${maxUploadBytes} bytes). ` + 'The limit is the "Max upload size (MB)" storage setting (max_upload_mb in the storage settings), ' + - 'which an administrator can change.' + 'which an administrator can change; with nothing saved, the host sets it with the storage plugin\'s ' + + 'maxUploadMb option.' ); } @@ -214,8 +345,8 @@ function uploadTooLargeMessage(measured: string, maxUploadBytes: number): string * otherwise the refusal's message (sent or thrown with * {@link UPLOAD_TOO_LARGE_STATUS} / {@link UPLOAD_TOO_LARGE_CODE}). * - * No limit (`maxUploadBytes` undefined: no settings namespace bound) admits - * any size. `bytes` that is not a finite number cannot be judged and is + * No limit (`maxUploadBytes` undefined: only an explicit host + * `maxUploadMb: 'unlimited'`) admits any size. `bytes` that is not a finite number cannot be judged and is * admitted — the byte-carrying doors judge what they actually receive. * `measured` words the size for the message ("The declared file size is N * bytes"), because each door knows what it measured. diff --git a/packages/services/service-storage/src/storage-routes.ts b/packages/services/service-storage/src/storage-routes.ts index d4d617e9470..9e97dd0ab2f 100644 --- a/packages/services/service-storage/src/storage-routes.ts +++ b/packages/services/service-storage/src/storage-routes.ts @@ -86,10 +86,13 @@ import { uploadLinkCopy, uploadLinkRefusalText, type UploadLinkCopy } from './up // [#23306] The size refusal itself lives there too, beside the limit it // enforces, because a second door asks it: the server-side attach verb. import { + announceUploadBound, + parseHostMaxUploadMb, resolveStorageLimits, uploadSizeRefusal, UPLOAD_TOO_LARGE_CODE, UPLOAD_TOO_LARGE_STATUS, + type HostMaxUploadMb, type ResolvedStorageLimits, type StorageLimitsSnapshot, } from './storage-limits.js'; @@ -319,7 +322,7 @@ function declaredContentLength(req: IHttpRequest): number | undefined { * length is (`IHttpRequest.rawBody`). `{ over: true }` when the read was * refused for passing the `maxBytes` this door stated; any other failure, * a size refusal on a read that stated no bound included, is thrown. With no bound - * (`max_upload_mb` unset) the whole body is read, as before. + * (only a host's explicit `maxUploadMb: 'unlimited'`) the whole body is read. * * `null` when the request offers no raw bytes and its body is not a buffer: * the door answers that it needs a binary body. @@ -415,6 +418,14 @@ export interface StorageRoutesOptions { * `storage.session_ttl` wins over it; the namespace's own default does not. */ sessionTtl?: number; + /** + * The host's upload bound, in MB (counted as MiB), or `'unlimited'` to + * accept uploads of any size. A SAVED `storage.max_upload_mb` wins over it; + * it wins over the namespace's own default; left out, the namespace default + * or else the built-in 100 MB applies. Anything but a positive number or + * `'unlimited'` is refused when the routes are registered. + */ + maxUploadMb?: HostMaxUploadMb; /** * [#22283] The `storage` settings namespace's Limits group as last read — * `presigned_ttl`, `session_ttl` and `max_upload_mb` — asked once per @@ -423,9 +434,9 @@ export interface StorageRoutesOptions { * (`storage-limits.ts`): a saved value wins over these options, these options * win over the namespace default. * - * Absent, or answering `undefined` (no settings namespace bound): the TTLs - * are the options above and NO upload size limit applies — the behaviour - * before the Limits group was honoured. `composeStorageRoutes` binds it from + * Absent, or answering `undefined` (no settings namespace bound): the + * options above apply, else the built-in defaults — the upload bound + * included, which is never unset. `composeStorageRoutes` binds it from * the `storage` service the plugin registers, for both mounts. */ limitsSnapshot?: () => StorageLimitsSnapshot | undefined; @@ -521,7 +532,11 @@ export interface StorageRoutesOptions { * download keeps `presignedTtl`. */ downloadTtl?: number; - /** Optional logger for the one-time open-mode notice. */ + /** + * Optional logger for the one-time notices (open mode, and on + * `registerStorageRoutes` the upload bound in force). Without one, an + * explicit `maxUploadMb: 'unlimited'` is still announced, on `console.warn`. + */ logger?: { info(msg: string): void; warn(msg: string): void }; } @@ -551,6 +566,15 @@ export function registerStorageRoutes( opts: StorageRoutesOptions = {}, ): void { registerStorageFamily(httpServer, storage, store, opts, undefined); + // The direct registrar is a host door too: the upload bound in force is said + // once, and no bound (an explicit `'unlimited'`) at `warn` with or without a + // logger. The two composed mounts say it themselves (the plugin's boot hook, + // `mountStorageRoutes`), so it is said here and not in the family. + announceUploadBound( + 'registerStorageRoutes', + resolveStorageLimits(opts.limitsSnapshot?.(), { maxUploadMb: opts.maxUploadMb as HostMaxUploadMb | undefined }), + opts.logger, + ); } /** @@ -657,10 +681,14 @@ export function registerStorageFamily( // [#22283] The limits THIS request is served under — the saved Limits group // resolved against this mount's own options, asked per request (never // hoisted to registration) so a settings save reaches the next request. + // The host's upload bound is judged once, here: a malformed one refuses the + // mount rather than leave a door with a guessed bound. + const hostMaxUploadMb = parseHostMaxUploadMb(opts.maxUploadMb, 'registerStorageRoutes'); const currentLimits = (): ResolvedStorageLimits => resolveStorageLimits(opts.limitsSnapshot?.(), { presignedTtl: opts.presignedTtl, sessionTtl: opts.sessionTtl, + maxUploadMb: hostMaxUploadMb, }); // [#22283] The size gate every upload door asks before it stores a byte or diff --git a/packages/services/service-storage/src/storage-service-plugin.ts b/packages/services/service-storage/src/storage-service-plugin.ts index fef0602501e..389627aceaa 100644 --- a/packages/services/service-storage/src/storage-service-plugin.ts +++ b/packages/services/service-storage/src/storage-service-plugin.ts @@ -128,6 +128,10 @@ import { readStorageLimits, sameStorageLimits, describeStorageLimits, + parseHostMaxUploadMb, + resolveStorageLimits, + uploadBoundBootLine, + type HostMaxUploadMb, type StorageLimitsSnapshot, } from './storage-limits.js'; @@ -179,6 +183,20 @@ export interface StorageServicePluginOptions { * @default 86400 */ sessionTtl?: number; + /** + * Upload size bound in MB (counted as MiB), or `'unlimited'` to accept + * uploads of any size. + * + * Same precedence as the TTLs: a value SAVED in the `storage` settings + * (`max_upload_mb`) wins over this one, and this one wins over the + * namespace's manifest default. Left out, the namespace default applies, or + * — with no settings bound (`bindToSettings: false`, no settings service, a + * settings read that failed) — the built-in 100 MB. The bound is never unset + * by omission: no limit takes `'unlimited'`, and boot says so at `warn`. + * Anything but a positive number or `'unlimited'` refuses construction. + * @default 100 (via the storage settings, else built in) + */ + maxUploadMb?: HostMaxUploadMb; /** * Bind to the `storage` settings namespace and rebuild the inner * adapter on every `settings:changed` event. Disable to keep the @@ -307,7 +325,9 @@ export class StorageServicePlugin implements Plugin { private pendingSwapMovesStore?: boolean; constructor(options: StorageServicePluginOptions = {}) { - this.options = { adapter: 'local', ...options }; + // Judged here, before any door exists: a malformed bound refuses the boot. + const maxUploadMb = parseHostMaxUploadMb(options.maxUploadMb, 'StorageServicePlugin'); + this.options = { adapter: 'local', ...options, maxUploadMb }; } /** Build a concrete adapter from a values map (settings-derived). */ @@ -418,6 +438,7 @@ export class StorageServicePlugin implements Plugin { getEngine: () => this.attachmentEngine, getStorage: () => storage, getLimitsSnapshot: () => storage.getLimitsSnapshot(), + hostMaxUploadMb: this.options.maxUploadMb, logger: ctx.logger, // The attach rule's verdict for the caller-scoped verbs, resolved per // call, the same two services the `sys_attachment` insert gate asks. @@ -472,6 +493,7 @@ export class StorageServicePlugin implements Plugin { }, getStorage: () => storage, getLimitsSnapshot: () => storage.getLimitsSnapshot(), + hostMaxUploadMb: this.options.maxUploadMb, logger: ctx.logger, }), ); @@ -767,6 +789,7 @@ export class StorageServicePlugin implements Plugin { basePath: this.options.basePath ?? '/api/v1/storage', presignedTtl: this.options.presignedTtl, sessionTtl: this.options.sessionTtl, + maxUploadMb: this.options.maxUploadMb, logger: ctx.logger, }); @@ -1065,6 +1088,21 @@ export class StorageServicePlugin implements Plugin { } }); + // ── The upload bound in force, named once at boot ───────────────── + // Registered after the settings hook above, so it runs after + // `applySettings` has settled (or never ran): the bound it names is the + // one the next upload meets, with the layer it came from. `warn` when there + // is no bound — only an explicit host `maxUploadMb: 'unlimited'` gets there. + ctx.hook('kernel:ready', async () => { + if (!this.storage) return; + const line = uploadBoundBootLine( + 'StorageServicePlugin', + resolveStorageLimits(this.storage.getLimitsSnapshot(), { maxUploadMb: this.options.maxUploadMb }), + ); + if (line.level === 'warn') ctx.logger.warn(line.message); + else ctx.logger.info(line.message); + }); + // ── cloud#3814: no unshared local root under declared replicas ───── // Registered after the hook above, so it runs after `applySettings` has // settled: the adapter in use is decided there, not in `init()` — a @@ -1255,6 +1293,8 @@ export interface StorageRoutesComposition { basePath?: string; presignedTtl?: number; sessionTtl?: number; + /** The host's upload bound — validated by the routes' registration. */ + maxUploadMb?: HostMaxUploadMb; downloadTtl?: number; logger?: { info(msg: string): void; warn(msg: string): void }; } @@ -1333,7 +1373,8 @@ export function composeStorageRoutes( // the same object an adapter save swaps — so both mounts read it from the // one place it is written. Duck-typed like the routes' `verifyToken`: a host // whose `storage` is a bare adapter (no plugin, no settings) has no Limits - // group, and its doors keep their options and no size limit. + // group, and its doors keep their options, else the built-in defaults — the + // upload bound included. const limitsCarrier = composition.storage as { getLimitsSnapshot?: () => StorageLimitsSnapshot | undefined }; const limitsSnapshot = typeof limitsCarrier.getLimitsSnapshot === 'function' ? () => limitsCarrier.getLimitsSnapshot!() @@ -1347,6 +1388,7 @@ export function composeStorageRoutes( basePath, presignedTtl: composition.presignedTtl, sessionTtl: composition.sessionTtl, + maxUploadMb: composition.maxUploadMb, limitsSnapshot, downloadTtl: composition.downloadTtl, resolveSession, diff --git a/packages/services/service-storage/vitest.config.ts b/packages/services/service-storage/vitest.config.ts index 8a9ae91706c..c8881800a0c 100644 --- a/packages/services/service-storage/vitest.config.ts +++ b/packages/services/service-storage/vitest.config.ts @@ -75,11 +75,17 @@ export default defineConfig({ // (cloud#3814): the plugin asks its `declaresMultiReplicaOnRedis` whether // a local root is refused under declared replicas, and that predicate read // from `dist/` would make those pins a verdict about build state. + // + // `@objectstack/service-settings` joins them for the same reason: the + // built-in upload bound is pinned equal to the storage manifest's declared + // `max_upload_mb` default, and a manifest read from `dist/` would make that + // drift pin a verdict about build state. alias: [ { find: /^@objectstack\/core$/, replacement: path.resolve(__dirname, '../../core/src/index.ts') }, { find: /^@objectstack\/driver-sql$/, replacement: path.resolve(__dirname, '../../drivers/driver-sql/src/index.ts') }, { find: /^@objectstack\/plugin-audit$/, replacement: path.resolve(__dirname, '../../plugins/plugin-audit/src/index.ts') }, { find: /^@objectstack\/service-cluster$/, replacement: path.resolve(__dirname, '../service-cluster/src/index.ts') }, + { find: /^@objectstack\/service-settings$/, replacement: path.resolve(__dirname, '../service-settings/src/index.ts') }, ], }, }); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9200dfb19e6..eee49b58b90 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -3410,6 +3410,9 @@ importers: '@objectstack/plugin-audit': specifier: workspace:* version: link:../../plugins/plugin-audit + '@objectstack/service-settings': + specifier: workspace:* + version: link:../service-settings '@types/node': specifier: ^26.6.5 version: 26.6.5