diff --git a/src/build/worker-update.ts b/src/build/worker-update.ts index 47a25a814..ac3f19ecf 100644 --- a/src/build/worker-update.ts +++ b/src/build/worker-update.ts @@ -26,7 +26,20 @@ export type WorkerAdmin = { update(spec: UpdateSpec): Promise; }; -const sshArgs = (s: UpdateSpec): string[] => ["-i", s.keyFile, "-o", "IdentitiesOnly=yes", "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=accept-new", s.ssh]; +/** True when every field has the expected shape; the values reach ssh and git argument lists. */ +export function validSpec(s: UpdateSpec): boolean { + return ( + typeof s.sha === "string" && /^[0-9a-f]{40,64}$/.test(s.sha) && + typeof s.ssh === "string" && /^[A-Za-z0-9._-]+@[A-Za-z0-9.:_-]+$/.test(s.ssh) && !s.ssh.startsWith("-") && + typeof s.gitDir === "string" && s.gitDir.startsWith("/") && + typeof s.keyFile === "string" && s.keyFile.startsWith("/") + ); +} + +const sshArgs = (s: UpdateSpec): string[] => { + if (!validSpec(s)) throw new Error("invalid worker update spec"); + return ["-i", s.keyFile, "-o", "IdentitiesOnly=yes", "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=accept-new", s.ssh]; +}; function collect(cmd: string, args: string[], input?: NodeJS.ReadableStream): Promise<{ code: number | null; out: string; err: string }> { return new Promise((resolve, reject) => { @@ -50,6 +63,7 @@ export const sshAdmin: WorkerAdmin = { } }, async update(s) { + if (!validSpec(s)) throw new Error("invalid worker update spec"); const git = spawn("git", [`--git-dir=${s.gitDir}`, "archive", s.sha], { stdio: ["ignore", "pipe", "pipe"] }); let gitErr = ""; git.stderr.on("data", (d) => (gitErr += d)); @@ -72,7 +86,7 @@ export function pendingUpdate(db: DatabaseSync): UpdateSpec | null { if (!raw) return null; try { const s = JSON.parse(raw) as UpdateSpec; - return s && typeof s.sha === "string" ? s : null; + return s && validSpec(s) ? s : null; } catch { return null; } diff --git a/src/embed/text.ts b/src/embed/text.ts index b544c42c4..81157d43f 100644 --- a/src/embed/text.ts +++ b/src/embed/text.ts @@ -23,7 +23,7 @@ export function cleanBody(body: string): string { } export function itemText(title: string | null, body: string | null): string { - const t = (title ?? "").trim(); + const t = (title ?? "").trim().slice(0, 200); const b = cleanBody(body ?? "").slice(0, BODY_CHARS); return b ? `${t}\n${b}` : t; } diff --git a/src/fixup/conflict.ts b/src/fixup/conflict.ts index 624fc8fee..c7587ab9b 100644 --- a/src/fixup/conflict.ts +++ b/src/fixup/conflict.ts @@ -216,7 +216,9 @@ export async function mergeConflict(db: DatabaseSync, x: ConflictRun, c: Conflic if (merge.clean || [...merge.conflicted].sort().join("\n") !== [...files].sort().join("\n")) { fail("failed", "the merge no longer conflicts in the files that were resolved"); return; } const scratch = mkdtempSync(join(x.d.root, ".index-")); try { - tree = await git.withFiles(merge.tree, JSON.parse(c.lint.resolved) as { path: string; mode: string; content: string }[], join(scratch, "index")); + const stored = JSON.parse(c.lint.resolved) as { path: string; mode: string; content: string }[]; + if (stored.some((f) => !resolvablePath(f.path) || (f.mode !== "100644" && f.mode !== "100755"))) { fail("refused", "the stored resolution touches a path or mode a resolution may not"); return; } + tree = await git.withFiles(merge.tree, stored, join(scratch, "index")); } finally { rmSync(scratch, { recursive: true, force: true }); } @@ -258,7 +260,7 @@ export async function mergeConflict(db: DatabaseSync, x: ConflictRun, c: Conflic for (const path of files) { if (!resolvablePath(path)) { refuse(`${path} is not a file a conflict resolution may touch`); return; } const f = await git.file(merge.tree, path); - if (!f.ok) { fail("refused", f.reason); return; } + if (!f.ok) { if (f.tooLarge) refuse(f.reason); else fail("refused", f.reason); return; } if (!hasMarkers(f.content)) { refuse(`${path} conflicts without content markers`); return; } if (f.content.includes("\uFFFD")) { refuse(`${path} is not UTF-8`); return; } const crlf = f.content.includes("\r\n"); diff --git a/src/fixup/git.ts b/src/fixup/git.ts index 588b562c4..05a614eb3 100644 --- a/src/fixup/git.ts +++ b/src/fixup/git.ts @@ -37,6 +37,9 @@ const spawned = (cmd: string, args: string[], opts: ExecOpts, env: NodeJS.Proces p.stdin.end(opts.input ?? ""); }); +/** Largest file read whole into memory for a conflict. */ +const MAX_FILE_BYTES = 1024 * 1024; + export function fixupDir(): string { return envVar("FIXUP_DIR") ?? join(homedir(), ".cache/autocraft/fixups"); } @@ -111,11 +114,14 @@ export class Git { } /** The blob at `sha:path` as text with its mode, or why it can't be used. */ - async file(sha: string, path: string): Promise<{ ok: true; mode: string; content: string } | { ok: false; reason: string }> { + async file(sha: string, path: string): Promise<{ ok: true; mode: string; content: string } | { ok: false; reason: string; tooLarge?: true }> { const t = await this.git(["ls-tree", sha, "--", path]); const m = t.stdout.match(/^(\d+) (\w+) [0-9a-f]+\t/); if (t.code !== 0 || !m) return { ok: false, reason: `${path} does not exist at the head commit` }; if (m[2] !== "blob" || (m[1] !== "100644" && m[1] !== "100755")) return { ok: false, reason: `${path} is not a regular file` }; + const size = await this.git(["cat-file", "-s", `${sha}:${path}`]); + if (size.code !== 0) return { ok: false, reason: `could not read ${path}` }; + if (Number(size.stdout.trim()) > MAX_FILE_BYTES) return { ok: false, reason: `${path} is over the size limit`, tooLarge: true }; const r = await this.git(["cat-file", "blob", `${sha}:${path}`]); if (r.code !== 0) return { ok: false, reason: `could not read ${path}` }; if (r.stdout.includes("\0")) return { ok: false, reason: `${path} is binary` }; diff --git a/src/github/write.ts b/src/github/write.ts index f05ddef72..bd6d0862f 100644 --- a/src/github/write.ts +++ b/src/github/write.ts @@ -573,6 +573,8 @@ export function ghRerunMainFailed(w: Writer, g: GuardedRepo, exec: Exec, o: { re /** Pushes `sha` to a PR's branch `branch` of `remote` (owner/name); refused by git when the branch is no longer at the guarded head. */ export function pushBranch(w: Writer, git: Pick, action: string, g: Guarded, o: { remote: string; branch: string; sha: string }, details: Details = {}): Promise { const b = g.action.bucket; + // The remote is the PR's head repository, which is a fork for an outside PR: only its shape can be checked here. + if (!/^[A-Za-z0-9][A-Za-z0-9._-]*\/[A-Za-z0-9._-]+$/.test(o.remote) || o.branch.startsWith("-") || !/^[0-9a-f]{40,64}$/.test(o.sha)) throw new Error("the push target is not a repository and branch"); if ((g.action.kind === "fixup" && b === "ask") || (g.action.kind === "cifix" && b === "rerun")) throw new Error(`a ${g.action.kind}:${b} grant does not allow a push`); return pushed(w, g, git, action, refOf(g.repo, g.number), o, `--force-with-lease=refs/heads/${o.branch}:${g.head}`, details, { repo: g.repo, number: g.number }); } diff --git a/src/mirror.ts b/src/mirror.ts index 8db5005c0..3d84bb8fa 100644 --- a/src/mirror.ts +++ b/src/mirror.ts @@ -275,9 +275,9 @@ function baseRow(repo: string, kind: Kind, n: Node, detail: Detail): Record x.name)), - assignees: JSON.stringify(n.assignees.nodes.map((x: Node) => x.login)), - comments_count: n.commentCount.totalCount, reactions_count: n.reactionCount?.totalCount ?? null, detail_level: detail, + labels: JSON.stringify((n.labels?.nodes ?? []).filter(Boolean).map((x: Node) => x.name)), + assignees: JSON.stringify((n.assignees?.nodes ?? []).filter(Boolean).map((x: Node) => x.login)), + comments_count: n.commentCount?.totalCount ?? 0, reactions_count: n.reactionCount?.totalCount ?? null, detail_level: detail, }); if (kind === "issue") { r.state_reason = n.stateReason; @@ -288,12 +288,12 @@ function baseRow(repo: string, kind: Kind, n: Node, detail: Detail): Record x.number)), + closing_issues: JSON.stringify((n.closingIssuesReferences?.nodes ?? []).filter(Boolean).map((x: Node) => x.number)), }); if (detail === "full") { Object.assign(r, { maintainer_can_modify: Number(n.maintainerCanModify), mergeable: n.mergeable, - review_decision: n.reviewDecision, ci_state: n.commits.nodes[0]?.commit.statusCheckRollup?.state ?? null, + review_decision: n.reviewDecision, ci_state: n.commits?.nodes?.[0]?.commit?.statusCheckRollup?.state ?? null, }); } return r; @@ -309,10 +309,10 @@ const mentions = (body: unknown, names: string[]): number => { function commentRows(repo: string, kind: Kind, n: Node, own: string[]): SQLInputValue[][] { // `counted`: whether the entry counts as new discussion for the review stage (src/review/discussion.ts). const counted = (c: Node) => Number(isCounted({ author: login(c.author), association: c.authorAssociation, bot: c.author?.__typename === "Bot", prAuthor: login(n.author), state: c.state, body: c.body, inline: c.comments?.totalCount })); - const rows = n.comments.nodes.map((c: Node) => + const rows = (n.comments?.nodes ?? []).filter(Boolean).map((c: Node) => [repo, n.number, c.id, "comment", login(c.author), c.createdAt, c.body, null, null, counted(c), c.authorAssociation ?? null, mentions(c.body, own), c.url ?? null]); if (kind === "pr") { - for (const c of n.reviews.nodes) { + for (const c of (n.reviews?.nodes ?? []).filter(Boolean)) { // A review without a body still counts: its inline threads are the discussion, and it makes earlier reviews stale. rows.push([repo, n.number, c.id, "review", login(c.author), c.createdAt, c.body, c.state, c.commit?.oid ?? null, counted(c), c.authorAssociation ?? null, mentions(c.body, own), c.url ?? null]); } diff --git a/src/reference.ts b/src/reference.ts index c4c1e2f13..ef02b55be 100644 --- a/src/reference.ts +++ b/src/reference.ts @@ -10,6 +10,7 @@ import type { DatabaseSync } from "node:sqlite"; import { audit } from "./dash/audit.ts"; import { connect, dbPath } from "./db.ts"; import { isTracked } from "./repos.ts"; +import { isInstructionPath } from "./sandbox/instruction-paths.ts"; export class ReferenceError extends Error {} @@ -50,6 +51,7 @@ function checkArchive(tarFile: string): { files: number; bytes: number } { if (type !== "-" && type !== "d") throw new ReferenceError("the archive may hold only plain files and directories"); const name = rawName.replace(/^\.\//, "").replace(/\/$/, ""); if (name === "" || name === ".") continue; + if (isInstructionPath(name)) throw new ReferenceError("a name in the archive is not allowed"); const parts = name.split("/"); if (parts.length > (type === "d" ? 1 : 2) || !parts.every((p) => SEGMENT.test(p))) throw new ReferenceError("a name in the archive is not allowed"); if (type === "-") { diff --git a/src/review/opus-parse.ts b/src/review/opus-parse.ts index c230b36d4..42f99c50f 100644 --- a/src/review/opus-parse.ts +++ b/src/review/opus-parse.ts @@ -242,7 +242,7 @@ export function parseOpusReply(text: string, ref: string, last = true, drop: Rea if (typeof verdict !== "string" || !(VERDICTS as readonly string[]).includes(verdict)) return null; if (typeof r.reason !== "string" || !r.reason.trim() || typeof r.sure !== "boolean") return null; const fixes = (Array.isArray(r.fixes) ? r.fixes : []) - .filter((f): f is { file: string; change: string } => !!f && typeof f.file === "string" && typeof f.change === "string" && !!f.change.trim() && (keepLeaky || (!REFERENCE_LEAK.test(f.file) && !REFERENCE_LEAK.test(f.change)))) + .filter((f): f is { file: string; change: string } => !!f && typeof f.file === "string" && safePath(f.file) && typeof f.change === "string" && !!f.change.trim() && (keepLeaky || (!REFERENCE_LEAK.test(f.file) && !REFERENCE_LEAK.test(f.change)))) .slice(0, OPUS_MAX_FIXES).map((f) => ({ file: f.file.slice(0, 200), change: f.change.slice(0, 800) })); if (verdict === "take-fix" && !fixes.length) return null; const risks = Array.isArray(r.risks) ? r.risks.filter((x): x is string => typeof x === "string").slice(0, 8).map((x) => x.slice(0, 300)) : []; diff --git a/src/sandbox/checkout.ts b/src/sandbox/checkout.ts index 9525e96f9..3cb05dedf 100644 --- a/src/sandbox/checkout.ts +++ b/src/sandbox/checkout.ts @@ -32,9 +32,39 @@ function git(gitDir: string, args: string[], input?: string): Promise { }); } +/** Lists the tree of `sha`, killing git as soon as the listing alone shows more than `maxFiles` records or `maxBytes` of file sizes. */ +function lsTree(gitDir: string, sha: string, caps: CheckoutCaps): Promise<{ code: number; stdout: string; tooLarge: string | null }> { + return new Promise((resolve, reject) => { + const p = spawn("git", [...HARDENING, "ls-tree", "-r", "-z", "-l", "--full-tree", sha], { cwd: gitDir, env: { ...process.env, ...GIT_ENV }, stdio: ["ignore", "pipe", "ignore"], timeout: 300_000 }); + let text = ""; + let rest = ""; + let files = 0; + let bytes = 0; + let tooLarge: string | null = null; + p.stdout.setEncoding("utf8"); + p.stdout.on("data", (d: string) => { + if (tooLarge) return; + text += d; + const recs = (rest + d).split("\0"); + rest = recs.pop() ?? ""; + for (const r of recs) { + files++; + bytes += Number(/ +(\d+)\t/.exec(r)?.[1] ?? 0); + } + if (files > caps.maxFiles || bytes > caps.maxBytes) { + tooLarge = `tree too large (over ${files} files, ${bytes} bytes)`; + text = ""; + p.kill("SIGKILL"); + } + }); + p.on("error", reject); + p.on("close", (code) => resolve({ code: code ?? 1, stdout: text, tooLarge })); + }); +} + /** True for a path that is safe to create under the checkout root. */ export function safePath(p: string): boolean { - if (!p || p.length > 500 || p.includes("\0") || p.startsWith("/")) return false; + if (!p || p.length > 500 || p.includes("\0") || p.includes("\\") || p.startsWith("/")) return false; return p.split("/").every((c) => c !== "" && c !== "." && c !== ".." && c.toLowerCase() !== ".git"); } @@ -83,9 +113,10 @@ export async function buildCheckout(gitDir: string, sha: string, dest: string, c touch(dest); return { ok: true, dir: dest, files: 0, bytes: 0 }; } - const ls = await git(gitDir, ["ls-tree", "-r", "-z", "-l", "--full-tree", sha]); + const ls = await lsTree(gitDir, sha, caps); + if (ls.tooLarge) return { ok: false, reason: ls.tooLarge }; if (ls.code !== 0) return { ok: false, reason: "could not list the commit's files" }; - const entries = parseTree(ls.stdout.toString("utf8"), caps); + const entries = parseTree(ls.stdout, caps); const bytes = entries.reduce((a, e) => a + e.size, 0); if (entries.length > caps.maxFiles || bytes > caps.maxBytes) return { ok: false, reason: `tree too large (${entries.length} files, ${bytes} bytes)` }; const cat = await git(gitDir, ["cat-file", "--batch"], entries.map((e) => `${e.oid}\n`).join("")); diff --git a/src/sandbox/index.ts b/src/sandbox/index.ts index 1b3f008b4..d26be6b81 100644 --- a/src/sandbox/index.ts +++ b/src/sandbox/index.ts @@ -4,6 +4,7 @@ import { accessSync, constants, existsSync, readFileSync, realpathSync } from "node:fs"; import { delimiter, join } from "node:path"; import { exec, fixupDir, Git } from "../fixup/git.ts"; +import { SHARED_NAME } from "./command.ts"; import { pruneSessionStores } from "./session-store.ts"; import { buildCheckout, checkoutRoot, pruneCheckouts } from "./checkout.ts"; @@ -66,7 +67,7 @@ export async function checkoutForCommit(repo: string, branch: string, sha: strin } async function checkoutOf(repo: string, sha: string, label: string, log: (line: string) => void, fetch: (g: Git) => Promise): Promise { - if (!sandboxAvailable()) return null; + if (!sandboxAvailable() || !SHARED_NAME.test(repo)) return null; try { const dest = join(checkoutRoot(), repo, sha); pruneCheckouts(checkoutRoot(), MAX_AGE_MS); diff --git a/src/worker/patch.ts b/src/worker/patch.ts index 681d82975..7b21ff4ec 100644 --- a/src/worker/patch.ts +++ b/src/worker/patch.ts @@ -23,7 +23,8 @@ function badPath(p: string): boolean { /** Reason the patch text must be refused, or null. */ export function patchProblem(patch: string): string | null { for (const line of patch.split("\n")) { - if (/^(new file mode|deleted file mode|old mode|new mode|index [0-9a-f.]+\.\.[0-9a-f.]+) 120000\b/.test(line) || /^index [0-9a-f]+\.\.[0-9a-f]+ 120000$/.test(line)) return "patch touches a symlink"; + const mode = /^(?:new file mode|deleted file mode|old mode|new mode) (\S+)\s*$/.exec(line) ?? /^index [0-9a-f.]+\.\.[0-9a-f.]+ (\S+)\s*$/.exec(line); + if (mode && !/^100(644|755)$/.test(mode[1]!)) return "patch touches a symlink or special file"; if (/^(GIT binary patch|Binary files .* differ)$/.test(line)) return "patch has binary content"; if (/^(rename|copy) (from|to) /.test(line) || /^(---|\+\+\+) /.test(line) || /^diff --git /.test(line)) { const rest = line.replace(/^(diff --git|---|\+\+\+|(rename|copy) (from|to)) /, ""); diff --git a/test/worker-patch.test.ts b/test/worker-patch.test.ts new file mode 100644 index 000000000..40d8c9e45 --- /dev/null +++ b/test/worker-patch.test.ts @@ -0,0 +1,14 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { patchProblem } from "../src/worker/patch.ts"; + +const head = "diff --git a/x b/x\n"; + +test("a patch is refused unless every mode is a regular file mode", () => { + assert.equal(patchProblem(`${head}new file mode 100644\nindex 0000000..e69de29\n--- /dev/null\n+++ b/x\n`), null); + assert.equal(patchProblem(`${head}index e69de29..0123456 100755\n--- a/x\n+++ b/x\n`), null); + assert.ok(patchProblem(`${head}new file mode 0120000\n--- /dev/null\n+++ b/x\n`)); + assert.ok(patchProblem(`${head}new file mode 120000\n`)); + assert.ok(patchProblem(`${head}index e69de29..0123456 160000\n`)); + assert.ok(patchProblem(`${head}new mode 100666\n`)); +});