diff --git a/CMakeLists.txt b/CMakeLists.txt index 478fce9..947c063 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -68,6 +68,7 @@ add_library(VoidBuild_Core STATIC src/Package/RegistryClient.cpp src/Package/Resolver.cpp src/Package/Manifest.cpp + src/Package/Audit.cpp src/Sandbox/Linux/NamespaceSandbox.cpp src/Provider/PkgConfig.cpp src/Provider/Provider.cpp @@ -78,6 +79,7 @@ add_library(VoidBuild_Core STATIC src/SelfHost/TestRegistryGen.cpp src/Provenance/Sbom.cpp src/Provenance/Signing.cpp + src/Provenance/Attestation.cpp src/Provenance/Verification.cpp src/Provenance/TrustedKeys.cpp recipes/VoidLibrary/VoidLibraryRecipe.cpp diff --git a/docs/agent-workflow/STATE.md b/docs/agent-workflow/STATE.md index a2a4da2..0488b60 100644 --- a/docs/agent-workflow/STATE.md +++ b/docs/agent-workflow/STATE.md @@ -401,6 +401,8 @@ Stage: VERIFIED — Plans 01–19 + Plan 20 Slices 1–2C + Track A + Track B (B ## Remaining future scope +- **Wave 149 (Trust layer, G5 start)**: `vbs attest create|verify` produces and verifies DSSE-wrapped in-toto Statement v1 / SLSA provenance v1 attestations (subjects, build definition with project/profile/targets/lock revision, internal parameters, run details) signed with the existing Ed25519 primitives; verification requires a trusted key, checks the DSSE PAE signature and requires every supplied artifact digest to be covered. `vbs audit --advisories OSV.json` matches OSV records (introduced/fixed/last_affected/limit ranges and exact versions) against `vbs.lock` packages with a severity threshold and JSON output; `vbs doctor` reports the signing backend. Unsignable hosts fail closed. Verified by `FullV1Tests.attest_create_and_verify_detects_tampering` (valid, wrong artifact, tampered payload, untrusted key, missing keys) and `FullV1Tests.audit_matches_osv_advisories_against_lock` (affected/fixed versions, severity thresholds, JSON). + - **Wave 148 (Hermetic sandboxing, F1)**: `Sandbox::sandbox_supported()` probes unprivileged user namespaces; `vbs build|test|run --sandbox=off|warn|strict` (or `VBS_SANDBOX`) wraps every action in the hidden `vbs __sandbox-exec` mode, which unshares user/mount/network namespaces, maps the caller to root, binds the project read-only, the build root (snapshots included) read-write, and `/usr`, `/lib`, `/bin`, `/etc` and the Nix store read-only before `pivot_root` and exec. `/proc`, `/sys` and `/dev` are bound read-write (their mounts cannot be remounted read-only from a user namespace), `/tmp` is an empty directory, and system read-only remounts that the kernel refuses degrade to writable binds (the project itself is required to be read-only). `vbs doctor` reports availability, CI runs a strict smoke build when the runner allows user namespaces, and `FullV1Tests.sandbox_strict_allows_project_builds_and_hides_outside_files` proves a strict build succeeds while an action that reads an outside file fails. - **Wave 147 (Lifecycle CLI and native compiler caching, G1/G7 start)**: diff --git a/docs/agent-workflow/TASKS.md b/docs/agent-workflow/TASKS.md index 7992349..c1adff5 100644 --- a/docs/agent-workflow/TASKS.md +++ b/docs/agent-workflow/TASKS.md @@ -148,4 +148,5 @@ Base HEAD: `fe0d1a6` | Wave 146 (CI hardening, explainability, shared caches, CLI surface, migration breadth) | CI image tool upgrades + coverage lane; test `--repeat/--retry/--shuffle/--stop-on-failure`; `vbs explain`; `--trace` Chrome traces; shared descriptor/probe caches; `vbs completions`/`vbs man`; `vbs migrate --from meson`; `vbs init --template`; `vbs presets --export`; MSI installer | COMPLETE & VERIFIED (GCC 16.2; new FullV1Tests cases for every feature pass, CLI contract suite passes; cold build 3897 -> 755 ms measured) | `src/Main.cpp`, `src/Execution/Scheduler.{hpp,cpp}`, `src/Cli/CommandModel.{hpp,cpp}`, `src/Config/{Frontend,Scaffold,CmakeImport}.cpp`, `src/Toolchain/Driver.cpp`, `include/Void/Build/Util/UserCache.hpp`, `.gitea/workflows/ci.yml`, [Void/CI-Images](https://git.faumaray.com/Void/CI-Images), `tests/{FullV1Tests,CliContracts}`, docs | | Wave 147 (Lifecycle CLI + native caching + BEP) | `vbs run` (Void::Process inherited stdio, exit-code passthrough, Wine), `vbs metadata` (StrictJson schema v1), `vbs why`, `vbs tree`, `vbs fmt`/`vbs lint`, `vbs install-binary`, `vbs add`/`vbs remove` (Semver-validated manifest editing + lock refresh), `vbs new`, `--frozen`, `--bep` event stream, `--native-cache off/auto/ccache/sccache` with doctor reporting | COMPLETE & VERIFIED for the implemented commands (GCC 16.2; lifecycle, tree, fmt, BEP and native-cache tests pass; CLI contracts pass) | `src/Main.cpp`, `src/Toolchain/Driver.{hpp,cpp}`, `src/Package/Manifest.{hpp,cpp}`, `include/Void/Build/Package/Manifest.hpp`, `tests/{FullV1Tests,CliContracts}`, docs | | Wave 148 (Hermetic sandboxing) | `Sandbox::sandbox_supported`, `Sandbox::apply_sandbox`, hidden `vbs __sandbox-exec` wrapper, `--sandbox=off|warn|strict`/`VBS_SANDBOX`, project read-only + build root writable + system/toolchain roots read-only, doctor reporting, CI strict smoke step | COMPLETE & VERIFIED (GCC 16.2; `sandbox_strict_allows_project_builds_and_hides_outside_files` passes: strict build succeeds and an action reading an outside file fails; CLI contracts pass) | `include/Void/Build/Sandbox/Sandbox.hpp`, `src/Sandbox/Linux/NamespaceSandbox.cpp`, `include/Void/Build/Execution/Scheduler.hpp`, `src/Execution/Scheduler.cpp`, `src/Main.cpp`, `.gitea/workflows/ci.yml`, `tests/{FullV1Tests,CliContracts}`, docs | +| Wave 149 (Trust layer) | `vbs attest create\|verify` (DSSE + in-toto Statement v1 + SLSA provenance v1, Ed25519 over the PAE, trusted-key and subject-digest enforcement), `vbs audit --advisories OSV.json` (introduced/fixed/last_affected/limit ranges, severity threshold, JSON), signing availability in `vbs doctor` | COMPLETE & VERIFIED (GCC 16.2; `attest_create_and_verify_detects_tampering` and `audit_matches_osv_advisories_against_lock` pass; CLI contracts pass) | `include/Void/Build/Provenance/Attestation.hpp`, `src/Provenance/Attestation.cpp`, `include/Void/Build/Package/Audit.hpp`, `src/Package/Audit.cpp`, `src/Main.cpp`, `tests/{FullV1Tests,CliContracts}`, docs | | Future (Plans 23–24) | Gap closure and superiority tracks | PLANNED (see the plans for per-track acceptance gates) | [23-remaining-upgrade-plan.md](../roadmap/23-remaining-upgrade-plan.md), [24-superiority-tracks.md](../roadmap/24-superiority-tracks.md) | diff --git a/docs/roadmap/24-superiority-tracks.md b/docs/roadmap/24-superiority-tracks.md index 206e46e..ca86749 100644 --- a/docs/roadmap/24-superiority-tracks.md +++ b/docs/roadmap/24-superiority-tracks.md @@ -110,8 +110,8 @@ the concrete acceptance gate. ### G1 — Cargo-grade lifecycle CLI *(S–M per command)* **Status: partially implemented (Wave 147).** Done: `new`, `run`, `metadata`, `why`, `add`, -`remove`, `tree`, `fmt`, `lint`, `install-binary`, `--frozen`. Pending: `bench`, `doc`, -`outdated`, `update -p`, `audit`, `deny`, `vendor`. +`remove`, `tree`, `fmt`, `lint`, `audit`, `install-binary`, `--frozen`. Pending: `bench`, `doc`, +`outdated`, `update -p`, `deny`, `vendor`. **Beats:** Cargo (parity), CMake/Meson/build2 (they have no unified lifecycle). @@ -265,9 +265,11 @@ Fortran are cheap to add to images); each language's incremental model differs. ### G5 — Trust: enforced hermeticity, attestations, reproducibility, advisories *(L)* -**Status: partially implemented (Wave 148).** Done: the enforced hermetic sandbox (Plan 23 F1) -for compile/link/custom actions. Pending: SLSA/in-toto attestations, the sandboxed descriptor, -`vbs audit` advisories, dependency-confusion guards, policy-as-code (G11) and `verify-repro`. +**Status: partially implemented (Wave 149).** Done: the enforced hermetic sandbox (Plan 23 F1) +for compile/link/custom actions, DSSE/in-toto/SLSA attestations (`vbs attest create|verify`, +trusted-key and subject-digest enforcement), and `vbs audit` over OSV advisories against the +lockfile. Pending: sandboxing the build descriptor itself, dependency-confusion guards, +policy-as-code (G11) and `vbs verify-repro`. **Beats:** all four. Cargo has `cargo-deny` externally; CMake/Meson/build2 have nothing built in. diff --git a/include/Void/Build/Package/Audit.hpp b/include/Void/Build/Package/Audit.hpp new file mode 100644 index 0000000..4a73e7f --- /dev/null +++ b/include/Void/Build/Package/Audit.hpp @@ -0,0 +1,32 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include + +namespace Void::Build::Package { + +struct AuditFinding { + std::string package; + std::string version; + std::string advisory_id; + std::string severity; // "critical", "high", "medium", "low", "unknown" + std::string summary; +}; + +// Matches OSV-format advisories (a JSON array, or an object with a "vulnerabilities" array) +// against every package entry in the lockfile. Versions that are not strict SemVer (git +// revisions, empty path-dependency versions) are skipped. +[[nodiscard]] Void::Result::Result, Void::Result::Error> +match_advisories(const LockfileDocument &lock, std::string_view osv_json); + +// Severity ordering used by `vbs audit --severity-threshold`. +[[nodiscard]] int severity_rank(std::string_view severity) noexcept; +[[nodiscard]] bool severity_at_least(std::string_view severity, std::string_view threshold) noexcept; +[[nodiscard]] bool valid_severity_threshold(std::string_view threshold) noexcept; + +} // namespace Void::Build::Package diff --git a/include/Void/Build/Provenance/Attestation.hpp b/include/Void/Build/Provenance/Attestation.hpp new file mode 100644 index 0000000..8f57151 --- /dev/null +++ b/include/Void/Build/Provenance/Attestation.hpp @@ -0,0 +1,65 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include + +namespace Void::Build::Provenance { + +// One subject of an in-toto statement (an artifact and its SHA-256 digest). +struct AttestationSubject { + std::string name; + std::string sha256; +}; + +// Build facts embedded in the SLSA provenance predicate. +struct AttestationBuild { + std::string project_root; + std::string profile; + std::string compiler; + std::vector targets; + std::string lock_revision; // vbs.lock revision hash, empty when absent + std::string vbs_version; + std::string host_os; + std::string host_architecture; + std::int64_t created_epoch{0}; +}; + +struct SignedAttestation { + std::string statement; // canonical in-toto statement JSON + std::string public_key; // Ed25519 public key (hex) + std::string signature; // Ed25519 signature over the DSSE PAE (hex) + std::string envelope; // DSSE envelope JSON +}; + +struct VerifiedAttestation { + std::string statement; + std::string public_key; + std::vector subjects; +}; + +// Renders the canonical in-toto Statement v1 / SLSA provenance v1 JSON. +[[nodiscard]] Void::Result::Result +render_statement(const AttestationBuild &build, const std::vector &subjects); + +// Signs a statement in a DSSE envelope. Fails closed when no Ed25519 backend is available. +[[nodiscard]] Void::Result::Result +sign_statement(std::string_view statement, const std::filesystem::path &seed_path); + +// Verifies a DSSE envelope against trusted Ed25519 keys and, when `expected_subjects` is +// non-empty, requires every expected artifact digest to appear in the statement. +// Unsigned, untrusted, malformed or mismatched attestations fail explicitly. +[[nodiscard]] Void::Result::Result +verify_envelope(std::string_view envelope_json, + const std::vector &expected_subjects, + const std::vector &trusted_public_keys); + +// DSSE pre-authentication encoding (exposed for tests). +[[nodiscard]] std::string dsse_pae(std::string_view payload_type, std::string_view payload); + +} // namespace Void::Build::Provenance diff --git a/src/Main.cpp b/src/Main.cpp index 0060dbd..4973686 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -23,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -4859,6 +4861,223 @@ int execute_install_binary_command(const InstallBinaryCmdOptions &opts) { return 0; } +struct AttestCmdOptions { + std::string project_arg{"."}; + std::string profile_name{"debug"}; + std::optional compiler_arg; + std::vector artifacts; + std::vector targets; + std::optional output_arg; + std::optional seed_arg; + std::optional attestation_arg; + std::optional epoch_arg; + std::vector trusted_public_keys; + std::vector trusted_key_files; +}; + +int execute_attest_command(std::string_view sub, const AttestCmdOptions &opts) { + if (sub == "create") { + if (opts.artifacts.empty() || !opts.output_arg || !opts.seed_arg) { + std::cerr << "vbs attest create: --artifact, --output and --signing-key are " + "required\n"; + return 2; + } + std::int64_t epoch = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()) + .count(); + if (opts.epoch_arg) { + int parsed = 0; + if (!Void::Str::to_int(*opts.epoch_arg, parsed) || parsed < 0) { + std::cerr << "vbs attest create: invalid --epoch value '" << *opts.epoch_arg + << "'\n"; + return 2; + } + epoch = parsed; + } + std::vector subjects; + for (const auto &artifact : opts.artifacts) { + const std::filesystem::path path{artifact}; + std::error_code ec; + if (!std::filesystem::is_regular_file(path, ec)) { + std::cerr << "vbs attest create: artifact '" << artifact << "' does not exist\n"; + return 1; + } + auto digest = Util::sha256_file_hex(path); + if (!digest) { + std::cerr << "vbs attest create: cannot hash '" << artifact + << "': " << digest.error().message() << '\n'; + return 1; + } + subjects.push_back({path.filename().string(), *digest}); + } + const std::filesystem::path project_root{opts.project_arg}; + Provenance::AttestationBuild build; + build.project_root = std::filesystem::absolute(project_root).string(); + build.profile = opts.profile_name; + build.compiler = opts.compiler_arg.value_or(""); + build.targets = opts.targets; + build.vbs_version = std::string{Bootstrap::version}; + build.host_os = Toolchain::host_os_name(); + build.host_architecture = Toolchain::host_architecture_name(); + build.created_epoch = epoch; + auto pinned = Package::load_pinned_lock(project_root / "vbs.lock"); + if (pinned && pinned->has_value()) { + build.lock_revision = (*pinned)->revision_hash; + } + auto statement = Provenance::render_statement(build, subjects); + if (!statement) { + std::cerr << statement.error().message() << '\n'; + return 1; + } + auto signed_attestation = Provenance::sign_statement(*statement, *opts.seed_arg); + if (!signed_attestation) { + std::cerr << signed_attestation.error().message() << '\n'; + return 1; + } + if (auto written = + Platform::atomic_write_file(*opts.output_arg, signed_attestation->envelope, false); + !written) { + std::cerr << "vbs attest create: cannot write '" << *opts.output_arg + << "': " << written.error().message() << '\n'; + return 1; + } + std::cout << "attested " << subjects.size() << " artifact(s) -> " << *opts.output_arg + << " (key " << signed_attestation->public_key << ")\n"; + return 0; + } + if (sub == "verify") { + if (!opts.attestation_arg) { + std::cerr << "vbs attest verify: --attestation is required\n"; + return 2; + } + auto trusted = combine_trusted_keys(opts.trusted_public_keys, opts.trusted_key_files, + std::filesystem::current_path()); + if (!trusted) { + std::cerr << "vbs attest verify: " << trusted.error().message() << '\n'; + return 1; + } + if (trusted->empty()) { + std::cerr << "vbs attest verify: --trusted-public-key or --trusted-key-file is " + "required\n"; + return 2; + } + std::vector expected; + for (const auto &artifact : opts.artifacts) { + const std::filesystem::path path{artifact}; + std::error_code ec; + if (!std::filesystem::is_regular_file(path, ec)) { + std::cerr << "vbs attest verify: artifact '" << artifact << "' does not exist\n"; + return 1; + } + auto digest = Util::sha256_file_hex(path); + if (!digest) { + std::cerr << "vbs attest verify: cannot hash '" << artifact << "'\n"; + return 1; + } + expected.push_back({path.filename().string(), *digest}); + } + auto envelope = Void::FileSystem::read_file(*opts.attestation_arg); + if (!envelope) { + std::cerr << "vbs attest verify: cannot read '" << *opts.attestation_arg + << "': " << envelope.error().message() << '\n'; + return 1; + } + auto verified = Provenance::verify_envelope(*envelope, expected, *trusted); + if (!verified) { + std::cerr << verified.error().message() << '\n'; + return 1; + } + std::cout << "verified " << verified->subjects.size() << " subject(s) signed by " + << verified->public_key << '\n'; + return 0; + } + std::cerr << "vbs attest: unknown subcommand '" << sub << "' (expected create or verify)\n"; + return 2; +} + +struct AuditCmdOptions { + std::string project_arg{"."}; + std::optional lock_arg; + std::optional advisories_arg; + std::string severity_threshold{"low"}; + bool json{false}; +}; + +int execute_audit_command(const AuditCmdOptions &opts) { + if (!opts.advisories_arg) { + std::cerr << "vbs audit: --advisories FILE is required\n"; + return 2; + } + if (!Package::valid_severity_threshold(opts.severity_threshold)) { + std::cerr << "vbs audit: invalid --severity-threshold '" << opts.severity_threshold + << "' (expected any, low, medium, high or critical)\n"; + return 2; + } + const std::filesystem::path project_root{opts.project_arg}; + const auto lock_path = opts.lock_arg ? std::filesystem::path{*opts.lock_arg} + : (project_root / "vbs.lock"); + auto pinned = Package::load_pinned_lock(lock_path); + if (!pinned) { + std::cerr << "vbs audit: " << pinned.error().message() << '\n'; + return 1; + } + if (!pinned->has_value()) { + std::cerr << "vbs audit: '" << lock_path.string() << "' does not exist\n"; + return 1; + } + auto advisories = Void::FileSystem::read_file(*opts.advisories_arg); + if (!advisories) { + std::cerr << "vbs audit: cannot read '" << *opts.advisories_arg + << "': " << advisories.error().message() << '\n'; + return 1; + } + auto matched = Package::match_advisories((*pinned)->document, *advisories); + if (!matched) { + std::cerr << matched.error().message() << '\n'; + return 1; + } + std::vector findings; + for (auto &finding : *matched) { + if (Package::severity_at_least(finding.severity, opts.severity_threshold)) { + findings.push_back(std::move(finding)); + } + } + if (opts.json) { + using JsonValue = Void::Json::Strict::Value; + using JsonObject = JsonValue::Object; + using JsonArray = JsonValue::Array; + JsonArray array; + for (const auto &finding : findings) { + JsonObject entry; + entry["package"] = JsonValue{finding.package}; + entry["version"] = JsonValue{finding.version}; + entry["id"] = JsonValue{finding.advisory_id}; + entry["severity"] = JsonValue{finding.severity}; + entry["summary"] = JsonValue{finding.summary}; + array.push_back(JsonValue{std::move(entry)}); + } + JsonObject root; + root["findings"] = JsonValue{std::move(array)}; + root["count"] = JsonValue{static_cast(findings.size())}; + JsonValue document; + document.value = std::move(root); + if (auto serialized = Void::Json::Strict::serialize(document); serialized) { + std::cout << *serialized << '\n'; + } + } else { + for (const auto &finding : findings) { + std::cout << finding.package << ' ' << finding.version << ": " + << finding.advisory_id << " [" << finding.severity << "]"; + if (!finding.summary.empty()) { + std::cout << ' ' << finding.summary; + } + std::cout << '\n'; + } + std::cout << findings.size() << " finding(s)\n"; + } + return findings.empty() ? 0 : 1; +} + struct InitCmdOptions { std::string dir_arg; std::optional name_arg; @@ -4971,6 +5190,12 @@ int execute_doctor_command() { << '\n'; std::cout << " [ok] Void::Crypto built-in SHA-256: enabled\n"; + std::cout << " " << (Provenance::signing_available() ? "[ok] " : "[opt] ") + << " Ed25519 signing/attestations: " + << (Provenance::signing_available() + ? "available (vbs attest, package and installer signing)" + : "unavailable (the Ed25519 backend is not linked)") + << '\n'; std::cout << " [ok] Void::Archive built-in USTAR/PAX: enabled\n"; if (has_gcc) { @@ -5492,6 +5717,8 @@ int main(int argc, char **argv) { TreeCmdOptions tree_opts; tree_opts.project_arg = cwd; InstallBinaryCmdOptions install_binary_opts; + AttestCmdOptions attest_opts; + AuditCmdOptions audit_opts; CompletionsCmdOptions completions_opts; ManCmdOptions man_opts; IdeCmdOptions ide_opts; @@ -6080,6 +6307,46 @@ int main(int argc, char **argv) { .positional("name", "Package name", install_binary_opts.name_arg); add_log_flags(install_binary_cmd); + auto &attest_cmd = + root.subcommand("attest", "Create or verify in-toto/SLSA provenance attestations"); + auto &attest_create = attest_cmd.subcommand("create", "Create a signed provenance attestation"); + attest_create + .option_default("--project", "-C", "Project directory", attest_opts.project_arg, ".") + .option_default("--profile", "-p", "Profile name", attest_opts.profile_name, "debug") + .option("--compiler", "", "Compiler identity recorded in the statement", + attest_opts.compiler_arg) + .option_many("--artifact", "", "Artifact to attest (repeatable)", attest_opts.artifacts) + .option_many("--target", "", "Target recorded in the statement (repeatable)", + attest_opts.targets) + .option("--output", "-o", "DSSE envelope output file", attest_opts.output_arg) + .option("--signing-key", "", "Ed25519 seed file", attest_opts.seed_arg) + .option("--epoch", "", "Fixed timestamp (deterministic tests)", attest_opts.epoch_arg); + add_log_flags(attest_create); + auto &attest_verify = + attest_cmd.subcommand("verify", "Verify a signed provenance attestation"); + attest_verify + .option("--attestation", "-a", "DSSE envelope file", attest_opts.attestation_arg) + .option_many("--artifact", "", + "Artifact whose digest must be covered (repeatable)", attest_opts.artifacts) + .option_many("--trusted-public-key", "", "Trusted Ed25519 public key (repeatable)", + attest_opts.trusted_public_keys) + .option_many("--trusted-key-file", "", "Trusted key file (repeatable)", + attest_opts.trusted_key_files); + add_log_flags(attest_verify); + + auto &audit_cmd = root.subcommand("audit", "Match OSV advisories against vbs.lock packages"); + audit_cmd + .option_default("--project", "-C", "Project directory", audit_opts.project_arg, ".") + .option("--lock", "", "Lockfile path (default: /vbs.lock)", + audit_opts.lock_arg) + .option("--advisories", "", "OSV JSON file (array or 'vulnerabilities' object)", + audit_opts.advisories_arg) + .option_default("--severity-threshold", "", + "Minimum severity: any, low, medium, high or critical", + audit_opts.severity_threshold, "low") + .flag("--json", "", "Emit JSON findings", audit_opts.json); + add_log_flags(audit_cmd); + auto &ide_cmd = root.subcommand("ide", "Generate editor/IDE configs and query workspace metadata"); auto configure_ide_common = [&](Void::Argparse::Parser &p) { @@ -6478,6 +6745,12 @@ int main(int argc, char **argv) { if (cmd == "install-binary") { return execute_install_binary_command(install_binary_opts); } + if (cmd == "attest") { + return execute_attest_command(parsed.matched_command_path.at(1), attest_opts); + } + if (cmd == "audit") { + return execute_audit_command(audit_opts); + } if (cmd == "ide") { return execute_ide_command(parsed.matched_command_path.at(1), ide_opts); } diff --git a/src/Package/Audit.cpp b/src/Package/Audit.cpp new file mode 100644 index 0000000..bd16c23 --- /dev/null +++ b/src/Package/Audit.cpp @@ -0,0 +1,267 @@ +#include + +#include +#include +#include +#include + +#include +#include +#include + +namespace Void::Build::Package { +namespace { + +using JsonValue = Void::Json::Strict::Value; +using JsonObject = JsonValue::Object; +using JsonArray = JsonValue::Array; + +std::string get_string(const JsonObject &object, std::string_view key) { + const auto it = object.find(std::string{key}); + if (it == object.end()) { + return {}; + } + const auto *value = std::get_if(&it->second.value); + return value ? *value : std::string{}; +} + +const JsonArray *get_array(const JsonObject &object, std::string_view key) { + const auto it = object.find(std::string{key}); + return it == object.end() ? nullptr : std::get_if(&it->second.value); +} + +const JsonObject *get_object(const JsonObject &object, std::string_view key) { + const auto it = object.find(std::string{key}); + return it == object.end() ? nullptr : std::get_if(&it->second.value); +} + +std::optional parse_version(std::string_view text) { + return Void::Semver::parse_strict(text); +} + +bool version_in_range(const Void::Semver::Version &version, const JsonObject &range) { + const auto *events = get_array(range, "events"); + if (events == nullptr) { + return false; + } + bool affected = false; + for (const auto &entry : *events) { + const auto *event = std::get_if(&entry.value); + if (event == nullptr) { + continue; + } + if (const std::string introduced = get_string(*event, "introduced"); + !introduced.empty()) { + if (introduced == "0") { + affected = true; + } else if (auto bound = parse_version(introduced); bound && version >= *bound) { + affected = true; + } + } + if (const std::string fixed = get_string(*event, "fixed"); !fixed.empty()) { + if (auto bound = parse_version(fixed); bound && version >= *bound) { + affected = false; + } + } + if (const std::string limit = get_string(*event, "limit"); !limit.empty()) { + if (auto bound = parse_version(limit); bound && version >= *bound) { + affected = false; + } + } + if (const std::string last = get_string(*event, "last_affected"); !last.empty()) { + if (auto bound = parse_version(last); bound && version > *bound) { + affected = false; + } + } + } + return affected; +} + +std::string advisory_severity(const JsonObject &advisory) { + if (const auto *database = get_object(advisory, "database_specific"); database != nullptr) { + const std::string severity = get_string(*database, "severity"); + if (!severity.empty()) { + return Void::Str::to_lower(severity); + } + } + if (const auto *severities = get_array(advisory, "severity"); severities != nullptr) { + for (const auto &entry : *severities) { + const auto *object = std::get_if(&entry.value); + if (object == nullptr) { + continue; + } + const std::string score = get_string(*object, "score"); + if (!score.empty() && !Void::Str::starts_with(score, "CVSS:")) { + return Void::Str::to_lower(score); + } + } + } + return "unknown"; +} + +bool package_matches(std::string_view advisory_name, std::string_view lock_name) { + return Void::Str::to_lower(advisory_name) == Void::Str::to_lower(lock_name); +} + +bool affected_by(const JsonObject &affected, const Void::Semver::Version &version, + std::string_view package_name) { + const auto *package = get_object(affected, "package"); + if (package == nullptr || !package_matches(get_string(*package, "name"), package_name)) { + return false; + } + if (const auto *versions = get_array(affected, "versions"); versions != nullptr) { + for (const auto &entry : *versions) { + const auto *value = std::get_if(&entry.value); + if (value != nullptr && *value == version.to_string()) { + return true; + } + } + } + const auto *ranges = get_array(affected, "ranges"); + if (ranges == nullptr) { + return false; + } + for (const auto &entry : *ranges) { + const auto *range = std::get_if(&entry.value); + if (range == nullptr) { + continue; + } + // GIT ranges carry commit hashes rather than versions: not comparable. + if (get_string(*range, "type") == "GIT") { + continue; + } + if (version_in_range(version, *range)) { + return true; + } + } + return false; +} + +} // namespace + +int severity_rank(std::string_view severity) noexcept { + const std::string value = Void::Str::to_lower(severity); + if (value == "critical") { + return 4; + } + if (value == "high") { + return 3; + } + if (value == "medium" || value == "moderate") { + return 2; + } + if (value == "low") { + return 1; + } + if (value.empty() || value == "unknown" || value == "none") { + return 0; + } + return 0; +} + +bool valid_severity_threshold(std::string_view threshold) noexcept { + return threshold == "any" || threshold == "low" || threshold == "medium" || + threshold == "high" || threshold == "critical"; +} + +bool severity_at_least(std::string_view severity, std::string_view threshold) noexcept { + if (threshold == "any" || threshold == "low") { + // Unknown severities still fail the default gate: an unrated advisory is not "safe". + return true; + } + return severity_rank(severity) >= severity_rank(threshold); +} + +Void::Result::Result, Void::Result::Error> +match_advisories(const LockfileDocument &lock, std::string_view osv_json) { + auto parsed = Void::Json::Strict::parse(std::string{osv_json}); + if (!parsed) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "audit: the advisories file is not valid JSON")}; + } + const JsonArray *advisories = nullptr; + if (const auto *root_array = std::get_if(&parsed->value); root_array != nullptr) { + advisories = root_array; + } else if (const auto *root_object = std::get_if(&parsed->value); + root_object != nullptr) { + advisories = get_array(*root_object, "vulnerabilities"); + if (advisories == nullptr) { + advisories = get_array(*root_object, "advisories"); + } + } + if (advisories == nullptr) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "audit: expected an OSV array or an object with a 'vulnerabilities' array")}; + } + + std::vector findings; + std::set> seen; + for (const auto &lock_entry : lock.contexts) { + for (const auto &entry : lock_entry.second.entries) { + if (entry.package_name.empty() || entry.version.empty()) { + continue; + } + auto version = parse_version(entry.version); + if (!version) { + continue; + } + for (const auto &advisory_entry : *advisories) { + const auto *advisory = std::get_if(&advisory_entry.value); + if (advisory == nullptr) { + continue; + } + const auto *affected = get_array(*advisory, "affected"); + if (affected == nullptr) { + continue; + } + std::string id = get_string(*advisory, "id"); + if (id.empty()) { + const auto *aliases = get_array(*advisory, "aliases"); + if (aliases != nullptr && !aliases->empty()) { + if (const auto *first = std::get_if(&aliases->front().value)) { + id = *first; + } + } + } + if (id.empty()) { + id = get_string(*advisory, "summary"); + } + bool matched = false; + for (const auto &affected_entry : *affected) { + const auto *affected_object = + std::get_if(&affected_entry.value); + if (affected_object == nullptr) { + continue; + } + if (affected_by(*affected_object, *version, entry.package_name)) { + matched = true; + break; + } + } + if (!matched) { + continue; + } + const auto key = std::make_tuple(entry.package_name, entry.version, id); + if (!seen.insert(key).second) { + continue; + } + AuditFinding finding; + finding.package = entry.package_name; + finding.version = entry.version; + finding.advisory_id = id; + finding.severity = advisory_severity(*advisory); + finding.summary = get_string(*advisory, "summary"); + findings.push_back(std::move(finding)); + } + } + } + std::ranges::sort(findings, [](const AuditFinding &a, const AuditFinding &b) { + return std::tie(a.package, a.version, a.advisory_id) < + std::tie(b.package, b.version, b.advisory_id); + }); + return findings; +} + +} // namespace Void::Build::Package diff --git a/src/Provenance/Attestation.cpp b/src/Provenance/Attestation.cpp new file mode 100644 index 0000000..c1ab8e9 --- /dev/null +++ b/src/Provenance/Attestation.cpp @@ -0,0 +1,338 @@ +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace Void::Build::Provenance { +namespace { + +using JsonValue = Void::Json::Strict::Value; +using JsonObject = JsonValue::Object; +using JsonArray = JsonValue::Array; + +Void::Result::Error make_error(std::string message) { + return Void::System::make_system_error(Void::System::SystemErrorCode::invalid_argument, + std::move(message)); +} + +JsonValue text(std::string value) { + JsonValue v; + v.value = std::move(value); + return v; +} + +JsonValue number(std::int64_t value) { + JsonValue v; + v.value = value; + return v; +} + +JsonValue array(JsonArray value) { + JsonValue v; + v.value = std::move(value); + return v; +} + +JsonValue object(JsonObject value) { + JsonValue v; + v.value = std::move(value); + return v; +} + +std::string rfc3339(std::int64_t epoch) { + std::time_t seconds = static_cast(epoch); + std::tm tm{}; +#if defined(_WIN32) + ::gmtime_s(&tm, &seconds); +#else + ::gmtime_r(&seconds, &tm); +#endif + return std::format("{:04d}-{:02d}-{:02d}T{:02d}:{:02d}:{:02d}Z", tm.tm_year + 1900, + tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); +} + +std::string invitation_id(const AttestationBuild &build, + const std::vector &subjects) { + std::string material = build.project_root + "\n" + build.profile + "\n" + build.lock_revision + + "\n" + std::to_string(build.created_epoch) + "\n"; + for (const auto &subject : subjects) { + material += subject.name + ":" + subject.sha256 + "\n"; + } + return Util::sha256_hex(material); +} + +std::string serialize(const JsonObject &value) { + JsonValue root; + root.value = value; + auto text_value = Void::Json::Strict::serialize(root); + return text_value ? *text_value : std::string{}; +} + +std::string get_string(const JsonObject &object, std::string_view key) { + const auto it = object.find(std::string{key}); + if (it == object.end()) { + return {}; + } + const auto *value = std::get_if(&it->second.value); + return value ? *value : std::string{}; +} + +const JsonObject *get_object(const JsonObject &object, std::string_view key) { + const auto it = object.find(std::string{key}); + return it == object.end() ? nullptr : std::get_if(&it->second.value); +} + +const JsonArray *get_array(const JsonObject &object, std::string_view key) { + const auto it = object.find(std::string{key}); + return it == object.end() ? nullptr : std::get_if(&it->second.value); +} + +} // namespace + +std::string dsse_pae(std::string_view payload_type, std::string_view payload) { + return "DSSE-v1 " + std::string{payload_type} + " " + std::to_string(payload.size()) + " " + + std::string{payload}; +} + +Void::Result::Result +render_statement(const AttestationBuild &build, const std::vector &subjects) { + if (subjects.empty()) { + return std::unexpected{make_error("attest: at least one artifact subject is required")}; + } + for (const auto &subject : subjects) { + if (subject.sha256.size() != 64 || + !std::ranges::all_of(subject.sha256, [](char c) { + return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); + })) { + return std::unexpected{ + make_error("attest: subject '" + subject.name + "' has an invalid sha256 digest")}; + } + } + + JsonArray subject_array; + for (const auto &subject : subjects) { + JsonObject digest; + digest["sha256"] = text(subject.sha256); + JsonObject entry; + entry["name"] = text(subject.name); + entry["digest"] = object(std::move(digest)); + subject_array.push_back(object(std::move(entry))); + } + + JsonObject external; + external["project"] = text(build.project_root); + external["profile"] = text(build.profile); + external["compiler"] = text(build.compiler); + JsonArray targets; + for (const auto &target : build.targets) { + targets.push_back(text(target)); + } + external["targets"] = array(std::move(targets)); + + JsonObject internal; + internal["vbsVersion"] = text(build.vbs_version); + internal["hostOs"] = text(build.host_os); + internal["hostArchitecture"] = text(build.host_architecture); + + JsonArray resolved; + if (!build.lock_revision.empty()) { + JsonObject digest; + digest["sha256"] = text(build.lock_revision); + JsonObject entry; + entry["uri"] = text("vbs.lock"); + entry["digest"] = object(std::move(digest)); + resolved.push_back(object(std::move(entry))); + } + + JsonObject build_definition; + build_definition["buildType"] = text("https://void.build/vbs/v1"); + build_definition["externalParameters"] = object(std::move(external)); + build_definition["internalParameters"] = object(std::move(internal)); + build_definition["resolvedDependencies"] = array(std::move(resolved)); + + JsonObject builder; + builder["id"] = text("https://void.build/vbs"); + JsonObject metadata; + metadata["invocationId"] = text(invitation_id(build, subjects)); + metadata["startedOn"] = text(rfc3339(build.created_epoch)); + metadata["finishedOn"] = text(rfc3339(build.created_epoch)); + JsonObject run_details; + run_details["builder"] = object(std::move(builder)); + run_details["metadata"] = object(std::move(metadata)); + + JsonObject predicate; + predicate["buildDefinition"] = object(std::move(build_definition)); + predicate["runDetails"] = object(std::move(run_details)); + + JsonObject statement; + statement["_type"] = text("https://in-toto.io/Statement/v1"); + statement["subject"] = array(std::move(subject_array)); + statement["predicateType"] = text("https://slsa.dev/provenance/v1"); + statement["predicate"] = object(std::move(predicate)); + + auto serialized = serialize(statement); + if (serialized.empty()) { + return std::unexpected{make_error("attest: cannot serialize the statement")}; + } + return serialized; +} + +Void::Result::Result +sign_statement(std::string_view statement, const std::filesystem::path &seed_path) { + if (!signing_available()) { + return std::unexpected{make_error( + "attest: no Ed25519 signing backend is available (fail-closed)")}; + } + auto public_key = public_key_from_seed(seed_path); + if (!public_key) { + return std::unexpected{public_key.error()}; + } + const std::string pae = dsse_pae("application/vnd.in-toto+json", statement); + const auto bytes = std::as_bytes(std::span{pae.data(), pae.size()}); + auto signature = sign_message(bytes, seed_path); + if (!signature) { + return std::unexpected{signature.error()}; + } + + JsonObject signature_entry; + signature_entry["keyid"] = text(*public_key); + signature_entry["sig"] = text(*signature); + JsonArray signatures; + signatures.push_back(object(std::move(signature_entry))); + + JsonObject envelope; + envelope["payloadType"] = text("application/vnd.in-toto+json"); + envelope["payload"] = text(Void::Encoding::Base64::encode(statement)); + envelope["signatures"] = array(std::move(signatures)); + + SignedAttestation result; + result.statement = std::string{statement}; + result.public_key = *public_key; + result.signature = *signature; + result.envelope = serialize(envelope); + if (result.envelope.empty()) { + return std::unexpected{make_error("attest: cannot serialize the DSSE envelope")}; + } + return result; +} + +Void::Result::Result +verify_envelope(std::string_view envelope_json, + const std::vector &expected_subjects, + const std::vector &trusted_public_keys) { + if (trusted_public_keys.empty()) { + return std::unexpected{make_error( + "attest: at least one trusted public key is required to verify an attestation")}; + } + auto parsed = Void::Json::Strict::parse(std::string{envelope_json}); + if (!parsed) { + return std::unexpected{make_error("attest: the attestation is not valid JSON")}; + } + const auto *envelope = std::get_if(&parsed->value); + if (envelope == nullptr) { + return std::unexpected{make_error("attest: the DSSE envelope must be a JSON object")}; + } + const std::string payload_type = get_string(*envelope, "payloadType"); + if (payload_type != "application/vnd.in-toto+json") { + return std::unexpected{make_error("attest: unsupported payloadType '" + payload_type + "'")}; + } + const auto payload_b64 = get_string(*envelope, "payload"); + auto payload = Void::Encoding::Base64::decode(payload_b64); + if (!payload) { + return std::unexpected{make_error("attest: the payload is not valid base64")}; + } + const auto *signatures = get_array(*envelope, "signatures"); + if (signatures == nullptr || signatures->empty()) { + return std::unexpected{make_error("attest: the envelope has no signatures")}; + } + const std::string pae = dsse_pae(payload_type, *payload); + const auto bytes = std::as_bytes(std::span{pae.data(), pae.size()}); + + std::string verified_key; + for (const auto &entry : *signatures) { + const auto *signature_object = std::get_if(&entry.value); + if (signature_object == nullptr) { + continue; + } + const std::string keyid = get_string(*signature_object, "keyid"); + const std::string signature = get_string(*signature_object, "sig"); + if (keyid.empty() || signature.empty()) { + continue; + } + if (std::ranges::find(trusted_public_keys, keyid) == trusted_public_keys.end()) { + continue; // Signed by an untrusted key. + } + auto valid = verify_message(bytes, signature, keyid); + if (!valid) { + return std::unexpected{valid.error()}; + } + if (*valid) { + verified_key = keyid; + break; + } + } + if (verified_key.empty()) { + return std::unexpected{ + make_error("attest: no signature from a trusted key verifies this statement")}; + } + + auto statement = Void::Json::Strict::parse(*payload); + if (!statement) { + return std::unexpected{make_error("attest: the signed payload is not valid JSON")}; + } + const auto *statement_object = std::get_if(&statement->value); + if (statement_object == nullptr) { + return std::unexpected{make_error("attest: the statement must be a JSON object")}; + } + if (get_string(*statement_object, "predicateType") != "https://slsa.dev/provenance/v1") { + return std::unexpected{ + make_error("attest: the statement is not SLSA provenance v1")}; + } + + VerifiedAttestation verified; + verified.statement = *payload; + verified.public_key = verified_key; + if (const auto *subjects = get_array(*statement_object, "subject"); subjects != nullptr) { + for (const auto &entry : *subjects) { + const auto *subject = std::get_if(&entry.value); + if (subject == nullptr) { + continue; + } + const auto *digest = get_object(*subject, "digest"); + if (digest == nullptr) { + continue; + } + AttestationSubject parsed_subject; + parsed_subject.name = get_string(*subject, "name"); + parsed_subject.sha256 = get_string(*digest, "sha256"); + verified.subjects.push_back(std::move(parsed_subject)); + } + } + if (!expected_subjects.empty()) { + for (const auto &expected : expected_subjects) { + const auto match = std::ranges::find_if( + verified.subjects, [&](const AttestationSubject &subject) { + return subject.name == expected.name && subject.sha256 == expected.sha256; + }); + if (match == verified.subjects.end()) { + return std::unexpected{make_error( + std::format("attest: artifact '{}' with digest {} is not covered by the " + "attestation", + expected.name, expected.sha256))}; + } + } + } + return verified; +} + +} // namespace Void::Build::Provenance diff --git a/tests/CliContracts.cmake b/tests/CliContracts.cmake index 0224796..b1b0e6d 100644 --- a/tests/CliContracts.cmake +++ b/tests/CliContracts.cmake @@ -43,6 +43,15 @@ check_process(2 "" "invalid value 'bazel' for '--from'" migrate --from bazel) check_process(2 "" "invalid value 'bogus' for '--template'" init --template bogus) check_process(0 "--template" "" init --help) check_process(0 "--export" "" presets --help) +check_process(0 "Usage: vbs attest " "" attest --help) +check_process(0 "Usage: vbs attest create " "" attest create --help) +check_process(0 "Usage: vbs attest verify " "" attest verify --help) +check_process(0 "Usage: vbs audit " "" audit --help) +check_process(2 "" "missing subcommand" attest) +check_process(2 "" "--artifact, --output and --signing-key are required" attest create) +check_process(2 "" "--attestation is required" attest verify) +check_process(2 "" "--advisories FILE is required" audit) +check_process(2 "" "invalid --severity-threshold" audit --advisories x --severity-threshold nope) check_process(0 "Usage: vbs run " "" run --help) check_process(0 "Usage: vbs metadata " "" metadata --help) check_process(0 "Usage: vbs why " "" why --help) diff --git a/tests/FullV1Tests.cpp b/tests/FullV1Tests.cpp index 4d8ce32..af8a6db 100644 --- a/tests/FullV1Tests.cpp +++ b/tests/FullV1Tests.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -17,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -4793,3 +4795,190 @@ VOID_TEST(FullV1Tests, sandbox_strict_allows_project_builds_and_hides_outside_fi output.find("not found") != std::string::npos); } } + +// === Trust layer: signed in-toto/SLSA attestations === +VOID_TEST(FullV1Tests, attest_create_and_verify_detects_tampering) { + const auto vbs_bin = locate_vbs_binary(); + Void::Testing::expect(!vbs_bin.empty() && std::filesystem::exists(vbs_bin)); + if (vbs_bin.empty() || !std::filesystem::exists(vbs_bin)) { + return; + } + if (!Provenance::signing_available()) { + return; // No Ed25519 backend: the CLI fails closed, nothing to verify. + } + Void::FileSystem::TempDir tmp{"vbs_attest_"}; + const auto artifact = tmp / "app.tar"; + write_file(artifact, "artifact-bytes"); + const auto seed = tmp / "signing.key"; + Void::Testing::require(Provenance::generate_signing_seed(seed).has_value()); + auto public_key = Provenance::public_key_from_seed(seed); + Void::Testing::require(public_key.has_value()); + + auto run_vbs = [&](std::vector args) { + Platform::ProcessRequest req; + req.executable = vbs_bin; + req.arguments = std::move(args); + req.timeout = std::chrono::seconds{300}; + return Platform::run_supervised(req); + }; + const auto attestation = tmp / "attestation.json"; + auto created = run_vbs({"attest", "create", "--artifact", artifact.string(), "--output", + attestation.string(), "--signing-key", seed.string(), "--epoch", + "1700000000", "--profile", "release", "--target", "app"}); + Void::Testing::expect(created.has_value() && created->succeeded()); + if (created && !created->succeeded()) { + std::cerr << created->stdout_data << created->stderr_data << '\n'; + } + auto envelope_text = Void::FileSystem::read_file(attestation); + Void::Testing::require(envelope_text.has_value()); + auto envelope = Void::Json::Strict::parse(*envelope_text); + Void::Testing::require(envelope.has_value()); + const auto *envelope_object = std::get_if(&envelope->value); + Void::Testing::require(envelope_object != nullptr); + const auto *payload_type = std::get_if( + &envelope_object->at("payloadType").value); + Void::Testing::require(payload_type != nullptr); + Void::Testing::expect_eq(*payload_type, std::string{"application/vnd.in-toto+json"}); + const auto *signatures = + std::get_if(&envelope_object->at("signatures").value); + Void::Testing::require(signatures != nullptr); + Void::Testing::expect_eq(signatures->size(), std::size_t{1}); + + auto verified = run_vbs({"attest", "verify", "--attestation", attestation.string(), + "--artifact", artifact.string(), "--trusted-public-key", + *public_key}); + Void::Testing::expect(verified.has_value() && verified->succeeded()); + if (verified && !verified->succeeded()) { + std::cerr << verified->stdout_data << verified->stderr_data << '\n'; + } + + // A different artifact digest is rejected. + const auto other = tmp / "other.tar"; + write_file(other, "tampered"); + auto mismatched = run_vbs({"attest", "verify", "--attestation", attestation.string(), + "--artifact", other.string(), "--trusted-public-key", + *public_key}); + Void::Testing::expect(mismatched.has_value() && !mismatched->succeeded()); + + // Tampering with the payload invalidates the signature. + auto tampered_text = *envelope_text; + const auto payload_pos = tampered_text.find("\"payload\":\""); + Void::Testing::require(payload_pos != std::string::npos); + const auto char_pos = payload_pos + std::string{"\"payload\":\""}.size(); + tampered_text[char_pos] = tampered_text[char_pos] == 'A' ? 'B' : 'A'; + const auto tampered = tmp / "tampered.json"; + write_file(tampered, tampered_text); + auto tampered_result = run_vbs({"attest", "verify", "--attestation", tampered.string(), + "--artifact", artifact.string(), "--trusted-public-key", + *public_key}); + Void::Testing::expect(tampered_result.has_value() && !tampered_result->succeeded()); + + // An untrusted key is rejected, and verification without keys is a usage error. + auto untrusted = run_vbs({"attest", "verify", "--attestation", attestation.string(), + "--artifact", artifact.string(), "--trusted-public-key", + std::string(64, '0')}); + Void::Testing::expect(untrusted.has_value() && !untrusted->succeeded()); + auto missing_keys = run_vbs({"attest", "verify", "--attestation", attestation.string()}); + Void::Testing::expect(missing_keys.has_value() && missing_keys->exit_code == 2); +} + +// === Trust layer: OSV advisory audit against vbs.lock === +VOID_TEST(FullV1Tests, audit_matches_osv_advisories_against_lock) { + const auto vbs_bin = locate_vbs_binary(); + Void::Testing::expect(!vbs_bin.empty() && std::filesystem::exists(vbs_bin)); + if (vbs_bin.empty() || !std::filesystem::exists(vbs_bin)) { + return; + } + Void::FileSystem::TempDir tmp{"vbs_audit_"}; + const auto lock_path = tmp / "vbs.lock"; + const auto make_context = [&]() { + Package::LockContextRecord context; + context.context_key = "debug:gcc:Linux:x86_64:target"; + context.profile_name = "debug"; + context.compiler = "gcc"; + context.os = "Linux"; + context.architecture = "x86_64"; + context.machine_role = "target"; + return context; + }; + auto vulnerable = make_context(); + for (const auto &[name, version] : + {std::pair{"zlib", "1.2.11"}, + std::pair{"openssl", "3.0.0"}}) { + Package::LockedSourceEntry entry; + entry.alias = name; + entry.package_name = name; + entry.version = version; + entry.source_kind = "package"; + entry.sha256 = std::string(64, 'a'); + vulnerable.entries.push_back(entry); + } + auto published = Package::publish_lock_context_cas(lock_path, "", vulnerable, false); + Void::Testing::require(published.has_value()); + + const auto advisories = tmp / "osv.json"; + write_file(advisories, R"json([ + {"id":"OSV-ZLIB-1","summary":"zlib overflow","database_specific":{"severity":"HIGH"}, + "affected":[{"package":{"name":"zlib","ecosystem":"OSS-Fuzz"}, + "ranges":[{"type":"ECOSYSTEM","events":[{"introduced":"1.2.0"},{"fixed":"1.2.13"}]}]}]}, + {"id":"OSV-OPENSSL-1","summary":"openssl issue","database_specific":{"severity":"medium"}, + "affected":[{"package":{"name":"openssl"}, + "ranges":[{"type":"ECOSYSTEM","events":[{"introduced":"3.0.0"},{"fixed":"3.0.1"}]}]}]} +])json"); + auto run_vbs = [&](std::vector args) { + Platform::ProcessRequest req; + req.executable = vbs_bin; + req.arguments = std::move(args); + req.timeout = std::chrono::seconds{120}; + return Platform::run_supervised(req); + }; + auto audit = run_vbs({"audit", "--lock", lock_path.string(), "--advisories", + advisories.string()}); + Void::Testing::expect(audit.has_value() && audit->exit_code == 1); + if (audit) { + Void::Testing::expect(audit->stdout_data.find("zlib 1.2.11") != std::string::npos); + Void::Testing::expect(audit->stdout_data.find("openssl 3.0.0") != std::string::npos); + } + auto high_only = run_vbs({"audit", "--lock", lock_path.string(), "--advisories", + advisories.string(), "--severity-threshold", "high"}); + Void::Testing::expect(high_only.has_value() && high_only->exit_code == 1); + if (high_only) { + Void::Testing::expect(high_only->stdout_data.find("zlib 1.2.11") != std::string::npos); + Void::Testing::expect(high_only->stdout_data.find("openssl") == std::string::npos); + } + auto critical_only = run_vbs({"audit", "--lock", lock_path.string(), "--advisories", + advisories.string(), "--severity-threshold", "critical"}); + Void::Testing::expect(critical_only.has_value() && critical_only->succeeded()); + auto json = run_vbs({"audit", "--lock", lock_path.string(), "--advisories", + advisories.string(), "--json"}); + Void::Testing::expect(json.has_value() && json->exit_code == 1); + if (json) { + auto parsed = Void::Json::Strict::parse(json->stdout_data); + Void::Testing::require(parsed.has_value()); + const auto *object = std::get_if(&parsed->value); + Void::Testing::require(object != nullptr); + const auto *count = std::get_if(&object->at("count").value); + Void::Testing::require(count != nullptr); + Void::Testing::expect_eq(*count, 2LL); + } + + // Fixed versions are not reported. + auto fixed = make_context(); + for (const auto &[name, version] : + {std::pair{"zlib", "1.2.13"}, + std::pair{"openssl", "3.0.1"}}) { + Package::LockedSourceEntry entry; + entry.alias = name; + entry.package_name = name; + entry.version = version; + entry.source_kind = "package"; + entry.sha256 = std::string(64, 'b'); + fixed.entries.push_back(entry); + } + auto updated = + Package::publish_lock_context_cas(lock_path, published->revision_hash, fixed, false); + Void::Testing::require(updated.has_value()); + auto clean = run_vbs({"audit", "--lock", lock_path.string(), "--advisories", + advisories.string()}); + Void::Testing::expect(clean.has_value() && clean->succeeded()); +}