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
19 changes: 19 additions & 0 deletions pm-stack/aggregator/src/path-segment.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// path-segment.ts — the guarded path-segment decode (#2747/#2748).
//
// Routes that take a value from the URL path (/discuss/<ref>,
// /item/<id>) must decode it exactly once, and a malformed
// percent-encoding is client input gone wrong — a JSON 400 in the
// aggregator's established shape, never a raw URIError escaping the
// handler as an unhandled 500. This helper is the one place that
// decode happens: it wraps decodeURIComponent only (decode-once
// semantics are unchanged — %2F still decodes inside a value, and
// 100%25 still yields the literal "100%") and returns null on
// URIError so the route can answer 400 naming the bad encoding.

export function decodePathSegment(raw: string): string | null {
try {
return decodeURIComponent(raw);
} catch {
return null;
}
}
14 changes: 12 additions & 2 deletions pm-stack/aggregator/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
// (GitHub, Kaneo, Grist) stays read-only from here — the fleet jobs
// apply actions; the dashboard only records them.
import { stat } from "node:fs/promises";
import { decodePathSegment } from "./path-segment.ts";
import { ActionsStore, validateNewAction } from "./actions.ts";
import { checkActionAgainstItem, effectiveNeedsOrder, effectiveStandingAuto, findTierItem } from "./tier-items.ts";
import { CommentsStore, validateNewComment } from "./comments.ts";
Expand Down Expand Up @@ -727,7 +728,12 @@ async function handler(req: Request): Promise<Response> {

const discussMatch = /^\/discuss\/(.+)$/.exec(path);
if (discussMatch) {
const objectRef = decodeURIComponent(discussMatch[1]);
// #2748: a malformed percent-encoding is a JSON 400, never a raw
// URIError out of the handler.
const objectRef = decodePathSegment(discussMatch[1]);
if (objectRef === null) {
return json({ error: `malformed percent-encoding in path segment: ${discussMatch[1]}` }, 400);
}
const { title, githubRefs } = await discussTitle(objectRef);
const thread = await commentsStore.forObject(objectRef);
return html(renderDiscuss(objectRef, title, thread, await commentFormOpts(githubRefs), prov()));
Expand Down Expand Up @@ -839,7 +845,11 @@ async function handler(req: Request): Promise<Response> {

const itemMatch = /^\/item\/(.+)$/.exec(path);
if (itemMatch) {
const id = decodeURIComponent(itemMatch[1]);
// #2748: same guard as /discuss — JSON 400 on malformed encoding.
const id = decodePathSegment(itemMatch[1]);
if (id === null) {
return json({ error: `malformed percent-encoding in path segment: ${itemMatch[1]}` }, 400);
}
const [board, rows] = await Promise.all([source.board(), source.roadmap()]);
const subject = board.find((b) => b.id === id) ?? rows.find((r) => r.subject === id);
if (subject) {
Expand Down
100 changes: 100 additions & 0 deletions pm-stack/aggregator/test/path-segment.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
// #2748: the two aggregator path-segment decodes (/discuss, /item) are
// guarded — malformed percent-encoding earns the shared contract's
// JSON 400 instead of a raw URIError escaping the handler (the #2747
// probe matrix), and every legitimate encoding behaves byte-identically
// to the unguarded decode it replaces.
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
import { spawn, type Subprocess } from "bun";
import { decodePathSegment } from "../src/path-segment.ts";

describe("decodePathSegment", () => {
const malformed = ["%", "%zz", "%E0%A4%A", "%2", "a%", "%u1234"];
for (const raw of malformed) {
test(`malformed ${JSON.stringify(raw)} -> null`, () => {
expect(decodePathSegment(raw)).toBeNull();
});
}
const controls: Array<[string, string]> = [
["plain-ref", "plain-ref"],
["a%20b", "a b"],
["a%2Fb", "a/b"], // %2F still decodes inside values (decode-once)
["100%25", "100%"], // escaped percent yields the literal
["gh%3Adeveloping-today%2Fcode%231", "gh:developing-today/code#1"],
["", ""],
];
for (const [raw, want] of controls) {
test(`control ${JSON.stringify(raw)} -> ${JSON.stringify(want)}`, () => {
expect(decodePathSegment(raw)).toBe(want);
});
}
});

// Handler level: boot the real server from fixtures (the boot.test.ts
// pattern) and pin the probe matrix on both routes.
let proc: Subprocess<"ignore", "pipe", "inherit"> | null = null;
let port = 0;

beforeAll(async () => {
port = 5100 + Math.floor(Math.random() * 1000);
proc = spawn({
cmd: ["bun", "run", "src/server.ts"],
cwd: import.meta.dir + "/..",
env: { ...Bun.env, PM_AGG_PORT: String(port), PM_AGG_SOURCE: "fixtures" },
stdout: "pipe",
stderr: "inherit",
});
const deadline = Date.now() + 8000;
let ready = false;
while (Date.now() < deadline) {
try {
const res = await fetch(`http://127.0.0.1:${port}/api/health`);
if (res.ok) {
ready = true;
break;
}
} catch {
/* not up yet */
}
await Bun.sleep(120);
}
expect(ready).toBe(true);
});

afterAll(() => {
proc?.kill();
});

describe("malformed percent-encoding is a JSON 400 on both routes (#2747 matrix)", () => {
const malformed = ["%", "%zz", "%E0%A4%A"];
for (const route of ["/discuss/", "/item/"]) {
for (const raw of malformed) {
test(`${route}${raw} -> 400 naming the bad encoding`, async () => {
const res = await fetch(`http://127.0.0.1:${port}${route}${raw}`);
expect(res.status).toBe(400);
expect(res.headers.get("content-type")).toContain("application/json");
const body = (await res.json()) as { error: string };
expect(body.error).toContain("malformed percent-encoding");
expect(body.error).toContain(raw);
});
}
test(`${route}plain value still routes (not a 400)`, async () => {
const res = await fetch(`http://127.0.0.1:${port}${route}plain-ref`);
expect(res.status).not.toBe(400);
});
}

test("/item/<known board id> still resolves 200", async () => {
const board = (await (
await fetch(`http://127.0.0.1:${port}/api/board.json`)
).json()) as { board: { id: string }[] };
const id = encodeURIComponent(board.board[0].id);
const res = await fetch(`http://127.0.0.1:${port}/item/${id}`);
expect(res.status).toBe(200);
});

test("/discuss/<encoded ref> still renders 200", async () => {
const ref = encodeURIComponent("gh:developing-today/code#1");
const res = await fetch(`http://127.0.0.1:${port}/discuss/${ref}`);
expect(res.status).toBe(200);
});
});