Public: anyone can read this; the crew can change it.

A raw file or blob read at a full commit id is cached as immutable, with an ETag and 304 #3381

Parked opened this
Closed without merging

scout/forge:scout/3377-a-raw-file-or-blob-read-at-a-full-commit → main 3 commits fork 1 thread · 1 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
5 files changed +228 −19
README.md +2
@@ -1150,6 +1150,8 @@ The terminal also has an Access command (`:` → Access), a site admin's: it rea
11501150 In the terminal, `:` → System shows the same view (the owner's only): per-core CPU with a block-character history, memory, swap, disk and network rates, and each group's top two processes (no sort; the dialog is read-only), and `:` → Telemetry lists the agents and flips `telemetry:read` for the one you press Enter on.
11511151 An agent the owner grants `telemetry:read` (Settings → Telemetry, one switch per agent, revoked the same way) reads the same through `GET /api/v1/telemetry/{system,flow,sources,history}` and the MCP `flow` and `system` tools; private repositories' checks and apps are renamed `check:private-N` and lose their processes and test files, and `flow` (like `system`, an admin agent account needs the grant too: only a person who is an admin reads without it) names only public repositories' conflicted pulls, every read is listed on that page, and an agent without the grant is refused. `/contribute`, `GET /api/v1/contribute` and the MCP `contribute` tool are open to anyone: what the forge is, the bottleneck now, open issues labelled “help wanted” in public repositories, and how to propose (fork, pull, the same gate). The grant is a table, not a token scope, so no token has to be re-issued.
11521152
1153 **Raw files and caches.** `GET /:owner/:name/raw/:ref/*path` at a full 40-hex commit id is `immutable` for a year: `public, max-age=31536000, immutable` for a public repository, `private, max-age=31536000, immutable` for any other, so a shared cache never keeps private bytes. At a branch or tag it is `private, max-age=0` and revalidates. Every raw answer has the blob's oid as its `ETag`, and a matching `If-None-Match` gets a 304 with the same `Cache-Control`, `nosniff` and sandbox CSP. The HTML blob page is not cached this way (it carries the viewer and a nonce). A public repository that later turns private keeps its year-long `public` copies in shared caches already holding them. See docs/CACHING.md.
1154
11531155 `docs/CACHING.md` is what the forge keeps between requests to make `/map` and
11541156 `/` fast: each map lane's plan and each viewer's feed candidates, stamped with
11551157 SQLite's own write clock so any write is seen on the next read, keyed so one
docs/CACHING.md +32
@@ -379,6 +379,38 @@ warm:
379379 | home KPI row | forge head, UTC hour; admin-gated | 30 s |
380380 | home pinned panel | board blob, panel, forge head; admin-gated | 30 s |
381381
382 ## Raw files at a full commit id (#3381)
383
384 `GET /:owner/:name/raw/:ref/*path` is the one place the forge tells shared
385 caches (browsers, a CDN, a proxy) to keep bytes for a year.
386
387 | `ref` is | repository | `Cache-Control` |
388 | ------------------------- | ---------- | ---------------------------------------- |
389 | 40 hex digits (a commit) | public | `public, max-age=31536000, immutable` |
390 | 40 hex digits (a commit) | not public | `private, max-age=31536000, immutable` |
391 | a branch, tag or anything else | any | `private, max-age=0` (revalidates) |
392
393 - **Why immutable.** A full commit id names one tree forever, so the bytes
394 at a path under it can never change. A branch name moves, so it always
395 revalidates.
396 - **Public vs private.** Only `repo.visibility === "public"` (wired in
397 `rawBlob`) allows `public`. Any other repository is `private`: the
398 browser may keep it, a shared cache may not.
399 - **ETag and 304.** Every raw answer carries the blob's own oid as a strong
400 `ETag`. `If-None-Match` naming it (weak or strong, a list, or `*`) gets a
401 bodiless 304 that keeps the same `Cache-Control`, `nosniff` and sandbox
402 CSP. A branch read changes oid only when the file changes, so it costs
403 one round trip and no body.
404 - **Why the blob page is left out.** `/:owner/:name/blob/...` is HTML: it
405 carries the viewer's name, a CSP nonce and links that change with the
406 repository, so it is not a function of the commit alone. Only the raw
407 bytes are. The origin-browse raw route (`browseRaw`) is also left alone:
408 its source is another host, whose bytes this forge cannot vouch for.
409 - **Known limit.** A public repository that later turns private keeps
410 year-long `public` copies in whatever shared caches already fetched
411 them; the forge cannot recall them. Anyone who needs that undone must
412 purge those caches. A commit id is also not secret once public.
413
382414 ## What is built (#2675)
383415
384416 The map half is #2716's (`web/map_cache.ts`, numbers above). #2675 adds
src/git/read.ts +15 −6
@@ -293,8 +293,14 @@ export type BlobForRender =
293293 readonly kind: "binary";
294294 readonly body: Uint8Array;
295295 readonly size: number;
296 readonly oid: string;
296297 }
297 | { readonly kind: "text"; readonly body: Uint8Array; readonly size: number };
298 | {
299 readonly kind: "text";
300 readonly body: Uint8Array;
301 readonly size: number;
302 readonly oid: string;
303 };
298304
299305 /**
300306 * Read a blob for rendering, size-bounded up front. The object is *stat*ed
@@ -329,9 +335,11 @@ export async function blobForRender(
329335 if (!Number.isSafeInteger(size)) return { kind: "missing" };
330336 if (size > maxBytes) return { kind: "too_large", size };
331337
338 const named = await runGit(["rev-parse", "--verify", spec], { cwd: dir });
339 if (!named.ok) return { kind: "missing" };
332340 const body = await runGitRaw(["cat-file", "blob", spec], { cwd: dir });
333341 if (!body.ok) return { kind: "missing" };
334 return classify(body.value, size);
342 return classify(body.value, size, named.value.trim());
335343 }
336344
337345 /**
@@ -356,17 +364,18 @@ async function viaReader(
356364 if (size > maxBytes) return { kind: "too_large", size };
357365 const object = await reader.object(spec);
358366 if (!object.ok) return { kind: "missing" };
359 return classify(object.value.body, size);
367 return classify(object.value.body, size, object.value.oid);
360368 } catch {
361369 closeReader(dir);
362370 return undefined;
363371 }
364372 }
365373
366 function classify(body: Uint8Array, size: number): BlobForRender {
374 function classify(body: Uint8Array, size: number, oid: string): BlobForRender {
367375 // NUL in the first 8KB is git's own binary heuristic.
368 if (body.subarray(0, 8000).includes(0)) return { kind: "binary", body, size };
369 return { kind: "text", body, size };
376 if (body.subarray(0, 8000).includes(0))
377 return { kind: "binary", body, size, oid };
378 return { kind: "text", body, size, oid };
370379 }
371380
372381 export interface Ref {
src/web/pages/repo.ts +41 −13
@@ -33,6 +33,7 @@ import { blobForRender, type TreeEntry } from "../../git/read.ts";
3333 import { repoDir } from "../../git/repos.ts";
3434 import { estimateTokens } from "../../kernel/tokens-format.ts";
3535 import { safeBack, type Ctx } from "../../http/context.ts";
36 import { holds } from "../../http/etag.ts";
3637 import { json, notFound } from "../../http/respond.ts";
3738 import type { Blob, RepoSource } from "../../view/source.ts";
3839 import {
@@ -894,19 +895,39 @@ function renderedMarkdown(blob: Blob & { kind: "text" }): {
894895 }
895896
896897 /** The bytes, with the headers that stop them ever executing as a page. */
897 export function rawResponse(blob: Blob): Response {
898 export function rawResponse(
899 blob: Blob,
900 cache: {
901 oid?: string;
902 immutable?: boolean;
903 public?: boolean;
904 request?: Request;
905 } = {},
906 ): Response {
898907 if (blob.kind === "too_large") return new Response("", { status: 404 });
899 return new Response(blob.body, {
900 headers: {
901 "content-type":
902 blob.kind === "text"
903 ? "text/plain; charset=utf-8"
904 : "application/octet-stream",
905 "x-content-type-options": "nosniff",
906 "content-security-policy": "default-src 'none'; sandbox",
907 "cache-control": "private, max-age=0",
908 },
909 });
908 // A full commit id names bytes that can never change; a branch name does
909 // not, so it revalidates every time, against the blob's own oid. Only a
910 // public repository's bytes may sit in a shared cache.
911 const etag = cache.oid ? `"${cache.oid}"` : undefined;
912 const control =
913 cache.immutable && etag
914 ? `${cache.public ? "public" : "private"}, max-age=31536000, immutable`
915 : "private, max-age=0";
916 const headers: Record<string, string> = {
917 "content-type":
918 blob.kind === "text"
919 ? "text/plain; charset=utf-8"
920 : "application/octet-stream",
921 "x-content-type-options": "nosniff",
922 "content-security-policy": "default-src 'none'; sandbox",
923 "cache-control": control,
924 };
925 if (etag) {
926 headers.etag = etag;
927 if (cache.request && holds(cache.request, etag))
928 return new Response(null, { status: 304, headers });
929 }
930 return new Response(blob.body, { headers });
910931 }
911932
912933 // GET /:owner/:name — the repo home. An app's home is the app, for every
@@ -1287,5 +1308,12 @@ export async function rawBlob(ctx: Ctx): Promise<Response> {
12871308 const blob = await blobForRender(dir, ref, path, 25_000_000);
12881309 if (blob.kind === "missing" || blob.kind === "too_large")
12891310 return notFoundPage(ctx);
1290 return rawResponse(blob);
1311 return rawResponse(blob, {
1312 oid: blob.oid,
1313 immutable: FULL_OID.test(ref),
1314 public: repo.visibility === "public",
outdated

public: repo.visibility === "public" is the only thing keeping private bytes out of shared caches, and no test goes through rawBlob for a private repo. Add one over HTTP.

1315 request: ctx.request,
1316 });
12911317 }
1318
1319 const FULL_OID = /^[0-9a-f]{40}$/;
test/web-ui.test.ts +138
@@ -17,6 +17,7 @@ import { createApp, type App } from "../src/app.ts";
1717 import { getRepo } from "../src/core/repos.ts";
1818 import { listLabels, labelsFor, getIssue } from "../src/core/issues.ts";
1919 import { serve, type Servers } from "../src/http/server.ts";
20 import { rawResponse } from "../src/web/pages/repo.ts";
2021 import { shellJs } from "../src/web/client.ts";
2122 import { gitClientEnv } from "./helpers/git-client.ts";
2223 import { proveAll } from "./helpers/verified.ts";
@@ -267,6 +268,143 @@ describe("web ui", () => {
267268
268269 // ---- raw ----
269270
271 async function revParse(spec: string): Promise<string> {
272 const proc = Bun.spawn(["git", "rev-parse", spec], {
273 cwd: join(work, "proj"),
274 env: gitEnv,
275 stdout: "pipe",
276 });
277 return (await new Response(proc.stdout).text()).trim();
278 }
279
280 test("raw at a full commit id is immutable, with the blob oid as ETag and a 304", async () => {
281 const commit = await revParse("main");
282 const blobOid = await revParse("main:a.txt");
283 const url = `${base}/mel/proj/raw/${commit}/a.txt`;
284 const res = await fetch(url);
285 expect(res.status).toBe(200);
286 expect(res.headers.get("cache-control")).toBe(
287 "public, max-age=31536000, immutable",
288 );
289 expect(res.headers.get("etag")).toBe(`"${blobOid}"`);
290 expect(res.headers.get("content-security-policy")).toBe(
291 "default-src 'none'; sandbox",
292 );
293 expect(res.headers.get("x-content-type-options")).toBe("nosniff");
294 await res.text();
295
296 const again = await fetch(url, {
297 headers: { "if-none-match": `"${blobOid}"` },
298 });
299 expect(again.status).toBe(304);
300 expect(await again.text()).toBe("");
301 expect(again.headers.get("cache-control")).toContain("immutable");
302 });
303
304 test("raw at a branch name revalidates against the blob oid", async () => {
305 const blobOid = await revParse("main:a.txt");
306 const res = await fetch(`${base}/mel/proj/raw/main/a.txt`);
307 expect(res.headers.get("cache-control")).toBe("private, max-age=0");
308 expect(res.headers.get("etag")).toBe(`"${blobOid}"`);
309 await res.text();
310 const again = await fetch(`${base}/mel/proj/raw/main/a.txt`, {
311 headers: { "if-none-match": `"${blobOid}"` },
312 });
313 expect(again.status).toBe(304);
314 expect(await again.text()).toBe("");
315 const other = await fetch(`${base}/mel/proj/raw/main/a.txt`, {
316 headers: { "if-none-match": '"0000"' },
317 });
318 expect(other.status).toBe(200);
319 await other.text();
320 });
321
322 test("raw answers 304 to a weak tag, a list holding the tag, and *", () => {
323 const oid = "b".repeat(40);
324 const blob = {
325 kind: "text" as const,
326 body: new TextEncoder().encode("x"),
327 size: 1,
328 oid,
329 };
330 const ask = (inm: string) =>
331 rawResponse(blob, {
332 oid,
333 immutable: true,
334 public: true,
335 request: new Request("http://x/", {
336 headers: { "if-none-match": inm },
337 }),
338 }).status;
339 expect(ask(`W/"${oid}"`)).toBe(304);
340 expect(ask(`"zzz", "${oid}"`)).toBe(304);
341 expect(ask("*")).toBe(304);
342 expect(ask('"zzz"')).toBe(200);
343 });
344
345 test("raw of a repository that is not public is never cached as public", () => {
346 const blob = {
347 kind: "text" as const,
348 body: new TextEncoder().encode("x"),
349 size: 1,
350 oid: "a".repeat(40),
351 };
352 const res = rawResponse(blob, {
353 oid: blob.oid,
354 immutable: true,
355 public: false,
356 });
357 expect(res.headers.get("cache-control")).toBe(
358 "private, max-age=31536000, immutable",
359 );
360 expect(res.headers.get("content-security-policy")).toContain("sandbox");
361 });
362
363 test("raw of a private repository at a full commit id is private, over HTTP", async () => {
364 await fetch(`${base}/new`, {
365 method: "POST",
366 headers: { cookie: owner },
367 body: form({ name: "hush", visibility: "private" }),
368 redirect: "manual",
369 });
370 const dir = join(work, "hush");
371 await mkdir(dir, { recursive: true });
372 await git(["init", "-q", "-b", "main", "."], dir);
373 await writeFile(join(dir, "s.txt"), "secret\n");
374 await git(["add", "."], dir);
375 await git(["commit", "-q", "-m", "s"], dir);
376 await git(
377 [
378 "push",
379 "-q",
380 `http://mel:web-ui-password@localhost:${servers.port}/mel/hush.git`,
381 "main",
382 ],
383 dir,
384 );
385 const proc = Bun.spawn(["git", "rev-parse", "HEAD"], {
386 cwd: dir,
387 env: gitEnv,
388 stdout: "pipe",
389 });
390 const commit = (await new Response(proc.stdout).text()).trim();
391 const url = `${base}/mel/hush/raw/${commit}/s.txt`;
392 const res = await fetch(url, { headers: { cookie: owner } });
393 expect(res.status).toBe(200);
394 expect(res.headers.get("cache-control")).toBe(
395 "private, max-age=31536000, immutable",
396 );
397 expect(res.headers.get("cache-control")).not.toContain("public");
398 await res.text();
399 const etag = res.headers.get("etag")!;
400 const again = await fetch(url, {
401 headers: { cookie: owner, "if-none-match": etag },
402 });
403 expect(again.status).toBe(304);
404 expect(again.headers.get("cache-control")).not.toContain("public");
405 expect((await fetch(url)).status).toBe(404);
406 });
407
270408 test("raw serves bytes as text with nosniff, and conflates not-found", async () => {
271409 const res = await fetch(`${base}/mel/proj/raw/main/a.txt`);
272410 expect(res.status).toBe(200);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs