Skip to content

feat(deps): add SBOM risk report - #71005

Merged
vincentkoc merged 2 commits into
mainfrom
feat/sbom-risk-report
Apr 24, 2026
Merged

vincentkoc merged 2 commits into
mainfrom
feat/sbom-risk-report

Conversation

@vincentkoc

Copy link
Copy Markdown
Member

Summary

  • add pnpm deps:sbom-risk and pnpm deps:sbom-risk:check
  • seed scripts/lib/dependency-ownership.json with current root dependency owners/classes/risks
  • report root/importer closure sizes, build/native/bin risk packages, top root dependency cones, ownership gaps, and source ownership warnings

Validation

  • pnpm test test/scripts/sbom-risk-report.test.ts test/scripts/root-dependency-ownership-audit.test.ts
  • pnpm deps:sbom-risk:check
  • pnpm deps:root-ownership:check
  • pnpm exec oxlint scripts/sbom-risk-report.mjs test/scripts/sbom-risk-report.test.ts
  • pnpm format:check scripts/lib/dependency-ownership.json scripts/sbom-risk-report.mjs test/scripts/sbom-risk-report.test.ts package.json CHANGELOG.md

pnpm check:changed currently fails in tsgo:all on existing model compat type errors around supportsLongCacheRetention / @mariozechner/pi-ai exports and sparse-worktree missing UI/package test imports; the focused dependency/tooling gates above pass.

@aisle-research-bot

aisle-research-bot Bot commented Apr 24, 2026 •

Copy link
Copy Markdown

🔒 Aisle Security Analysis

We found 3 potential security issue(s) in this PR:

# Severity Title
1 🟡 Medium Unbounded lockfile dependency-graph traversal can cause DoS in sbom-risk-report
2 🟡 Medium Unbounded repository file scan and full-file reads can allow CI denial of service
3 🔵 Low Terminal/CI log escape injection via unsanitized dependency metadata in sbom-risk-report
1. 🟡 Unbounded lockfile dependency-graph traversal can cause DoS in sbom-risk-report
Property Value
Severity Medium
CWE CWE-400
Location scripts/sbom-risk-report.mjs:77-98

Description

The collectClosure() function performs an unbounded breadth-first traversal over pnpm-lock.yaml snapshots.

  • Input is attacker-controlled in many CI contexts: the script reads pnpm-lock.yaml from the working tree (readLockfile(path.join(repoRoot, "pnpm-lock.yaml"))), which can be modified in untrusted PRs.
  • No limits on nodes/edges/queue size: traversal continues until the queue is empty and stores all seen keys in memory.
  • Amplification: collectSbomRiskReport() calls collectClosure() once per root dependency (potentially dozens/hundreds of traversals) and again for the full root set and for each importer, multiplying cost.
  • Inefficient queue: using queue.shift() inside the loop is O(n) per pop in JS arrays, turning large traversals into potentially quadratic time.

This can lead to excessive CPU and memory usage (CI job timeouts or runner exhaustion) on large or malicious lockfiles.

Recommendation

Add explicit resource limits and avoid quadratic queue operations.

1) Use an index-based queue (O(1) pop) and cap traversal:

function collectClosure(lockfile, rootKeys, { maxNodes = 50_000, maxMissing = 5_000 } = {}) {
  const seen = new Set();
  const missing = new Set();
  const queue = [...rootKeys].filter(Boolean);

  for (let i = 0; i < queue.length; i++) {
    if (seen.size >= maxNodes) break;

    const key = queue[i];
    if (seen.has(key)) continue;
    seen.add(key);

    const snapshot = lockfile.snapshots?.[key];
    if (!snapshot) {
      if (missing.size < maxMissing) missing.add(key);
      continue;
    }

    for (const dep of dependencyEntriesFromSnapshot(snapshot)) {
      const depKey = lockKeyForDependency(dep.name, dep.version);
      if (depKey && !seen.has(depKey)) queue.push(depKey);
    }
  }

  return {
    truncated: seen.size >= maxNodes,
    missing: [...missing].toSorted(compareStrings),
    packageKeys: [...seen].toSorted(compareStrings),
  };
}

2) Reduce amplification: compute closure once for all roots, or memoize closures per key (or reuse a single traversal from all roots) rather than running a full traversal for every root dependency.

3) Consider upfront validation: reject/short-circuit processing when lockfile size or snapshot/package counts exceed a safe threshold for your CI environment.

2. 🟡 Unbounded repository file scan and full-file reads can allow CI denial of service
Property Value
Severity Medium
CWE CWE-400
Location scripts/root-dependency-ownership-audit.mjs:39-60

Description

The dependency ownership audit used by scripts/sbom-risk-report.mjs performs a synchronous recursive walk of multiple repository directories and reads every matching source file fully into memory.

If this script is executed in CI for untrusted pull requests, an attacker can cause resource exhaustion by committing:

  • Extremely large .js/.ts/... files under scanned roots (e.g., src/, packages/, ui/, etc.)
  • A very large number of scannable files/directories

This can significantly increase runtime and memory usage (the scan is synchronous and single-threaded), potentially causing CI job timeouts or runner instability.

Vulnerable behavior:

  • walkFiles() traverses the tree without limits
  • Each file is read via fs.readFileSync(..., "utf8") and then regex-scanned

Recommendation

Add guardrails to make the scan safe for untrusted inputs and large trees:

  • Enforce a maximum file size before reading (skip or truncate)
  • Enforce maximum file count / maximum total bytes read
  • Consider using async IO and/or streaming reads with early termination
  • Optionally add a --max-files / --max-bytes CLI flag and a CI-default budget

Example mitigation (size + count caps):

const MAX_FILE_BYTES = 512 * 1024; // 512KB
const MAX_FILES = 20_000;

function safeReadUtf8(filePath) {
  const st = fs.statSync(filePath, { throwIfNoEntry: false });
  if (!st || !st.isFile() || st.size > MAX_FILE_BYTES) return null;
  return fs.readFileSync(filePath, "utf8");
}

​// when walking
if (files.length >= MAX_FILES) break;

​// when reading
const source = safeReadUtf8(filePath);
if (source == null) continue;

This limits worst-case CI impact while still providing useful audit output.

3. 🔵 Terminal/CI log escape injection via unsanitized dependency metadata in sbom-risk-report
Property Value
Severity Low
CWE CWE-117
Location scripts/sbom-risk-report.mjs:243-292

Description

scripts/sbom-risk-report.mjs prints several fields derived from repository-controlled files directly to stdout/stderr without neutralizing control characters.

If this script is executed in CI on untrusted PRs (or locally on untrusted branches), an attacker can modify inputs such as:

  • pnpm-lock.yaml importer keys (e.g., lockfile.importers keys), dependency keys, and other string fields parsed from YAML
  • scripts/lib/dependency-ownership.json values like owner (free-form strings)
  • sourceSections (derived from repository source layout via collectRootDependencyOwnershipAudit)

to include ANSI escape sequences or other terminal control characters. This can enable terminal escape injection / log spoofing, potentially hiding failures, forging success messages, or misleading reviewers by altering CI log rendering.

Vulnerable code examples:

console.log(`- ${warning.name}: ${warning.message} (${warning.sourceSections.join(",")})`);
console.log(`- ${dependency.name}: closure=${dependency.closureSize} owner=${owner} class=${dependency.class ?? "-"}`);
console.error(`[sbom-risk] ${error}`);
console.log(`- ${importer.importer}: closure=${importer.closureSize} direct=${importer.directDependencyCount}`);

Recommendation

Neutralize terminal control characters before writing attacker-influenced strings to stdout/stderr.

A simple mitigation is to strip ANSI escape sequences and other control characters from values before interpolating them into log lines:

function sanitizeForTerminal(value) {
  const s = String(value ?? "");
  ​// Strip ANSI escape sequences
  const noAnsi = s.replace(/\u001B\[[0-9;]*[A-Za-z]/g, "");
  ​// Strip other C0 control chars except \n and \t
  return noAnsi.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g, "");
}

console.log(`- ${sanitizeForTerminal(dependency.name)}: closure=${dependency.closureSize} owner=${sanitizeForTerminal(owner)} class=${sanitizeForTerminal(dependency.class ?? "-")}`);

Alternatively, for machine consumption prefer --json in CI and avoid human-oriented terminal formatting for untrusted inputs.


Analyzed PR: #71005 at commit 202648c

Last updated on: 2026-04-24T16:00:27Z

@vincentkoc vincentkoc self-assigned this Apr 24, 2026
@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts size: L maintainer Maintainer-authored PR labels Apr 24, 2026
@greptile-apps

greptile-apps Bot commented Apr 24, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds a new deps:sbom-risk script that walks the pnpm v9 lockfile to report root-dependency closure sizes, build/native/bin risk packages, ownership gaps, and importer closure rankings, backed by a seeded dependency-ownership.json registry. The implementation is clean and well-tested with a self-contained temp-repo fixture.

Confidence Score: 5/5

Safe to merge — all findings are minor P2 suggestions that do not affect current runtime correctness.

All three findings are P2 style/design improvements (double traversal, hardcoded path in error message, stale records not checked). None affect existing functionality or the default execution path.

No files require special attention.

Prompt To Fix All With AI
This is a comment left during a code review.
Path: scripts/sbom-risk-report.mjs
Line: 214-219

Comment:
**Double traversal of build-risk packages**

`collectBuildRiskPackages(lockfile)` is called twice in the same return statement — once to get `.length` for the summary, and again to get the `.slice(0, 50)` list. On large lockfiles this traverses all packages entries twice. Compute it once before the `return`.

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: scripts/sbom-risk-report.mjs
Line: 233-237

Comment:
**Error message always references default ownership path**

`collectSbomRiskCheckErrors` is a pure function that takes only `report`, but its error text is hard-wired to `DEFAULT_OWNERSHIP_PATH`. When `collectSbomRiskReport` is called with a custom `ownershipPath` parameter (e.g. in tests or future tooling), the reported path will be wrong — pointing to `scripts/lib/dependency-ownership.json` even though a different file was actually used. Consider including the resolved path in the returned report so error messages stay accurate, or accept the path as a parameter.

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: scripts/sbom-risk-report.mjs
Line: 188-190

Comment:
**Stale ownership records not surfaced by `--check`**

`staleOwnershipRecords` is computed and included in the JSON output, but `collectSbomRiskCheckErrors` only checks `ownershipGaps`. Over time, entries whose packages have been removed from `package.json` will silently accumulate in `dependency-ownership.json` without causing a `pnpm deps:sbom-risk:check` failure. If the intent is to keep the file tidy, consider surfacing stale records as check errors too.

How can I resolve this? If you propose a fix, please make it concise.

Reviews (1): Last reviewed commit: "feat(deps): add sbom risk report" | Re-trigger Greptile

Comment on lines +214 to +219
buildRiskPackageCount: collectBuildRiskPackages(lockfile).length,
},
ownershipGaps,
staleOwnershipRecords,
ownershipWarnings,
buildRiskPackages: collectBuildRiskPackages(lockfile).slice(0, 50),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Double traversal of build-risk packages

collectBuildRiskPackages(lockfile) is called twice in the same return statement — once to get .length for the summary, and again to get the .slice(0, 50) list. On large lockfiles this traverses all packages entries twice. Compute it once before the return.

Prompt To Fix With AI
This is a comment left during a code review.
Path: scripts/sbom-risk-report.mjs
Line: 214-219

Comment:
**Double traversal of build-risk packages**

`collectBuildRiskPackages(lockfile)` is called twice in the same return statement — once to get `.length` for the summary, and again to get the `.slice(0, 50)` list. On large lockfiles this traverses all packages entries twice. Compute it once before the `return`.

How can I resolve this? If you propose a fix, please make it concise.

Comment on lines +233 to +237
export function collectSbomRiskCheckErrors(report) {
return report.ownershipGaps.map(
(name) => `root dependency '${name}' is missing from ${DEFAULT_OWNERSHIP_PATH}`,
);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Error message always references default ownership path

collectSbomRiskCheckErrors is a pure function that takes only report, but its error text is hard-wired to DEFAULT_OWNERSHIP_PATH. When collectSbomRiskReport is called with a custom ownershipPath parameter (e.g. in tests or future tooling), the reported path will be wrong — pointing to scripts/lib/dependency-ownership.json even though a different file was actually used. Consider including the resolved path in the returned report so error messages stay accurate, or accept the path as a parameter.

Prompt To Fix With AI
This is a comment left during a code review.
Path: scripts/sbom-risk-report.mjs
Line: 233-237

Comment:
**Error message always references default ownership path**

`collectSbomRiskCheckErrors` is a pure function that takes only `report`, but its error text is hard-wired to `DEFAULT_OWNERSHIP_PATH`. When `collectSbomRiskReport` is called with a custom `ownershipPath` parameter (e.g. in tests or future tooling), the reported path will be wrong — pointing to `scripts/lib/dependency-ownership.json` even though a different file was actually used. Consider including the resolved path in the returned report so error messages stay accurate, or accept the path as a parameter.

How can I resolve this? If you propose a fix, please make it concise.

Comment thread scripts/sbom-risk-report.mjs Outdated
Comment on lines +188 to +190
const staleOwnershipRecords = Object.keys(dependencyOwnership.dependencies ?? {})
.filter((name) => !rootDependencyNames.has(name))
.toSorted();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Stale ownership records not surfaced by --check

staleOwnershipRecords is computed and included in the JSON output, but collectSbomRiskCheckErrors only checks ownershipGaps. Over time, entries whose packages have been removed from package.json will silently accumulate in dependency-ownership.json without causing a pnpm deps:sbom-risk:check failure. If the intent is to keep the file tidy, consider surfacing stale records as check errors too.

Prompt To Fix With AI
This is a comment left during a code review.
Path: scripts/sbom-risk-report.mjs
Line: 188-190

Comment:
**Stale ownership records not surfaced by `--check`**

`staleOwnershipRecords` is computed and included in the JSON output, but `collectSbomRiskCheckErrors` only checks `ownershipGaps`. Over time, entries whose packages have been removed from `package.json` will silently accumulate in `dependency-ownership.json` without causing a `pnpm deps:sbom-risk:check` failure. If the intent is to keep the file tidy, consider surfacing stale records as check errors too.

How can I resolve this? If you propose a fix, please make it concise.

@vincentkoc
vincentkoc force-pushed the feat/sbom-risk-report branch from 3666c2a to 202648c Compare April 24, 2026 15:58
@vincentkoc
vincentkoc merged commit 58f5480 into main Apr 24, 2026
65 checks passed
@vincentkoc
vincentkoc deleted the feat/sbom-risk-report branch April 24, 2026 16:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

maintainer Maintainer-authored PR scripts Repository scripts size: L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant