mirror of
https://github.com/storytold/autocraft.git
synced 2026-11-26 01:11:04 +01:00
Security landing: quiet until published, viewer veil on model text, single draft advisory, Land reset from awaiting-admin, warm build scope, block-comment tracking
This commit is contained in:
1 parent
f22740fc6c
commit
fefca4928f
13 files changed
+95
-28
No files matched your search
@@ -264,5 +264,6 @@ export function fromRow(r: Partial<SettledRow> | undefined): Settled {
|
||||
};
|
||||
}
|
||||
|
||||
/** The verdict without its `security` flag, for the quiet pull request of a security fix that is still landing. */
|
||||
export const unflagged = (s: Settled, quiet: boolean): Settled => (quiet ? { ...s, flags: s.flags.filter((f) => f !== "security") } : s);
|
||||
/** The verdict of a quiet pull request without its `security` flag (for every role), and without the referee's reason for viewers. */
|
||||
export const unflagged = (s: Settled, quiet: boolean, staff = true): Settled =>
|
||||
quiet ? { ...s, flags: s.flags.filter((f) => f !== "security"), referee: s.referee && !staff ? { ...s.referee, reason: "" } : s.referee } : s;
|
||||
+2
-6
@@ -1,6 +1,8 @@
|
||||
// Facts: everything the review-to-merge rules read about open PRs, loaded in one pass for a whole database or a slice of it.
|
||||
// Each concept has one definition here. Where a step selector and the merge queue used different
|
||||
// definitions, the queue's wins; the differences are listed in the report of this change, not here.
|
||||
import { quietFixPrs } from "../security/quiet.ts";
|
||||
export { quietFixPrs };
|
||||
import type { DatabaseSync } from "node:sqlite";
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
@@ -434,12 +436,6 @@ export function ownFixPrs(db: DatabaseSync, repo?: string): { login: string | nu
|
||||
return { login, prs, quiet };
|
||||
}
|
||||
|
||||
/** Quiet pull requests of security fixes that are still landing, as `repo#number`. They are the pipeline's own fix PRs; nothing public may call them a security matter until they merge. */
|
||||
export function quietFixPrs(db: DatabaseSync, repo?: string): Set<string> {
|
||||
const rows = db.prepare("SELECT repo, fix_pr AS n FROM main.security_findings WHERE state = 'landing' AND fork IS NULL AND fix_pr IS NOT NULL" + (repo ? " AND repo = ?" : "")).all(...(repo ? [repo] : [])) as { repo: string; n: number }[];
|
||||
return new Set(rows.map((r) => `${r.repo}#${r.n}`));
|
||||
}
|
||||
|
||||
/** Reads the pipeline account and the last successful assign or unassign of every item from the audit once; the returned function gives an item's assignment facts from its mirrored `assignees` (JSON). */
|
||||
export function assignmentsOf(db: DatabaseSync, repo?: string): (ref: string, assignees: string | null) => AssignFacts {
|
||||
const login = (db.prepare("SELECT value FROM main.settings WHERE key = ?").get(PIPELINE_LOGIN_KEY) as { value: string } | undefined)?.value ?? null;
|
||||
|
||||
@@ -23,6 +23,7 @@ import { queueSlots } from "../../rank/position.ts";
|
||||
import { hiddenRepos, visibleRepos } from "./visible.ts";
|
||||
import { pickDecision, shortRepo } from "../../../web/src/lib/links.ts";
|
||||
import { canSeeInternals } from "./staff.ts";
|
||||
import { isQuiet } from "../../security/quiet.ts";
|
||||
|
||||
export const CLAIM_TTL = 10 * 60_000;
|
||||
const COMMENT_MAX = 4000;
|
||||
@@ -197,7 +198,9 @@ export function toDecision(db: DatabaseSync, d: DecisionRow, viewer: Viewer): De
|
||||
const claimRow = db.prepare(`SELECT login, since FROM decision_claims WHERE decision_id = ? AND at > ? AND login <> ? ORDER BY at DESC LIMIT 1`)
|
||||
.get(d.id, new Date(Date.now() - CLAIM_TTL).toISOString(), viewer.login) as Claim | undefined;
|
||||
const commentCount = (db.prepare("SELECT COUNT(*) AS n FROM decision_comments WHERE decision_id = ?").get(d.id) as { n: number }).n;
|
||||
return {
|
||||
// Viewers get none of the model text of a decision about a quiet pull request.
|
||||
const veil = !viewer.staff && !batch && d.repo !== null && d.number !== null && isQuiet(db, d.repo, d.number);
|
||||
const out: Decision = {
|
||||
id: d.id, kind: d.kind as DecisionKind,
|
||||
repo: d.repo ?? refs[0]?.repo ?? "",
|
||||
number: d.number,
|
||||
@@ -234,6 +237,11 @@ export function toDecision(db: DatabaseSync, d: DecisionRow, viewer: Viewer): De
|
||||
priority: batch ? null : priorityOf(db, d.repo!, d.number!),
|
||||
queue: batch ? null : (viewer.slots?.get(`${d.repo}#${d.number}`) ?? null),
|
||||
};
|
||||
if (!veil) return out;
|
||||
return {
|
||||
...out, question: "", summary: "", context: [], facts: [], recommendedReason: "", risks: [], publicText: null, optionTexts: [],
|
||||
classifications: out.classifications.map((c) => ({ ...c, reason: "" })), priority: out.priority && { ...out.priority, reason: null },
|
||||
};
|
||||
}
|
||||
|
||||
const list = (req: Req, key: string): string[] => req.query.getAll(key).flatMap((v) => v.split(",")).map((s) => s.trim()).filter(Boolean);
|
||||
|
||||
+13
-3
@@ -44,7 +44,7 @@ import { actionsOf as releasesOf } from "../../operator-actions.ts";
|
||||
import { verificationOf } from "../../verify/results.ts";
|
||||
import { areaNameOf } from "../../areas/store.ts";
|
||||
import { settledOf, unflagged } from "../../classify/settled.ts";
|
||||
import { quietFixPrs } from "../../core/facts.ts";
|
||||
import { isQuiet } from "../../security/quiet.ts";
|
||||
import { classificationsOf, itemState, relatedOf } from "./decisions.ts";
|
||||
import * as sim from "./similar.ts";
|
||||
import { needs } from "./needs.ts";
|
||||
@@ -124,7 +124,9 @@ async function item(db: DatabaseSync, req: Req): Promise<Item> {
|
||||
const decisionIds = (db.prepare(`SELECT id FROM decisions WHERE (repo = :repo AND number = :n) OR (number IS NULL AND EXISTS (
|
||||
SELECT 1 FROM json_each(CASE WHEN json_valid(items) THEN items ELSE '[]' END) j
|
||||
WHERE json_extract(j.value, '$.repo') = :repo AND json_extract(j.value, '$.number') = :n)) ORDER BY asked_at`).all({ repo, n }) as { id: string }[]).map((r) => r.id);
|
||||
return {
|
||||
// The quiet pull request of a security fix: viewers get none of the model text about it.
|
||||
const veil = !canSeeInternals(req) && isQuiet(db, repo, n);
|
||||
const out: Item = {
|
||||
repo, number: n, kind: it.kind === "pr" ? "pr" : "issue",
|
||||
title: it.title ?? "", body: it.body ?? "", state: itemState(it.state), author: it.author ?? "",
|
||||
tier: TIER[c?.tier ?? "not"] ?? "not", authorMerged: c?.merged ?? 0, authorClosedUnmerged: c?.closed ?? 0,
|
||||
@@ -140,7 +142,7 @@ async function item(db: DatabaseSync, req: Req): Promise<Item> {
|
||||
related: relatedOf(db, repo, n), classifications: classificationsOf(db, repo, n), area: areaNameOf(db, repo, n),
|
||||
stages: stages.map((s) => ({ ...s, by: s.by ?? "" })),
|
||||
comments: comments.map((x) => ({ ...x, author: x.author ?? "", body: x.body ?? "" })),
|
||||
decisionIds, settled: unflagged(settledOf(db, repo, n), quietFixPrs(db, repo).has(`${repo}#${n}`)) as Item["settled"], priority: priorityOf(db, repo, n),
|
||||
decisionIds, settled: unflagged(settledOf(db, repo, n), isQuiet(db, repo, n), !veil) as Item["settled"], priority: priorityOf(db, repo, n),
|
||||
...(it.kind === "pr" ? prWork(db, repo, n, canSeeInternals(req)) : { verification: null, fixups: [] }),
|
||||
// The reviewer's reasons quote the patch, so viewers get the verdict only.
|
||||
patchChecks: checksOf(db, repo, n).map(({ kind, subject, patchHash, round, verdict, reasons, problems, model, createdAt }) =>
|
||||
@@ -153,6 +155,14 @@ async function item(db: DatabaseSync, req: Req): Promise<Item> {
|
||||
// The operator's instructions are shown to those who see the internals only.
|
||||
...(it.kind === "pr" ? { preapproval: ((p) => (p && !canSeeInternals(req) ? { ...p, instructions: "" } : p))(preapprovalOf(db, repo, n)) } : {}),
|
||||
};
|
||||
if (!veil) return out;
|
||||
return {
|
||||
...out,
|
||||
classifications: out.classifications.map((c) => ({ ...c, reason: "" })),
|
||||
priority: out.priority && { ...out.priority, reason: null },
|
||||
premerge: out.premerge?.map((p) => ({ ...p, findings: [] })),
|
||||
reviews: out.reviews && { ...out.reviews, conflicts: out.reviews.conflicts.map((c) => ({ ...c, reason: "" })) },
|
||||
};
|
||||
}
|
||||
|
||||
/** The changed files the activity sync stored for the current head; empty until the sync has read the PR. */
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
// The Items browser (`GET /api/items`) and the top-bar search (`GET /api/search`),
|
||||
// both over the full-text tables items_fts and comments_fts (src/schema.sql).
|
||||
import { canSeeInternals } from "./staff.ts";
|
||||
import type { DatabaseSync, SQLInputValue } from "node:sqlite";
|
||||
import type {
|
||||
ItemList, ItemListRow, ItemSort, SearchHit, SettledStatus, Snippet, Stage,
|
||||
} from "../../../web/src/api/types.ts";
|
||||
import { quietFixPrs } from "../../core/facts.ts";
|
||||
import { quietFixPrs, quietSqlFor } from "../../security/quiet.ts";
|
||||
import { fromRow, unflagged, latestRun, settledTable, type SettledRow } from "../../classify/settled.ts";
|
||||
import { LABELS } from "../../classify/rules.ts";
|
||||
import { HttpError } from "../server/util.ts";
|
||||
@@ -128,7 +129,7 @@ function build(db: DatabaseSync, req: Req, hidden: string[]): Built & { sort: It
|
||||
}
|
||||
list(req, "flag").forEach((f) => {
|
||||
if (!FLAGS.includes(f)) throw new HttpError(400, "flag must be security or needs decision");
|
||||
where.push(f === "security" ? "s.security = 1 AND NOT EXISTS (SELECT 1 FROM main.security_findings q WHERE q.repo = i.repo AND q.fix_pr = i.number AND q.state = 'landing' AND q.fork IS NULL)" : "s.needs_decision = 1");
|
||||
where.push(f === "security" ? "s.security = 1 AND NOT " + quietSqlFor("i.repo", "i.number") : "s.needs_decision = 1");
|
||||
});
|
||||
const author = q.get("author")?.trim();
|
||||
if (author) {
|
||||
@@ -277,7 +278,7 @@ export async function listItems(db: DatabaseSync, req: Req): Promise<ItemList> {
|
||||
rows: rows.map((r): ItemListRow => ({
|
||||
repo: r.repo, number: r.number, kind: r.kind === "pr" ? "pr" : "issue", state: itemState(r.state),
|
||||
title: r.title ?? "", author: r.author ?? "", createdAt: r.created_at ?? "", updatedAt: r.updated_at ?? "",
|
||||
comments: r.comments_count ?? 0, settled: unflagged(fromRow(r), quiet.has(`${r.repo}#${r.number}`)) as ItemListRow["settled"],
|
||||
comments: r.comments_count ?? 0, settled: unflagged(fromRow(r), quiet.has(`${r.repo}#${r.number}`), canSeeInternals(req)) as ItemListRow["settled"],
|
||||
stage: (stages.get(`${r.repo}#${r.number}`) ?? null) as Stage | null, snippet: snips.get(r.rid) ?? null,
|
||||
queue: slots.get(`${r.repo}#${r.number}`) ?? null,
|
||||
mergedHow: how.get(`${r.repo}#${r.number}`) ?? null, mergedAt: how.has(`${r.repo}#${r.number}`) ? r.merged_by_us_at ?? null : null,
|
||||
|
||||
@@ -131,14 +131,16 @@ async function startStep(db: DatabaseSync, req: Req, repo: string, n: number, ac
|
||||
throw new HttpError(409, "this finding is already being published");
|
||||
}
|
||||
if (action === "fix" && !row.verification) throw new HttpError(409, "the finding has not been verified");
|
||||
if (s.to && !advance(db, repo, n, s.from, s.to, { note: null }, req.user.login)) throw new HttpError(409, "the finding changed; reload and try again");
|
||||
// Land after the advisory route starts over on the public fork: the advisory's private fork and its pull request are forgotten (ghsa_id stays).
|
||||
const reset: Record<string, null> = action === "land" && row.state === "awaiting-admin" ? { fork: null, fix_pr: null } : {};
|
||||
if (s.to && !advance(db, repo, n, s.from, s.to, { note: null, ...reset }, req.user.login)) throw new HttpError(409, "the finding changed; reload and try again");
|
||||
try {
|
||||
const params: Record<string, string | number> = { repo, number: n, ...(action === "publish" && { cve: b.cve === true ? 1 : 0 }) };
|
||||
const job = await enqueue(db, s.step, params, req.user.login);
|
||||
// The job is recorded under the scan's pseudo repo, like the scan's own jobs, so job listings leave it out for viewers.
|
||||
db.prepare("UPDATE jobs SET repo = ? WHERE id = ?").run(securityRepo(repo), job.id);
|
||||
} catch (e) {
|
||||
if (s.to) advance(db, repo, n, [s.to], row.state, {});
|
||||
if (s.to) advance(db, repo, n, [s.to], row.state, { fork: row.fork, fix_pr: row.fix_pr });
|
||||
if (e instanceof JobError) throw new HttpError(e.status, e.message);
|
||||
throw e;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// The item trace: every event of one GitHub item, oldest first, from the tables that hold per-item history.
|
||||
// Each source is a small function that returns events for the item through an index on (repo, number) or a
|
||||
// key derived from it; the list carries no bodies. A source also keeps the fields its detail view shows.
|
||||
import { isQuiet } from "../../security/quiet.ts";
|
||||
import { createHash } from "node:crypto";
|
||||
import type { DatabaseSync } from "node:sqlite";
|
||||
import type { ItemTrace, ItemTraceDetail, ItemTraceHeader, TraceActor, TraceEvent, TraceKind } from "../../../web/src/api/types.ts";
|
||||
@@ -16,7 +17,7 @@ import { hiddenRepos, needVisible } from "./visible.ts";
|
||||
|
||||
export type Ev = TraceEvent & { detail?: Record<string, unknown> };
|
||||
/** `staff`: operators and maintainers; `hidden`: repos the viewer may not see, whose runs are left out like getRun does. */
|
||||
type Ctx = { db: DatabaseSync; repo: string; n: number; ref: string; own: string; staff: boolean; operator: boolean; hidden: string[] };
|
||||
type Ctx = { db: DatabaseSync; repo: string; n: number; ref: string; own: string; staff: boolean; /** A quiet pull request seen by a viewer: model output stays out of the trace. */ veiled: boolean; operator: boolean; hidden: string[] };
|
||||
type Source = { kinds: TraceKind[]; run: (c: Ctx) => Ev[] };
|
||||
|
||||
export const TRACE_PAGE_DEFAULT = 100, TRACE_PAGE_MAX = 500;
|
||||
@@ -383,9 +384,12 @@ export function linkReviewCalls(events: Ev[]): Set<number> {
|
||||
}
|
||||
|
||||
/** Every source runs whatever the filter, so a filtered event still gets the head its neighbours carry. */
|
||||
const VEILED_KINDS: TraceKind[] = ["model-call", "check", "review", "decision", "conversation"];
|
||||
|
||||
function gather(c: Ctx, kinds: Set<TraceKind> | null): Ev[] {
|
||||
const all: Ev[] = [];
|
||||
for (const e of SOURCES.flatMap((s) => s.run(c))) {
|
||||
if (c.veiled && VEILED_KINDS.includes(e.kind)) continue;
|
||||
const at = iso(e.at);
|
||||
if (at) all.push({ ...e, at });
|
||||
}
|
||||
@@ -467,7 +471,7 @@ async function context(db: DatabaseSync, req: Req): Promise<Ctx> {
|
||||
await needVisible(db, req, repo);
|
||||
if (!db.prepare("SELECT 1 FROM items WHERE repo = ? AND number = ?").get(repo, n)) throw new HttpError(404, `no item ${repo}#${n} in the mirror`);
|
||||
const own = (db.prepare("SELECT value FROM main.settings WHERE key = 'pipeline_login'").get() as { value: string } | undefined)?.value ?? "";
|
||||
return { db, repo, n, ref: `${repo}#${n}`, own, staff: canSeeInternals(req), operator: req.user.role === "operator", hidden: await hiddenRepos(db, req) };
|
||||
return { db, repo, n, ref: `${repo}#${n}`, own, staff: canSeeInternals(req), veiled: !canSeeInternals(req) && isQuiet(db, repo, n), operator: req.user.role === "operator", hidden: await hiddenRepos(db, req) };
|
||||
}
|
||||
|
||||
/** Job errors and patch-check reasons carry log and patch text: viewers get the other fields. */
|
||||
|
||||
+2
-1
@@ -3,6 +3,7 @@
|
||||
// Empty or absent means no pilot. A Fix PR the pipeline opened for a pilot issue, a follow-up issue it filed for a pilot PR, and a Fix PR it opened for such a follow-up issue count as pilot items.
|
||||
// A fast-tracked item (src/fasttrack.ts) is in scope whatever its repo's flag and the pilot say.
|
||||
// No Node imports besides the type, so candidate queries can use the SQL fragments.
|
||||
import { quietSqlFor } from "./security/quiet.ts";
|
||||
import type { DatabaseSync } from "node:sqlite";
|
||||
import { audit } from "./dash/audit.ts";
|
||||
|
||||
@@ -93,7 +94,7 @@ export const pilotSqlFor = (repo: string, number: string): string =>
|
||||
OR (EXISTS (SELECT 1 FROM main.tracked_repos pt WHERE pt.name = ${repo} AND pt.pipeline = 1)
|
||||
AND (COALESCE(json_array_length(${LIST}), 0) = 0
|
||||
OR EXISTS (SELECT 1 FROM json_each(${LIST}) pj WHERE pj.value = ${repo} || '#' || ${number})
|
||||
OR EXISTS (SELECT 1 FROM main.security_findings psf WHERE psf.repo = ${repo} AND psf.fix_pr = ${number} AND psf.state = 'landing' AND psf.fork IS NULL)
|
||||
OR ${quietSqlFor(repo, number)}
|
||||
OR EXISTS (SELECT 1 FROM main.fix_attempts pf, json_each(${LIST}) pj WHERE pf.repo = ${repo} AND pf.pr_url LIKE '%/pull/' || ${number}
|
||||
AND pj.value = pf.repo || '#' || pf.number)
|
||||
OR EXISTS (SELECT 1 FROM main.fix_attempts pf2 JOIN main.postmerge_followups pm2 ON pm2.repo = pf2.repo AND pm2.issue_number = pf2.number, json_each(${LIST}) pj
|
||||
|
||||
+3
-1
@@ -22,6 +22,7 @@ import { REPO_PATH } from "../sandbox/command.ts";
|
||||
import { checkoutForCommit } from "../sandbox/index.ts";
|
||||
import { cachedCrates, ghCrates, type CratesFetcher } from "../verify/crates.ts";
|
||||
import { regressionPath } from "../verify/plan.ts";
|
||||
import { baseScopeRepos } from "../pilot.ts";
|
||||
import { cloneTask, queueWarmBuild } from "../verify/tasks.ts";
|
||||
import { outcomeOf } from "../verify/results.ts";
|
||||
import type { Crate } from "../verify/types.ts";
|
||||
@@ -67,7 +68,8 @@ export async function buildInWorker(db: DatabaseSync, r: BuildRequest, cancelled
|
||||
// Tasks need the real repo to fetch it. Their step name says nothing about what the patch is for, and they carry no item number.
|
||||
const queue = (): number[] => {
|
||||
const ids = tasksFor({ repo: r.repo, number: null, main_sha: r.sha, crate: r.crate }, r.patch, r.testPatch, "fix-check").map((t: NewTask) => createTask(db, t));
|
||||
queueWarmBuild(db, r.repo, r.sha);
|
||||
// The warm build is a pipeline task: it would never be claimed for a repo outside the pipeline scope.
|
||||
if (baseScopeRepos(db).has(r.repo)) queueWarmBuild(db, r.repo, r.sha);
|
||||
return ids;
|
||||
};
|
||||
let ids: number[];
|
||||
|
||||
@@ -183,9 +183,13 @@ export async function runAdvisory(db: DatabaseSync, repo: string, n: number, by:
|
||||
/** Creates the finding's draft advisory (private) and stores its id. A finding landed by a quiet pull request has none until its fix merges. */
|
||||
async function draftAdvisory(db: DatabaseSync, row: FindingRow, w: Writer, g: Parameters<typeof ghAdvisoryCreate>[1], d: Pick<LandDeps, "exec">): ReturnType<typeof ghAdvisoryCreate> {
|
||||
const key = findingKey(row.repo, row.number);
|
||||
// One draft per finding: the empty id claims the creation, so the merge poll and a Publish press never both create one. A claim older than ten minutes is a crashed attempt.
|
||||
const stale = new Date(Date.now() - 600_000).toISOString();
|
||||
const claimed = db.prepare("UPDATE security_findings SET ghsa_id = '', updated_at = ? WHERE repo = ? AND number = ? AND (ghsa_id IS NULL OR (ghsa_id = '' AND updated_at < ?))").run(new Date().toISOString(), row.repo, row.number, stale).changes;
|
||||
if (!claimed) return { ghsa: null, result: { code: 1, stdout: "", stderr: "the advisory is being created" } };
|
||||
const text = `${advisoryText(row)}${row.fix_pr ? `\n### Fix\n\nFixed in ${slugOf(row.repo)}#${row.fix_pr}.\n` : ""}`;
|
||||
const a = await ghAdvisoryCreate(w, g, d.exec, { repo: row.repo, key, summary: row.title, description: text, severity: row.severity });
|
||||
if (a.ghsa) db.prepare("UPDATE security_findings SET ghsa_id = ? WHERE repo = ? AND number = ?").run(a.ghsa, row.repo, row.number);
|
||||
db.prepare("UPDATE security_findings SET ghsa_id = ? WHERE repo = ? AND number = ? AND ghsa_id = ''").run(a.ghsa, row.repo, row.number);
|
||||
return a;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
// The quiet pull request of a security fix: opened by the Land step, in the pipeline's name, and kept free of anything that
|
||||
// names the problem from the moment it opens until the advisory is published. One definition for every place that asks.
|
||||
import type { DatabaseSync } from "node:sqlite";
|
||||
|
||||
/** SQL condition: the findings whose pull request is quiet (the quiet route has no fork). */
|
||||
export const QUIET_FINDING_SQL = "state IN ('landing', 'landed') AND fork IS NULL AND fix_pr IS NOT NULL";
|
||||
|
||||
/** SQL condition on item expressions `repo` and `number`: the item is a quiet pull request. */
|
||||
export const quietSqlFor = (repo: string, number: string): string =>
|
||||
`EXISTS (SELECT 1 FROM main.security_findings qf WHERE qf.repo = ${repo} AND qf.fix_pr = ${number} AND qf.state IN ('landing', 'landed') AND qf.fork IS NULL)`;
|
||||
|
||||
/** Quiet pull requests as `repo#number`. */
|
||||
export function quietFixPrs(db: DatabaseSync, repo?: string): Set<string> {
|
||||
const rows = db.prepare(`SELECT repo, fix_pr AS n FROM main.security_findings WHERE ${QUIET_FINDING_SQL}${repo ? " AND repo = ?" : ""}`).all(...(repo ? [repo] : [])) as { repo: string; n: number }[];
|
||||
return new Set(rows.map((r) => `${r.repo}#${r.n}`));
|
||||
}
|
||||
|
||||
/** True when `repo#number` is a quiet pull request. */
|
||||
export const isQuiet = (db: DatabaseSync, repo: string, number: number): boolean =>
|
||||
!!db.prepare(`SELECT 1 FROM main.security_findings WHERE repo = ? AND fix_pr = ? AND ${QUIET_FINDING_SQL} LIMIT 1`).get(repo, number);
|
||||
+19
-6
@@ -164,12 +164,21 @@ const GIVEAWAY_CODE = /\b(?:security|vulnerab\w*|exploit\w*|attack\w*|attacker\w
|
||||
/** The first giveaway word in `text`, or null. */
|
||||
export const giveaway = (text: string): string | null => GIVEAWAY.exec(text)?.[0] ?? null;
|
||||
|
||||
/** The comment parts of one source line: from a double slash to the end, block-comment segments, and block-comment continuation lines. */
|
||||
function commentText(line: string): string {
|
||||
/** The comment parts of one source line: from a double slash to the end, block-comment segments, and the lines inside a block comment. `inBlock` carries across the lines of a hunk. */
|
||||
function commentText(line: string, st: { inBlock: boolean }): string {
|
||||
const out: string[] = [];
|
||||
const t = line.trim();
|
||||
if (t.startsWith("*") || t.startsWith("/*")) out.push(t);
|
||||
for (const m of line.matchAll(/\/\/.*$|\/\*.*?(?:\*\/|$)/g)) out.push(m[0]);
|
||||
let rest = line;
|
||||
if (st.inBlock) {
|
||||
const end = rest.indexOf("*/");
|
||||
out.push(end < 0 ? rest : rest.slice(0, end));
|
||||
if (end < 0) return out.join(" ");
|
||||
st.inBlock = false;
|
||||
rest = rest.slice(end + 2);
|
||||
}
|
||||
for (const m of rest.matchAll(/\/\/.*$|\/\*.*?(?:\*\/|$)/g)) {
|
||||
out.push(m[0]);
|
||||
if (m[0].startsWith("/*") && !m[0].endsWith("*/")) st.inBlock = true;
|
||||
}
|
||||
return out.join(" ");
|
||||
}
|
||||
|
||||
@@ -182,6 +191,7 @@ export const nameGiveaway = (s: string): string | null => giveaway(s.replace(/[_
|
||||
*/
|
||||
export function patchGiveaway(patch: string): string | null {
|
||||
let prev = "";
|
||||
const block = { inBlock: false };
|
||||
for (const line of patch.split("\n")) {
|
||||
// Existing file names are public already; only the path of a file the patch adds is checked.
|
||||
if (line.startsWith("+++ ")) {
|
||||
@@ -192,9 +202,12 @@ export function patchGiveaway(patch: string): string | null {
|
||||
}
|
||||
if (line.startsWith("--- ")) { prev = line; continue; }
|
||||
if (line.startsWith("diff --git ")) continue;
|
||||
if (line.startsWith("@@")) block.inBlock = false;
|
||||
// Unchanged lines can open or close a block comment that added lines sit in.
|
||||
if (line.startsWith(" ")) commentText(line.slice(1), block);
|
||||
if (!line.startsWith("+")) continue;
|
||||
const added = line.slice(1);
|
||||
const w = GIVEAWAY_CODE.exec(added)?.[0] ?? giveaway(commentText(added)) ?? nameGiveaway([...added.matchAll(/\bfn\s+(\w+)/g)].map((m) => m[1]).join(" "));
|
||||
const w = GIVEAWAY_CODE.exec(added)?.[0] ?? giveaway(commentText(added, block)) ?? nameGiveaway([...added.matchAll(/\bfn\s+(\w+)/g)].map((m) => m[1]).join(" "));
|
||||
if (w) return w;
|
||||
}
|
||||
return null;
|
||||
|
||||
@@ -75,6 +75,8 @@ describe("private fix and landing", () => {
|
||||
assert.equal(patchGiveaway("diff --git a/x.rs b/x.rs\n+fn rejects_crafted_input() {}\n"), "crafted");
|
||||
assert.equal(patchGiveaway("diff --git a/src/sanitize_names.rs b/src/sanitize_names.rs\nnew file mode 100644\n--- /dev/null\n+++ b/src/sanitize_names.rs\n"), "sanitize", "a new file's name counts");
|
||||
assert.equal(patchGiveaway("diff --git a/src/sanitize.rs b/src/sanitize.rs\n--- a/src/sanitize.rs\n+++ b/src/sanitize.rs\n"), null, "an existing file's name does not");
|
||||
assert.equal(patchGiveaway("diff --git a/x.rs b/x.rs\n@@ -1,1 +1,2 @@\n let y = 1;\n+ * crafted\n"), null, "a star line outside a block comment is code");
|
||||
assert.equal(patchGiveaway("diff --git a/x.rs b/x.rs\n@@ -1,2 +1,3 @@\n /*\n+ * crafted input\n */\n"), "crafted", "inside a block comment it is a comment");
|
||||
// L1: the branch has the shape of the other pipeline branches and no finding number.
|
||||
assert.match(fixBranch("Check layer length", "a1b2c3"), /^autocraft\/fix-check-layer-length-a1b2c3$/);
|
||||
});
|
||||
@@ -144,6 +146,9 @@ describe("private fix and landing", () => {
|
||||
const n = finding("landing", { fix_pr: 91 });
|
||||
assert.ok(ownFixPrs(db, "photocraft").prs.has("photocraft#91"), "counted as an own fix PR");
|
||||
assert.ok(ownFixPrs(db, "photocraft").quiet.has("photocraft#91"));
|
||||
db.prepare("UPDATE security_findings SET state = 'landed' WHERE number = ?").run(n);
|
||||
assert.ok(ownFixPrs(db, "photocraft").quiet.has("photocraft#91"), "still quiet after the merge, until published");
|
||||
db.prepare("UPDATE security_findings SET state = 'landing' WHERE number = ?").run(n);
|
||||
db.prepare("INSERT INTO items (repo, number, kind, state) VALUES ('photocraft', 5, 'issue', 'OPEN')").run();
|
||||
setPilot(db, "boss", ["photocraft#5"]);
|
||||
assert.equal(inPilot(db, "photocraft", 91), true, "in scope although the pilot list names other items");
|
||||
|
||||
Reference in new issue
Block a user