Skip to content

Commit 810b403

Browse files
committed
chore: support generic opengrep rule sources
1 parent 3d8c234 commit 810b403

5 files changed

Lines changed: 121 additions & 77 deletions

File tree

‎security/README.md‎

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
# Security tooling
22

33
This directory holds OpenClaw's shipped OpenGrep security rulepack and the
4-
supporting tooling that validates and runs it. Maintainer-only GHSA advisory
5-
triage and detector-generation prompts live outside the public repo; this repo
6-
keeps the durable artifacts needed to block regressions in PRs and support local
7-
rule validation.
4+
supporting tooling that validates and runs it. Maintainer-only advisory triage
5+
and detector-generation prompts live outside the public repo; this repo keeps the
6+
durable artifacts needed to block regressions in PRs and support local rule
7+
validation.
88

99
## Layout
1010

@@ -36,9 +36,8 @@ node security/opengrep/compile-rules.mjs \
3636
--rules-dir <folder-with-source-rule-yaml>
3737
```
3838

39-
Commit the resulting `security/opengrep/precise.yml` diff. The compile manifest
40-
is written into the source rules directory as a local troubleshooting artifact.
41-
Durable rule provenance lives in each compiled rule's metadata and is checked by
39+
Commit the resulting `security/opengrep/precise.yml` diff. Durable rule
40+
provenance lives in each compiled rule's metadata and is checked by
4241
`pnpm check:opengrep-rule-metadata`.
4342

4443
Rule quality contract: precise rules must catch the vulnerable behavior they were
@@ -125,12 +124,13 @@ To drop a noisy rule:
125124
To narrow a rule's path scope, edit the source rule's `paths.include` /
126125
`paths.exclude` fields in the same local artifact location and recompile.
127126

128-
## Tracing a finding back to its advisory
127+
## Tracing a finding back to its source
129128

130-
Every compiled rule's `id` is `ghsa-xxxx-xxxx-xxxx.<original-id>` and its
131-
`metadata` includes `ghsa`, `advisory-url`, `detector-bucket`, and
132-
`source-rule-id`. New compilations also add `source-file` when available.
133-
`pnpm check:opengrep-rule-metadata` enforces the durable source fields so each
134-
committed rule is traceable without a separate committed manifest. The compile
135-
manifest is written into the source rules directory for audit and debugging of a
136-
specific compile run.
129+
Every compiled rule's `id` is `<source-id>.<original-id>`. For GHSA-backed rules,
130+
`<source-id>` is the lower-case GHSA ID. For other source-backed rules, use a
131+
stable source identifier without dots such as a CVE, OSV ID, internal advisory ID, or other
132+
review identifier. Rule `metadata` must include `advisory-url`,
133+
`detector-bucket`, and `source-rule-id`, plus either `ghsa` or `advisory-id`.
134+
New compilations also add `source-file` when available.
135+
`pnpm check:opengrep-rule-metadata` enforces these durable source fields so each
136+
committed rule is traceable without a separate committed manifest.

‎security/opengrep/README.md‎

Lines changed: 23 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
# Compiled OpenGrep super-configs
22

33
`precise.yml` is OpenClaw's shipped precise OpenGrep rulepack. Each rule is tied
4-
to a source advisory through metadata and is intended to have concrete coverage
5-
of the original vulnerable behavior or a verified variant.
4+
to a source advisory, vulnerability report, or review identifier through metadata
5+
and is intended to have concrete coverage of the original vulnerable behavior or
6+
a verified variant.
67

7-
Rule provenance lives in each compiled rule's metadata. `compile-manifest.json`
8-
is written into the source rules directory as an audit/debug artifact, not as a
9-
committed source of truth.
8+
Rule provenance lives in each compiled rule's metadata; no separate manifest is
9+
committed or generated by default.
1010

1111
Noisy exploratory rules are intentionally kept out of the tracked repo. Anything
1212
appended to `precise.yml` must be low-noise enough to run as a blocking PR-diff
@@ -23,17 +23,18 @@ metadata, duplicate, and OpenGrep validation.
2323

2424
## Rule naming and metadata
2525

26-
Every rule's id is rewritten to `ghsa-xxxx-xxxx-xxxx.<original-id>`. Every
27-
rule's `metadata` block is augmented with source fields enforced by
26+
Every rule's id is rewritten to `<source-id>.<original-id>`. Every rule's
27+
`metadata` block is augmented with source fields enforced by
2828
`pnpm check:opengrep-rule-metadata`:
2929

30-
| Key | Value |
31-
| ----------------- | -------------------------------------------------------------- |
32-
| `ghsa` | `GHSA-xxxx-xxxx-xxxx` |
33-
| `advisory-url` | `https://github.com/openclaw/openclaw/security/advisories/...` |
34-
| `detector-bucket` | `precise` |
35-
| `source-rule-id` | the original source rule id |
36-
| `source-file` | optional source YAML file used during compilation |
30+
| Key | Value |
31+
| ----------------- | --------------------------------------------------------------------- |
32+
| `ghsa` | `GHSA-xxxx-xxxx-xxxx` for GHSA-backed rules |
33+
| `advisory-id` | non-GHSA source identifier, or the GHSA ID normalized by the compiler |
34+
| `advisory-url` | durable URL to the advisory, report, review record, or source context |
35+
| `detector-bucket` | `precise` |
36+
| `source-rule-id` | the original source rule id |
37+
| `source-file` | optional source YAML file used during compilation |
3738

3839
## Recompiling
3940

@@ -47,13 +48,14 @@ The script:
4748

4849
1. Recursively walks every `.yml` / `.yaml` file under `--rules-dir`
4950
2. Reads top-level `rules` arrays from those source files
50-
3. Requires each source rule to provide `metadata.ghsa`
51-
4. Rewrites ids and injects metadata as above
52-
5. Appends only new precise rule ids to the existing `precise.yml` by default; pass `--replace-precise` to rebuild it from just the supplied source folder
53-
6. 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
54-
7. Writes `precise.yml` and `<rules-dir>/compile-manifest.json`
55-
56-
Anything skipped (YAML parse error, duplicate compiled rule id, or schema/parser-invalid) is recorded under `preciseInvalid` / `preciseDuplicateSkipped` in the source-folder `compile-manifest.json` for follow-up.
51+
3. Requires each source rule to provide `metadata.ghsa` or `metadata.advisory-id`
52+
4. Requires `metadata.advisory-url` for non-GHSA source identifiers
53+
5. Rewrites ids and injects metadata as above
54+
6. Appends only new precise rule ids to the existing `precise.yml` by default; pass `--replace-precise` to rebuild it from just the supplied source folder
55+
7. 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
56+
8. Writes `precise.yml`
57+
58+
Skipped, duplicate, or invalid rules are summarized on stdout/stderr for follow-up.
5759

5860
## Validating locally
5961

‎security/opengrep/check-rule-metadata.mjs‎

Lines changed: 35 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,12 @@ import { parseDocument } from "yaml";
55

66
const DEFAULT_RULEPACK = path.resolve("security", "opengrep", "precise.yml");
77
const GHSA_RE = /^GHSA-[0-9A-Z]{4}-[0-9A-Z]{4}-[0-9A-Z]{4}$/;
8-
const RULE_ID_RE = /^(ghsa-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4})\..+$/;
8+
const RULE_ID_RE = /^([a-z0-9][a-z0-9_-]*)\..+$/;
99

1010
function printHelp() {
1111
console.log(`Usage: node security/opengrep/check-rule-metadata.mjs [rulepack.yml]
1212
13-
Checks that every compiled GHSA OpenGrep rule carries source/provenance metadata.
13+
Checks that every compiled OpenGrep rule carries source/provenance metadata.
1414
Default rulepack: ${DEFAULT_RULEPACK}
1515
`);
1616
}
@@ -34,6 +34,19 @@ function hasNonEmptyString(value) {
3434
return typeof value === "string" && value.trim().length > 0;
3535
}
3636

37+
function sanitizeIdComponent(value) {
38+
return (
39+
String(value || "")
40+
.replace(/[^a-zA-Z0-9._-]+/g, "-")
41+
.replace(/^-+|-+$/g, "")
42+
.toLowerCase() || "rule"
43+
);
44+
}
45+
46+
function sanitizeSourceIdComponent(value) {
47+
return sanitizeIdComponent(value).replace(/[.]+/g, "-");
48+
}
49+
3750
export function validateRuleMetadata(rules) {
3851
const violations = [];
3952

@@ -48,26 +61,37 @@ export function validateRuleMetadata(rules) {
4861

4962
const idMatch = id.match(RULE_ID_RE);
5063
if (!idMatch) {
51-
violations.push(`${label}: id must match ghsa-xxxx-xxxx-xxxx.<source-rule-id>`);
64+
violations.push(`${label}: id must match <source-id>.<source-rule-id>`);
5265
}
5366

5467
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()) {
68+
const advisoryId = String(metadata["advisory-id"] ?? metadata.ghsa ?? "")
69+
.trim()
70+
.toUpperCase();
71+
if (!hasNonEmptyString(advisoryId)) {
72+
violations.push(`${label}: missing metadata.advisory-id or metadata.ghsa`);
73+
} else if (idMatch && idMatch[1] !== sanitizeSourceIdComponent(advisoryId)) {
74+
violations.push(
75+
`${label}: source id in metadata (${advisoryId}) must match source id in rule id (${idMatch[1]})`,
76+
);
77+
}
78+
79+
if (ghsa && !GHSA_RE.test(ghsa)) {
80+
violations.push(`${label}: metadata.ghsa must match GHSA-XXXX-XXXX-XXXX when present`);
81+
} else if (ghsa && advisoryId !== ghsa) {
5882
violations.push(
59-
`${label}: metadata.ghsa (${ghsa}) must match GHSA component in id (${idMatch[1]})`,
83+
`${label}: metadata.advisory-id must match metadata.ghsa when both are present`,
6084
);
6185
}
6286

6387
const advisoryUrl = String(metadata["advisory-url"] ?? "");
64-
const expectedUrl = ghsa
65-
? `https://github.com/openclaw/openclaw/security/advisories/${ghsa}`
88+
const expectedGhsaUrl = GHSA_RE.test(advisoryId)
89+
? `https://github.com/openclaw/openclaw/security/advisories/${advisoryId}`
6690
: "";
6791
if (!hasNonEmptyString(advisoryUrl)) {
6892
violations.push(`${label}: missing metadata.advisory-url`);
69-
} else if (expectedUrl && advisoryUrl !== expectedUrl) {
70-
violations.push(`${label}: metadata.advisory-url must be ${expectedUrl}`);
93+
} else if (expectedGhsaUrl && advisoryUrl !== expectedGhsaUrl) {
94+
violations.push(`${label}: metadata.advisory-url must be ${expectedGhsaUrl}`);
7195
}
7296

7397
if (metadata["detector-bucket"] !== "precise") {

‎security/opengrep/compile-rules.mjs‎

Lines changed: 29 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
* Compiles source OpenGrep rule YAML files from a folder into OpenClaw's shipped
66
* precise super-config. The input folder is intentionally generic: any nested
77
* .yml/.yaml file containing a top-level `rules` array can be compiled as long
8-
* as each rule carries metadata.ghsa.
8+
* as each rule carries metadata.ghsa or metadata.advisory-id.
99
*/
1010

1111
import { spawn } from "node:child_process";
@@ -27,7 +27,6 @@ function printHelp() {
2727
Options:
2828
--rules-dir <path> Required. Directory containing source OpenGrep YAML files.
2929
--out-dir <path> Output directory for precise.yml (default: <repo>/security/opengrep).
30-
--manifest-dir <path> Directory for compile-manifest.json (default: <rules-dir>).
3130
--advisory-repo <r> GitHub owner/repo used in advisory-url metadata.
3231
Default: ${REPO_BASENAME}
3332
--replace-precise Replace precise.yml instead of appending new rule ids.
@@ -39,7 +38,6 @@ function parseArgs(argv) {
3938
const opts = {
4039
rulesDir: "",
4140
outDir: "",
42-
manifestDir: "",
4341
advisoryRepo: REPO_BASENAME,
4442
replacePrecise: false,
4543
};
@@ -58,10 +56,6 @@ function parseArgs(argv) {
5856
opts.outDir = path.resolve(argv[i + 1] ?? "");
5957
i += 1;
6058
break;
61-
case "--manifest-dir":
62-
opts.manifestDir = path.resolve(argv[i + 1] ?? "");
63-
i += 1;
64-
break;
6559
case "--advisory-repo":
6660
opts.advisoryRepo = argv[i + 1] ?? REPO_BASENAME;
6761
i += 1;
@@ -93,13 +87,21 @@ function sanitizeIdComponent(value) {
9387
);
9488
}
9589

96-
function normalizeGhsa(value) {
90+
function normalizeSourceId(value) {
9791
return String(value || "")
9892
.trim()
9993
.toUpperCase();
10094
}
10195

102-
function buildAdvisoryUrl(advisoryRepo, ghsa) {
96+
function sanitizeSourceIdComponent(value) {
97+
return sanitizeIdComponent(value).replace(/[.]+/g, "-");
98+
}
99+
100+
function sourceIdFromMetadata(metadata) {
101+
return normalizeSourceId(metadata?.["advisory-id"] || metadata?.ghsa);
102+
}
103+
104+
function buildGhsaAdvisoryUrl(advisoryRepo, ghsa) {
103105
return `https://github.com/${advisoryRepo}/security/advisories/${ghsa}`;
104106
}
105107

@@ -114,20 +116,29 @@ function toPortablePath(filePath, repoRoot = REPO_ROOT) {
114116

115117
function rewriteRule(rule, params) {
116118
const originalId = String(rule.id ?? "rule");
117-
const ghsa = normalizeGhsa(rule.metadata?.ghsa);
118-
if (!GHSA_RE.test(ghsa)) {
119+
const metadata = { ...(rule.metadata ?? {}) };
120+
const sourceId = sourceIdFromMetadata(metadata);
121+
if (!sourceId) {
119122
throw new Error(
120-
`${params.sourceFile}: rule ${originalId} must set metadata.ghsa to GHSA-XXXX-XXXX-XXXX`,
123+
`${params.sourceFile}: rule ${originalId} must set metadata.advisory-id or metadata.ghsa`,
121124
);
122125
}
123-
const metadata = { ...(rule.metadata ?? {}) };
124-
metadata.ghsa = ghsa;
125-
metadata["advisory-url"] =
126-
metadata["advisory-url"] || buildAdvisoryUrl(params.advisoryRepo, ghsa);
126+
127+
if (GHSA_RE.test(sourceId)) {
128+
metadata.ghsa = sourceId;
129+
metadata["advisory-url"] =
130+
metadata["advisory-url"] || buildGhsaAdvisoryUrl(params.advisoryRepo, sourceId);
131+
} else if (!metadata["advisory-url"]) {
132+
throw new Error(
133+
`${params.sourceFile}: rule ${originalId} must set metadata.advisory-url for non-GHSA source ${sourceId}`,
134+
);
135+
}
136+
137+
metadata["advisory-id"] = sourceId;
127138
metadata["detector-bucket"] = "precise";
128139
metadata["source-rule-id"] = originalId;
129140
metadata["source-file"] = toPortablePath(params.sourceFile);
130-
const newId = `${ghsa.toLowerCase()}.${sanitizeIdComponent(originalId)}`;
141+
const newId = `${sanitizeSourceIdComponent(sourceId)}.${sanitizeIdComponent(originalId)}`;
131142
return { ...rule, id: newId, metadata };
132143
}
133144

@@ -552,20 +563,11 @@ async function writeOutputs(buckets, manifest, outDir, opts) {
552563
manifest.totals.preciseInvalid = droppedDetails.length;
553564
manifest.preciseInvalid = droppedDetails;
554565
manifest.preciseDuplicateSkipped = appendResult.skippedDuplicateIds;
555-
556-
const manifestDir = opts.manifestDir || opts.rulesDir;
557-
await fs.mkdir(manifestDir, { recursive: true });
558-
const manifestPath = path.join(manifestDir, "compile-manifest.json");
559-
manifest.output = { precisePath, manifestPath };
560-
await fs.writeFile(manifestPath, JSON.stringify(manifest, null, 2) + "\n");
561566
}
562567

563568
function printSummary(buckets, manifest, outDir) {
564569
console.log(`compile-rules: done`);
565570
console.log(` out-dir : ${outDir}`);
566-
if (manifest.output?.manifestPath) {
567-
console.log(` manifest : ${manifest.output.manifestPath}`);
568-
}
569571
console.log(` files scanned : ${manifest.totals.filesScanned}`);
570572
console.log(` files with rules : ${manifest.totals.filesWithAnyRule}`);
571573
console.log(
@@ -579,7 +581,7 @@ function printSummary(buckets, manifest, outDir) {
579581
console.log(` [precise] ${s.file}: yaml: ${s.error.split("\n")[0]}`);
580582
}
581583
for (const s of (buckets.precise.invalid ?? []).slice(0, 3)) {
582-
console.log(` [precise] ${s.ghsa}: schema-invalid id=${s.id}`);
584+
console.log(` [precise] ${s.id}: schema-invalid`);
583585
}
584586
}
585587
}

‎test/scripts/check-opengrep-rule-metadata.test.ts‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ const validRule = {
1212
};
1313

1414
describe("check-opengrep-rule-metadata", () => {
15-
it("accepts compiled GHSA rules with durable source metadata", () => {
15+
it("accepts GHSA-backed rules with durable source metadata", () => {
1616
expect(validateRuleMetadata([validRule])).toEqual([]);
1717
});
1818

@@ -33,7 +33,23 @@ describe("check-opengrep-rule-metadata", () => {
3333
]);
3434
});
3535

36-
it("keeps the GHSA id, rule id, and advisory URL consistent", () => {
36+
it("accepts non-GHSA source-backed rules with durable source metadata", () => {
37+
expect(
38+
validateRuleMetadata([
39+
{
40+
id: "cve-2026-12345.source-rule",
41+
metadata: {
42+
"advisory-id": "CVE-2026-12345",
43+
"advisory-url": "https://example.test/advisories/CVE-2026-12345",
44+
"detector-bucket": "precise",
45+
"source-rule-id": "source-rule",
46+
},
47+
},
48+
]),
49+
).toEqual([]);
50+
});
51+
52+
it("keeps the source id, rule id, and GHSA advisory URL consistent", () => {
3753
expect(
3854
validateRuleMetadata([
3955
{
@@ -47,7 +63,7 @@ describe("check-opengrep-rule-metadata", () => {
4763
},
4864
]),
4965
).toEqual([
50-
"ghsa-1234-abcd-5678.source-rule: metadata.ghsa (GHSA-9999-ABCD-5678) must match GHSA component in id (ghsa-1234-abcd-5678)",
66+
"ghsa-1234-abcd-5678.source-rule: source id in metadata (GHSA-9999-ABCD-5678) must match source id in rule id (ghsa-1234-abcd-5678)",
5167
"ghsa-1234-abcd-5678.source-rule: metadata.advisory-url must be https://github.com/openclaw/openclaw/security/advisories/GHSA-9999-ABCD-5678",
5268
]);
5369
});

0 commit comments

Comments
 (0)