Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,10 +103,13 @@ The number after each rule is the PR where it was raised.
- Base corpus-shaped tests on real markup from the docs, not simplified examples. (#13, #28)
- Back every documented invariant with a test that pins it. (#48, #53, #54)
- Run any change that widens strict validation against the real corpus in strict mode before merging. (#50)
- Name a test file after the module it covers (`archive.test.ts`), never after the PR or the batch it came from. (#232)

### Security and content handling

- Fail closed: reject ambiguous or unsafe input, and throw when a size or shape can't be determined, instead of assuming it's safe. (#28, #51)
- Refuse up front the input an upstream is known to reject, and treat its error statuses as failures (503) rather than misses (404): a crawler reads a 404 as gone and a 503 as try again. Never let a response produced from an error be cached. (#232)
- When a reader tolerates one bad item, it keeps that item's last good value instead of dropping it, and refuses the refresh when nothing good is left for an item the site depends on. (#232)
- CSS alone never gates or hides content. If gating is incomplete, say so. (#28, #49)
- Surface authoring defects at sync or build time rather than swallowing errors at runtime. (#28, #44)
- When scanning HTML, treat raw-text elements (`script`, `style`, `textarea`, `title`) as text, and keep that list the same in every scanner. (#52, #53)
Expand Down
123 changes: 118 additions & 5 deletions apps/router/lib/archive-handler.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import assert from "node:assert/strict";
import { mock, test } from "node:test";
import { DOCS_CONTENT_SECURITY_POLICY, docsContentSecurityPolicy } from "@coder/docs-config";
import { type ManifestReader, lineKey, parseManifestItems } from "@coder/docs-manifest";
import {
type ManifestReader,
createManifestReader,
lineKey,
parseManifestItems,
} from "@coder/docs-manifest";
import { createArchiveHandler } from "./archive-handler.js";
import type { Getter } from "./archive.js";

const DEPLOYMENT = "https://coder-docs-versions-abc123-codercom.vercel.app";
const PREFIX = "versions/2.36/5627dae63cb058e4c0b4f3eb2019437ad3c268ce";
Expand All @@ -11,7 +17,7 @@ const MAINLINE_PREFIX = `versions/2.37/${"a".repeat(40)}`;
const MAINLINE_DEPLOYMENT = `https://abc123.private.blob.vercel-storage.com/${MAINLINE_PREFIX}`;
const SHORT_LIVED = "public, max-age=0, s-maxage=60, stale-while-revalidate=300";

const manifest = parseManifestItems({
const items: Record<string, unknown> = {
[lineKey("2.37")]: {
id: "2.37",
label: "v2.37",
Expand All @@ -37,7 +43,8 @@ const manifest = parseManifestItems({
publishedAt: "2026-09-04T10:17:00Z",
},
mainline: "2.37",
});
};
const manifest = parseManifestItems(items);
const reader: ManifestReader = { read: async () => ({ manifest, fetchedAt: Date.now() }) };

type Stored = { body: string; contentType: string; etag: string };
Expand Down Expand Up @@ -100,14 +107,20 @@ const storeWithoutNotFound = Object.fromEntries(
);

function handlerWith(
getter = fakeGet(store),
overrides: { reader?: ManifestReader; basePath?: string; headersTimeoutMs?: number } = {},
getter: { get: Getter; calls: string[] } = fakeGet(store),
overrides: {
reader?: ManifestReader;
basePath?: string;
headersTimeoutMs?: number;
now?: () => number;
} = {},
) {
const handler = createArchiveHandler({
getReader: () => overrides.reader ?? reader,
get: () => getter.get,
basePath: overrides.basePath,
headersTimeoutMs: overrides.headersTimeoutMs,
now: overrides.now,
});
return { handler, calls: getter.calls };
}
Expand Down Expand Up @@ -496,6 +509,81 @@ test("a store failure degrades to a 503 that is never cached", async () => {
assert.equal(await response.text(), "Documentation is temporarily unavailable.");
});

/** A store that refuses `refused` keys with `status` and holds nothing else. */
function refusingGet(status: string, refused: (key: string) => boolean) {
const calls: string[] = [];
const get: Getter = async (pathname) => {
calls.push(pathname);
if (refused(pathname)) throw new Error(`Vercel Blob: Failed to fetch blob: ${status}`);
return null;
};
return { get, calls };
}

test("a store 400 or 414 on an ordinary key is a 503 that is never cached, logged once a minute with the key's shape", async () => {
for (const status of ["400 Bad Request", "414 URI Too Long"]) {
const error = mock.method(console, "error", () => {});
try {
let now = 0;
const { handler } = handlerWith(
refusingGet(status, () => true),
{ now: () => now },
);
const request = () => new Request("https://docs.example/@2.36/admin/");
const first = await handler(request());
assert.equal(first.status, 503, status);
assert.equal(first.headers.get("cache-control"), "no-store", status);
await handler(request());
assert.equal(error.mock.callCount(), 1, status);
const logged = error.mock.calls[0]?.arguments.map(String).join(" ") ?? "";
assert.match(logged, /length \d+/, status);
assert.doesNotMatch(logged, /admin/, status);
now += 60_000;
await handler(request());
assert.equal(error.mock.callCount(), 2, status);
} finally {
error.mock.restore();
}
}
});

test("any other 4xx from the store is a 503 that is never cached, not a miss", async () => {
const error = mock.method(console, "error", () => {});
try {
for (const status of [
"401 Unauthorized",
"402 Payment Required",
"403 Forbidden",
"408 Request Timeout",
"410 Gone",
"429 Too Many Requests",
"451 Unavailable For Legal Reasons",
]) {
const { handler } = handlerWith(refusingGet(status, () => true));
const response = await handler(new Request("https://docs.example/@2.36/admin/"));
assert.equal(response.status, 503, status);
assert.equal(response.headers.get("cache-control"), "no-store", status);
}
} finally {
error.mock.restore();
}
});

test("a store refusal of a version's redirects object is logged and the miss is never cached", async () => {
const error = mock.method(console, "error", () => {});
try {
const { handler } = handlerWith(
refusingGet("400 Bad Request", (key) => key.endsWith("/_redirects.json")),
);
const response = await handler(new Request("https://docs.example/@2.36/gone/"));
assert.equal(response.status, 404);
assert.equal(response.headers.get("cache-control"), "no-store");
assert.ok(error.mock.callCount() >= 1);
} finally {
error.mock.restore();
}
});

test("a manifest failure degrades to the same 503", async () => {
const { handler } = handlerWith(fakeGet(store), {
reader: {
Expand Down Expand Up @@ -622,3 +710,28 @@ test("the sitemap is served from the mainline at the base path, as XML, and from
"the request went to 2.36's own archive, not the mainline's",
);
});

test("a version a cold reader dropped as malformed gets a not-found page that is never cached", async () => {
const error = mock.method(console, "error", () => {});
try {
const cold = createManifestReader({
getAll: async () => ({
...items,
[lineKey("2.36")]: { ...(items[lineKey("2.36")] as object), sha: "not-a-sha" },
}),
onInvalidItem: () => {},
});
const { handler } = handlerWith(fakeGet(store), { reader: cold });
const dropped = await handler(new Request("https://docs.example/@2.36/admin/"));
assert.equal(dropped.status, 404);
assert.equal(dropped.headers.get("cache-control"), "no-store");
const unknown = await handler(new Request("https://docs.example/@2.30/admin/"));
assert.equal(unknown.status, 404);
assert.equal(unknown.headers.get("cache-control"), SHORT_LIVED);
const mainline = await handler(new Request("https://docs.example/"));
assert.equal(mainline.status, 200);
assert.equal(mainline.headers.get("cache-control"), SHORT_LIVED);
} finally {
error.mock.restore();
}
});
31 changes: 30 additions & 1 deletion apps/router/lib/archive-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@ import {
versionSegment,
normalizeRouterBasePath,
isVersionShapedSegment,
namesDegradedVersion,
resolveRoute,
} from "@coder/docs-manifest";
import {
type Getter,
isArchiveDeployment,
isStoreKeyRefusal,
serveArchive,
serveNotFoundPage,
setCacheRule,
Expand Down Expand Up @@ -44,6 +46,12 @@ export interface ArchiveHandlerDeps {
now?: () => number;
}

/** A path's shape for a log line, without the path itself. */
function keyShape(path: string): string {
const encoded = (path.match(/%[0-9A-Fa-f]{2}/g) ?? []).length;
return `length ${path.length}, ${path.split("/").length - 1} segments, ${encoded} percent-escapes`;
}

/** A target `redirectResponse` refuses is answered as a miss, never as a 500. */
export async function redirectOrNotFound(
location: string,
Expand Down Expand Up @@ -76,6 +84,8 @@ export function createArchiveHandler(
archive: () => ({ get: deps.get(), headersTimeoutMs: deps.headersTimeoutMs }),
now: deps.now,
});
const now = deps.now ?? Date.now;
let keyRefusalLoggedAt = Number.NEGATIVE_INFINITY;
return async (request) => {
// The archive only ever answers reads; refuse anything else before the
// manifest or the store is consulted.
Expand Down Expand Up @@ -137,7 +147,15 @@ export function createArchiveHandler(
// The literal root with nothing to serve there (no mainline published, or
// a base path that puts the site elsewhere) keeps its placeholder; any
// other unresolved path is an unknown version.
if (!target) return pathname === "/" ? placeholderResponse() : notFound();
if (!target) {
if (pathname === "/") return placeholderResponse();
const response = await notFound();
// Other isolates may still serve a version this one dropped as malformed.
if (namesDegradedVersion(pathname, manifest, { basePath })) {
setCacheRule(response.headers, "no-store");
}
return response;
}
// An item written before every version moved to the archive may still name
// a Vercel deployment; the router fetches from no such origin, so it is
// treated as unpublished.
Expand Down Expand Up @@ -227,6 +245,17 @@ export function createArchiveHandler(
if (probeFailed) setCacheRule(response.headers, "no-store");
return response;
} catch (error) {
if (isStoreKeyRefusal(error)) {
// One hostile key and a broken token look alike, so the line carries the key's shape, rate-limited.
if (now() - keyRefusalLoggedAt >= 60_000) {
keyRefusalLoggedAt = now();
console.error(
`docs-router: the store refused a key (${keyShape(target.path)}; logged once a minute)`,
error,
);
}
return unavailableResponse();
}
// A store outage or an expired OIDC token must not 500 every archived
// path; degrade to the same unavailable response a manifest outage
// gets, but log it distinctly so an operator is not sent chasing the
Expand Down
52 changes: 52 additions & 0 deletions apps/router/lib/archive.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -347,3 +347,55 @@ test("the llms index files resolve as objects under their version's own prefix",
assert.equal(headers.get("content-type"), "text/plain; charset=utf-8");
assert.equal(headers.get("x-content-type-options"), "nosniff");
});

test("the publisher's and build's root objects are never served, however the name is spelled", async () => {
const prefix = "versions/2.36/5627dae63cb058e4c0b4f3eb2019437ad3c268ce";
const object = { body: "{}", contentType: "application/json", etag: '"b1"' };
const { get, calls } = fakeGet({
[`${prefix}/_publish.json`]: object,
[`${prefix}/_objects.json`]: object,
[`${prefix}/_redirects.json`]: object,
[`${prefix}/%5Fobjects.json`]: object,
[`${prefix}/%5fobjects.json`]: object,
[`${prefix}/%E0%A4%A.json`]: object,
[`${prefix}/_next/static/a.js`]: { ...object, contentType: "text/javascript" },
});
for (const path of [
"/_publish.json",
"/_objects.json",
"/_redirects.json",
"/%5Fobjects.json",
"/%5fobjects.json",
"/%E0%A4%A.json",
]) {
const target = { deployment, path, versionId: "2.36" };
assert.equal(
await serveArchive(target, new Request("https://docs.example/x"), { get }),
null,
path,
);
}
assert.deepEqual(calls, []);
const asset = await serveArchive(
{ deployment, path: "/_next/static/a.js", versionId: "2.36" },
new Request("https://docs.example/x"),
{ get },
);
assert.equal(asset?.status, 200);
});

test("a key the store would refuse (a control character, or over its 950-character limit) is refused before any store call", async () => {
const { get, calls } = fakeGet({});
const longest = (length: number) => {
const base = archiveKey({ deployment, path: "/.js", versionId: "2.36" }).key.length;
return `/${"a".repeat(length - base)}.js`;
};
for (const path of ["/a%00b/", "/a%0Ab/", "/a%1Fb.js", "/a%7Fb.js", longest(951)]) {
const target = { deployment, path, versionId: "2.36" };
assert.equal(await serveArchive(target, new Request("https://docs.example/x"), { get }), null);
}
assert.deepEqual(calls, []);
const target = { deployment, path: longest(950), versionId: "2.36" };
assert.equal(await serveArchive(target, new Request("https://docs.example/x"), { get }), null);
assert.equal(calls.length, 1);
});
36 changes: 36 additions & 0 deletions apps/router/lib/archive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,18 @@ export const STORE_HEADERS_TIMEOUT_MS = 10_000;
type GetOptions = Parameters<Getter>[1];
export type ArchiveDeps = { get: Getter; headersTimeoutMs?: number };

// The statuses the store answers for a key it cannot take; still failures, since a broken token gets a 400 too.
const KEY_REFUSAL_STATUSES = new Set([400, 414]);
// `@vercel/blob`'s MAXIMUM_PATHNAME_LENGTH, which it does not export: no stored key is longer.
const MAX_KEY_LENGTH = 950;

/** Whether the store refused the requested key itself; the SDK carries the status only in the message. */
export function isStoreKeyRefusal(error: unknown): boolean {
const match =
error instanceof Error ? /Failed to fetch blob: (\d{3})\b/.exec(error.message) : null;
return match !== null && KEY_REFUSAL_STATUSES.has(Number(match[1]));
}

/**
* `get`, cancelled when the client disconnects (for the whole read, body
* included) or when the store has not answered within the headers timeout.
Expand Down Expand Up @@ -265,6 +277,19 @@ export async function readVersionRedirectsText(
return text === null ? { kind: "too-large", reportedSize: blob.size } : { kind: "text", text };
}

function hasControlCharacter(value: string): boolean {
return [...value].some((char) => char.charCodeAt(0) < 0x20 || char === "\u007f");
}

/** The key as a store that percent-decodes it would read it; null when it does not decode. */
function decodedKey(key: string): string | null {
try {
return decodeURIComponent(key);
} catch {
return null;
}
}

/**
* Serve a request from the private archive. Returns null on a miss, or on a
* request whose path this router will not resolve against the store at all,
Expand All @@ -289,6 +314,17 @@ export async function serveArchive(
// so the invariant does not come to depend solely on that call site never
// changing.
if (prefix !== "" && !mapped.key.startsWith(`${prefix}/`)) return null;
// The publisher's and build's own bookkeeping objects sit at the prefix root.
// Refused here rather than sent: the store would answer 400 or 414, which the handler treats as a failure.
const relativeKey = decodedKey(prefix === "" ? mapped.key : mapped.key.slice(prefix.length + 1));
if (
relativeKey === null ||
(relativeKey.startsWith("_") && !relativeKey.includes("/")) ||
hasControlCharacter(relativeKey) ||
(prefix === "" ? 0 : prefix.length + 1) + relativeKey.length > MAX_KEY_LENGTH
) {
return null;
}

const ifNoneMatch = request.headers.get("if-none-match") ?? undefined;
// The read goes through the Blob store's own CDN cache (the SDK's default;
Expand Down
6 changes: 6 additions & 0 deletions apps/router/lib/manifest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ export function getManifestReader(): ManifestReader {
reader = createManifestReader({
getAll: () => client.getAll<Record<string, unknown>>(),
ttlMs: 60_000,
onInvalidItem: (key, error) => {
console.error(
`docs-router: malformed manifest item ${key}; serving its last good value, if any`,
error,
);
},
onError: (error) => {
console.error("docs-router: manifest refresh failed, serving the last good copy", error);
},
Expand Down
14 changes: 14 additions & 0 deletions apps/router/lib/releases-handler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,3 +112,17 @@ test("with no schedule at all the answer is a 503 no cache keeps", async () => {
assert.equal((await handler()).status, 200);
mock.restoreAll();
});

test("a schedule that fails validation is never cached or served", async () => {
const error = mock.method(console, "error", () => {});
try {
const valid = schedule("v2.36.6");
const rows = valid.rows.map((row) => ({ ...row, releasedAt: "not a date" }));
const handler = createReleasesHandler({ load: async () => ({ ...valid, rows }) });
const response = await handler();
assert.equal(response.status, 503);
assert.equal(response.headers.get("cache-control"), "no-store");
} finally {
error.mock.restore();
}
});
Loading
Loading