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
15 changes: 14 additions & 1 deletion pm-stack/aggregator/src/sources/live.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ import {
type SessionRecord,
type SourceCoverage,
type UsageView,
isValidRef,
parseRef,
refsInText,
refUrl,
Expand Down Expand Up @@ -485,7 +486,19 @@ export async function projectorLinks(baseUrl: string, subject: string): Promise<
const r = await getJson(`${baseUrl}/links?subject=${encodeURIComponent(subject)}`);
if (!r.ok) return [];
const rows = (r.json as { links?: ProjectorLinkRow[] }).links ?? [];
return rows.map((row) => ({ ref: row.ref, relation: asRelation(row.relation) }));
// Stored rows bypass the projector's POST /links gate (legacy/seeded
// data), so the shared ref rule (#4952) is applied here at the read
// boundary (#6211): a ref parseRef rejects - an unsafe-integer number,
// or not owner/repo#N at all - must never reach a renderer, where
// refUrl would throw on it and 500 the page. The drop is logged so a
// bad registry row stays visible instead of silently vanishing.
return rows.flatMap((row) => {
if (!isValidRef(row.ref)) {
console.error(`[registry] WARNING: dropping projector link with invalid ref ${JSON.stringify(row.ref)} for subject ${subject} (#6211)`);
return [];
}
return [{ ref: row.ref, relation: asRelation(row.relation) }];
});
}

/**
Expand Down
121 changes: 121 additions & 0 deletions pm-stack/aggregator/test/registry-ref-filter-6211.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
// Registry-link ref filter (#6211): a stored pmp_links row whose ref fails
// isValidRef (unsafe-integer number, or not owner/repo#N at all) bypasses
// the projector's POST gate when it is legacy/seeded data, and used to flow
// verbatim through projectorLinks into board items and roadmap rows, where
// renderSearch / project-page rendering threw in refUrl and 500'd the page.
// projectorLinks now drops invalid refs at the read boundary (with a logged
// warning); these tests pin the drop for both subject kinds and the render
// survival of /search with the filtered links attached.
//
// Run: bun test test/registry-ref-filter-6211.test.ts
import { describe, expect, test } from "bun:test";
import type { BoardItem, GhItem, Provenance, ProvenanceDetail, RefKey, RoadmapRow } from "../src/model.ts";
import { renderSearch } from "../src/render.ts";
import { searchWork } from "../src/search-view.ts";
import { projectorLinks } from "../src/sources/live.ts";

const GOOD = "developing-today/code#6211";
const BAD_UNSAFE = "developing-today/code#99999999999999999999";
const BAD_SHAPE = "not-a-ref";

const rowsBySubject: Record<string, { ref: string; relation: string }[]> = {
"kaneo:board-item": [
{ ref: BAD_UNSAFE, relation: "relates" },
{ ref: GOOD, relation: "implements" },
],
"grist:roadmap-row": [
{ ref: BAD_SHAPE, relation: "relates" },
{ ref: BAD_UNSAFE, relation: "relates" },
{ ref: GOOD, relation: "tracks" },
],
};

const realFetch = globalThis.fetch;
globalThis.fetch = (async (input: unknown) => {
const url = new URL(String(input));
const subject = url.searchParams.get("subject") ?? "";
return {
ok: true,
json: async () => ({ links: rowsBySubject[subject] ?? [] }),
} as Response;
}) as typeof fetch;

const provenance = {
board: "live",
roadmap: "live",
items: "live",
comments: "live",
quota: "live",
usage: "live",
attention: "live",
orchestration: "live",
dns: "live",
registry: "live",
aa: "live",
} as Provenance;
const detail = Object.fromEntries(
Object.entries(provenance).map(([key, text]) => [key, { text, state: "live" }]),
) as ProvenanceDetail;

describe("projectorLinks ref filter (#6211)", () => {
test("board subject: unsafe-integer registry ref dropped, good ref kept", async () => {
const links = await projectorLinks("http://projector", "kaneo:board-item");
expect(links).toEqual([{ ref: GOOD, relation: "implements" }]);
});

test("roadmap subject: non-GitHub-shaped and unsafe refs dropped, good ref kept", async () => {
const links = await projectorLinks("http://projector", "grist:roadmap-row");
expect(links).toEqual([{ ref: GOOD, relation: "tracks" }]);
});

test("/search renders a board item and roadmap row enriched from filtered registry links", async () => {
const boardLinks = await projectorLinks("http://projector", "kaneo:board-item");
const roadmapLinks = await projectorLinks("http://projector", "grist:roadmap-row");
const board: BoardItem[] = [
{
id: "kaneo:pm-stack/task-6211",
title: "Registry ref filter",
repo: "developing-today/code",
source: "kaneo",
status: "in-progress",
links: boardLinks,
},
];
const rows: RoadmapRow[] = [
{
id: 6211,
subject: "grist:program/roadmap/6211",
title: "Registry ref filter",
area: "Work",
status: "In Progress",
horizon: "November 2026",
source: "Grist",
notes: "",
links: roadmapLinks,
},
];
const projected = new Map<RefKey, GhItem>([
[
GOOD as RefKey,
{
ref: GOOD as RefKey,
kind: "issue",
url: "https://github.com/developing-today/code/issues/6211",
title: "Unsafe-integer registry refs",
state: "open",
labels: [],
author: "octocat",
updatedAt: "2026-11-05T00:00:00Z",
resolution: "projector",
},
],
]);
const results = searchWork(board, rows, projected, "Registry ref filter");
expect(results.map((r) => r.kind)).toEqual(["board", "roadmap"]);
const html = renderSearch("Registry ref filter", results, projected, provenance, detail);
expect(html).toContain(GOOD);
expect(html).not.toContain(BAD_UNSAFE);
expect(html).not.toContain(BAD_SHAPE);
globalThis.fetch = realFetch;
});
});
15 changes: 14 additions & 1 deletion pm-stack/projector/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,19 @@ export function parseCursor(raw: string | null): number | null {
return Number.isSafeInteger(n) ? n : null;
}

/** A link ref is storable only if it is owner/repo#N with a safe-integer
* N - the same rule the aggregator's parseRef enforces (#4952, #6211).
* The shape regex alone admits numbers parseRef (and refUrl) throw on
* (e.g. a 20-digit issue number), and one such stored row 500s the
* aggregator's /search and project pages at render, so the write gate
* checks the number itself, not just the shape. */
export function isStorableLinkRef(ref: unknown): ref is string {
if (typeof ref !== "string") return false;
const m = /^[\w.-]+\/[\w.-]+#(\d+)$/.exec(ref);
if (!m) return false;
return Number.isSafeInteger(Number(m[1]));
}

function bearerAuthorized(req: Request, env: ServerEnv): boolean {
const token = env.PM_PROJECTOR_API_TOKEN;
if (!token) return false; // fail closed when no token configured
Expand Down Expand Up @@ -243,7 +256,7 @@ export async function handleRequest(req: Request, db: Client, env: ServerEnv): P
typeof subject !== "string" ||
subject.length === 0 ||
typeof ref !== "string" ||
!/^[\w.-]+\/[\w.-]+#\d+$/.test(ref)
!isStorableLinkRef(ref)
) {
return jsonResponse(400, { error: "subject (non-empty string) and ref (owner/repo#N) required" });
}
Expand Down
90 changes: 90 additions & 0 deletions pm-stack/projector/test/links-ref-gate-6211.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
// POST /links ref gate alignment (#6211): the shape regex alone admitted
// refs whose number is not a safe integer (e.g. a 20-digit issue number) -
// exactly the values the aggregator's parseRef rejects (#4952). One such
// stored row then 500s /search and project pages at render. The write gate
// now applies the same rule as parseRef: owner/repo#N AND a safe-integer N.
//
// Run: bun test test/links-ref-gate-6211.test.ts
import { describe, test, expect, beforeAll, afterAll } from "bun:test";
import { createClient, type Client } from "@libsql/client";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { migrate } from "../src/store";
import { handleRequest, isStorableLinkRef, type ServerEnv } from "../src/server";

const TOKEN = "test-api-token";
const env: ServerEnv = { PM_PROJECTOR_API_TOKEN: TOKEN };

let db: Client;
let dir: string;

async function post(body: unknown): Promise<{ status: number; body: any }> {
const res = await handleRequest(
new Request("http://127.0.0.1/links", {
method: "POST",
headers: { "content-type": "application/json", authorization: `Bearer ${TOKEN}` },
body: JSON.stringify(body),
}),
db,
env,
);
return { status: res.status, body: await res.json() };
}

async function linkCount(): Promise<number> {
const rows = await db.execute("SELECT COUNT(*) AS n FROM pmp_links");
return Number((rows.rows[0] as any).n);
}

const subject = "kaneo:code/CODE-6211";

beforeAll(async () => {
dir = mkdtempSync(join(tmpdir(), "pm-projector-ref-gate-"));
db = createClient({ url: `file:${join(dir, "links.db")}` });
await migrate(db);
});

afterAll(() => {
db.close();
rmSync(dir, { recursive: true, force: true });
});

describe("isStorableLinkRef", () => {
test("accepts ordinary and max-safe-integer refs", () => {
expect(isStorableLinkRef("developing-today/code#123")).toBe(true);
expect(isStorableLinkRef("developing-today/code#9007199254740991")).toBe(true);
});

test("rejects unsafe-integer numbers the shape regex admits", () => {
expect(isStorableLinkRef("developing-today/code#99999999999999999999")).toBe(false);
expect(isStorableLinkRef("developing-today/code#9007199254740992")).toBe(false);
});

test("rejects non-refs and non-strings", () => {
expect(isStorableLinkRef("not-a-ref")).toBe(false);
expect(isStorableLinkRef("developing-today/code#12e3")).toBe(false);
expect(isStorableLinkRef(123)).toBe(false);
expect(isStorableLinkRef(null)).toBe(false);
});
});

describe("POST /links safe-integer gate", () => {
test("unsafe-integer ref -> 400, nothing stored", async () => {
const r = await post({ subject, ref: "developing-today/code#99999999999999999999" });
expect(r.status).toBe(400);
expect(await linkCount()).toBe(0);
});

test("max safe integer ref -> 201, stored", async () => {
const r = await post({ subject, ref: "developing-today/code#9007199254740991" });
expect(r.status).toBe(201);
expect(await linkCount()).toBe(1);
});

test("ordinary ref -> 201, stored", async () => {
const r = await post({ subject, ref: "developing-today/code#6211" });
expect(r.status).toBe(201);
expect(await linkCount()).toBe(2);
});
});