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:
12 files changed
+271
-7
No files matched your search
@@ -6,6 +6,25 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|||||||
green-tea uses calendar versioning: `YY.M.PATCH` — the month is not zero-padded, since
|
green-tea uses calendar versioning: `YY.M.PATCH` — the month is not zero-padded, since
|
||||||
npm treats versions as semver and semver forbids leading zeros.
|
npm treats versions as semver and semver forbids leading zeros.
|
||||||
|
|
||||||
|
## [Unreleased]
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- **`static` no longer serves files outside its root through a symlink** (#106). The traversal guard
|
||||||
|
compared paths lexically, and the file read then followed symlinks, so `public/leak -> /etc/hosts`
|
||||||
|
was served. Containment now compares real paths: the requested file, and a directory's
|
||||||
|
`index.html`, must resolve beneath the root's real path. Links that stay inside the root, and a
|
||||||
|
root that is itself a symlink, keep working.
|
||||||
|
|
||||||
|
A link that resolves outside the root, or a dangling link, is a **404** — the same miss as a file
|
||||||
|
that does not exist, rendered through `onError` like any other, and `405`/`204` where the path has
|
||||||
|
routes. It is deliberately not a `403`, so a probe cannot tell "exists outside the root" from
|
||||||
|
"does not exist". The content-type still follows the requested name, not the link target.
|
||||||
|
|
||||||
|
The root's real path is resolved on the first request and cached, so **re-pointing a root symlink
|
||||||
|
while the app runs needs a restart** to take effect. A link swapped inside the root between the
|
||||||
|
check and the read can still escape; exploiting that needs write access to the served directory.
|
||||||
|
|
||||||
## [26.9.0-beta.2] - 2026-09-22
|
## [26.9.0-beta.2] - 2026-09-22
|
||||||
|
|
||||||
### Breaking
|
### Breaking
|
||||||
|
|||||||
+49
-6
@@ -86,9 +86,40 @@ export interface StaticHit {
|
|||||||
/** Resolves a URL path to a static file under a fixed root, or `undefined` for a miss. */
|
/** Resolves a URL path to a static file under a fixed root, or `undefined` for a miss. */
|
||||||
export type StaticResolver = (urlPath: string) => Promise<StaticHit | undefined>;
|
export type StaticResolver = (urlPath: string) => Promise<StaticHit | undefined>;
|
||||||
|
|
||||||
|
/** The real path of `path` when it is `root` or lies beneath it, else `undefined`. Rejects on ENOENT.
|
||||||
|
* The separator suffix keeps a sibling such as `root-evil` out of `root`. */
|
||||||
|
async function confine(fs: typeof import('node:fs'), sep: string, root: string, path: string) {
|
||||||
|
const real = await fs.promises.realpath(path);
|
||||||
|
return real === root || real.startsWith(root + sep) ? real : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reads `full` (or its `index.html` when a directory) if its real path stays inside the real `root`. */
|
||||||
|
async function readConfined(
|
||||||
|
fs: typeof import('node:fs'),
|
||||||
|
nodePath: typeof import('node:path'),
|
||||||
|
root: string,
|
||||||
|
full: string,
|
||||||
|
): Promise<StaticHit | undefined> {
|
||||||
|
let real = await confine(fs, nodePath.sep, root, full);
|
||||||
|
if (!real) return undefined;
|
||||||
|
const isDir = (await fs.promises.stat(real)).isDirectory();
|
||||||
|
// `index.html` is a second resolution and can itself be a link, so it is confined on its own.
|
||||||
|
if (isDir) real = await confine(fs, nodePath.sep, root, nodePath.join(real, 'index.html'));
|
||||||
|
if (!real) return undefined;
|
||||||
|
// ponytail: a link swapped between `realpath` and `readFile` can still escape. Exploiting it needs
|
||||||
|
// write access inside the served root, which already owns the app; closing it needs `O_NOFOLLOW`
|
||||||
|
// on every path component, which Node, Deno and Bun do not offer portably.
|
||||||
|
const body = await fs.promises.readFile(real);
|
||||||
|
// The content-type follows the requested name, not the link target (`app.js -> app.3f2a.js`).
|
||||||
|
const target = isDir ? nodePath.join(full, 'index.html') : full;
|
||||||
|
return { body, contentType: contentTypeFor(nodePath.extname(target)) };
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Builds a static-file resolver rooted at `root` (`true` → `./public`). Requires a filesystem: throws at
|
* Builds a static-file resolver rooted at `root` (`true` → `./public`). Requires a filesystem: throws at
|
||||||
* boot on a runtime without one (edge). Path-traversal-safe — a resolved path outside the root is a miss.
|
* boot on a runtime without one (edge). Path-traversal-safe — a resolved path outside the root is a miss,
|
||||||
|
* and so is a symlink whose real target lies outside the root's real path (#106). Escapes are misses
|
||||||
|
* (404), not 403, so a probe cannot tell "exists outside the root" from "does not exist".
|
||||||
*/
|
*/
|
||||||
export function buildStaticResolver(root: string | true): StaticResolver {
|
export function buildStaticResolver(root: string | true): StaticResolver {
|
||||||
let fs: typeof import('node:fs');
|
let fs: typeof import('node:fs');
|
||||||
@@ -105,6 +136,18 @@ export function buildStaticResolver(root: string | true): StaticResolver {
|
|||||||
|
|
||||||
const abs = nodePath.resolve(process.cwd(), root === true ? 'public' : root);
|
const abs = nodePath.resolve(process.cwd(), root === true ? 'public' : root);
|
||||||
|
|
||||||
|
// The root's real path, resolved once on the first request rather than at build time, so a missing
|
||||||
|
// `public/` at boot is still not fatal — it just makes every request a miss, as before. Containment
|
||||||
|
// compares real paths, so the root must be real too: a symlinked `public/` would otherwise fail every
|
||||||
|
// check. Cached for the life of the app: re-pointing a root symlink at runtime needs a restart. A failed
|
||||||
|
// lookup is not cached, so a root created after boot starts serving, as it did before.
|
||||||
|
let realRoot: Promise<string | undefined> | undefined;
|
||||||
|
const resolveRoot = () =>
|
||||||
|
(realRoot ??= fs.promises.realpath(abs).catch(() => {
|
||||||
|
realRoot = undefined;
|
||||||
|
return undefined;
|
||||||
|
}));
|
||||||
|
|
||||||
return async (urlPath) => {
|
return async (urlPath) => {
|
||||||
let rel: string;
|
let rel: string;
|
||||||
|
|
||||||
@@ -118,13 +161,13 @@ export function buildStaticResolver(root: string | true): StaticResolver {
|
|||||||
const full = nodePath.resolve(abs, '.' + (rel.startsWith('/') ? rel : '/' + rel));
|
const full = nodePath.resolve(abs, '.' + (rel.startsWith('/') ? rel : '/' + rel));
|
||||||
if (full !== abs && !full.startsWith(abs + nodePath.sep)) return undefined; // traversal guard
|
if (full !== abs && !full.startsWith(abs + nodePath.sep)) return undefined; // traversal guard
|
||||||
|
|
||||||
|
const rootReal = await resolveRoot();
|
||||||
|
if (!rootReal) return undefined;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const stat = await fs.promises.stat(full);
|
return await readConfined(fs, nodePath, rootReal, full);
|
||||||
const target = stat.isDirectory() ? nodePath.join(full, 'index.html') : full;
|
|
||||||
const body = await fs.promises.readFile(target);
|
|
||||||
return { body, contentType: contentTypeFor(nodePath.extname(target)) };
|
|
||||||
} catch {
|
} catch {
|
||||||
return undefined;
|
return undefined; // includes ENOENT from `realpath` on a dangling link: a miss, never a rejection
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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>');
|
||||||
|
});
|
||||||
@@ -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' });
|
assertEquals(await res.json(), { name: 'joe', filename: 'p.png' });
|
||||||
await app.close();
|
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
@@ -0,0 +1 @@
|
|||||||
|
root
|
||||||
Vendored
+1
@@ -0,0 +1 @@
|
|||||||
|
in root
|
||||||
+1
@@ -0,0 +1 @@
|
|||||||
|
../nope.txt
|
||||||
+1
@@ -0,0 +1 @@
|
|||||||
|
a.txt
|
||||||
+1
@@ -0,0 +1 @@
|
|||||||
|
../secret.txt
|
||||||
+1
@@ -0,0 +1 @@
|
|||||||
|
<h1>Sub</h1>
|
||||||
Vendored
+1
@@ -0,0 +1 @@
|
|||||||
|
TOP SECRET
|
||||||
+108
-1
@@ -1,9 +1,11 @@
|
|||||||
import { describe, expect, it } from 'vitest';
|
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 { join } from 'node:path';
|
||||||
import { tmpdir } from 'node:os';
|
import { tmpdir } from 'node:os';
|
||||||
import { createApp, Route, Get, Module } from '../src/index';
|
import { createApp, Route, Get, Module } from '../src/index';
|
||||||
import { buildStaticResolver } from '../src/views';
|
import { buildStaticResolver } from '../src/views';
|
||||||
|
import { isHttpError } from '../src/signals';
|
||||||
|
import type { ErrorRenderer } from '../src/transformers';
|
||||||
|
|
||||||
const root = join(tmpdir(), 'gt-static-test');
|
const root = join(tmpdir(), 'gt-static-test');
|
||||||
mkdirSync(root, { recursive: true });
|
mkdirSync(root, { recursive: true });
|
||||||
@@ -67,3 +69,108 @@ describe('static serving', () => {
|
|||||||
expect(await resolve('/%2e%2e/gt-secret.txt')).toBeUndefined();
|
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');
|
||||||
|
});
|
||||||
Reference in new issue
Block a user