Skip to content

Commit 20d025f

Browse files
fix(service-storage)!: stored bytes outside the inline allow-list are served as attachments, with nosniff and a sandbox CSP (#36518)
Clause-②: no (narrowing) Metadata-protocol: none ## 维护者速读 - 用户在附件、文件下载里打开文件时:图片、PDF、纯文本照常在新标签页里直接预览;音视频会在浏览器的播放器里打开,用户按下播放后开始播放;其余类型(包括 SVG、HTML)改为下载到本地,不再在浏览器里直接打开。 - 这是文件存储加固:用一条规则决定哪些类型可以在浏览器里直接显示,本地存储和 S3 签名链接执行同一条规则。 - 如果有人依赖在浏览器里直接打开 SVG 或网页类附件,现在会变成下载;页面里用图片标签显示的 SVG 不受影响。可以整体撤回本改动。 - 要你做什么:本 PR 申报为收窄,契约审核 PASS 在案,需要授权账号批准当前 head。 ## What changes One rule for answering stored bytes, stated once in `packages/services/service-storage/src/served-bytes-policy.ts` and applied by every door that answers them: 1. **Inline only for the allow-list.** `INLINE_CONTENT_TYPES` holds raster images (PNG, JPEG, GIF, WebP, AVIF, BMP), PDF, plain text, and common audio and video types. - Every other type, SVG and HTML included, is answered as an `attachment`. So is a missing or malformed type. - The type is judged by its essence: case is folded and parameters are dropped. A `charset` is kept on `text/plain` only. - A caller asking for `inline` never overrides the list. 2. **`X-Content-Type-Options: nosniff` on every answer** from the local byte route. 3. **A sandbox `Content-Security-Policy` on every answer** from the local byte route, which lets no script run. - Allow-listed audio and video answered inline carry `sandbox allow-same-origin; default-src 'none'; media-src 'self'; style-src 'unsafe-inline'`, so the browser's player can load the file's own URL. - Every other answer carries `sandbox; default-src 'none'; style-src 'unsafe-inline'`. Doors held to the rule: | Door | Origin | What it does | |---|---|---| | `GET /api/v1/storage/_local/raw/:token` (local adapter) | the app's own | sets type (essence), disposition, `nosniff` and the CSP from the rule | | S3 adapter `getPresignedDownload` (behind `getSignedUrl`, `GET /files/:fileId`, `GET /files/:fileId/url` and the record-file read) | the bucket's | always bakes `ResponseContentType` (essence) and `ResponseContentDisposition`; a signed `GetObject` URL can carry no other response header, so `nosniff` and the CSP are the bucket's to send | `GET /files/:fileId` and `GET /files/:fileId/url` serve no bytes of their own; both mint through `mintDownloadUrl`. Docs and contract text: - `content/docs/permissions/attachments-access.mdx` gains a "How a downloaded file is answered" section, which tells a host that fronts its bucket on the app's own origin to send the two headers at its proxy. - The TSDoc of `PresignedDownloadOptions.disposition` (`packages/spec/src/contracts/storage-service.ts`) now says `inline` is a request the allow-list decides. The change is description-only. Not in this PR: holding a declared type to its bytes. The maintainer ruled it a separate serve-time follow-up. ## Tests - `packages/services/service-storage/src/served-bytes-policy.test.ts`: the allow-list table, essence parsing, the local raw route's headers (both CSP variants as literals), and the S3 signed URL's baked parameters. - `packages/qa/dogfood/test/stored-bytes-served-disposition.dogfood.test.ts`: a real boot with the local adapter. It covers presign, byte PUT, commit, the download door's signed link, and the raw route's answer. - `ui/e2e/live/stored-bytes-inline-allow-list.spec.ts`, in the required Live E2E lane: a browser reads a PNG that renders, a text file that renders, and a WAV that loads in the player, and an HTML file arrives as a download. - Controls: an ordinary PNG and PDF still preview inline. - Every rule pin is red on the base and green on the head. Each guard was ablated and restored. ## Acceptance notes - Measured in Chromium only; Firefox and Safari were not measured. - Under the media policy the player does not start playback on its own; it starts when the user presses play. - An `<img>` that shows a stored SVG keeps showing it: an image element ignores the disposition. ## Verification - CI on the head: every required check is green, including the Live E2E lane with the new spec. - Contract review: PASS on the head (security seat). 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_017xRBcW9L8Noz9BxEwjwiov <!-- signed: security#2 · sunhaolin · session_017xRBcW9L8Noz9BxEwjwiov --> --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: objectstack-fleet[bot] <332303061+objectstack-fleet[bot]@users.noreply.github.com>
1 parent 934ac07 commit 20d025f

11 files changed

Lines changed: 729 additions & 17 deletions

File tree

‎.changeset/sec2-865p.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
---
2+
'@objectstack/service-storage': patch
3+
'@objectstack/spec': patch
4+
---
5+
6+
fix(service-storage)!: stored bytes outside the inline allow-list are served as attachments, and every stored-bytes answer carries nosniff and a sandbox CSP
7+
8+
Clause-②: no (narrowing)
9+
Metadata-protocol: none
10+
11+
<!-- adr-0087: not-required (no-migration-prescription) No key of any schema is added, removed or re-shaped, and no stored row, registry key or authored value changes. What moves is the response headers a downloaded file is answered with; there is nothing for a migration to rewrite. -->
12+
13+
**BREAKING** — how a downloaded file is answered to a browser. One rule, stated once in the storage service and applied by every door that answers stored bytes:
14+
15+
- FROM: a file was answered under the type recorded for it, and rendered in place by default, whatever that type was.
16+
- TO: only a type on the inline allow-list is rendered in place: raster images (PNG, JPEG, GIF, WebP, AVIF, BMP), PDF, plain text, and common audio and video types. Every other type, SVG and HTML included, and a missing or malformed type, is answered as an `attachment`, which the browser saves rather than opens. The type is judged by its essence, and the answered `Content-Type` is that essence: case is folded and parameters are dropped (a `charset` is kept on `text/plain` only), so neither changes the verdict.
17+
- FROM: the local adapter's byte route sent no `X-Content-Type-Options` and no `Content-Security-Policy`.
18+
- TO: every answer from it carries `X-Content-Type-Options: nosniff` and a sandbox `Content-Security-Policy` that lets no script run, inline or not. Allow-listed audio and video answered inline carry a media variant of it, `sandbox allow-same-origin; default-src 'none'; media-src 'self'; style-src 'unsafe-inline'`, so the browser's player can load the file's own URL. Every other answer carries `sandbox; default-src 'none'; style-src 'unsafe-inline'`, which asks the browser for a sandboxed document that runs no script and loads no subresource.
19+
- Measured in Chromium (the Console's download in a new tab, and direct navigation): PNG, PDF and plain text render in place; HTML and SVG are saved. WAV, Ogg, MP3, WebM and MP4 open in the browser's player, which loads the file and starts playback when the user presses play; before this change the player started playback on its own. Firefox and Safari were not measured.
20+
- The S3 adapter's signed download URL always carries the same type and disposition; a call that names no type is signed as `application/octet-stream`, an attachment. A caller's `disposition: 'inline'` no longer overrides the list. A signed `GetObject` URL can set no other response header, so `nosniff` and the CSP are the bucket's to send there.
21+
22+
The fix for a host: nothing to change. A file outside the list still downloads under its own name and type; open it from the saved copy. An `<img>` that shows a stored SVG keeps showing it: an image element ignores the disposition.

‎content/docs/permissions/attachments-access.mdx‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -322,6 +322,20 @@ requires only a signed-in caller (`AUTH_REQUIRED`, 401, otherwise). A browser's
322322
rendering these files. Only a file marked `acl: 'public_read'` is served to a
323323
caller with no session: mark a file that way when it must render before sign-in.
324324

325+
### How a downloaded file is answered
326+
327+
A file opened from its signed URL is rendered in place only when its type is on
328+
the storage service's inline allow-list: raster images (PNG, JPEG, GIF, WebP,
329+
AVIF, BMP), PDF, plain text, and common audio and video types. Every other type,
330+
SVG and HTML included, and a file with no type, is answered as an
331+
`attachment`, so the browser saves it under its name instead of opening it. The
332+
local adapter's byte route sends `X-Content-Type-Options: nosniff` and a sandbox
333+
`Content-Security-Policy` that lets no script run on every answer; audio and video
334+
shown in place carry a media variant of it, so the browser's player can load the
335+
file. This was measured in Chromium. The S3 adapter's signed URL carries the same
336+
type and disposition; the other response headers are the bucket's to send, so a
337+
host that fronts the bucket with its own proxy sends them there.
338+
325339
The upload entry points (presigned / chunked) likewise require a session when
326340
an auth service is wired, and stamp `owner_id` on the new `sys_file`. A stored
327341
file's uploader is the user who created it, as an attachment's is: a
Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
//
3+
// Stored bytes are answered under one rule on a REAL boot with the local
4+
// storage adapter: a type outside the inline allow-list is served as an
5+
// `attachment`, every answer carries `nosniff` and the sandbox CSP, and an
6+
// allow-listed type is still served `inline`.
7+
//
8+
// The package suite (`service-storage/src/served-bytes-policy.test.ts`) pins
9+
// the rule and the S3 signed-URL parameters; this file runs the whole path a
10+
// browser takes — presign, the byte PUT, commit, the download door's signed
11+
// URL, and the raw byte route that answers it — through the real Hono app.
12+
13+
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
14+
import { mkdtempSync } from 'node:fs';
15+
import { join } from 'node:path';
16+
import { tmpdir } from 'node:os';
17+
import { bootStack, type VerifyStack } from '@objectstack/verify';
18+
import { StorageServicePlugin } from '@objectstack/service-storage';
19+
import { attachmentsFixtureStack, attachmentsFixtureSecurity } from './fixtures/attachments-fixture.js';
20+
21+
const PNG = Buffer.from('89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4890000000d4944415478da63f8ffff3f0005fe02fea7d6a6a30000000049454e44ae426082', 'hex');
22+
const PDF = Buffer.from('%PDF-1.4\n1 0 obj<<>>endobj\ntrailer<<>>\n%%EOF\n');
23+
const HTML = Buffer.from('<!doctype html><title>t</title><p>stored page</p>');
24+
const SVG = Buffer.from('<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"><rect width="1" height="1"/></svg>');
25+
const TEXT = Buffer.from('plain words\n');
26+
27+
const SANDBOX_CSP = "sandbox; default-src 'none'; style-src 'unsafe-inline'";
28+
const MEDIA_CSP = "sandbox allow-same-origin; default-src 'none'; media-src 'self'; style-src 'unsafe-inline'";
29+
/** A WAV of `samples` silent 8 kHz mono 8-bit PCM samples. */
30+
function wav(samples: number): Buffer {
31+
const out = Buffer.alloc(44 + samples, 0x80);
32+
out.write('RIFF', 0, 'ascii');
33+
out.writeUInt32LE(36 + samples, 4);
34+
out.write('WAVEfmt ', 8, 'ascii');
35+
out.writeUInt32LE(16, 16);
36+
out.writeUInt16LE(1, 20); // PCM
37+
out.writeUInt16LE(1, 22); // mono
38+
out.writeUInt32LE(8000, 24);
39+
out.writeUInt32LE(8000, 28);
40+
out.writeUInt16LE(1, 32);
41+
out.writeUInt16LE(8, 34);
42+
out.write('data', 36, 'ascii');
43+
out.writeUInt32LE(samples, 40);
44+
return out;
45+
}
46+
const WAV = wav(800);
47+
48+
describe('stored bytes are served by the inline allow-list rule on a real boot', () => {
49+
let stack: VerifyStack;
50+
let token: string;
51+
52+
const authed = (extra: Record<string, string> = {}) => ({ Authorization: `Bearer ${token}`, ...extra });
53+
54+
/** Upload through the presigned door and answer the raw byte route's response for the file. */
55+
async function uploadAndFetch(filename: string, mimeType: string, bytes: Buffer): Promise<Response> {
56+
const presign = await stack.api('/storage/upload/presigned', {
57+
method: 'POST',
58+
headers: authed({ 'Content-Type': 'application/json' }),
59+
body: JSON.stringify({ filename, mimeType, size: bytes.byteLength, scope: 'user' }),
60+
});
61+
expect(presign.status, await presign.clone().text()).toBe(200);
62+
const { data } = (await presign.json()) as any;
63+
64+
const put = await stack.raw(String(data.uploadUrl).replace(/^https?:\/\/[^/]+/, ''), {
65+
method: 'PUT',
66+
headers: { 'content-type': mimeType },
67+
body: new Uint8Array(bytes),
68+
});
69+
expect(put.status, await put.clone().text()).toBeLessThan(300);
70+
71+
const complete = await stack.api('/storage/upload/complete', {
72+
method: 'POST',
73+
headers: authed({ 'Content-Type': 'application/json' }),
74+
body: JSON.stringify({ fileId: data.fileId }),
75+
});
76+
expect(complete.status, await complete.clone().text()).toBe(200);
77+
78+
const link = await stack.api(`/storage/files/${data.fileId}/url`, { headers: authed() });
79+
expect(link.status, await link.clone().text()).toBe(200);
80+
const url = String(((await link.json()) as any).data.url);
81+
// The signed link is the app's own raw byte route: it is answered on the app origin.
82+
expect(url).toMatch(/\/api\/v1\/storage\/_local\/raw\//);
83+
const served = await stack.raw(url.replace(/^https?:\/\/[^/]+/, ''));
84+
expect(served.status).toBe(200);
85+
return served;
86+
}
87+
88+
beforeAll(async () => {
89+
const rootDir = mkdtempSync(join(tmpdir(), 'served-bytes-dogfood-'));
90+
stack = await bootStack(attachmentsFixtureStack as never, {
91+
security: attachmentsFixtureSecurity(),
92+
extraPlugins: [new StorageServicePlugin({ adapter: 'local', local: { rootDir } })],
93+
});
94+
token = await stack.signIn();
95+
}, 120_000);
96+
97+
afterAll(async () => {
98+
await stack?.stop();
99+
});
100+
101+
it('a text/html upload is served as an attachment, with nosniff and the sandbox CSP', async () => {
102+
const res = await uploadAndFetch('page.html', 'text/html', HTML);
103+
expect(res.headers.get('content-disposition')).toMatch(/^attachment;/);
104+
expect(res.headers.get('x-content-type-options')).toBe('nosniff');
105+
expect(res.headers.get('content-security-policy')).toBe(SANDBOX_CSP);
106+
});
107+
108+
it('an image/svg+xml upload is served as an attachment, with nosniff', async () => {
109+
const res = await uploadAndFetch('drawing.svg', 'image/svg+xml', SVG);
110+
expect(res.headers.get('content-disposition')).toMatch(/^attachment;/);
111+
expect(res.headers.get('x-content-type-options')).toBe('nosniff');
112+
});
113+
114+
it('a declared type is answered by its essence, so no spelling of it reaches inline', async () => {
115+
const res = await uploadAndFetch('odd.html', 'Text/HTML ; charset=utf-8', HTML);
116+
expect(res.headers.get('content-type')).toBe('text/html');
117+
expect(res.headers.get('content-disposition')).toMatch(/^attachment;/);
118+
});
119+
120+
it('a declared type that is not a media type is served as opaque bytes, as an attachment', async () => {
121+
const res = await uploadAndFetch('odd.bin', 'not a type', HTML);
122+
expect(res.headers.get('content-type')).toBe('application/octet-stream');
123+
expect(res.headers.get('content-disposition')).toMatch(/^attachment;/);
124+
});
125+
126+
it('control: an ordinary PNG still previews, inline under its own type and bytes', async () => {
127+
const res = await uploadAndFetch('pixel.png', 'image/png', PNG);
128+
expect(res.headers.get('content-type')).toBe('image/png');
129+
expect(res.headers.get('content-disposition')).toMatch(/^inline;/);
130+
expect(Buffer.from(await res.arrayBuffer()).equals(PNG), 'the stored bytes, unchanged').toBe(true);
131+
});
132+
133+
it('an allow-listed audio file is served inline, with nosniff and the media policy', async () => {
134+
const res = await uploadAndFetch('tone.wav', 'audio/wav', WAV);
135+
expect(res.headers.get('content-type')).toBe('audio/wav');
136+
expect(res.headers.get('content-disposition')).toMatch(/^inline;/);
137+
expect(res.headers.get('x-content-type-options')).toBe('nosniff');
138+
expect(res.headers.get('content-security-policy')).toBe(MEDIA_CSP);
139+
});
140+
141+
it('an allow-listed PNG, PDF or plain text is served inline, with nosniff and the sandbox CSP', async () => {
142+
for (const [name, type, bytes] of [['pixel.png', 'image/png', PNG], ['doc.pdf', 'application/pdf', PDF], ['notes.txt', 'text/plain', TEXT]] as const) {
143+
const res = await uploadAndFetch(name, type, bytes);
144+
expect(res.headers.get('content-type'), name).toBe(type);
145+
expect(res.headers.get('content-disposition'), name).toMatch(/^inline;/);
146+
expect(res.headers.get('x-content-type-options'), name).toBe('nosniff');
147+
expect(res.headers.get('content-security-policy'), name).toBe(SANDBOX_CSP);
148+
}
149+
});
150+
});

‎packages/services/service-storage/src/content-disposition.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,10 @@
55
*
66
* Emits both a sanitized ASCII `filename=` (legacy fallback) and the RFC 5987
77
* `filename*=UTF-8''…` form that modern browsers prefer — so a download saves
8-
* under its real name instead of the opaque URL token. Used by the local
9-
* adapter's `_local/raw` route (header) and the S3 adapter's
10-
* `ResponseContentDisposition` (baked into the signed URL).
8+
* under its real name instead of the opaque URL token. Called through
9+
* `served-bytes-policy.ts`, which decides the disposition for every door that
10+
* answers stored bytes (the local `_local/raw` route's header and the S3
11+
* adapter's `ResponseContentDisposition`); a door never picks it itself.
1112
*/
1213
export function contentDispositionValue(
1314
filename: string,

‎packages/services/service-storage/src/s3-storage-adapter.ts‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ import {
2020
encodeStorageListCursor,
2121
resolveStorageListLimit,
2222
} from '@objectstack/spec/contracts';
23-
import { contentDispositionValue } from './content-disposition.js';
23+
import { servedContentDisposition, servedContentType } from './served-bytes-policy.js';
2424

2525
/**
2626
* Hard ceiling `ListObjectsV2` applies to `MaxKeys`, regardless of what the
@@ -575,13 +575,14 @@ export class S3StorageAdapter implements IStorageService {
575575
const { getSignedUrl } = await this.presignerMod();
576576
// S3 bakes these response overrides into the signed URL, so the download
577577
// carries the real filename + type instead of the object key + octet-stream.
578+
// Both are always baked, by the stored-bytes rule (`served-bytes-policy.ts`).
579+
// A signed `GetObject` URL can set no other response header, so `nosniff`
580+
// and the CSP are the bucket's to send.
578581
const cmd = new s3.GetObjectCommand({
579582
Bucket: this.bucket,
580583
Key: this.storageKey(key),
581-
...(options?.contentType ? { ResponseContentType: options.contentType } : {}),
582-
...(options?.filename
583-
? { ResponseContentDisposition: contentDispositionValue(options.filename, options.disposition ?? 'inline') }
584-
: {}),
584+
ResponseContentType: servedContentType(options?.contentType),
585+
ResponseContentDisposition: servedContentDisposition(options?.contentType, options?.filename, options?.disposition),
585586
});
586587
const url = await getSignedUrl(client, cmd, { expiresIn });
587588
return { downloadUrl: url, expiresIn };

0 commit comments

Comments
 (0)