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: 2 additions & 1 deletion apps/docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -251,14 +251,15 @@ The object is always written: a missing file or an empty array yields `{"version
`_redirects.json` is listed in `_publish.json` and uploaded like any other object, so it is read back and hashed by `publish:verify`.
One invalid rule fails the whole file, as it does for `apps/router/redirects.json`: the version's build fails, nothing is uploaded, and the previous publish keeps serving.
The error names the rule; the fix is a commit to `docs/redirects.json` on that branch.
The normalized `_redirects.json` must be at most 1 MiB (`MAX_VERSION_REDIRECTS_BYTES`), which the router will not read past; `sync-docs.mjs` and `archive-layout.mjs` check its serialized size, and the upload checks the file again and fails the publish before anything is put.
The router applies the rules on a miss inside that version (`apps/router/README.md`, "Redirects"); the check that a destination exists belongs to `coder/coder`'s CI and to the router's probe, not to the publisher.
A change to only `docs/redirects.json` changes the docs tree, so reconcile sees the version as behind and republishes it within the hourly cycle.

`DOCS_UPLOAD_REUSE` is also opt-in.
Every upload writes `_objects.json` beside `_publish.json`, recording the SHA-256 and size of each object as the publish job itself read it; the untrusted `build` job never writes it.
With the variable set to `true`, the publish job reads the manifest before uploading, finds the prefix this version is served from now, and copies each object whose bytes hash to what that prefix's `_objects.json` recorded with a server-side `copy()` instead of uploading it again.
The storage layout does not change: every prefix still holds a full copy of its version, so the router, cleanup, and rollback are untouched.
A missing record, a failed manifest read, or a failed copy falls back to a plain upload, and the "Upload to the archive" step's log line reports how many objects were copied and how many megabytes were sent.
A missing record, a record over 16 MiB (which is not read), a failed manifest read, or a failed copy falls back to a plain upload, and the "Upload to the archive" step's log line reports how many objects were copied and how many megabytes were sent.

Three settings must instead be **repository**-level, never environment-scoped, because `publish-version.yml`'s `build` job carries no `environment:` at all and could not read an environment-scoped value:

Expand Down
29 changes: 25 additions & 4 deletions apps/docs/scripts/publish/upload.mjs
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
#!/usr/bin/env node
// Upload a laid-out version to the private archive under its immutable prefix.
import { createHash } from "node:crypto";
import { readFile, readdir } from "node:fs/promises";
import { readFile, readdir, stat } from "node:fs/promises";
import path from "node:path";
import { DEV_KEY, lineKey, tagKey } from "@coder/docs-manifest";
import {
DEV_KEY,
MAX_VERSION_REDIRECTS_BYTES,
VERSION_REDIRECTS_KEY,
lineKey,
readBlobTextWithLimit,
tagKey,
} from "@coder/docs-manifest";
import { copy, get, put } from "@vercel/blob";
import { contentTypeFor } from "../archive-layout-helpers.mjs";
import { logBlobRetry, withBlobRetry } from "./blob-retry.mjs";
Expand Down Expand Up @@ -110,6 +117,9 @@ export function liveArchivePrefix({ items, plan }) {
// `_publish.json` hashes are the untrusted build's claims.
const OBJECTS_KEY = "_objects.json";

// Far above a real record (one short entry per file); refuses a runaway one.
const MAX_RECORDED_OBJECTS_BYTES = 16 * 1024 * 1024;

/** Written first by every upload, so cleanup can tell a prefix being re-uploaded from an idle orphan. */
export const UPLOADING_KEY = "_uploading.json";

Expand All @@ -120,9 +130,12 @@ async function readRecordedObjects({ prefix, token, blobGet, onReuseSkipped }) {
{ key: `${prefix}/${OBJECTS_KEY}` },
);
if (!result?.stream) throw new Error("not found");
const recorded = JSON.parse(
Buffer.from(await new Response(result.stream).arrayBuffer()).toString("utf8"),
const text = await readBlobTextWithLimit(
{ stream: result.stream, size: result.blob?.size },
MAX_RECORDED_OBJECTS_BYTES,
);
if (text === null) throw new Error(`larger than ${MAX_RECORDED_OBJECTS_BYTES} bytes`);
const recorded = JSON.parse(text);
if (recorded?.version !== 1 || typeof recorded.files !== "object" || recorded.files === null) {
throw new Error("unrecognised format");
}
Expand Down Expand Up @@ -183,6 +196,14 @@ export async function uploadDir({
.toSorted();
if (files.length === 0)
throw new Error(`upload: ${dir} has no files to upload (besides _publish.json)`);
if (files.includes(VERSION_REDIRECTS_KEY)) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should fix, docs outside the diff: apps/docs/README.md (around lines 247 to 260) doesn't mention that a publish now fails when _redirects.json is over 1 MiB, or that an _objects.json over 16 MiB now means a full upload instead of a reuse. One sentence for each would do.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in d552494: the "Version redirects" section now says a normalized _redirects.json over 1 MiB fails the version at sync and layout and again at upload, and the DOCS_UPLOAD_REUSE paragraph lists a record over 16 MiB (not read) among the cases that fall back to a plain upload.

const { size } = await stat(path.join(dir, VERSION_REDIRECTS_KEY));
if (size > MAX_VERSION_REDIRECTS_BYTES) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: parseVersionRedirectsFile checks the size of the source file, but the normalised _redirects.json can be bigger because "permanent":true is added to each rule that omits it. With a scratch file, an 837,781-byte source passed sync-docs and archive-layout and produced a 1,177,804-byte object, so the publish only failed here. That still fails closed, but AGENTS.md prefers surfacing authoring defects at build time. Checking the size of the serialised output in readVersionRedirects would catch it there, and this check can stay as the guard at the trust boundary.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 650d4be: readVersionRedirects now checks the byte length of the serialized output and fails with the same "docs/redirects.json is invalid" error, so the case you found fails at sync-docs. The new test builds a 25,000-rule source under 1 MiB whose normalized output is over it. The upload check stays as the guard at the trust boundary.

throw new Error(
`upload: ${VERSION_REDIRECTS_KEY} is larger than ${MAX_VERSION_REDIRECTS_BYTES} bytes (${size})`,
);
}
}
const reusable =
reuseFrom === undefined || reuseFrom === prefix
? new Map()
Expand Down
56 changes: 56 additions & 0 deletions apps/docs/scripts/publish/upload.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { test } from "node:test";
import { MAX_VERSION_REDIRECTS_BYTES } from "@coder/docs-manifest";
import { BlobServiceRateLimited } from "@vercel/blob";
import {
DEFAULT_UPLOAD_CONCURRENCY,
Expand Down Expand Up @@ -609,6 +610,61 @@ test("liveArchivePrefix finds the prefix the manifest serves this version from",
assert.equal(liveArchivePrefix({ items, plan: { kind: "line", id: "2.35" } }), undefined);
});

test("a _redirects.json over the cap fails the upload before anything is put", async () => {
const dir = await archiveFixture([entry("index.html"), entry("_redirects.json")]);
await writeFile(path.join(dir, "_redirects.json"), "x".repeat(MAX_VERSION_REDIRECTS_BYTES + 1));
const store = recordingStore();
await assert.rejects(
() => uploadDir({ dir, prefix: `versions/2.36/${sha}`, token: "t", concurrency: 1, ...store }),
/_redirects\.json is larger than/,
);
assert.equal(store.puts.length, 0);
});

test("a _redirects.json at the cap is uploaded", async () => {
const dir = await archiveFixture([
entry("index.html"),
entry("_next/static/chunks/a.js"),
entry("_redirects.json"),
]);
await writeFile(path.join(dir, "_redirects.json"), "x".repeat(MAX_VERSION_REDIRECTS_BYTES));
const store = recordingStore();
await uploadDir({ dir, prefix: `versions/2.36/${sha}`, token: "t", concurrency: 1, ...store });
assert.ok(store.puts.some((p) => p.key.endsWith("/_redirects.json")));
});

test("a recorded _objects.json that reports a size over the limit is not read, and reuse is skipped", async () => {
const dir = await archiveFixture([entry("index.html"), entry("_next/static/chunks/a.js")]);
const store = recordingStore();
let streamed = false;
store.blobGet = async () => ({
blob: { size: 10 * 1024 * 1024 * 1024 },
stream: new ReadableStream(
{
pull(controller) {
streamed = true;
controller.close();
},
},
{ highWaterMark: 0 },
),
});
const skipped = [];
const result = await uploadDir({
dir,
prefix: `versions/2.36/${sha}`,
token: "t",
concurrency: 1,
reuseFrom: previous,
onReuseSkipped: (info) => skipped.push(info.reason),
...store,
});
assert.equal(streamed, false);
assert.equal(result.copied, 0);
assert.equal(skipped.length, 1);
assert.match(skipped[0], /larger than/);
});

test("the upload marker is written before any object, so a cleanup sweep sees the prefix as in flight", async () => {
const dir = await archiveFixture([entry("index.html"), entry("_next/static/chunks/a.js")]);
const prefix = `versions/main/${sha}`;
Expand Down
15 changes: 13 additions & 2 deletions apps/docs/scripts/version-redirects.mjs
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
// Read and validate the `docs/redirects.json` of the exact content commit a version is built from.
import { readFile } from "node:fs/promises";
import path from "node:path";
import { parseVersionRedirectsFile, serializeVersionRedirects } from "@coder/docs-manifest";
import {
MAX_VERSION_REDIRECTS_BYTES,
parseVersionRedirectsFile,
serializeVersionRedirects,
} from "@coder/docs-manifest";

/**
* The artifact body for a docs tree: the file's rules, validated and
Expand Down Expand Up @@ -29,5 +33,12 @@ export async function readVersionRedirects(docsRoot) {
`docs/redirects.json is invalid, so this version is not published: ${error.message}`,
);
}
return { body: serializeVersionRedirects(rules), count: rules.length };
const body = serializeVersionRedirects(rules);
const size = Buffer.byteLength(body);
if (size > MAX_VERSION_REDIRECTS_BYTES) {
throw new Error(
`docs/redirects.json is invalid, so this version is not published: its normalized rules are larger than ${MAX_VERSION_REDIRECTS_BYTES} bytes (${size})`,
);
}
return { body, count: rules.length };
}
12 changes: 11 additions & 1 deletion apps/docs/scripts/version-redirects.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { test } from "node:test";
import { parseVersionRedirectsArtifact } from "@coder/docs-manifest";
import { MAX_VERSION_REDIRECTS_BYTES, parseVersionRedirectsArtifact } from "@coder/docs-manifest";
import { readVersionRedirects } from "./version-redirects.mjs";

async function withDocs(redirects, run) {
Expand Down Expand Up @@ -64,3 +64,13 @@ test("an invalid file fails the build and names the file and the rule", async ()
);
await assert.rejects(() => withDocs("{}", readVersionRedirects), /JSON array/);
});

test("a file under the cap whose normalized rules are over it fails the build", async () => {
const rules = Array.from({ length: 25_000 }, (_, i) => ({ source: `r${i}`, destination: "d" }));
const text = JSON.stringify(rules);
assert.equal(Buffer.byteLength(text) < MAX_VERSION_REDIRECTS_BYTES, true);
await assert.rejects(
() => withDocs(text, readVersionRedirects),
/docs\/redirects\.json is invalid.*larger than/,
);
});
2 changes: 2 additions & 0 deletions apps/router/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ Its older content rules stay until each version's own file is live, and are then

A version's rules are its `docs/redirects.json` from the `coder/coder` commit it was built from, validated at publish and stored as `_redirects.json` at its archive prefix root, beside `_publish.json` (`apps/docs/README.md`, "Version redirects").
`parseVersionRedirectsArtifact` in `@coder/docs-manifest` reads it back as strictly as the publisher wrote it, because the build job that produced it compiles untrusted content; an object that fails the check is logged and treated as absent.
An object over the 1 MiB cap (`MAX_VERSION_REDIRECTS_BYTES`) is not read past the cap: it is logged with its archive prefix and the size the store reported, and the version gets no rules of its own.
The object is `{"version":1,"rules":[{"source","destination","permanent"}]}`, with routes relative to the version's docs root.
A request path is matched relative to that root, ignoring one trailing slash: `/v2.38/a/b` and `/@main/a/b` match `a/b`, and so does `/a/b` on the mainline served at the root.
Matching is case-insensitive, as for the static rules, so `/v2.38/A/B` matches `a/b` too; the part a wildcard matched keeps the request's case.
Expand All @@ -63,6 +64,7 @@ A version whose own rule matched but whose destination page is missing gets its

The router loads the object once per archive prefix and keeps it for ten minutes, which bounds how long a warm instance serves old rules after a forced tag republish rewrites the prefix in place.
A prefix with no object (published before this existed) is asked again after a minute, so a republish that adds one is picked up; until then the version behaves as before, with only the static rules.
An object that fails the check is also asked again after a minute, but one over the size cap is kept as no rules for the full ten minutes, so an oversized object is not fetched again every minute.
A store failure while reading the object is not cached: the reader gets the version's not-found page with `cache-control: no-store`, as for a failed probe, and the static rules still run.
`lib/version-redirects.test.ts` covers it.

Expand Down
25 changes: 20 additions & 5 deletions apps/router/lib/archive.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { analyticsEnabled, docsContentSecurityPolicy } from "@coder/docs-config";
import {
MAX_VERSION_REDIRECTS_BYTES,
type ObjectPath,
type RouteTarget,
VERSION_REDIRECTS_KEY,
hasUnsafePathSegment,
objectPath,
readBlobTextWithLimit,
} from "@coder/docs-manifest";
import { get as blobGet } from "@vercel/blob";

Expand Down Expand Up @@ -233,21 +235,34 @@ export async function serveNotFoundPage(
return new Response(result.stream, { status: 404, headers });
}

/** What the store holds at a version's `_redirects.json`. */
export type VersionRedirectsRead =
| { kind: "absent" }
| { kind: "too-large"; reportedSize: number }
| { kind: "text"; text: string };

/**
* The version's own redirects object, `_redirects.json` beside `_publish.json`
* under the deployment's archive prefix, as text; null when the prefix has none
* (published before the object existed). A store failure throws.
* under the deployment's archive prefix. An object over the size cap is
* reported as `too-large` without its body being read: the store's reported
* size is checked first, and the read itself stops at the cap in case the
* size is missing or wrong. A store failure throws.
*/
export async function readVersionRedirectsText(
deployment: string,
request: Request,
deps: ArchiveDeps,
): Promise<string | null> {
): Promise<VersionRedirectsRead> {
const prefix = prefixFor({ deployment, path: "/", versionId: "" });
const key = prefix ? `${prefix}/${VERSION_REDIRECTS_KEY}` : VERSION_REDIRECTS_KEY;
const result = await readObject(key, { access: "private" }, request, deps);
if (!result?.stream) return null;
return new Response(result.stream).text();
if (!result?.stream) return { kind: "absent" };

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: this sequence (check the reported size, cancel, bounded read, treat null as too large) is repeated almost line for line at upload.mjs:130 to 135. An exported readBlobTextWithLimit({ stream, size }, max) next to readTextWithLimit would stop the two callers drifting apart.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 7ceb6b1: readBlobTextWithLimit({ stream, size }, maxBytes) is exported next to readTextWithLimit, and both archive.ts and upload.mjs use it instead of their own copies of the sequence.

const { stream, blob } = result;
const text = await readBlobTextWithLimit(
{ stream, size: blob.size },
MAX_VERSION_REDIRECTS_BYTES,
);
return text === null ? { kind: "too-large", reportedSize: blob.size } : { kind: "text", text };
}

/**
Expand Down
105 changes: 105 additions & 0 deletions apps/router/lib/version-redirects.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { mock, test } from "node:test";
import {
CANONICAL_LAYOUT,
DEV_KEY,
MAX_VERSION_REDIRECTS_BYTES,
type ManifestReader,
type VersionRedirect,
lineKey,
Expand Down Expand Up @@ -460,3 +461,107 @@ test("a destination fragment is kept after the query, and only the route is prob
assert.equal(missing.response.status, 404);
assert.equal(missing.response.headers.has("location"), false);
});

const TOO_LARGE = MAX_VERSION_REDIRECTS_BYTES + 1;

// The size @vercel/blob reports: Content-Length, 0 when it is missing, NaN when it is not a number.
function oversizedGetter(size: number, pulled: { bytes: number }): Getter {
const working = storeGetter(store);
return async (pathname) => {
if (!pathname.endsWith(`${prefix("2.38")}/_redirects.json`)) return working(pathname);
const chunk = new Uint8Array(64 * 1024);
return {
statusCode: 200,
stream: new ReadableStream<Uint8Array>(
{
pull(controller) {
if (pulled.bytes >= 16 * TOO_LARGE) return controller.close();
pulled.bytes += chunk.length;
controller.enqueue(chunk);
},
},
{ highWaterMark: 0 },
),
blob: { contentType: "application/json", etag: '"e"', size },
};
};
}

async function quietly<T>(run: () => Promise<T>): Promise<T> {
const error = mock.method(console, "error", () => {});
try {
return await run();
} finally {
error.mock.restore();
}
}

test("a rules object whose reported size is over the cap is never streamed", async () => {
const pulled = { bytes: 0 };
const { response } = await quietly(() =>
serve({ get: oversizedGetter(16 * TOO_LARGE, pulled) }).fetch("/v2.38/templates"),
);
assert.equal(response.status, 404);
assert.equal(response.headers.has("location"), false);
assert.equal(pulled.bytes, 0);
});

test("a rules object reported as 0 or NaN bytes is cut off once it passes the cap", async () => {
for (const size of [0, Number.NaN]) {
const pulled = { bytes: 0 };
const { response } = await quietly(() =>
serve({ get: oversizedGetter(size, pulled) }).fetch("/v2.38/templates"),
);
assert.equal(response.status, 404, String(size));
assert.equal(
pulled.bytes < 2 * TOO_LARGE,
true,
`size ${size}: streamed ${pulled.bytes} bytes`,
);
}
});

test("a rules object reported at exactly the cap is read and applied", async () => {
const body = artifact(...rules238).trimEnd();
const padded = body + " ".repeat(MAX_VERSION_REDIRECTS_BYTES - body.length);
const { response } = await serve({
objects: { ...store, [`${prefix("2.38")}/_redirects.json`]: padded },
}).fetch("/v2.38/templates");
assert.equal(response.status, 308);
assert.equal(location(response), "/beta-docs/v2.38/admin/templates");
});

test("an oversized rules object is logged with its archive prefix and reported size", async () => {
const error = mock.method(console, "error", () => {});
try {
await serve({ get: oversizedGetter(16 * TOO_LARGE, { bytes: 0 }) }).fetch("/v2.38/templates");
const logged = error.mock.calls.map((call) => call.arguments.join(" ")).join("\n");
assert.match(logged, new RegExp(`over the size cap.*/${prefix("2.38")}`));
assert.match(logged, new RegExp(`${16 * TOO_LARGE}`));
} finally {
error.mock.restore();
}
});

test("an oversized rules object is remembered as long as a valid one, not re-fetched every minute", async () => {
const objects = { ...store };
const calls: string[] = [];
const oversized = oversizedGetter(16 * TOO_LARGE, { bytes: 0 });
const get: Getter = async (pathname) => {
calls.push(pathname);
return oversized(pathname);
};
let clock = 0;
const { fetch } = serve({ get, objects, now: () => clock });
const reads = () => calls.filter((key) => key === `${prefix("2.38")}/_redirects.json`).length;

await quietly(async () => {
await fetch("/v2.38/nothing");
clock += ABSENT_TTL_MS + 1;
await fetch("/v2.38/nothing");
assert.equal(reads(), 1);
clock += PRESENT_TTL_MS;
await fetch("/v2.38/nothing");
assert.equal(reads(), 2);
});
});
Loading
Loading