fix(trust-fence): accept a bfcache-restored image with a stale cross-site marker

Chromium can restore a same-origin image subresource from bfcache while the
request still carries `Sec-Fetch-Site: cross-site`. The fence refused every
cross-site marker outright, so /sidebar/file answered 403 and the image
preview stayed blank until the tab was reloaded. Reproduced on a real
`dsh web` instance: the same URL returns 200 image/png normally and 403 once
the cross-site marker is present with no Origin.

The exception is deliberately narrow — GET /sidebar/file only, browser image
subresources only (`Sec-Fetch-Mode: no-cors` + `Sec-Fetch-Dest: image`), and
the unforgeable Referer must name the request's exact authority. `Sec-Fetch-*`
and `Referer` are forbidden request headers, so a foreign page cannot forge
them. API requests, non-GET media, non-image subresources, CORS image reads,
foreign/look-alike/malformed Referers and Referer-less requests stay refused,
and the existing Origin hostname check is unchanged.

tests/trusted-hosts.spec.ts covers the accepted loopback and trusted-remote
cases plus the refusal matrix over real GET /sidebar/file requests.
This commit is contained in:
Pluto-Yt committed 2026-09-15 10:47:30 +08:00
1 parent 1fcf43ccbe
commit 32e8f56c4a
2 files changed
+115 -12

No files matched your search

+27 -2
View File
@@ -12,6 +12,9 @@ import type { IncomingHttpHeaders } from 'node:http'
/** The request facts the fence reads (structural subset of IncomingMessage). */
interface ApiTrustRequest {
headers: IncomingHttpHeaders
/** Present on a real node request; the bfcache exception is media-route only. */
method?: string
url?: string
}
function header(headers: IncomingHttpHeaders, name: string): string | undefined {
@@ -56,7 +59,8 @@ function isTrustedAuthority(hostUrl: URL, trustedHosts: readonly string[]): bool
/**
* Decide whether one sidebar request may reach the plugin routes.
* @param request - node HTTP request facts (headers).
* @param request - node HTTP request facts (headers, and the method/url the
* media-route exception is scoped to).
* @param trustedHosts - non-loopback authorities this deployment serves.
* @returns true when the Host is ours (loopback or trusted) and browser markers are same-origin.
*/
@@ -66,7 +70,28 @@ export function isTrustedApiRequest(request: ApiTrustRequest, trustedHosts: read
const hostUrl = parseAuthority(host)
if (hostUrl === undefined) return false
if (!isLoopbackHostname(hostUrl.hostname) && !isTrustedAuthority(hostUrl, trustedHosts)) return false
if (header(request.headers, 'sec-fetch-site') === 'cross-site') return false
const fetchSite = header(request.headers, 'sec-fetch-site')
if (fetchSite === 'cross-site') {
// Chromium can restore a same-origin image from bfcache with a stale
// cross-site marker. The exception is deliberately narrow: the media route
// only, browser image subresources only (`no-cors` + `image`), and the
// unforgeable Referer must name this exact authority. API requests, uploads,
// HTML previews, foreign embeds and Referer-less requests stay refused.
const referer = header(request.headers, 'referer')
const mediaRequest = request.method === 'GET' && (request.url ?? '').startsWith('/sidebar/file')
const restoredImage = mediaRequest
&& header(request.headers, 'sec-fetch-mode') === 'no-cors'
&& header(request.headers, 'sec-fetch-dest') === 'image'
&& referer !== undefined
&& (() => {
try {
return new URL(referer).host === hostUrl.host
} catch {
return false
}
})()
if (!restoredImage) return false
}
// Origin fence: when a browser attaches an Origin it must name this
// hostname (the Host fence above already bound the authority, so the port
// must not re-decide trust). Comparing hostname, not host: some Chromium
+88 -10
View File
@@ -10,7 +10,10 @@
* every remote /sidebar request was 403 "forbidden".
*/
import { describe, expect, it } from 'vitest'
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import type { IncomingMessage, ServerResponse } from 'node:http'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { apply } from '../src/index.ts'
import type { SidebarWebRoute, SidebarWebUpgradeRoute } from '../src/context-types.ts'
@@ -57,6 +60,7 @@ function req(
/** Mount apply() against a fake context with a replaceable webRuntime trust list. */
function mount(initialTrustedHosts: readonly string[] = []): {
api: (r: IncomingMessage, s: ServerResponse) => Promise<void>
media: (r: IncomingMessage, s: ServerResponse) => Promise<void>
setTrustedHosts: (hosts: readonly string[]) => void
cleanup: () => void
} {
@@ -84,8 +88,11 @@ function mount(initialTrustedHosts: readonly string[] = []): {
apply(ctx as never)
const api = routes.find(route => route.path === '/sidebar/api')?.handler
if (api === undefined) throw new Error('test setup: /sidebar/api route not registered')
const media = routes.find(route => route.path === '/sidebar/file')?.handler
if (media === undefined) throw new Error('test setup: /sidebar/file route not registered')
return {
api: api as (r: IncomingMessage, s: ServerResponse) => Promise<void>,
media: media as (r: IncomingMessage, s: ServerResponse) => Promise<void>,
setTrustedHosts: (hosts) => { runtime.trustedHosts = [...hosts] },
cleanup: () => { for (const cleanup of effects) cleanup() },
}
@@ -198,23 +205,94 @@ describe('remote-access trust (webRuntime.trustedHosts)', () => {
}
})
it('rejects cross-site browser markers even for a trusted host', async () => {
const { api, cleanup } = mount(['example.com'])
/**
* The four headers a same-origin `<img>` carries after Chromium restores it
* from bfcache: the stale cross-site marker plus the real Referer. The
* `Sec-Fetch-*` and `Referer` headers are forbidden request headers, so a
* foreign page cannot forge them.
*/
function restoredImageHeaders(host: string, referer: string): Record<string, string> {
return {
host,
'sec-fetch-site': 'cross-site',
'sec-fetch-mode': 'no-cors',
'sec-fetch-dest': 'image',
referer,
}
}
/** One real GET /sidebar/file for a temp PNG with `headers` on the request. */
async function mediaRequestWith(
headers: Record<string, string>,
trustedHosts: readonly string[] = [],
): Promise<{ status: number; headers: Record<string, string> }> {
const directory = mkdtempSync(join(tmpdir(), 'dsh-sidebar-fence-'))
const file = join(directory, 'shot.png')
writeFileSync(file, Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))
const { media, cleanup } = mount(trustedHosts)
try {
const query = new URLSearchParams({ sessionId: 'test-session', cwd: directory, path: file }).toString()
const res = fakeRes()
// Same-origin origin: only the explicit cross-site marker can reject —
// this pins the marker branch (a mismatched origin would also 403).
await api(req('POST', '/sidebar/api/session.cwd', {
host: 'example.com',
'sec-fetch-site': 'cross-site',
origin: 'https://example.com',
}, '{"sessionId":"test-session"}'), res as unknown as ServerResponse)
expect(res.status).toBe(403)
await media(req('GET', `/sidebar/file?${query}`, headers), res as unknown as ServerResponse)
return { status: res.status, headers: res.headers }
} finally {
cleanup()
rmSync(directory, { recursive: true, force: true })
}
}
it('accepts a restored same-origin image on the media route (Chromium stale cross-site marker)', async () => {
const res = await mediaRequestWith(restoredImageHeaders('127.0.0.1:3080', 'http://127.0.0.1:3080/'))
expect(res.status).toBe(200)
expect(res.headers['content-type']).toBe('image/png')
})
it('accepts the same restored image on a trusted remote host', async () => {
const res = await mediaRequestWith(restoredImageHeaders('example.com', 'https://example.com/'), ['example.com'])
expect(res.status).toBe(200)
})
it('refuses a cross-site image without a Referer', async () => {
const headers = restoredImageHeaders('127.0.0.1:3080', 'http://127.0.0.1:3080/')
delete headers.referer
expect((await mediaRequestWith(headers)).status).toBe(403)
})
it.each([
['a non-image no-cors subresource', { ...restoredImageHeaders('127.0.0.1:3080', 'http://127.0.0.1:3080/'), 'sec-fetch-dest': 'script' }],
['a CORS image read', { ...restoredImageHeaders('127.0.0.1:3080', 'http://127.0.0.1:3080/'), 'sec-fetch-mode': 'cors' }],
['a foreign Referer', restoredImageHeaders('127.0.0.1:3080', 'https://attacker.invalid/')],
['a look-alike Referer host', restoredImageHeaders('127.0.0.1:3080', 'http://127.0.0.1.attacker.invalid/')],
['a userinfo-spoofed Referer', restoredImageHeaders('127.0.0.1:3080', 'http://127.0.0.1@attacker.invalid/')],
['a malformed Referer', restoredImageHeaders('127.0.0.1:3080', 'null')],
['a Referer on a different port', restoredImageHeaders('127.0.0.1:3080', 'http://127.0.0.1:9999/')],
['a Referer naming localhost instead of the Host', restoredImageHeaders('127.0.0.1:3080', 'http://localhost:3080/')],
])('refuses a restored image carrying %s', async (_case, headers) => {
expect((await mediaRequestWith(headers)).status).toBe(403)
})
it('still refuses a matching-Referer image whose Origin is foreign or opaque', async () => {
const base = restoredImageHeaders('127.0.0.1:3080', 'http://127.0.0.1:3080/')
expect((await mediaRequestWith({ ...base, origin: 'https://attacker.invalid' })).status).toBe(403)
expect((await mediaRequestWith({ ...base, origin: 'null' })).status).toBe(403)
})
it('keeps the exception off the API and non-GET media paths', async () => {
const headers = restoredImageHeaders('127.0.0.1:3080', 'http://127.0.0.1:3080/')
const { api, media, cleanup } = mount([])
try {
const onApi = fakeRes()
await api(req('POST', '/sidebar/api/session.cwd', headers, '{"sessionId":"test-session"}'), onApi as unknown as ServerResponse)
expect(onApi.status).toBe(403)
const onMediaPost = fakeRes()
await media(req('POST', '/sidebar/file', headers, ''), onMediaPost as unknown as ServerResponse)
expect(onMediaPost.status).toBe(403)
} finally {
cleanup()
}
})
it('reads webRuntime.trustedHosts per request, not once at apply', async () => {
const { api, setTrustedHosts, cleanup } = mount([])
try {