fix(views): confine static serving to the root's real path

The static resolver's traversal guard compared paths lexically, and the
read that followed it resolved symlinks, so a link inside the root such
as `public/leak -> /etc/hosts` served a file outside it.

Containment now compares real paths. The root's real path is resolved
on the first request and cached (a failed lookup is not, so a root
created after boot still starts serving); the requested file and a
directory's `index.html` are each realpath'd and must lie at or beneath
it, with the `root + sep` rule keeping a sibling such as `root-evil`
out. The lexical guard stays in front, since it rejects `..` without a
syscall.

An escape or a dangling link is a plain miss: 404 through `onError`, or
405/204 where the path has routes. Not 403, so a probe cannot tell a
file outside the root from one that does not exist. Re-pointing a root
symlink at runtime needs a restart. The realpath-to-read race is left
open and marked; closing it needs per-component O_NOFOLLOW, which is
not portable across Node, Deno and Bun.

Closes #106

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-10-09 13:59:03 -05:00
1 parent 42376c6693
commit 53660adcce
12 files changed
+271 -7

No files matched your search

+51
View File
@@ -0,0 +1,51 @@
// Static-file confinement (#106) under the real Bun runtime, which reaches `realpath` through its
// `node:fs` compat — a third implementation of symlink resolution, so not something to assume from
// the Node suite.
//
// Run with: npm run test:bun
import 'reflect-metadata';
import { test, expect } from 'bun:test';
import { mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { createApp } from '../../src/index.ts';
const base = mkdtempSync(join(tmpdir(), 'gt-static-bun-'));
const root = join(base, 'root');
mkdirSync(join(root, 'sub'), { recursive: true });
writeFileSync(join(root, 'a.txt'), 'in root');
writeFileSync(join(root, 'sub', 'index.html'), '<h1>Sub</h1>');
writeFileSync(join(base, 'secret.txt'), 'TOP SECRET');
symlinkSync('a.txt', join(root, 'in-link'));
symlinkSync('../secret.txt', join(root, 'out-link'));
symlinkSync('../nope.txt', join(root, 'dangling'));
symlinkSync('root', join(base, 'root-alias'));
const app = createApp({ modules: [], static: root });
const get = (path: string) => app.fetch(new Request(`http://x${path}`));
test('static on Bun: a link to a file outside the root is a miss', async () => {
const res = await get('/out-link');
expect(res.status).toBe(404);
expect(await res.text()).not.toContain('TOP SECRET');
});
test('static on Bun: a link to a file inside the root is served', async () => {
const res = await get('/in-link');
expect(res.status).toBe(200);
expect(await res.text()).toBe('in root');
});
test('static on Bun: a dangling link is a 404, not a rejection', async () => {
expect((await get('/dangling')).status).toBe(404);
});
test('static on Bun: a root that is itself a symlink still serves its files', async () => {
const aliased = createApp({ modules: [], static: join(base, 'root-alias') });
const a = await aliased.fetch(new Request('http://x/a.txt'));
expect(a.status).toBe(200);
expect(await a.text()).toBe('in root');
const sub = await aliased.fetch(new Request('http://x/sub/'));
expect(sub.status).toBe(200);
expect(await sub.text()).toBe('<h1>Sub</h1>');
});
+37
View File
@@ -74,3 +74,40 @@ Deno.test('multipart resolves the busboy peer dependency instead of reporting it
assertEquals(await res.json(), { name: 'joe', filename: 'p.png' });
await app.close();
});
// #106 on Deno, which reaches `realpath` through its `node:fs` compat. Committed symlinks rather than
// a temp tree, for the same `--allow-write` reason as above; `secret.txt` sits beside the root.
const linked = 'test/fixtures/static';
Deno.test('static: a link to a file outside the root is a miss', async () => {
const app = createApp({ modules: [], static: `${linked}/root` });
const res = await app.fetch(new Request('http://x/out-link'));
assertEquals(res.status, 404);
assertEquals((await res.text()).includes('TOP SECRET'), false);
await app.close();
});
Deno.test('static: a link to a file inside the root is served', async () => {
const app = createApp({ modules: [], static: `${linked}/root` });
const res = await app.fetch(new Request('http://x/in-link'));
assertEquals(res.status, 200);
assertEquals(await res.text(), 'in root');
await app.close();
});
Deno.test('static: a dangling link is a 404, not a rejection', async () => {
const app = createApp({ modules: [], static: `${linked}/root` });
assertEquals((await app.fetch(new Request('http://x/dangling'))).status, 404);
await app.close();
});
Deno.test('static: a root that is itself a symlink still serves its files', async () => {
const app = createApp({ modules: [], static: `${linked}/root-alias` });
const a = await app.fetch(new Request('http://x/a.txt'));
assertEquals(a.status, 200);
assertEquals(await a.text(), 'in root');
const sub = await app.fetch(new Request('http://x/sub/'));
assertEquals(sub.status, 200);
assertEquals(await sub.text(), '<h1>Sub</h1>');
await app.close();
});
+1
View File
@@ -0,0 +1 @@
root
+1
View File
@@ -0,0 +1 @@
in root
+1
View File
@@ -0,0 +1 @@
../nope.txt
+1
View File
@@ -0,0 +1 @@
a.txt
+1
View File
@@ -0,0 +1 @@
../secret.txt
+1
View File
@@ -0,0 +1 @@
<h1>Sub</h1>
+1
View File
@@ -0,0 +1 @@
TOP SECRET
+108 -1
View File
@@ -1,9 +1,11 @@
import { describe, expect, it } from 'vitest';
import { writeFileSync, mkdirSync } from 'node:fs';
import { writeFileSync, mkdirSync, mkdtempSync, symlinkSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { createApp, Route, Get, Module } from '../src/index';
import { buildStaticResolver } from '../src/views';
import { isHttpError } from '../src/signals';
import type { ErrorRenderer } from '../src/transformers';
const root = join(tmpdir(), 'gt-static-test');
mkdirSync(root, { recursive: true });
@@ -67,3 +69,108 @@ describe('static serving', () => {
expect(await resolve('/%2e%2e/gt-secret.txt')).toBeUndefined();
});
});
// #106: the traversal guard above is lexical, and `stat`/`readFile` follow symlinks, so a link
// inside the root could serve a file outside it. Confinement has to compare real paths. On macOS
// `tmpdir()` is itself behind a symlink (`/var` → `/private/var`), so every case below also
// exercises a root whose lexical and real paths differ.
describe('static serving confined to the real root (#106)', () => {
const base = mkdtempSync(join(tmpdir(), 'gt-static-real-'));
const sroot = join(base, 'root');
mkdirSync(join(sroot, 'sub'), { recursive: true });
mkdirSync(join(sroot, 'idx'));
mkdirSync(join(base, 'root-evil'));
mkdirSync(join(base, 'outside'));
writeFileSync(join(sroot, 'a.txt'), 'in root');
writeFileSync(join(sroot, 'sub', 'index.html'), '<h1>Sub</h1>');
writeFileSync(join(base, 'root-evil', 'x.txt'), 'SIBLING');
writeFileSync(join(base, 'secret.txt'), 'TOP SECRET');
writeFileSync(join(base, 'outside', 's.txt'), 'OUTSIDE');
// Windows without the symlink privilege refuses to create links; the cases that need them skip
// there rather than pass vacuously.
let symlinks = true;
try {
symlinkSync('a.txt', join(sroot, 'in-link'));
symlinkSync('../secret.txt', join(sroot, 'out-link'));
symlinkSync('../outside', join(sroot, 'dir-link'));
symlinkSync('../nope.txt', join(sroot, 'dangling'));
symlinkSync('../root-evil/x.txt', join(sroot, 'evil-link'));
symlinkSync('../../secret.txt', join(sroot, 'idx', 'index.html'));
symlinkSync('root', join(base, 'root-alias'));
} catch (err) {
if ((err as NodeJS.ErrnoException).code !== 'EPERM') throw err;
symlinks = false;
}
const withLinks = it.skipIf(!symlinks);
const app = createApp({ modules: [], static: sroot });
const get = (path: string) => app.fetch(new Request(`http://x${path}`));
withLinks('T1: does not serve a link to a file outside the root', async () => {
const res = await get('/out-link');
expect(res.status).toBe(404);
expect(await res.text()).not.toContain('TOP SECRET');
});
withLinks('T2: serves a link to a file inside the root', async () => {
const res = await get('/in-link');
expect(res.status).toBe(200);
expect(await res.text()).toBe('in root');
});
withLinks('T3: a symlinked directory cannot expose an out-of-root file', async () => {
expect((await get('/dir-link/s.txt')).status).toBe(404);
});
it('T4: a sibling-prefix directory is not reachable by traversal', async () => {
expect((await get('/../root-evil/x.txt')).status).toBe(404);
expect((await get('/%2e%2e/root-evil/x.txt')).status).toBe(404);
});
withLinks('T5: a real path in a sibling-prefix directory is outside the root', async () => {
const resolve = buildStaticResolver(sroot);
expect(await resolve('/../root-evil/x.txt')).toBeUndefined();
// Passes the lexical guard, then really lands in `root-evil` — only the `root + sep` rule on the
// real path stops it.
expect(await resolve('/evil-link')).toBeUndefined();
});
withLinks('T6: a dangling link is a miss, not a rejection', async () => {
await expect(buildStaticResolver(sroot)('/dangling')).resolves.toBeUndefined();
expect((await get('/dangling')).status).toBe(404);
});
withLinks('T7: a directory index that links outside the root is a miss', async () => {
const res = await get('/idx/');
expect(res.status).toBe(404);
expect(await res.text()).not.toContain('TOP SECRET');
});
withLinks('T8: a root that is itself a symlink still serves its files', async () => {
const aliased = createApp({ modules: [], static: join(base, 'root-alias') });
const a = await aliased.fetch(new Request('http://x/a.txt'));
expect(a.status).toBe(200);
expect(await a.text()).toBe('in root');
const sub = await aliased.fetch(new Request('http://x/sub/'));
expect(sub.status).toBe(200);
expect(await sub.text()).toBe('<h1>Sub</h1>');
});
withLinks('T10: an escape renders through onError exactly like a plain miss', async () => {
const onError: ErrorRenderer = (error) => ({
status: isHttpError(error) ? error.status : 500,
headers: { 'content-type': 'text/html' },
body: `<h1>${isHttpError(error) ? error.status : 500}</h1>`,
});
const custom = createApp({ modules: [], static: sroot, onError });
const escape = await custom.fetch(new Request('http://x/out-link'));
const miss = await custom.fetch(new Request('http://x/nope.txt'));
expect(escape.status).toBe(404);
expect(escape.headers.get('content-type')).toBe('text/html');
expect(await escape.text()).toBe(await miss.text());
});
});
it('a root created after the first request starts serving without a restart', async () => {
const late = join(mkdtempSync(join(tmpdir(), 'gt-static-late-')), 'public');
const resolve = buildStaticResolver(late);
expect(await resolve('/a.txt')).toBeUndefined();
mkdirSync(late);
writeFileSync(join(late, 'a.txt'), 'late');
expect((await resolve('/a.txt'))?.body.toString()).toBe('late');
});