# cdxrs — Rust-native CycloneDX tooling for cdxgen This document specifies the protocol, exit codes, environment variables, and extension points for the `cdxrs` Rust binary. Every Track B/C/D deliverable that ports JS logic to Rust must follow this specification. ## Overview `cdxrs` lives in the `cdxgen-plugins-bin` repository at `thirdparty/cdxrs/`. It is a single crate with a single binary, following the same shape as `thirdparty/cdxui/` (not the `rusi` workspace). The JS bridge is at `lib/inventory/cdxrs.js` in the cdxgen repository. It is the **only** module that spawns the `cdxrs` binary. ## Architecture ``` cdxgen (JS) └── lib/inventory/cdxrs.js ← bridge: spawns binary, handles failure modes └── cdxrs binary ← Rust crate in cdxgen-plugins-bin ├── src/main.rs ← clap parsing + dispatch ONLY ├── src/lib.rs ← library: all logic ├── src/cli.rs ← clap derive structs ├── src/io.rs ← input/output resolution ├── src/log.rs ← NDJSON logging to stderr ├── src/error.rs ← thiserror types + exit-code mapping ├── src/bom/ ← CycloneDX model, read, write, refs └── src/cmd/ ← subcommand implementations ``` ### Library/binary split (mandatory) All logic lives in `src/lib.rs` modules. `src/main.rs` is argument parsing plus thin dispatch — it contains no business logic and has no `std::process::exit` calls outside of the dispatch return. This is what makes the eventual napi-rs move cheap. ## Binary resolution The bridge reuses `lib/inventory/plugins.js` conventions: - `CDXRS_CMD` environment variable overrides the binary path. - Otherwise, the binary is resolved from the platform-specific plugins-bin package: `plugins/cdxrs/cdxrs--[.exe]`. - Platform/arch detection uses `getPluginsBinTarget()` from plugins.js. ## Protocol ### Invocation ``` cdxrs [--input ] [--output ] [--max-input-bytes N] ``` - `--input -` reads stdin; `--input ` reads a file. Default: `-`. `--input` is always a **path**; BOM content is never passed as an argument. The bridge writes content to stdin, spilling to a temp file above 32 MB. - `--output -` or omitted writes stdout; `--output ` writes a file. - `--max-input-bytes` guards against hostile input (default: 2 GB). - Inputs over 32 MB should go through a file path, not a pipe (enforced by the bridge). ### I/O channels | Channel | Content | | ------- | ----------------------------------------------------------- | | stdin | JSON BOM data (when `--input -`) | | stdout | JSON output (command results, BOM data) | | stderr | NDJSON log records ONLY (never interleave logs into stdout) | ### Exit codes | Code | Meaning | | ---- | -------------------------------------------------------------------------- | | 0 | Success | | 1 | Operational failure (I/O error, parse error, size limit) | | 2 | Bad usage (invalid arguments) | | 3 | Validation failure with findings on stdout (findings are data, not errors) | ### NDJSON log records (stderr) Every log record is a single-line JSON object: ```json { "level": "info", "msg": "reading BOM" } ``` Levels: `debug`, `info`, `warn`, `error`. The bridge forwards these to cdxgen's logger at the corresponding levels. ## Subcommands ### `cdxrs info` Reads a BOM and prints summary statistics as a JSON object: ```json { "bomFormat": "CycloneDX", "specVersion": "1.6", "componentCount": 42, "dependencyCount": 35, "serviceCount": 0, "vulnerabilityCount": 0, "hasEvidence": true, "cdxrsVersion": "3.0.0" } ``` ### `cdxrs --version` Prints `cdxrs ` (e.g., `cdxrs 3.0.0`). ### `cdxrs schema-version` Prints supported spec versions, and in newer builds the optional behaviours the binary supports, as JSON: ```json { "supportedSpecVersions": ["1.6", "1.7"], "capabilities": ["fetch-github-token"] } ``` A build without the `capabilities` array has none. cdxgen reads it through `cdxrsCapabilities()` before it relies on any of them. ## Adding a new subcommand 1. **Create `src/cmd/.rs`** with a `pub fn run(...) -> Result<(), CdxrsError>` function. All logic goes here. 2. **Add to `src/cmd/mod.rs`:** ```rust pub mod ; ``` 3. **Add to the clap enum in `src/cli.rs`:** ```rust pub enum Command { Info, SchemaVersion, /// Description for --help. , } ``` 4. **Add dispatch in `src/main.rs`:** ```rust Some(Command::) => cdxrs::cmd::::run(&cli.input, &cli.output, cli.max_input_bytes), ``` 5. **Register in the JS bridge** (`lib/inventory/cdxrs.js`): Add the subcommand name to `KNOWN_SUBCOMMANDS`. 6. **Add the subcommand to `cdxrsDisabled` coverage** if it should be individually disableable via `CDXGEN_RS_DISABLE`. 7. **Write tests** — unit tests in the `.rs` file, and a bridge test with a fake binary fixture covering at least success and one failure mode. ## Testing against a locally-built binary Until plugins-bin is published, use `contrib/link-local-plugins.sh`: ```bash make -C ../cdxgen-plugins-bin/thirdparty/cdxrs darwin # or: linux ./contrib/link-local-plugins.sh # stages cdxrs export CDXGEN_PLUGINS_DIR=/tmp/cdxgen-local-plugins # path it prints node bin/cdxgen.js --version --verbose # => cdxrs 3.0.0 (available) ``` Two notes, because the obvious approaches do not work: - **`pnpm link` does not help.** Binary discovery is purely path-based — `//--` — and the version pinned in `package.json` is only used to construct npx/global-store paths, so aligning it does nothing for local testing. The platform packages' `plugins/` directories are also empty in git (binaries are build artifacts), so linking one yields an empty plugins dir. - **Prefer this over a bare `CDXRS_CMD`.** `CDXRS_CMD` short-circuits `resolvePluginBinary`, so it never exercises the filename convention or the plugins-dir layout — the two things most likely to be wrong. The script stages a composite directory (symlinks to your installed plugins, local builds layered on top), so everything else keeps resolving. Run the bridge tests with a binary present as well as without; they cover both: ```bash CDXGEN_PLUGINS_DIR=/tmp/cdxgen-local-plugins npx poku lib/inventory/cdxrs.poku.js ``` ## Environment variables | Variable | Purpose | | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `CDXGEN_PLUGINS_DIR` | Override the plugins directory (see above) | | `CDXRS_CMD` | Override the cdxrs binary path | | `CDXGEN_RS_DISABLE` | Disable Rust paths: `all` or comma-separated subcommand names | | `CDXGEN_NO_RUST` | Set to `true` to disable all Rust paths (same as `CDXGEN_RS_DISABLE=all`) | | `--no-rust` | CLI flag alias for `CDXGEN_NO_RUST=true` | | `CDXGEN_CACHE_DIR` | Override the metadata cache directory. Default: platform cache dir (`~/.cache/cdxgen` on Linux, `~/Library/Caches/cdxgen` on macOS, `%LOCALAPPDATA%\cdxgen\cache` on Windows). | | `CDXGEN_NO_CACHE` | Set to `true` or `1` to bypass the on-disk metadata cache for this run. | | `CDXGEN_CACHE_TTL` | Override the cache TTL in seconds. `0` means never expire. Default: 86400 (24h). | | `CDXGEN_CACHE_LOOPBACK` | Set to `1` to allow caching loopback hosts (`127.0.0.1`, `::1`, `localhost`). Loopback is excluded by default because test-double entries are keyed by ephemeral ports. Used by `contrib/bench-fetch.js`. | | `--no-cache` | CLI flag alias for `CDXGEN_NO_CACHE=true` | | `--cache-ttl ` | CLI flag alias for `CDXGEN_CACHE_TTL=` | ## Batch transport selection `prefetchJson` in `lib/inventory/fetchBatch.js` dispatches a batch to one of two transports, and callers do not choose between them: | Batch contains | Transport | | ------------------------------------------------------- | ------------------------ | | Plain JSON requests only, binary available | `cdxrs fetch` subprocess | | Any request with `responseType: "text"` or `"buffer"` | JS pool (`cdxgenAgent`) | | Any request carrying its own `headers` | JS pool | | A GitHub request cdxgen composed, cdxrs takes the token | `cdxrs fetch` subprocess | | Any other request to a GitHub host | JS pool | | No binary, or `CDXGEN_RS_DISABLE=fetch`, or `--no-rust` | JS pool | The protocol carries a URL, an `accept` value, an opaque `authRealm` and, for GitHub lookups cdxgen composed itself, a `githubToken`, and types a result body as JSON. These requests therefore stay on the pool: - a non-JSON `responseType`, because the envelope has nowhere to put HTML. Rather than parse HTML as JSON and record a failure, the batch goes to the pool, which passes `responseType` straight to the agent. Maven POMs, the pkg.go.dev pages behind `getGoPkgLicense`/`getGoPkgVCSUrl`, and CocoaPods podspecs rely on this; - request-specific `headers`, because the envelope has no field for them and cdxrs would send the request without the credential, turning an authenticated lookup into an anonymous one. `forgeEnricher` relies on this to carry `--forge-token` and `GITLAB_TOKEN`; - any GitHub host (`github.com`, `api.github.com` and `*.github.com`), except a lookup cdxgen composed itself when the bundled cdxrs takes a per-request token (see [GitHub token](#github-token)). The pool applies the same global and per-host concurrency and rate policy, so the batching win is unchanged; only the on-disk cache below is skipped. Within the pool, a credential the caller attached to a request wins over the ambient `GITHUB_TOKEN`. The ambient token is a fallback, never an override, and only a request whose caller composed the URL from the GitHub API base and set `ambientGitHubAuth: true` receives it. Many batch URLs come from the scanned project (a lockfile's `resolved` URL, an `.npmrc` scope registry), and naming a GitHub host must not let such a URL borrow the operator's token. ### GitHub token Whether a request may carry `GITHUB_TOKEN` is decided per request on the JS side, never by host name, and cdxrs never finds the token in its environment: `runCdxrs()`, the version probe and the capability probe all start the child without `GITHUB_TOKEN`. A request is a composed GitHub lookup when its caller set `ambientGitHubAuth: true` (today only `prefetchRepoLicenses()`, which builds the licence URL from the GitHub API base) and its URL is `https://api.github.com/repos//` or that path followed by `/license`, with plain owner and repository names (letters, digits, `.`, `_` and `-`), the default port, and no userinfo, query or fragment. `isComposedGitHubApiRequest()` in `lib/inventory/fetchBatch.js` makes that check. A lockfile's `resolved` URL, an `.npmrc` scope registry or any other URL read from the scanned project never sets the flag, so it never carries the token on either transport. cdxrs builds that accept the token list `fetch-github-token` in the `capabilities` array printed by `cdxrs schema-version`. `cdxrsCapabilities()` runs that probe once per binary and remembers the answer. With such a build, a batch of composed lookups goes to `cdxrs fetch`, and each request carries the token in its own `githubToken` field on stdin: ```json { "requests": [ { "id": "https://api.github.com/repos/acme/lib/license", "url": "https://api.github.com/repos/acme/lib/license", "authRealm": "github-auth:https://api.github.com/repos/acme/lib", "githubToken": "" } ] } ``` cdxrs sends the token as `Authorization: Bearer` with that request alone, and only when the URL is https on the default port to `github.com` or `api.github.com`. It never writes the token to its cache or its logs, never coalesces a token-bearing request with an anonymous one, and gives `api.github.com` its authenticated budget for that run. The envelope is never spilled to a temporary file while it carries a token: a payload over the stdin limit falls back to the JS pool instead. When GitHub answers 403 or 429 with no requests remaining, the result carries `quotaExhausted: true` and, when GitHub said, `retryAfterSecs`, and cdxgen pauses the GitHub API exactly as it does for the pool. With an older cdxrs, which lists no capabilities, every GitHub request stays on the JS pool. cdxrs from cdxgen-plugins-bin 4.3.x reads no credential at all, and older helpers attached `GITHUB_TOKEN` to `github.com` and `api.github.com` by host name, which removing the variable from the child's environment keeps from happening in a cdxgen run. ### Chunking Both transports attach the ambient token after the caller has built its request, and only to a request that sets `ambientGitHubAuth`. `prefetchJson` adds a digest of the token to the `authRealm` of such a request. The realm is part of the cache key on both sides: an answer obtained with a token is served only to a run holding the same token, and an anonymous answer only to an anonymous run. A batch routed to `cdxrs fetch` is sent in runs of at most 250 URLs, one run at a time so each host still sees a single rate gate. The envelope has to become one JavaScript string, and a large pnpm workspace fetching full npm packuments in a single run produced more than V8's string limit allows (issue 4393). If a run still fails with `stdout-too-large`, the bridge splits it in half and retries, which is cheap because the first attempt filled the disk cache below; only a single URL that is too large on its own goes to the JS pool. A run that fails for any other reason falls back to the JS pool without affecting the other runs. `lastBatchStats()` reports the whole batch: counts and elapsed time add up across runs, and peak concurrency is the widest run. ### Failed results A result that is not `ok` carries the HTTP `status` when the server answered. A 4xx other than 429 is final, and the caller sees it as the same error `cdxgenAgent.get` would throw. A 5xx or 429 has already been retried inside cdxrs and is passed on as an error too. A result with no status, such as a timeout or a connection reset, is worth one more try, so `prefetchedResponse()` returns nothing and the caller fetches the URL itself through `cdxgenAgent`. cdxrs from cdxgen-plugins-bin 4.4.0 also refuses a body for its size: one past the per-body cap, one whose gzip expansion passes 100 times the bytes received, and any that would take the run past its `--max-total-bytes` budget (512 MiB by default). Such a result has no status and carries `refused: true`: ```json { "id": "https://registry.npmjs.org/huge", "ok": false, "error": "batch decoded-body budget exhausted", "refused": true, "fromCache": false } ``` The JS agent would only fetch the same body again, with its own per-body cap and ratio check but no budget across the batch, so cdxgen treats a refused result as definite and never retries it. `prefetchedResponse()` throws an error with code `ERR_RESPONSE_BODY_TOO_LARGE`, the code `cdxgenAgent` gives an oversized body, and the caller's existing `catch` handles it. A refusal is not remembered as a missing document, so a later batch in the same run asks cdxrs again. Older cdxrs builds never send the field, and their status-less failures are retried as before. ## Metadata cache `cdxrs fetch` writes an on-disk conditional cache under `/cdxrs-fetch//.json`. The cache is bounded by both a TTL (default 24h, opportunistic sweep per host directory) and an LRU byte ceiling (default 256 MB). Enforcing the ceiling means walking the whole cache, so it is not done on every write: a run may add an eighth of the ceiling (at least 8 MB) before a pass is due. A cache can therefore sit that much over the ceiling between passes. A run counts only what it wrote itself, so runs that each add less than that would never make a pass, whatever earlier runs left behind. cdxgen therefore keeps a count of its own, of what its `cdxrs fetch` runs and its JS pool add, and makes the pass itself: at the first write of every cdxgen process, and again whenever an eighth of the ceiling has been added since. A cache left oversized by an earlier process is reclaimed by the next one that writes to it, or immediately by `cdxgen cache clear`. Entries are not fsynced. Every byte in the cache is re-derivable from the network and atomicity comes from `rename`, so a torn entry left by a crash is simply discarded on read and refetched. Inspect or purge the cache: ```bash cdxgen cache info # resolved directory, entry count, total bytes, per-host breakdown cdxgen cache clear # purge all entries ``` The cache directory is resolved by JS and passed to Rust via `--cache-dir` on every invocation, so both sides agree on the location. When `CDXGEN_CACHE_DIR` is unset, the platform cache directory is used. If no home directory can be resolved, the cache is disabled — it never falls back to the working directory. ## JS bridge API ```js import { cdxrsAvailable, cdxrsCapabilities, runCdxrs, cdxrsDisabled, CDXRS_FALLBACK, } from "./cdxrs.js"; // Check if the binary is present and version-compatible const { available, version, reason } = cdxrsAvailable("info"); // Optional behaviours the binary lists in `cdxrs schema-version` const takesToken = cdxrsCapabilities("fetch").has("fetch-github-token"); // Run a subcommand (async). Normal case: pass in-memory BOM data as `content`, // which is written to the child's stdin with `--input -`. const result = await runCdxrs("info", { content: bomJsonString, // fed over stdin args: [], // extra CLI args timeoutMs: 30_000, // default 30s secretContent: false, // true: never spill the content to a temp file }); // Alternative, when the BOM is already a file on disk: const result2 = await runCdxrs("info", { input: "/path/to/bom.json" }); // result: { ok: true, stdout, stderr, exitCode } on success // result: { ok: false, reason, stdout: "", exitCode: null } on failure // Check if a subcommand is disabled if (cdxrsDisabled("info")) { /* take JS path */ } ``` ### Failure modes (all non-fatal) Every failure mode logs once at `warn` and returns the `CDXRS_FALLBACK` sentinel (`{ ok: false, reason: "..." }`). The caller takes the JS path. | Failure | `reason` field | | ---------------------- | ----------------------- | | Binary not found | `binary-not-found` | | Non-zero exit | `non-zero-exit:` | | Timeout | `timeout` | | Oversized stdout | `stdout-too-large` | | Malformed stdout | `malformed-stdout` | | Stdout not collectable | `stdout-collect-failed` | | Version-major mismatch | `version-mismatch` | | CDXGEN_RS_DISABLE | `disabled` | | Spawn error | `spawn-error` | | Unknown subcommand | `unknown-subcommand` | | Secret input too large | `stdin-too-large` | The bridge kills the **process group** on timeout (`process.kill(-pid, "SIGKILL")`) so a hung child cannot outlive the parent. It also kills the group once collected stdout passes `CDXGEN_RS_MAX_STDOUT_BYTES` (default: V8's maximum string length, 0x1fffffe8): stdout must become a single JS string, so an oversized payload can never be delivered, and waiting for the child to finish would only end in `ERR_STRING_TOO_LONG` crashing the process (issue 4393). For `fetch`, the caller answers `stdout-too-large` by splitting the run (see [Batch transport selection](#batch-transport-selection)). ## BOM model and round-trip fidelity ### Model decision: hand-written The CycloneDX serde model in `src/bom/model.rs` is hand-written, not generated. typify was evaluated but rejected because: 1. The official JSON schemas declare `additionalProperties: false`, conflicting with the mandatory unknown-field-preservation requirement. 2. The 91 interlinked definitions with complex oneOf/anyOf produce unwieldy enums. 3. Every generated struct would need manual `#[serde(flatten)]` additions. ### Unknown-field preservation Every object that can carry vendor extensions has: ```rust #[serde(flatten)] pub extra: BTreeMap, ``` ### Round-trip strategy The I/O path (`bom::read`/`bom::write`) uses `serde_json::Value` rather than the typed structs, because `Value` cannot drop a field it has no struct member for. Output is 2-space indented with a trailing newline, matching `JSON.stringify(bom, null, 2) + "\n"`. `serde_json` **must** be built with the `preserve_order` feature: ```toml serde_json = { version = "1", features = ["preserve_order"] } ``` ### Field-order fidelity This is the subtlest requirement in the crate, so it is worth stating plainly. `preserve_order` backs `Value`'s maps with `IndexMap`, so keys are written in the order they were read. Without it, `Value` uses a `BTreeMap` and writes every object's keys **alphabetically**. That difference is invisible if you only test against golden files: cdxgen's normalizer (`contrib/sbom-normalize.js`) already sorts keys recursively, so a `BTreeMap` round-trips them unchanged. But real cdxgen output is insertion-ordered — `bomFormat, specVersion, serialNumber, version, metadata, components, dependencies` at the root, and similarly nested — so a `BTreeMap` backend silently reorders every object in any live BOM. The regression guard is `thirdparty/cdxrs/testdata/real-unsorted-npm.json`, a genuine unnormalized cdxgen BOM, together with two tests in `tests/roundtrip.rs`: `test_roundtrip_preserves_non_alphabetical_field_order` and `test_unsorted_fixture_is_actually_unsorted` (the latter fails if the fixture is ever normalized, which would quietly retire the former). **When vendoring new fixtures, do not normalize them.** A corpus of exclusively normalized goldens cannot detect a field-order regression. ## Build and release ### Release profile ```toml [profile.release] opt-level = "z" lto = "fat" codegen-units = 1 panic = "abort" strip = true ``` ### Cross-build The Makefile mirrors `thirdparty/cdxui/Makefile`: - `make darwin` — darwin-amd64, darwin-arm64 (native macOS) - `make linux` — 5 Linux GNU targets (requires Linux host + cargo-zigbuild) - `make linuxmusl` — 2 musl targets - `make windows` — 2 Windows GNU targets - `make all` — all targets for the current host OS + SBOM generation Each binary gets a `.sha256` sidecar. ### Size budget `scripts/check-package-size.sh` enforces 250 MB packed per platform package. cdxrs release binaries are ~440 KB (unstripped ~480 KB), well within budget. ## Testing | Test | What it verifies | | ---------------------------------------- | -------------------------------------------------------------- | | `cargo test` (9 tests) | `info`, round-trip incl. unsorted BOM, typed-model, fuzz guard | | `cargo clippy -- -D warnings` | No lint warnings | | `cargo fmt --check` | Code formatting | | `lib/inventory/cdxrs.poku.js` (11 tests) | Six bridge failure modes + success + cdxrsDisabled + sentinel | | `contrib/rs-disable-golden-test.js` | Default and `CDXGEN_RS_DISABLE=all` runs are byte-identical | ### CI integration Runs as a separate CI job: ```bash pnpm run test:rs-disable ``` This is a **permanent safety net** that must stay green for the entire v13 cycle. If it fails, a Rust path is changing output — fix the Rust path, do not weaken the test. Two properties of this job are load-bearing, and both are easy to lose in a well-meant simplification: 1. **It runs every scenario twice** — once with Rust enabled, once with `CDXGEN_RS_DISABLE=all` — and compares the two runs _against each other_. Running the golden corpus with `CDXGEN_RS_DISABLE=all` and checking it still matches the committed goldens is **not** equivalent and cannot detect a Rust path that ignores the flag, because that is exactly the run in which the Rust path is switched off. 2. **It compares serialized bytes, not `diffBoms`.** `contrib/sbom-diff.js` compares components, dependencies and `metadata.component` only; it returns `isEqual: true` for BOMs that differ in other top-level fields, `specVersion` included. Correct for its own purpose, far too loose for this one.