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
7 changes: 2 additions & 5 deletions pkgs/lab-ops-hub/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
validateMachineBody,
validateNoteBody,
validateTaskBody,
fileResponseForKey,
} from "./lib";

// ---------------------------------------------------------------------------
Expand Down Expand Up @@ -388,11 +389,7 @@ export default {
}
const fileMatch = p.match(/^\/api\/files\/(.+)$/);
if (fileMatch && req.method === "GET") {
const obj = await env.FILES.get(decodeURIComponent(fileMatch[1]));
if (!obj) return json({ error: "not found in R2" }, 404);
return new Response(obj.body, {
headers: { "content-type": obj.httpMetadata?.contentType ?? "application/octet-stream" },
});
return fileResponseForKey(fileMatch[1], (key) => env.FILES.get(key));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Await the file response inside the route's error boundary

When env.FILES.get() rejects, for example during an R2 outage, returning the helper's promise without awaiting it bypasses the enclosing catch at lines 462–463. Previously, the awaited R2 lookup routed these failures through the Worker's JSON 500 response; now the fetch handler rejects instead. Await the helper here so backend failures still reach the existing error handler. The new rejection test exercises only the helper, so it does not catch this route-level regression.

Useful? React with 👍 / 👎.

}

// Live board (Durable Object, one global room)
Expand Down
32 changes: 32 additions & 0 deletions pkgs/lab-ops-hub/src/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -469,6 +469,38 @@ export function uploadKey(name: string, now: number, rand: string = crypto.rando
return `uploads/${now}-${rand}-${name.replace(/[^\w.\-]+/g, "_")}`;
}

// Decode the path suffix before looking up an uploaded file. Keep this
// route-specific response logic pure so malformed keys and the 404 control
// can be covered without constructing a Worker environment.
export async function fileResponseForKey(
encodedKey: string,
getFile: (key: string) => Promise<{
body: ReadableStream<Uint8Array> | null;
httpMetadata?: { contentType?: string };
} | null>,
): Promise<Response> {
let key: string;
try {
key = decodeURIComponent(encodedKey);
} catch {
return new Response(JSON.stringify({ error: "bad file key encoding" }, null, 2), {
status: 400,
headers: { "content-type": "application/json" },
});
}

const obj = await getFile(key);
if (!obj) {
return new Response(JSON.stringify({ error: "not found in R2" }, null, 2), {
status: 404,
headers: { "content-type": "application/json" },
});
}
return new Response(obj.body, {
headers: { "content-type": obj.httpMetadata?.contentType ?? "application/octet-stream" },
});
}

// --- HTML extraction (#569) -------------------------------------------------
// extractHtml mirrors the container crawler's Extractor (container/app.py,
// an html.parser.HTMLParser) so the Worker fallback in index.ts and the
Expand Down
53 changes: 53 additions & 0 deletions pkgs/lab-ops-hub/test/file-response.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { fileResponseForKey } from "../src/lib.ts";

test("fileResponseForKey rejects malformed percent-encoded keys with a safe 400", async () => {
for (const encodedKey of ["%", "%zz", "uploads%2", "%E0%A4%A"]) {
let lookedUp = false;
const response = await fileResponseForKey(encodedKey, async () => {
lookedUp = true;
return null;
});

assert.equal(response.status, 400, encodedKey);
assert.match(response.headers.get("content-type") ?? "", /application\/json/, encodedKey);
assert.deepEqual(await response.json(), { error: "bad file key encoding" }, encodedKey);
assert.equal(lookedUp, false, encodedKey);
}
});

test("fileResponseForKey keeps valid encoded keys and downloads unchanged", async () => {
let requestedKey = "";
const response = await fileResponseForKey("uploads%2Freport.txt", async (key) => {
requestedKey = key;
return {
body: new Response("file contents").body,
httpMetadata: { contentType: "text/plain" },
};
});

assert.equal(requestedKey, "uploads/report.txt");
assert.equal(response.status, 200);
assert.equal(response.headers.get("content-type"), "text/plain");
assert.equal(await response.text(), "file contents");
});

test("fileResponseForKey keeps the missing-object 404 response", async () => {
const response = await fileResponseForKey("uploads%2Fmissing.txt", async (key) => {
assert.equal(key, "uploads/missing.txt");
return null;
});

assert.equal(response.status, 404);
assert.deepEqual(await response.json(), { error: "not found in R2" });
});

test("fileResponseForKey leaves R2 failures for the worker's 500 handler", async () => {
await assert.rejects(
fileResponseForKey("uploads%2Freport.txt", async () => {
throw new Error("R2 unavailable");
}),
/R2 unavailable/,
);
});