6ff8f34666af0f9d72d40cf40cee5c98ad090dc0 / bench/tasks/fix_hard/ts_cidr_allowlist.py · 16456 bytes · raw
"""TypeScript (bun): a CIDR allowlist split across addr / cidr / rules / allowlist / report.
rules.ts expands a FIRST-LAST range by handing parseSpan's half-open `end` (one past the last
address) to rangeToCidrs, whose `last` is inclusive, so every range also covers the address just
after it as an extra block. In the VPN fixture that extra block is an `allow 10.8.0.100/32` on a
later line than the pinned `deny 10.8.0.100`, so the kiosk address flips to allow: the symptom
reads as a tie-break problem in allowlist.ts. The tempting patches (deny wins ties in
allowlist.ts, an exclusive `last` in cidr.ts, an inclusive span end in addr.ts) each fix that test
but break the tie-break, rangeToCidrs or report tests."""
import re
ITEM_ID = "ts-cidr-allowlist"
LANG = "ts"
TOOL = "bun"
PROJECT = {
"src/addr.ts": r'''// IPv4 addresses as plain numbers (0 .. 2**32 - 1) and spans of them.
//
// Arithmetic here sticks to ordinary number math, never the 32-bit bitwise operators, so
// addresses at or above 128.0.0.0 stay positive.
export const ADDRESS_COUNT = 2 ** 32;
export function parseIp(text: string): number {
const parts = text.trim().split(".");
if (parts.length !== 4) throw new Error(`not an IPv4 address: ${text}`);
let n = 0;
for (const p of parts) {
if (!/^[0-9]{1,3}$/.test(p) || Number(p) > 255) throw new Error(`not an IPv4 address: ${text}`);
n = n * 256 + Number(p);
}
return n;
}
export function formatIp(n: number): string {
const out: number[] = [];
for (let i = 0; i < 4; i++) {
out.unshift(n % 256);
n = Math.floor(n / 256);
}
return out.join(".");
}
/** A run of consecutive addresses, half-open like Array.slice: `start` is the first address
* and `end` is one past the last, so the span holds `end - start` addresses. */
export interface Span {
start: number;
end: number;
}
/** Parses "a.b.c.d" (one address), "a.b.c.d/n" (a CIDR block; host bits must be zero) or
* "a.b.c.d-e.f.g.h" (both ends included, as rule files write ranges). */
export function parseSpan(text: string): Span {
const t = text.trim();
const dash = t.indexOf("-");
if (dash >= 0) {
const first = parseIp(t.slice(0, dash));
const last = parseIp(t.slice(dash + 1));
if (last < first) throw new Error(`range ends before it starts: ${text}`);
return { start: first, end: last + 1 };
}
const slash = t.indexOf("/");
if (slash < 0) {
const a = parseIp(t);
return { start: a, end: a + 1 };
}
const base = parseIp(t.slice(0, slash));
const bits = t.slice(slash + 1);
if (!/^[0-9]{1,2}$/.test(bits) || Number(bits) > 32) throw new Error(`bad prefix length: ${text}`);
const size = 2 ** (32 - Number(bits));
if (base % size !== 0) throw new Error(`host bits set: ${text}`);
return { start: base, end: base + size };
}
export function spanSize(s: Span): number {
return s.end - s.start;
}
/** Sorts spans and joins any that overlap or touch, e.g. [10, 20) and [20, 30) -> [10, 30). */
export function mergeSpans(spans: Span[]): Span[] {
const sorted = [...spans].sort((a, b) => a.start - b.start || a.end - b.end);
const out: Span[] = [];
for (const s of sorted) {
const last = out[out.length - 1];
if (last && s.start <= last.end) last.end = Math.max(last.end, s.end);
else out.push({ start: s.start, end: s.end });
}
return out;
}
''',
"src/cidr.ts": r'''import { formatIp, parseIp } from "./addr";
/** A CIDR block: `base` is its first address (host bits zero), `prefix` is 0..32. */
export interface Cidr {
base: number;
prefix: number;
}
export function blockSize(prefix: number): number {
return 2 ** (32 - prefix);
}
/** Parses "a.b.c.d/n", or a bare "a.b.c.d" as a /32. Host bits must be zero. */
export function parseCidr(text: string): Cidr {
const [ip, bits, extra] = text.trim().split("/");
if (extra !== undefined) throw new Error(`bad CIDR: ${text}`);
const base = parseIp(ip);
if (bits === undefined) return { base, prefix: 32 };
if (!/^[0-9]{1,2}$/.test(bits) || Number(bits) > 32) throw new Error(`bad prefix length: ${text}`);
const prefix = Number(bits);
if (base % blockSize(prefix) !== 0) throw new Error(`host bits set: ${text}`);
return { base, prefix };
}
export function formatCidr(c: Cidr): string {
return `${formatIp(c.base)}/${c.prefix}`;
}
export function contains(c: Cidr, addr: number): boolean {
return addr >= c.base && addr < c.base + blockSize(c.prefix);
}
/** The fewest CIDR blocks that together cover the addresses first..last, both ends included,
* in ascending order. rangeToCidrs(a, a) is the single /32 for a. */
export function rangeToCidrs(first: number, last: number): Cidr[] {
const out: Cidr[] = [];
let cur = first;
while (cur <= last) {
let prefix = 32;
while (prefix > 0) {
const wider = blockSize(prefix - 1);
if (cur % wider !== 0 || cur + wider - 1 > last) break;
prefix--;
}
out.push({ base: cur, prefix });
cur += blockSize(prefix);
}
return out;
}
''',
"src/rules.ts": r'''// Rule files: one rule per line, `allow|deny TARGET`, with `#` comments and blank lines.
// TARGET is a CIDR block (10.8.0.0/16), a single address (a /32) or a range written
// FIRST-LAST with both ends included (10.8.0.10-10.8.0.99).
import { parseSpan } from "./addr";
import { type Cidr, parseCidr, rangeToCidrs } from "./cidr";
export type Action = "allow" | "deny";
/** One rule line, before its target is interpreted. `line` is 1-based. */
export interface RuleLine {
line: number;
action: Action;
target: string;
}
/** A compiled rule. A range line compiles to several rules that share its line number. */
export interface Rule {
action: Action;
cidr: Cidr;
line: number;
}
export function tokenize(text: string): RuleLine[] {
const out: RuleLine[] = [];
text.split("\n").forEach((raw, i) => {
const body = raw.replace(/#.*/, "").trim();
if (body === "") return;
const words = body.split(/\s+/);
if (words.length !== 2 || (words[0] !== "allow" && words[0] !== "deny")) {
throw new Error(`line ${i + 1}: expected "allow|deny TARGET", got: ${raw.trim()}`);
}
out.push({ line: i + 1, action: words[0] as Action, target: words[1] });
});
return out;
}
/** Compiles a rule file. CIDR and single-address targets keep the prefix they were written
* with (precedence depends on it); a range becomes the fewest CIDR blocks that cover it. */
export function parseRules(text: string): Rule[] {
const rules: Rule[] = [];
for (const { line, action, target } of tokenize(text)) {
try {
if (target.includes("-")) {
const { start, end } = parseSpan(target);
for (const cidr of rangeToCidrs(start, end)) rules.push({ action, cidr, line });
} else {
rules.push({ action, cidr: parseCidr(target), line });
}
} catch (e) {
throw new Error(`line ${line}: ${(e as Error).message}`);
}
}
return rules;
}
''',
"src/allowlist.ts": r'''import { parseIp } from "./addr";
import { contains, formatCidr } from "./cidr";
import { type Action, type Rule, parseRules } from "./rules";
/** A compiled rule file, queried per source address.
*
* Precedence: among the rules whose block contains the address, the most specific one (the
* longest prefix) decides; between equally specific rules the one on the later line decides,
* so an appended line can override an older one. An address no rule covers is denied. */
export class Allowlist {
readonly rules: Rule[];
constructor(text: string) {
this.rules = parseRules(text);
}
/** The deciding rule for `ip`, or null when no rule covers it. */
match(ip: string | number): Rule | null {
const addr = typeof ip === "number" ? ip : parseIp(ip);
let best: Rule | null = null;
for (const r of this.rules) {
if (!contains(r.cidr, addr)) continue;
if (
best === null ||
r.cidr.prefix > best.cidr.prefix ||
(r.cidr.prefix === best.cidr.prefix && r.line > best.line)
) {
best = r;
}
}
return best;
}
decide(ip: string | number): Action {
return this.match(ip)?.action ?? "deny";
}
/** One line for logs, e.g. "deny 172.20.4.9 (line 2: 172.20.0.0/16)". */
explain(ip: string): string {
const r = this.match(ip);
if (r === null) return `deny ${ip} (no rule; default)`;
return `${r.action} ${ip} (line ${r.line}: ${formatCidr(r.cidr)})`;
}
}
''',
"src/report.ts": r'''// A summary of a rule file for change review: how many addresses each line names and how
// many distinct addresses all allow lines (and all deny lines) cover together.
import { type Span, mergeSpans, parseSpan, spanSize } from "./addr";
import { type Action, tokenize } from "./rules";
export interface LineSummary {
line: number;
action: Action;
target: string;
addresses: number;
}
export interface Summary {
lines: LineSummary[];
allowed: number;
denied: number;
}
function covered(spans: Span[]): number {
return mergeSpans(spans).reduce((n, s) => n + spanSize(s), 0);
}
export function summarize(text: string): Summary {
const lines: LineSummary[] = [];
const allow: Span[] = [];
const deny: Span[] = [];
for (const { line, action, target } of tokenize(text)) {
const span = parseSpan(target);
lines.push({ line, action, target, addresses: spanSize(span) });
(action === "allow" ? allow : deny).push(span);
}
return { lines, allowed: covered(allow), denied: covered(deny) };
}
/** e.g. "line 4 allow 90 10.8.0.10-10.8.0.99" */
export function formatSummary(s: Summary): string {
const rows = s.lines.map(
(l) => `line ${l.line} ${l.action.padEnd(5)} ${String(l.addresses).padStart(4)} ${l.target}`,
);
rows.push(`allow lines cover ${s.allowed} addresses; deny lines cover ${s.denied}`);
return rows.join("\n");
}
''',
"tests/allowlist.test.ts": r'''import { describe, expect, test } from "bun:test";
import { Allowlist } from "../src/allowlist";
const VPN = [
"# vpn.rules: client addresses handed out by the VPN concentrator",
"deny 10.8.0.0/24 # closed unless opened below",
"deny 10.8.0.100 # shared kiosk login",
"allow 10.8.0.10-10.8.0.99 # contractor pool",
"allow 10.8.0.101-10.8.0.120 # on-call staff",
"allow 10.8.0.7 # concentrator health check",
].join("\n");
describe("allowlist", () => {
test("the longest prefix wins whatever the line order", () => {
const a = new Allowlist("deny 10.66.6.0/24\nallow 10.0.0.0/8\n");
expect(a.decide("10.66.6.6")).toBe("deny");
expect(a.decide("10.1.2.3")).toBe("allow");
});
test("the later line wins between equally specific rules", () => {
const a = new Allowlist(
["allow 172.16.0.0/12", "deny 172.16.5.0/24", "allow 172.16.5.0/24 # reopened after the move"].join("\n"),
);
expect(a.decide("172.16.5.9")).toBe("allow");
expect(a.explain("172.16.5.9")).toBe("allow 172.16.5.9 (line 3: 172.16.5.0/24)");
});
test("addresses no rule covers are denied", () => {
const a = new Allowlist(VPN);
expect(a.decide("8.8.8.8")).toBe("deny");
expect(a.explain("8.8.8.8")).toBe("deny 8.8.8.8 (no rule; default)");
});
test("vpn: pools admit their first and last address", () => {
const a = new Allowlist(VPN);
expect(a.decide("10.8.0.9")).toBe("deny");
expect(a.decide("10.8.0.10")).toBe("allow");
expect(a.decide("10.8.0.99")).toBe("allow");
expect(a.decide("10.8.0.101")).toBe("allow");
expect(a.decide("10.8.0.120")).toBe("allow");
expect(a.decide("10.8.0.7")).toBe("allow");
});
test("vpn: the kiosk address stays closed", () => {
const a = new Allowlist(VPN);
expect(a.decide("10.8.0.100")).toBe("deny");
});
});
''',
"tests/cidr.test.ts": r'''import { describe, expect, test } from "bun:test";
import { formatIp, parseIp } from "../src/addr";
import { contains, formatCidr, parseCidr, rangeToCidrs } from "../src/cidr";
const cover = (a: string, b: string) => rangeToCidrs(parseIp(a), parseIp(b)).map(formatCidr);
describe("cidr", () => {
test("addresses above 128.0.0.0 stay positive", () => {
expect(parseIp("203.0.113.7")).toBe(3405803783);
expect(formatIp(parseIp("255.255.255.255"))).toBe("255.255.255.255");
});
test("parseCidr reads blocks and bare addresses", () => {
expect(parseCidr("10.8.0.0/16")).toEqual({ base: parseIp("10.8.0.0"), prefix: 16 });
expect(parseCidr("192.0.2.7")).toEqual({ base: parseIp("192.0.2.7"), prefix: 32 });
expect(() => parseCidr("10.8.0.1/16")).toThrow("host bits");
});
test("contains honours both block edges", () => {
const c = parseCidr("192.168.4.0/22");
expect(contains(c, parseIp("192.168.3.255"))).toBe(false);
expect(contains(c, parseIp("192.168.4.0"))).toBe(true);
expect(contains(c, parseIp("192.168.7.255"))).toBe(true);
expect(contains(c, parseIp("192.168.8.0"))).toBe(false);
});
test("rangeToCidrs covers exactly the given addresses", () => {
expect(cover("10.0.0.0", "10.0.0.255")).toEqual(["10.0.0.0/24"]);
expect(cover("192.0.2.7", "192.0.2.7")).toEqual(["192.0.2.7/32"]);
expect(cover("172.16.0.1", "172.16.0.6")).toEqual([
"172.16.0.1/32",
"172.16.0.2/31",
"172.16.0.4/31",
"172.16.0.6/32",
]);
expect(cover("198.51.100.255", "198.51.101.0")).toEqual(["198.51.100.255/32", "198.51.101.0/32"]);
});
});
''',
"tests/report.test.ts": r'''import { describe, expect, test } from "bun:test";
import { mergeSpans, parseIp, parseSpan } from "../src/addr";
import { formatSummary, summarize } from "../src/report";
describe("report", () => {
test("spans are half-open", () => {
expect(parseSpan("192.168.10.0/24")).toEqual({ start: parseIp("192.168.10.0"), end: parseIp("192.168.11.0") });
expect(parseSpan("172.16.0.1-172.16.0.254")).toEqual({ start: parseIp("172.16.0.1"), end: parseIp("172.16.0.255") });
expect(parseSpan("192.0.2.7")).toEqual({ start: parseIp("192.0.2.7"), end: parseIp("192.0.2.8") });
});
test("mergeSpans joins overlapping and touching spans", () => {
expect(mergeSpans([{ start: 30, end: 40 }, { start: 10, end: 20 }, { start: 20, end: 25 }])).toEqual([
{ start: 10, end: 25 },
{ start: 30, end: 40 },
]);
});
test("summarize counts each line and the distinct totals", () => {
const s = summarize(`
allow 10.8.0.10-10.8.0.99 # contractor pool
allow 10.8.0.64/26
deny 10.8.0.200
`);
expect(s.lines.map((l) => [l.line, l.addresses])).toEqual([[2, 90], [3, 64], [4, 1]]);
expect(s.allowed).toBe(118);
expect(s.denied).toBe(1);
expect(formatSummary(s).split("\n")[0]).toBe("line 2 allow 90 10.8.0.10-10.8.0.99");
});
});
''',
}
def _patched(path, old, new):
"""{path: PROJECT[path] with `old` replaced once}; fails loudly if `old` is not there."""
src = PROJECT[path]
assert src.count(old) == 1, (path, old)
return {path: src.replace(old, new)}
HIDDEN = ("tests/allowlist.test.ts", "tests/cidr.test.ts", "tests/report.test.ts")
FIX = _patched("src/rules.ts", "rangeToCidrs(start, end))", "rangeToCidrs(start, end - 1))")
TEST_CMD = ["bun", "test"] # bun hides its (pass) lines under an AI agent; tools.AGENT_ENV strips the markers
PASS_RE = r"^\(pass\) (.+?)(?: \[[^\]]*\])?$"
TESTS = tuple(re.search(r'^describe\("([^"]+)"', PROJECT[h], re.M).group(1) + " > " + name
for h in HIDDEN for name in re.findall(r'^ test\("([^"]+)"', PROJECT[h], re.M))
WRONG = [
# deny wins ties at the symptom site
_patched("src/allowlist.ts",
"(r.cidr.prefix === best.cidr.prefix && r.line > best.line)",
"(r.cidr.prefix === best.cidr.prefix && r.action === \"deny\")"),
# rangeToCidrs takes an exclusive end, matching what rules.ts passes
_patched("src/cidr.ts",
" while (cur <= last) {\n let prefix = 32;\n while (prefix > 0) {\n"
" const wider = blockSize(prefix - 1);\n"
" if (cur % wider !== 0 || cur + wider - 1 > last) break;\n",
" while (cur < last) {\n let prefix = 32;\n while (prefix > 0) {\n"
" const wider = blockSize(prefix - 1);\n"
" if (cur % wider !== 0 || cur + wider > last) break;\n"),
# ranges parse to an inclusive end
_patched("src/addr.ts",
" return { start: first, end: last + 1 };\n",
" return { start: first, end: last };\n"),
]