| 1 | import { readFileSync } from "node:fs"; |
| 2 | |
| 3 | const [rulesPath, lane] = process.argv.slice(2); |
| 4 | if (!rulesPath || !lane) { |
| 5 | console.error("usage: check-allowlist.mjs <rules-file> <lane> (git diff --name-status on stdin)"); |
| 6 | process.exit(2); |
| 7 | } |
| 8 | |
| 9 | const toRegExp = (glob) => |
| 10 | new RegExp( |
| 11 | "^" + |
| 12 | glob |
| 13 | .replace(/[.+^${}()|[\]\\]/g, "\\$&") |
| 14 | .replace(/\*\*\//g, "\u0000") |
| 15 | .replace(/\*\*/g, "\u0001") |
| 16 | .replace(/\*/g, "[^/]*") |
| 17 | .replace(/\u0000/g, "(?:.*/)?") |
| 18 | .replace(/\u0001/g, ".*") + |
| 19 | "$", |
| 20 | ); |
| 21 | |
| 22 | const allow = []; |
| 23 | const deny = []; |
| 24 | for (const raw of readFileSync(rulesPath, "utf8").split("\n")) { |
| 25 | const line = raw.trim(); |
| 26 | if (!line) continue; |
| 27 | if (line.startsWith("!")) { |
| 28 | deny.push(toRegExp(line.slice(1))); |
| 29 | continue; |
| 30 | } |
| 31 | const split = line.indexOf(": "); |
| 32 | if (split < 1) continue; |
| 33 | if (line.slice(0, split) === lane) allow.push(toRegExp(line.slice(split + 2))); |
| 34 | } |
| 35 | |
| 36 | if (allow.length === 0) { |
| 37 | console.error(`::error::no allowlist entries for lane "${lane}"`); |
| 38 | process.exit(1); |
| 39 | } |
| 40 | |
| 41 | const changes = readFileSync(0, "utf8").split("\n").filter(Boolean); |
| 42 | const bad = []; |
| 43 | for (const entry of changes) { |
| 44 | const [status, path, ...rest] = entry.split("\t"); |
| 45 | const unsafe = !path || rest.length > 0 || path.startsWith("/") || path.split("/").includes("..") || path.includes("\\"); |
| 46 | if (status !== "M" || unsafe || deny.some((re) => re.test(path)) || !allow.some((re) => re.test(path))) { |
| 47 | bad.push(entry.replace(/\t/g, " ")); |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | if (bad.length > 0) { |
| 52 | console.error(`::error::lane "${lane}" changed paths outside its allowlist or by something other than an in-place edit:`); |
| 53 | for (const entry of bad) console.error(` ${entry}`); |
| 54 | process.exit(1); |
| 55 | } |
| 56 | console.log(`lane "${lane}": ${changes.length} changed file(s), all inside the allowlist.`); |
| 57 |