Skip to content

Commit 2eb1787

Browse files
authored
fix(review): fail closed on out-of-block report metadata (no format migration) (#1051)
* fix(review): reject out-of-block report metadata * fix(review): harden decision packet metadata * fix(review): clear stale decision packets * fix(review): demote ambiguous maintainer metadata instead of crashing promotion maintainerDecisionFromReport now throws on ambiguous front matter; the promotion-facts caller was unwrapped, so one spoofed legacy report would crash the whole promotion batch. Guard it: ambiguity synthesizes a required manual_review decision, which close-decision gating already blocks, so the item demotes to human review and the batch continues. Proof: node --test test/decision-packets.test.ts (9 pass, including the new guard case).
1 parent 3f368a3 commit 2eb1787

16 files changed

Lines changed: 725 additions & 23 deletions
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
name: Audit report metadata spoofing
2+
3+
on:
4+
workflow_dispatch:
5+
inputs:
6+
repo_slugs:
7+
description: "Optional comma-separated canonical repository slugs (empty discovers all)"
8+
required: false
9+
type: string
10+
default: ""
11+
max_records:
12+
description: "Maximum canonical item records to inspect"
13+
required: true
14+
type: string
15+
default: "10000"
16+
17+
permissions:
18+
contents: read
19+
20+
jobs:
21+
audit:
22+
runs-on: ubuntu-latest
23+
timeout-minutes: 15
24+
env:
25+
CLAWSWEEPER_RECORDS_URL: ${{ vars.CLAWSWEEPER_EXACT_REVIEW_QUEUE_URL || 'https://clawsweeper.openclaw.ai' }}
26+
steps:
27+
- uses: actions/checkout@v7
28+
with:
29+
ref: main
30+
filter: blob:none
31+
fetch-depth: 1
32+
persist-credentials: false
33+
34+
- uses: ./.github/actions/setup-pnpm
35+
36+
- name: Audit canonical item report metadata
37+
env:
38+
CLAWSWEEPER_WEBHOOK_SECRET: ${{ secrets.CLAWSWEEPER_WEBHOOK_SECRET }}
39+
CONFIGURED_REPO_SLUGS: ${{ inputs.repo_slugs || vars.CLAWSWEEPER_RECORDS_REPO_SLUGS || '' }}
40+
MAX_RECORDS: ${{ inputs.max_records }}
41+
run: |
42+
args=(
43+
--max-records "$MAX_RECORDS"
44+
--output .artifacts/report-metadata-audit.json
45+
)
46+
if [[ -n "$CONFIGURED_REPO_SLUGS" ]]; then
47+
args+=(--repo-slugs "$CONFIGURED_REPO_SLUGS")
48+
fi
49+
node scripts/audit-report-metadata-spoofing.mjs "${args[@]}"
50+
51+
- uses: actions/upload-artifact@v6
52+
with:
53+
name: report-metadata-audit
54+
path: .artifacts/report-metadata-audit.json
55+
if-no-files-found: error
56+
retention-days: 14

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ checkpoint, and status-only commits are intentionally omitted.
4141

4242
### Fixed
4343

44+
- Legacy reports with canonical proof or rating keys outside the apparent leading front-matter block now fail closed, with a read-only workflow to inventory affected canonical records. (#1049)
4445
- Prevented model-authored report prose and body-shaped front matter from spoofing proof or rating sections, keeping unproven external pull requests in human review instead of routing them into automated repair. (#951)
4546

4647
### Added
Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
1+
#!/usr/bin/env node
2+
import { mkdirSync, writeFileSync } from "node:fs";
3+
import path from "node:path";
4+
import { pathToFileURL } from "node:url";
5+
6+
import { discoverWorkerRecordRepoSlugs, exportWorkerRecords } from "./worker-records.ts";
7+
8+
export const CANONICAL_PROMOTION_KEYS = Object.freeze([
9+
"real_behavior_proof_status",
10+
"real_behavior_proof_evidence_kind",
11+
"real_behavior_proof_needs_contributor_action",
12+
"pr_rating_overall",
13+
"pr_rating_proof",
14+
"pr_rating_patch",
15+
]);
16+
17+
const DEFAULT_MAX_RECORDS = 10_000;
18+
const DEFAULT_RECORDS_URL = "https://clawsweeper.openclaw.ai";
19+
const REPO_SLUG_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,199}$/;
20+
21+
export function reportMetadataSpoofingFinding(markdown) {
22+
const frontMatterMatch = markdown.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/);
23+
if (!frontMatterMatch) return null;
24+
const remainderStart = frontMatterMatch[0].length;
25+
const remainder = markdown.slice(remainderStart);
26+
const matches = [];
27+
for (const key of CANONICAL_PROMOTION_KEYS) {
28+
const match = new RegExp(`^${key}:`, "m").exec(remainder);
29+
if (!match) continue;
30+
const absoluteIndex = remainderStart + match.index;
31+
matches.push({ key, line: lineNumberAt(markdown, absoluteIndex) });
32+
}
33+
if (!matches.length) return null;
34+
matches.sort((left, right) => left.line - right.line || left.key.localeCompare(right.key));
35+
return {
36+
matched_keys: matches.map((match) => match.key),
37+
first_match_line: matches[0].line,
38+
};
39+
}
40+
41+
export async function auditCanonicalItemRecords(options) {
42+
const maxRecords = positiveInteger(options.maxRecords ?? DEFAULT_MAX_RECORDS, "maxRecords");
43+
const repoSlugs = await resolveRepoSlugs(options);
44+
const findings = [];
45+
let scannedRecords = 0;
46+
for (const repoSlug of repoSlugs) {
47+
const snapshot = await (options.exportRecords ?? exportWorkerRecords)({
48+
baseUrl: options.baseUrl,
49+
webhookSecret: options.webhookSecret,
50+
repoSlug,
51+
sections: ["items"],
52+
maxRecords: maxRecords - scannedRecords,
53+
fetch: options.fetch,
54+
});
55+
scannedRecords += snapshot.records.length;
56+
if (scannedRecords > maxRecords) {
57+
throw new Error(`Canonical item audit exceeded the ${maxRecords}-record bound`);
58+
}
59+
for (const record of snapshot.records) {
60+
if (record.section !== "items" || record.deleted || typeof record.content !== "string") {
61+
continue;
62+
}
63+
const finding = reportMetadataSpoofingFinding(record.content);
64+
if (!finding) continue;
65+
findings.push({
66+
repo_slug: repoSlug,
67+
item_number: Number(record.id),
68+
...finding,
69+
});
70+
}
71+
}
72+
findings.sort(
73+
(left, right) =>
74+
left.repo_slug.localeCompare(right.repo_slug) || left.item_number - right.item_number,
75+
);
76+
return {
77+
schema_version: 1,
78+
generated_at: (options.now ?? new Date()).toISOString(),
79+
repo_slugs: repoSlugs,
80+
scanned_records: scannedRecords,
81+
finding_count: findings.length,
82+
findings,
83+
};
84+
}
85+
86+
export async function runAuditCli(argv, env = process.env) {
87+
const args = parseArgs(argv);
88+
const webhookSecret = env.CLAWSWEEPER_RECORDS_SECRET ?? env.CLAWSWEEPER_WEBHOOK_SECRET ?? "";
89+
if (!webhookSecret) throw new Error("CLAWSWEEPER_WEBHOOK_SECRET is required");
90+
const inventory = await auditCanonicalItemRecords({
91+
baseUrl:
92+
args.recordsUrl ??
93+
env.CLAWSWEEPER_RECORDS_URL ??
94+
env.CLAWSWEEPER_STATE_COORDINATOR_URL ??
95+
DEFAULT_RECORDS_URL,
96+
webhookSecret,
97+
repoSlugs: args.repoSlugs ?? parseRepoSlugs(env.CLAWSWEEPER_RECORDS_REPO_SLUGS) ?? undefined,
98+
maxRecords: args.maxRecords ?? DEFAULT_MAX_RECORDS,
99+
});
100+
const json = `${JSON.stringify(inventory, null, 2)}\n`;
101+
if (args.output) {
102+
const output = path.resolve(args.output);
103+
mkdirSync(path.dirname(output), { recursive: true });
104+
writeFileSync(output, json, "utf8");
105+
console.error(
106+
`Audited ${inventory.scanned_records} canonical item records; wrote ${inventory.finding_count} finding(s) to ${args.output}`,
107+
);
108+
} else {
109+
process.stdout.write(json);
110+
}
111+
return inventory;
112+
}
113+
114+
async function resolveRepoSlugs(options) {
115+
const configured = options.repoSlugs?.length
116+
? options.repoSlugs
117+
: (
118+
await (options.discoverRepoSlugs ?? discoverWorkerRecordRepoSlugs)({
119+
baseUrl: options.baseUrl,
120+
webhookSecret: options.webhookSecret,
121+
fetch: options.fetch,
122+
})
123+
).map((entry) => entry.repoSlug);
124+
const repoSlugs = [...new Set(configured)].sort();
125+
if (!repoSlugs.length) throw new Error("Canonical record store returned no repository slugs");
126+
for (const repoSlug of repoSlugs) {
127+
if (!REPO_SLUG_PATTERN.test(repoSlug)) {
128+
throw new Error(`Invalid record repository slug: ${repoSlug}`);
129+
}
130+
}
131+
return repoSlugs;
132+
}
133+
134+
function parseArgs(argv) {
135+
const parsed = {};
136+
for (let index = 0; index < argv.length; index += 1) {
137+
const arg = argv[index];
138+
if (arg === "--") continue;
139+
if (arg === "--output") parsed.output = requiredValue(argv, ++index, arg);
140+
else if (arg === "--records-url") parsed.recordsUrl = requiredValue(argv, ++index, arg);
141+
else if (arg === "--repo-slugs") {
142+
parsed.repoSlugs = parseRepoSlugs(requiredValue(argv, ++index, arg));
143+
} else if (arg === "--max-records") {
144+
parsed.maxRecords = positiveInteger(requiredValue(argv, ++index, arg), arg);
145+
} else {
146+
throw new Error(`Unknown argument: ${arg}`);
147+
}
148+
}
149+
return parsed;
150+
}
151+
152+
function parseRepoSlugs(value) {
153+
if (value === undefined || value.trim() === "") return undefined;
154+
return [...new Set(value.split(/[\s,]+/).filter(Boolean))].sort();
155+
}
156+
157+
function requiredValue(argv, index, flag) {
158+
const value = argv[index];
159+
if (!value || value.startsWith("--")) throw new Error(`${flag} requires a value`);
160+
return value;
161+
}
162+
163+
function positiveInteger(value, name) {
164+
const number = Number(value);
165+
if (!Number.isSafeInteger(number) || number < 1) {
166+
throw new Error(`${name} requires a positive safe integer`);
167+
}
168+
return number;
169+
}
170+
171+
function lineNumberAt(markdown, index) {
172+
let line = 1;
173+
for (let offset = 0; offset < index; offset += 1) {
174+
if (markdown.charCodeAt(offset) === 10) line += 1;
175+
}
176+
return line;
177+
}
178+
179+
if (import.meta.url === pathToFileURL(process.argv[1] || "").href) {
180+
await runAuditCli(process.argv.slice(2));
181+
}

‎src/clawsweeper-promotion-facts.ts‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,11 @@ import type {
1919
WorkCandidateKind,
2020
} from "./clawsweeper-types.js";
2121
import { completeActivityContextSymbol } from "./clawsweeper-types.js";
22-
import { emptyMaintainerDecision, maintainerDecisionFromReport } from "./decision-packets.js";
22+
import {
23+
emptyMaintainerDecision,
24+
maintainerDecisionFromReport,
25+
type MaintainerDecision,
26+
} from "./decision-packets.js";
2327
import type { CreateReportOrchestrationDependencies } from "./clawsweeper-report-orchestration-dependencies.js";
2428
import type { createReportOrchestrationFoundation } from "./clawsweeper-orchestration-foundation.js";
2529
import type { createReportRendering } from "./clawsweeper-report-rendering.js";
@@ -97,7 +101,7 @@ export function createPullRequestPromotionFacts(
97101
likelyOwners: reportLikelyOwners(markdown),
98102
risks: [],
99103
bestSolution: reviewSectionValue(markdown, "bestSolution"),
100-
maintainerDecision: maintainerDecisionFromReport(markdown) ?? emptyMaintainerDecision(),
104+
maintainerDecision: ambiguityGuardedMaintainerDecision(markdown),
101105
triagePriority,
102106
impactLabels,
103107
mergeRiskLabels,
@@ -631,3 +635,21 @@ export function createPullRequestPromotionFacts(
631635
unsafeCanonicalPullRequestReason,
632636
};
633637
}
638+
639+
// Ambiguous (possibly spoofed) front matter must demote the item to human
640+
// review, not crash the promotion batch: close-decision gating blocks any
641+
// close while maintainerDecision.required is true.
642+
export function ambiguityGuardedMaintainerDecision(markdown: string): MaintainerDecision {
643+
try {
644+
return maintainerDecisionFromReport(markdown) ?? emptyMaintainerDecision();
645+
} catch {
646+
return {
647+
required: true,
648+
kind: "manual_review",
649+
question: "Report front matter is ambiguous or possibly spoofed; review manually.",
650+
rationale: "Duplicate front-matter metadata detected outside the leading block.",
651+
options: [],
652+
likelyOwner: { person: "", reason: "", confidence: "low" },
653+
};
654+
}
655+
}

‎src/clawsweeper-record-metadata.ts‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -67,13 +67,12 @@ export function createRecordMetadata({
6767
markdownFiles,
6868
numberForMarkdownFile,
6969
}: RecordMetadataDependencies) {
70-
function leadingFrontMatter(markdown: string): string | undefined {
71-
return markdown.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/)?.[1];
72-
}
73-
7470
function frontMatterField(markdown: string, key: string): FrontMatterField {
75-
const frontMatter = leadingFrontMatter(markdown);
76-
if (frontMatter === undefined) return { status: "absent" };
71+
const frontMatterMatch = markdown.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/);
72+
if (!frontMatterMatch) return { status: "absent" };
73+
const frontMatter = frontMatterMatch[1] ?? "";
74+
const remainder = markdown.slice(frontMatterMatch[0].length);
75+
if (new RegExp(`^${key}:`, "m").test(remainder)) return { status: "ambiguous" };
7776
const matches = [...frontMatter.matchAll(new RegExp(`^${key}:\\s*(.*)$`, "gm"))];
7877
if (matches.length === 0) return { status: "absent" };
7978
if (matches.length !== 1) return { status: "ambiguous" };

‎src/clawsweeper-report-comment-presentation.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -485,7 +485,12 @@ export function createReportCommentPresentation(
485485
options: ReviewCommentRenderOptions = {},
486486
): string {
487487
const decision = frontMatterValue(markdown, "decision");
488-
const requiresMaintainerDecision = maintainerDecisionFromReport(markdown)?.required === true;
488+
let requiresMaintainerDecision = true;
489+
try {
490+
requiresMaintainerDecision = maintainerDecisionFromReport(markdown)?.required === true;
491+
} catch {
492+
// Malformed or ambiguous decision metadata must keep the report on the human-review path.
493+
}
489494
const body =
490495
decision === "close" &&
491496
reason !== "none" &&

‎src/clawsweeper-review-comment-automation.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,9 @@ export function createReviewCommentAutomation(
8888
return markers.join("\n");
8989
};
9090

91-
if (maintainerDecisionFromReport(markdown)?.required) {
91+
try {
92+
if (maintainerDecisionFromReport(markdown)?.required) return humanReviewMarkers();
93+
} catch {
9294
return humanReviewMarkers();
9395
}
9496
if (frontMatterValue(markdown, "review_status") === "failed") {

0 commit comments

Comments
 (0)