Skip to content

Commit dad83d3

Browse files
committed
chore: enforce opengrep rule metadata provenance
1 parent 19afa2e commit dad83d3

8 files changed

Lines changed: 219 additions & 807 deletions

File tree

‎package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1281,6 +1281,7 @@
12811281
"check:madge-import-cycles": "node --import tsx scripts/check-madge-import-cycles.ts",
12821282
"check:no-conflict-markers": "node scripts/check-no-conflict-markers.mjs",
12831283
"check:no-runtime-action-load-config": "node scripts/check-no-runtime-action-load-config.mjs",
1284+
"check:opengrep-rule-metadata": "node scripts/check-opengrep-rule-metadata.mjs",
12841285
"check:runtime-sidecar-loaders": "node --import tsx scripts/check-runtime-sidecar-loaders.mjs",
12851286
"check:static-import-sccs": "pnpm check:madge-import-cycles",
12861287
"check:temp-path-guardrails": "node --import tsx scripts/check-temp-path-guardrails.ts",
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
#!/usr/bin/env node
2+
import { promises as fs } from "node:fs";
3+
import * as path from "node:path";
4+
import { parseDocument } from "yaml";
5+
6+
const DEFAULT_RULEPACK = path.resolve("security", "opengrep", "precise.yml");
7+
const GHSA_RE = /^GHSA-[0-9A-Z]{4}-[0-9A-Z]{4}-[0-9A-Z]{4}$/;
8+
const RULE_ID_RE = /^ghsa-detector\.(ghsa-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4})\..+$/;
9+
10+
function printHelp() {
11+
console.log(`Usage: node scripts/check-opengrep-rule-metadata.mjs [rulepack.yml]
12+
13+
Checks that every compiled GHSA OpenGrep rule carries source/provenance metadata.
14+
Default rulepack: ${DEFAULT_RULEPACK}
15+
`);
16+
}
17+
18+
export async function readRules(rulepackPath) {
19+
const raw = await fs.readFile(rulepackPath, "utf8");
20+
const doc = parseDocument(raw, { keepSourceTokens: false });
21+
if (doc.errors.length > 0) {
22+
throw new Error(
23+
`Could not parse ${rulepackPath}: ${doc.errors.map((e) => e.message).join("; ")}`,
24+
);
25+
}
26+
const data = doc.toJSON();
27+
if (!data || !Array.isArray(data.rules)) {
28+
throw new Error(`${rulepackPath} must contain a top-level rules array`);
29+
}
30+
return data.rules;
31+
}
32+
33+
function hasNonEmptyString(value) {
34+
return typeof value === "string" && value.trim().length > 0;
35+
}
36+
37+
export function validateRuleMetadata(rules) {
38+
const violations = [];
39+
40+
for (const [index, rule] of rules.entries()) {
41+
const id = String(rule?.id ?? "");
42+
const label = id || `rules[${index}]`;
43+
const metadata = rule?.metadata;
44+
if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) {
45+
violations.push(`${label}: missing metadata object`);
46+
continue;
47+
}
48+
49+
const idMatch = id.match(RULE_ID_RE);
50+
if (!idMatch) {
51+
violations.push(`${label}: id must match ghsa-detector.ghsa-xxxx-xxxx-xxxx.<source-rule-id>`);
52+
}
53+
54+
const ghsa = String(metadata.ghsa ?? "");
55+
if (!GHSA_RE.test(ghsa)) {
56+
violations.push(`${label}: metadata.ghsa must match GHSA-XXXX-XXXX-XXXX`);
57+
} else if (idMatch && idMatch[1] !== ghsa.toLowerCase()) {
58+
violations.push(
59+
`${label}: metadata.ghsa (${ghsa}) must match GHSA component in id (${idMatch[1]})`,
60+
);
61+
}
62+
63+
const advisoryUrl = String(metadata["advisory-url"] ?? "");
64+
const expectedUrl = ghsa
65+
? `https://github.com/openclaw/openclaw/security/advisories/${ghsa}`
66+
: "";
67+
if (!hasNonEmptyString(advisoryUrl)) {
68+
violations.push(`${label}: missing metadata.advisory-url`);
69+
} else if (expectedUrl && advisoryUrl !== expectedUrl) {
70+
violations.push(`${label}: metadata.advisory-url must be ${expectedUrl}`);
71+
}
72+
73+
if (metadata["detector-bucket"] !== "precise") {
74+
violations.push(`${label}: metadata.detector-bucket must be precise`);
75+
}
76+
if (!hasNonEmptyString(metadata["source-run"])) {
77+
violations.push(`${label}: missing metadata.source-run`);
78+
}
79+
if (!hasNonEmptyString(metadata["source-rule-id"])) {
80+
violations.push(`${label}: missing metadata.source-rule-id`);
81+
}
82+
}
83+
84+
return violations;
85+
}
86+
87+
export async function checkRulepack(rulepackPath = DEFAULT_RULEPACK) {
88+
const rules = await readRules(rulepackPath);
89+
return validateRuleMetadata(rules);
90+
}
91+
92+
export async function main(argv = process.argv.slice(2)) {
93+
if (argv.includes("--help") || argv.includes("-h")) {
94+
printHelp();
95+
return 0;
96+
}
97+
const rulepackPath = path.resolve(argv[0] ?? DEFAULT_RULEPACK);
98+
const violations = await checkRulepack(rulepackPath);
99+
if (violations.length > 0) {
100+
console.error(
101+
`check-opengrep-rule-metadata: ${violations.length} violation(s) in ${rulepackPath}`,
102+
);
103+
for (const violation of violations.slice(0, 50)) {
104+
console.error(` - ${violation}`);
105+
}
106+
if (violations.length > 50) {
107+
console.error(` ... ${violations.length - 50} more`);
108+
}
109+
return 1;
110+
}
111+
console.log(`check-opengrep-rule-metadata: ${rulepackPath} ok`);
112+
return 0;
113+
}
114+
115+
if (import.meta.main) {
116+
process.exitCode = await main();
117+
}

‎scripts/check.mjs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ export async function main(argv = process.argv.slice(2)) {
4242
{ name: "runtime sidecar loader guard", args: ["check:runtime-sidecar-loaders"] },
4343
{ name: "tool display", args: ["tool-display:check"] },
4444
{ name: "host env policy", args: ["check:host-env-policy:swift"] },
45+
{ name: "opengrep rule metadata", args: ["check:opengrep-rule-metadata"] },
4546
],
4647
},
4748
{

‎scripts/compile-opengrep-rules.mjs‎

Lines changed: 27 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,21 +2,22 @@
22
/**
33
* compile-opengrep-rules.mjs
44
*
5-
* Compiles per-case OpenGrep rules from a GHSA detector-review run and appends
6-
* newly generated precise rules to security/opengrep/precise.yml, plus a
7-
* compile-manifest.json with traceability back to each source advisory.
5+
* Compiles per-case OpenGrep rules from a GHSA detector-review run, appends
6+
* newly generated precise rules to security/opengrep/precise.yml, and writes a
7+
* run-local compile-manifest.json for compile auditing.
88
*
99
* Usage:
10-
* node scripts/compile-opengrep-rules.mjs --run-dir <path> [--out-dir <path>]
10+
* node scripts/compile-opengrep-rules.mjs --run-dir <path> [--out-dir <path>] [--manifest-dir <path>]
1111
*
1212
* Inputs:
13-
* --run-dir <path> Required. A run dir produced by run-ghsa-detector-review-batch.mjs
14-
* (e.g. .artifacts/ghsa-detector-review-runs/<run-id>/).
15-
* --out-dir <path> Optional. Default: <repo>/security/opengrep/.
13+
* --run-dir <path> Required. A run dir produced by run-ghsa-detector-review-batch.mjs
14+
* (e.g. .artifacts/ghsa-detector-review-runs/<run-id>/).
15+
* --out-dir <path> Optional. Default: <repo>/security/opengrep/.
16+
* --manifest-dir <path> Optional. Default: <run-dir>/.
1617
*
1718
* Outputs:
18-
* <out-dir>/precise.yml Existing precise super-config plus new precise rules
19-
* <out-dir>/compile-manifest.json Per-rule provenance map
19+
* <out-dir>/precise.yml Existing precise super-config plus new precise rules
20+
* <manifest-dir>/compile-manifest.json Run-local compile summary and skip details
2021
*
2122
* Each rule's id is rewritten to `ghsa-detector.<ghsa-lower>.<original-id>`
2223
* (ASCII-sanitized). Each rule's metadata is augmented with:
@@ -42,10 +43,11 @@ function printHelp() {
4243
4344
Options:
4445
--run-dir <path> Required. Detector-review run directory.
45-
--out-dir <path> Output directory (default: <repo>/security/opengrep).
46-
--advisory-repo <r> GitHub owner/repo used in advisory-url metadata.
47-
Default: ${REPO_BASENAME}
48-
--replace-precise Replace precise.yml instead of appending new rule ids.
46+
--out-dir <path> Output directory for precise.yml (default: <repo>/security/opengrep).
47+
--manifest-dir <path> Directory for compile-manifest.json (default: <run-dir>).
48+
--advisory-repo <r> GitHub owner/repo used in advisory-url metadata.
49+
Default: ${REPO_BASENAME}
50+
--replace-precise Replace precise.yml instead of appending new rule ids.
4951
--help Show this help.
5052
`);
5153
}
@@ -54,6 +56,7 @@ function parseArgs(argv) {
5456
const opts = {
5557
runDir: "",
5658
outDir: "",
59+
manifestDir: "",
5760
advisoryRepo: REPO_BASENAME,
5861
replacePrecise: false,
5962
};
@@ -68,6 +71,10 @@ function parseArgs(argv) {
6871
opts.outDir = path.resolve(argv[i + 1] ?? "");
6972
i += 1;
7073
break;
74+
case "--manifest-dir":
75+
opts.manifestDir = path.resolve(argv[i + 1] ?? "");
76+
i += 1;
77+
break;
7178
case "--advisory-repo":
7279
opts.advisoryRepo = argv[i + 1] ?? REPO_BASENAME;
7380
i += 1;
@@ -601,13 +608,19 @@ async function writeOutputs(buckets, manifest, outDir, opts) {
601608
manifest.preciseInvalid = droppedDetails;
602609
manifest.preciseDuplicateSkipped = appendResult.skippedDuplicateIds;
603610

604-
const manifestPath = path.join(outDir, "compile-manifest.json");
611+
const manifestDir = opts.manifestDir || opts.runDir;
612+
await fs.mkdir(manifestDir, { recursive: true });
613+
const manifestPath = path.join(manifestDir, "compile-manifest.json");
614+
manifest.output = { precisePath, manifestPath };
605615
await fs.writeFile(manifestPath, JSON.stringify(manifest, null, 2) + "\n");
606616
}
607617

608618
function printSummary(buckets, manifest, outDir) {
609619
console.log(`compile-opengrep-rules: done`);
610620
console.log(` out-dir : ${outDir}`);
621+
if (manifest.output?.manifestPath) {
622+
console.log(` manifest : ${manifest.output.manifestPath}`);
623+
}
611624
console.log(` cases scanned : ${manifest.totals.cases}`);
612625
console.log(` cases with rules : ${manifest.totals.casesWithAnyRule}`);
613626
console.log(

‎security/README.md‎

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,7 @@ security/
2323
│ └── init_case.py <- per-case workspace initializer
2424
└── opengrep/
2525
├── README.md <- precise rulepack details + regen recipe
26-
├── precise.yml <- compiled super-config: precise rules
27-
└── compile-manifest.json <- per-rule provenance back to source advisories
26+
└── precise.yml <- compiled super-config: precise rules
2827
```
2928

3029
The two scripts that drive everything live under `scripts/`:
@@ -50,7 +49,7 @@ GitHub Advisory API ─► run-ghsa-detector-review-batch.mjs ─► .artifacts/
5049
| └── cases/<ghsa>/...
5150
v
5251
compile-opengrep-rules.mjs ─► security/opengrep/precise.yml
53-
+ compile-manifest.json
52+
└── run-local compile-manifest.json
5453
|
5554
v
5655
.github/workflows/opengrep-precise.yml
@@ -113,7 +112,10 @@ node scripts/compile-opengrep-rules.mjs \
113112
--run-dir .artifacts/ghsa-detector-review-runs/<RUN_ID>
114113
```
115114

116-
Then commit the diff under `security/opengrep/`.
115+
Then commit the `security/opengrep/precise.yml` diff. The compile manifest is
116+
written into the run directory as a local troubleshooting artifact; durable rule
117+
provenance lives in each compiled rule's metadata and is checked by
118+
`pnpm check:opengrep-rule-metadata`.
117119

118120
Rule quality contract: precise rules must catch the vulnerable behavior they were
119121
written for, should be silent on the corresponding fixed behavior when a fix
@@ -163,6 +165,7 @@ Both workflows:
163165
- Inherit the same `.semgrepignore` exclusions used by the local wrapper
164166
- Upload SARIF to GitHub Code Scanning under stable OpenGrep categories
165167
- Fail on precise findings so the rulepack acts as a regression firewall
168+
- Enforce committed rule provenance with `pnpm check:opengrep-rule-metadata`
166169

167170
## Silencing or removing rules
168171

@@ -173,14 +176,16 @@ To drop a noisy rule:
173176
1. Delete the offending source rule from
174177
`.artifacts/ghsa-detector-review-runs/<RUN_ID>/cases/<ghsa>/.tmp/ghsa-detector-review/<ghsa>/opengrep/`
175178
2. Re-run `node scripts/compile-opengrep-rules.mjs --run-dir <run-dir>`
176-
3. Commit the resulting `security/opengrep/precise.yml` and `compile-manifest.json` diff
179+
3. Commit the resulting `security/opengrep/precise.yml` diff
177180

178181
To narrow a rule's path scope, edit the source rule's `paths.include` /
179182
`paths.exclude` fields in the same artifact location and recompile.
180183

181184
## Tracing a finding back to its advisory
182185

183186
Every compiled rule's `id` is `ghsa-detector.<ghsa-lower>.<original-id>` and
184-
its `metadata` includes `ghsa`, `advisory-url`, `detector-bucket`, and
185-
`source-rule-id`. The full forward map (ghsa → precise rule IDs → errors)
186-
lives in `security/opengrep/compile-manifest.json`.
187+
its `metadata` includes `ghsa`, `advisory-url`, `detector-bucket`, `source-run`,
188+
and `source-rule-id`. `pnpm check:opengrep-rule-metadata` enforces those durable
189+
source fields so each committed rule is traceable without a separate committed
190+
manifest. The compile manifest is written into the detector-review run directory
191+
for local audit/debugging of a specific compile run.

‎security/opengrep/README.md‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
`precise.yml` is the compiled output of the GHSA detector-review pipeline. Each rule corresponds to a specific GitHub Security Advisory for `openclaw/openclaw` and is intended to have concrete coverage of the original vulnerable line.
44

5-
`compile-manifest.json` is a per-rule provenance map for traceability.
5+
Rule provenance lives in each compiled rule's metadata. `compile-manifest.json` is written into the detector-review run directory as a local audit/debug artifact, not as a committed source of truth.
66

77
Noisy exploratory rules are intentionally kept out of the tracked repo. Anything appended to `precise.yml` must be low-noise enough to run as a blocking PR-diff check and as a manual full-repository audit.
88

@@ -15,7 +15,7 @@ will be lost the next time `scripts/compile-opengrep-rules.mjs` runs.
1515
## Rule naming and metadata
1616

1717
Every rule's id is rewritten to `ghsa-detector.<ghsa-lower>.<original-id>`.
18-
Every rule's `metadata` block is augmented with:
18+
Every rule's `metadata` block is augmented with source fields enforced by `pnpm check:opengrep-rule-metadata`:
1919

2020
| Key | Value |
2121
| ----------------- | -------------------------------------------------------------- |
@@ -40,9 +40,9 @@ The script:
4040
3. Rewrites ids and injects metadata as above
4141
4. Appends only new precise rule ids to the existing `precise.yml` by default; pass `--replace-precise` to rebuild it from just the supplied run
4242
5. Runs `opengrep scan --no-strict` against an empty target to identify schema-invalid or parser-invalid rules and drops mapped bad rules so the published super-config loads cleanly
43-
6. Writes `precise.yml` and `compile-manifest.json`
43+
6. Writes `precise.yml` and `<run-dir>/compile-manifest.json`
4444

45-
Anything skipped (YAML parse error, duplicate generated rule id, or schema/parser-invalid) is recorded under `preciseInvalid` / `preciseDuplicateSkipped` in `compile-manifest.json` for follow-up.
45+
Anything skipped (YAML parse error, duplicate generated rule id, or schema/parser-invalid) is recorded under `preciseInvalid` / `preciseDuplicateSkipped` in the run-local `compile-manifest.json` for follow-up.
4646

4747
## Validating locally
4848

0 commit comments

Comments
 (0)