feat: implement MoloApp plans 01-15 with integration
Full C++23 framework tree: runtime, observability, security, data, app, realtime, supervisor, clients, CLI, example plus enterprise tenancy, audit, operability, governance, supplychain. Postgres via docker compose for tests.
This commit is contained in:
@@ -0,0 +1,131 @@
|
||||
# Base-tree edits for the supply-chain part
|
||||
|
||||
This file lists every edit the base tree needs to wire in `src/supplychain/`.
|
||||
The isolated worktree does not contain the base `src/` tree, so `@@` line
|
||||
offsets below are illustrative: locate each hunk by its anchor line (taken
|
||||
from the seam handoff), apply, then `make supply-test` from the repo root.
|
||||
|
||||
Assumptions flagged inline with `NOTE(jsm)`: adapter signatures assumed from
|
||||
the seam summary (`Output::print/info/progress/warn/error/debug`,
|
||||
`JsonWriter::object(map<string,string>)`, `CommandTree` member access).
|
||||
Confirm against the real headers when applying.
|
||||
|
||||
## 1. Makefile (repo root)
|
||||
|
||||
Add the fragment include plus double-colon wiring. Multiple `.PHONY` lines
|
||||
and double-colon rules are legal in one Makefile, so these lines may also
|
||||
live as their own block.
|
||||
|
||||
```diff
|
||||
--- a/Makefile
|
||||
+++ b/Makefile
|
||||
@@ -3,6 +3,11 @@
|
||||
-include src/cli/cli.mk
|
||||
+-include src/supplychain/supplychain.mk
|
||||
+
|
||||
+all:: supply-all
|
||||
+test:: supply-test
|
||||
+
|
||||
+.PHONY: supply-all supply-test supply-clean
|
||||
```
|
||||
|
||||
## 2. src/cli/cli.mk
|
||||
|
||||
Append at end of file. `+=` works regardless of how `CLI_INC` is spelled,
|
||||
and the extra prerequisite-only rule merges with the existing `$(MOLO_BIN)`
|
||||
rule (single- or double-colon).
|
||||
|
||||
```diff
|
||||
--- a/src/cli/cli.mk
|
||||
+++ b/src/cli/cli.mk
|
||||
@@ -40,1 +40,4 @@
|
||||
# end of cli.mk
|
||||
+CLI_INC += -Isrc/supplychain
|
||||
+
|
||||
+$(MOLO_BIN): $(SUPPLY_LIB)
|
||||
```
|
||||
|
||||
NOTE(jsm): if `cli.mk` names the include variable or binary target
|
||||
differently than `CLI_INC` / `MOLO_BIN`, rename here to match; the supply
|
||||
sources only need `-Isrc/supplychain` on the CLI compile line and
|
||||
`build/supply/libsupply.a` linked into the CLI binary and its test links.
|
||||
|
||||
## 3. src/cli/cli/cli_app.cpp
|
||||
|
||||
Include the thin handler header (only supply header the CLI may include)
|
||||
and add the three leaves in `build_tree()`.
|
||||
|
||||
```diff
|
||||
--- a/src/cli/cli/cli_app.cpp
|
||||
+++ b/src/cli/cli/cli_app.cpp
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "cli/cli_app.hpp"
|
||||
+#include "supplychain/cli/SupplyCli.hpp"
|
||||
```
|
||||
|
||||
NOTE(jsm): if this file includes its own header with a different spelling
|
||||
(e.g. `cli/cli/cli_app.hpp`), keep that line untouched and add the second
|
||||
include next to it.
|
||||
|
||||
```diff
|
||||
--- a/src/cli/cli/cli_app.cpp
|
||||
+++ b/src/cli/cli/cli_app.cpp
|
||||
@@ -20,6 +20,45 @@
|
||||
void CliApp::build_tree() {
|
||||
+ auto verify = std::make_shared<Command>("verify", "verify release artifacts offline");
|
||||
+ verify->usage("molo verify [dir]")
|
||||
+ .long_help("Recompute sha256 digests, check the signature bundle chain, and match the wolfssl pin. Fully offline.")
|
||||
+ .example("molo verify ./dist")
|
||||
+ .flag(Flag("manifest", "", "subjects file", true, "subjects.txt"))
|
||||
+ .flag(Flag("bundle", "", "signature bundle", true, "bundle.json"))
|
||||
+ .flag(Flag("pin", "", "allow-list with wolfssl pin", true, ""))
|
||||
+ .handler(&molo::supply::cli::SupplyCli::run_verify);
|
||||
+ tree().add(verify);
|
||||
+
|
||||
+ auto check = std::make_shared<Command>("supply-check", "pin plus advisory gate");
|
||||
+ check->usage("molo supply-check [dir]")
|
||||
+ .long_help("Check the wolfssl pin and allow-list, then evaluate advisories. Blocked exits 1.")
|
||||
+ .example("molo supply-check ./dist")
|
||||
+ .flag(Flag("allow", "", "allow-list file", true, "supply.allow.json"))
|
||||
+ .flag(Flag("advisories", "", "advisories file", true, "advisories.json"))
|
||||
+ .flag(Flag("exceptions", "", "exceptions file", true, ""))
|
||||
+ .handler(&molo::supply::cli::SupplyCli::run_check);
|
||||
+ tree().add(check);
|
||||
+
|
||||
+ auto release = std::make_shared<Command>("release", "ordered release gate");
|
||||
+ release->usage("molo release --commit <sha> --suite-stamp <file>")
|
||||
+ .long_help("Run suite, sbom, scan, provenance, sign, tag in order. Any failed step exits 1.")
|
||||
+ .example("molo release --commit abc123 --suite-stamp build/suite.stamp")
|
||||
+ .flag(Flag("commit", "", "release commit", true, ""))
|
||||
+ .flag(Flag("suite-stamp", "", "file containing PASS", true, ""))
|
||||
+ .flag(Flag("dir", "", "release directory", true, "."))
|
||||
+ .handler(&molo::supply::cli::SupplyCli::run_release);
|
||||
+ tree().add(release);
|
||||
+
|
||||
// ... existing leaves follow
|
||||
}
|
||||
```
|
||||
|
||||
NOTE(jsm): `tree()` stands for whatever member or accessor holds the
|
||||
`CommandTree` in `build_tree()`; use the local name if it differs.
|
||||
`Flag(name, short, help, takes_value, default)` and the `Command` builder
|
||||
chain spellings are per the seam handoff.
|
||||
|
||||
## 4. src/cli/cli/cli_app.hpp
|
||||
|
||||
No change required. `build_tree()` is private to the `.cpp`, the new leaves
|
||||
are added there, and no forward declaration is needed because `cli_app.cpp`
|
||||
includes `supplychain/cli/SupplyCli.hpp` directly.
|
||||
|
||||
## 5. Verification after applying (base tree)
|
||||
|
||||
- `make supply-all` builds `build/supply/libsupply.a` with base headers
|
||||
(adapters are never on the include path, so any seam drift fails loudly).
|
||||
- `make supply-test` builds and runs the six suites, including CLI handler
|
||||
paths through the real `ParsedArgs`/`Output` types.
|
||||
- `molo verify --help`, `molo supply-check --help`, `molo release --help`
|
||||
print usage and exit 0; exit codes map via `to_int` (0/1/2).
|
||||
- No other base file is touched: no changes to `command.hpp`,
|
||||
`command_tree.hpp`, `exit_code.hpp`, `output.hpp`, `json_writer.hpp`,
|
||||
`flag.hpp`, `arg_parser.hpp`, `embed/sha256.hpp`, `version.hpp`,
|
||||
`caps.hpp`, logging, crypto, or TLS.
|
||||
@@ -0,0 +1,28 @@
|
||||
#pragma once
|
||||
// ADAPTER: standalone fallback mirroring the src/cli/cli/arg_parser.hpp seam.
|
||||
// The real build uses the base-tree header; this file only exists so the
|
||||
// supply-chain part compiles and tests in isolation.
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace molo::cli {
|
||||
|
||||
struct GlobalArgs {
|
||||
std::string format;
|
||||
int verbose = 0;
|
||||
bool quiet = false;
|
||||
bool show_help = false;
|
||||
bool show_version = false;
|
||||
};
|
||||
|
||||
struct ParsedArgs {
|
||||
GlobalArgs global;
|
||||
std::vector<std::string> command_path;
|
||||
std::map<std::string, std::string> flags;
|
||||
std::vector<std::string> positionals;
|
||||
std::string error;
|
||||
};
|
||||
|
||||
} // namespace molo::cli
|
||||
@@ -0,0 +1,12 @@
|
||||
#pragma once
|
||||
// ADAPTER: standalone fallback mirroring the src/cli/cli/exit_code.hpp seam.
|
||||
// The real build uses the base-tree header; this file only exists so the
|
||||
// supply-chain part compiles and tests in isolation.
|
||||
|
||||
namespace molo::cli {
|
||||
|
||||
enum class ExitCode : int { Ok = 0, Runtime = 1, Usage = 2, Unavailable = 69 };
|
||||
|
||||
inline int to_int(ExitCode code) { return static_cast<int>(code); }
|
||||
|
||||
} // namespace molo::cli
|
||||
@@ -0,0 +1,34 @@
|
||||
#pragma once
|
||||
// ADAPTER: standalone fallback mirroring the src/cli/cli/flag.hpp seam.
|
||||
// The real build uses the base-tree header; this file only exists so the
|
||||
// supply-chain part compiles and tests in isolation.
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace molo::cli {
|
||||
|
||||
class Flag {
|
||||
public:
|
||||
Flag(std::string name, std::string short_name, std::string help, bool takes_value,
|
||||
std::string default_value)
|
||||
: name_(std::move(name)),
|
||||
short_name_(std::move(short_name)),
|
||||
help_(std::move(help)),
|
||||
takes_value_(takes_value),
|
||||
default_value_(std::move(default_value)) {}
|
||||
|
||||
const std::string& name() const { return name_; }
|
||||
const std::string& short_name() const { return short_name_; }
|
||||
const std::string& help() const { return help_; }
|
||||
bool takes_value() const { return takes_value_; }
|
||||
const std::string& default_value() const { return default_value_; }
|
||||
|
||||
private:
|
||||
std::string name_;
|
||||
std::string short_name_;
|
||||
std::string help_;
|
||||
bool takes_value_;
|
||||
std::string default_value_;
|
||||
};
|
||||
|
||||
} // namespace molo::cli
|
||||
@@ -0,0 +1,72 @@
|
||||
#pragma once
|
||||
// ADAPTER: standalone fallback mirroring the src/cli/cli/json_writer.hpp seam.
|
||||
// Only escape/quote/object are consumed by supply-chain code; the rest matches
|
||||
// the seam signature list. The real build uses the base-tree header.
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace molo::cli {
|
||||
|
||||
class JsonWriter {
|
||||
public:
|
||||
JsonWriter() = delete;
|
||||
|
||||
static std::string escape(const std::string& in);
|
||||
static std::string quote(const std::string& in);
|
||||
static std::string str(const std::string& in) { return quote(in); }
|
||||
static std::string boolean(bool b) { return b ? "true" : "false"; }
|
||||
static std::string number(long long n) { return std::to_string(n); }
|
||||
static std::string object(const std::map<std::string, std::string>& fields);
|
||||
static std::string array(const std::vector<std::string>& items);
|
||||
static std::string field(const std::string& key, const std::string& rendered_value);
|
||||
};
|
||||
|
||||
inline std::string JsonWriter::escape(const std::string& in) {
|
||||
std::string out;
|
||||
out.reserve(in.size() + 8);
|
||||
for (char c : in) {
|
||||
switch (c) {
|
||||
case '"': out += "\\\""; break;
|
||||
case '\\': out += "\\\\"; break;
|
||||
case '\n': out += "\\n"; break;
|
||||
case '\r': out += "\\r"; break;
|
||||
case '\t': out += "\\t"; break;
|
||||
default: out.push_back(c); break;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
inline std::string JsonWriter::quote(const std::string& in) { return "\"" + escape(in) + "\""; }
|
||||
|
||||
inline std::string JsonWriter::object(const std::map<std::string, std::string>& fields) {
|
||||
std::string out = "{";
|
||||
bool first = true;
|
||||
for (const auto& [key, value] : fields) {
|
||||
if (!first) out += ",";
|
||||
first = false;
|
||||
out += quote(key) + ":" + value;
|
||||
}
|
||||
out += "}";
|
||||
return out;
|
||||
}
|
||||
|
||||
inline std::string JsonWriter::array(const std::vector<std::string>& items) {
|
||||
std::string out = "[";
|
||||
bool first = true;
|
||||
for (const auto& item : items) {
|
||||
if (!first) out += ",";
|
||||
first = false;
|
||||
out += item;
|
||||
}
|
||||
out += "]";
|
||||
return out;
|
||||
}
|
||||
|
||||
inline std::string JsonWriter::field(const std::string& key, const std::string& rendered_value) {
|
||||
return quote(key) + ":" + rendered_value;
|
||||
}
|
||||
|
||||
} // namespace molo::cli
|
||||
@@ -0,0 +1,63 @@
|
||||
#pragma once
|
||||
// ADAPTER: standalone fallback mirroring the src/cli/cli/output.hpp seam.
|
||||
// The real build uses the base-tree header; this file only exists so the
|
||||
// supply-chain part compiles and tests in isolation.
|
||||
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace molo::cli {
|
||||
|
||||
class Output {
|
||||
public:
|
||||
Output(bool json, int verbose, bool quiet, bool tty)
|
||||
: json_(json), verbose_(verbose), quiet_(quiet), tty_(tty) {}
|
||||
|
||||
static bool stdout_is_tty() { return false; } // ADAPTER: deterministic offline value
|
||||
|
||||
bool json() const { return json_; }
|
||||
bool quiet() const { return quiet_; }
|
||||
int verbose() const { return verbose_; }
|
||||
|
||||
void print(const std::string& line) {
|
||||
stdout_lines_.push_back(line);
|
||||
if (!quiet_) std::cout << line << "\n";
|
||||
}
|
||||
void info(const std::string& line) {
|
||||
stdout_lines_.push_back(line);
|
||||
if (!quiet_) std::cout << line << "\n";
|
||||
}
|
||||
void progress(const std::string& line) {
|
||||
stdout_lines_.push_back(line);
|
||||
if (!quiet_ && tty_) std::cout << line << "\n";
|
||||
}
|
||||
void warn(const std::string& line) {
|
||||
stderr_lines_.push_back(line);
|
||||
if (!quiet_) std::cerr << "warning: " << line << "\n";
|
||||
}
|
||||
void error(const std::string& line) {
|
||||
stderr_lines_.push_back(line);
|
||||
std::cerr << "error: " << line << "\n";
|
||||
}
|
||||
void debug(int level, const std::string& line) {
|
||||
if (level <= verbose_) {
|
||||
stdout_lines_.push_back(line);
|
||||
if (!quiet_) std::cout << line << "\n";
|
||||
}
|
||||
}
|
||||
|
||||
// ADAPTER-only inspection hook for tests; base Output has no such method.
|
||||
const std::vector<std::string>& stdout_lines() const { return stdout_lines_; }
|
||||
const std::vector<std::string>& stderr_lines() const { return stderr_lines_; }
|
||||
|
||||
private:
|
||||
bool json_;
|
||||
int verbose_;
|
||||
bool quiet_;
|
||||
bool tty_;
|
||||
std::vector<std::string> stdout_lines_;
|
||||
std::vector<std::string> stderr_lines_;
|
||||
};
|
||||
|
||||
} // namespace molo::cli
|
||||
@@ -0,0 +1,186 @@
|
||||
#pragma once
|
||||
// ADAPTER: standalone fallback mirroring the src/cli/embed/sha256.hpp seam
|
||||
// (molo::embed::Sha256 with hex_of_bytes / hex_of_string / hex_of_file).
|
||||
// The real build uses the base-tree header; this file carries its own small
|
||||
// SHA-256 so the supply-chain part verifies hashes in isolation.
|
||||
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace molo::embed {
|
||||
|
||||
class Sha256 {
|
||||
public:
|
||||
Sha256() = delete;
|
||||
|
||||
static std::string hex_of_string(const std::string& s);
|
||||
static std::string hex_of_bytes(const std::vector<unsigned char>& v);
|
||||
static bool hex_of_file(const std::string& path, std::string& hex_out);
|
||||
|
||||
private:
|
||||
struct Ctx {
|
||||
std::array<std::uint32_t, 8> h{};
|
||||
std::uint64_t total = 0;
|
||||
std::array<unsigned char, 64> buf{};
|
||||
std::size_t used = 0;
|
||||
};
|
||||
|
||||
static void init(Ctx& ctx);
|
||||
static void update(Ctx& ctx, const unsigned char* data, std::size_t len);
|
||||
static void final(Ctx& ctx, unsigned char out[32]);
|
||||
static void block(Ctx& ctx, const unsigned char p[64]);
|
||||
static std::string to_hex(const unsigned char digest[32]);
|
||||
};
|
||||
|
||||
inline std::uint32_t Shr(std::uint32_t x, unsigned n) { return x >> n; }
|
||||
inline std::uint32_t Rotr(std::uint32_t x, unsigned n) { return (x >> n) | (x << (32 - n)); }
|
||||
|
||||
inline void Sha256::init(Ctx& ctx) {
|
||||
ctx.h = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
|
||||
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
|
||||
ctx.total = 0;
|
||||
ctx.used = 0;
|
||||
}
|
||||
|
||||
inline void Sha256::block(Ctx& ctx, const unsigned char p[64]) {
|
||||
static constexpr std::uint32_t k[64] = {
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4,
|
||||
0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe,
|
||||
0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f,
|
||||
0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
|
||||
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
|
||||
0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
|
||||
0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116,
|
||||
0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
||||
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,
|
||||
0xc67178f2};
|
||||
std::uint32_t w[64];
|
||||
for (int i = 0; i < 16; ++i) {
|
||||
w[i] = (static_cast<std::uint32_t>(p[i * 4]) << 24) |
|
||||
(static_cast<std::uint32_t>(p[i * 4 + 1]) << 16) |
|
||||
(static_cast<std::uint32_t>(p[i * 4 + 2]) << 8) | static_cast<std::uint32_t>(p[i * 4 + 3]);
|
||||
}
|
||||
for (int i = 16; i < 64; ++i) {
|
||||
std::uint32_t s0 = Rotr(w[i - 15], 7) ^ Rotr(w[i - 15], 18) ^ Shr(w[i - 15], 3);
|
||||
std::uint32_t s1 = Rotr(w[i - 2], 17) ^ Rotr(w[i - 2], 19) ^ Shr(w[i - 2], 10);
|
||||
w[i] = w[i - 16] + s0 + w[i - 7] + s1;
|
||||
}
|
||||
std::uint32_t a = ctx.h[0], b = ctx.h[1], c = ctx.h[2], d = ctx.h[3];
|
||||
std::uint32_t e = ctx.h[4], f = ctx.h[5], g = ctx.h[6], h = ctx.h[7];
|
||||
for (int i = 0; i < 64; ++i) {
|
||||
std::uint32_t s1 = Rotr(e, 6) ^ Rotr(e, 11) ^ Rotr(e, 25);
|
||||
std::uint32_t ch = (e & f) ^ ((~e) & g);
|
||||
std::uint32_t t1 = h + s1 + ch + k[i] + w[i];
|
||||
std::uint32_t s0 = Rotr(a, 2) ^ Rotr(a, 13) ^ Rotr(a, 22);
|
||||
std::uint32_t maj = (a & b) ^ (a & c) ^ (b & c);
|
||||
std::uint32_t t2 = s0 + maj;
|
||||
h = g;
|
||||
g = f;
|
||||
f = e;
|
||||
e = d + t1;
|
||||
d = c;
|
||||
c = b;
|
||||
b = a;
|
||||
a = t1 + t2;
|
||||
}
|
||||
ctx.h[0] += a;
|
||||
ctx.h[1] += b;
|
||||
ctx.h[2] += c;
|
||||
ctx.h[3] += d;
|
||||
ctx.h[4] += e;
|
||||
ctx.h[5] += f;
|
||||
ctx.h[6] += g;
|
||||
ctx.h[7] += h;
|
||||
}
|
||||
|
||||
inline void Sha256::update(Ctx& ctx, const unsigned char* data, std::size_t len) {
|
||||
ctx.total += len;
|
||||
std::size_t off = 0;
|
||||
if (ctx.used > 0) {
|
||||
std::size_t take = 64 - ctx.used;
|
||||
if (take > len) take = len;
|
||||
for (std::size_t i = 0; i < take; ++i) ctx.buf[ctx.used + i] = data[i];
|
||||
ctx.used += take;
|
||||
off += take;
|
||||
if (ctx.used == 64) {
|
||||
block(ctx, ctx.buf.data());
|
||||
ctx.used = 0;
|
||||
}
|
||||
}
|
||||
while (off + 64 <= len) {
|
||||
block(ctx, data + off);
|
||||
off += 64;
|
||||
}
|
||||
while (off < len) ctx.buf[ctx.used++] = data[off++];
|
||||
}
|
||||
|
||||
inline void Sha256::final(Ctx& ctx, unsigned char out[32]) {
|
||||
std::uint64_t bits = ctx.total * 8;
|
||||
unsigned char pad = 0x80;
|
||||
update(ctx, &pad, 1);
|
||||
unsigned char zero = 0x00;
|
||||
while (ctx.used != 56) update(ctx, &zero, 1);
|
||||
unsigned char len_bytes[8];
|
||||
for (int i = 0; i < 8; ++i) len_bytes[i] = static_cast<unsigned char>(bits >> (56 - i * 8));
|
||||
// Append length without touching ctx.total again.
|
||||
for (int i = 0; i < 8; ++i) ctx.buf[ctx.used++] = len_bytes[i];
|
||||
block(ctx, ctx.buf.data());
|
||||
ctx.used = 0;
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
out[i * 4] = static_cast<unsigned char>(ctx.h[i] >> 24);
|
||||
out[i * 4 + 1] = static_cast<unsigned char>(ctx.h[i] >> 16);
|
||||
out[i * 4 + 2] = static_cast<unsigned char>(ctx.h[i] >> 8);
|
||||
out[i * 4 + 3] = static_cast<unsigned char>(ctx.h[i]);
|
||||
}
|
||||
}
|
||||
|
||||
inline std::string Sha256::to_hex(const unsigned char digest[32]) {
|
||||
static constexpr char kHex[] = "0123456789abcdef";
|
||||
std::string out;
|
||||
out.reserve(64);
|
||||
for (int i = 0; i < 32; ++i) {
|
||||
out.push_back(kHex[digest[i] >> 4]);
|
||||
out.push_back(kHex[digest[i] & 0x0F]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
inline std::string Sha256::hex_of_string(const std::string& s) {
|
||||
Ctx ctx;
|
||||
init(ctx);
|
||||
update(ctx, reinterpret_cast<const unsigned char*>(s.data()), s.size());
|
||||
unsigned char digest[32];
|
||||
final(ctx, digest);
|
||||
return to_hex(digest);
|
||||
}
|
||||
|
||||
inline std::string Sha256::hex_of_bytes(const std::vector<unsigned char>& v) {
|
||||
Ctx ctx;
|
||||
init(ctx);
|
||||
if (!v.empty()) update(ctx, v.data(), v.size());
|
||||
unsigned char digest[32];
|
||||
final(ctx, digest);
|
||||
return to_hex(digest);
|
||||
}
|
||||
|
||||
inline bool Sha256::hex_of_file(const std::string& path, std::string& hex_out) {
|
||||
std::FILE* f = std::fopen(path.c_str(), "rb");
|
||||
if (f == nullptr) return false;
|
||||
Ctx ctx;
|
||||
init(ctx);
|
||||
unsigned char chunk[8192];
|
||||
std::size_t n = 0;
|
||||
while ((n = std::fread(chunk, 1, sizeof(chunk), f)) > 0) update(ctx, chunk, n);
|
||||
bool ok = std::ferror(f) == 0;
|
||||
std::fclose(f);
|
||||
if (!ok) return false;
|
||||
unsigned char digest[32];
|
||||
final(ctx, digest);
|
||||
hex_out = to_hex(digest);
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace molo::embed
|
||||
@@ -0,0 +1,16 @@
|
||||
#pragma once
|
||||
// ADAPTER: standalone fallback mirroring the src/cli/version.hpp seam.
|
||||
// The real build uses the base-tree header; this file only exists so the
|
||||
// supply-chain part compiles and tests in isolation.
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace molo {
|
||||
|
||||
inline constexpr const char* kMoloName = "moloapp";
|
||||
inline constexpr const char* kMoloVersion = "0.0.0-standalone";
|
||||
inline constexpr const char* kEmbedToolVersion = "0.0.0-standalone";
|
||||
|
||||
inline std::string version_string() { return std::string(kMoloName) + " " + kMoloVersion; }
|
||||
|
||||
} // namespace molo
|
||||
@@ -0,0 +1,79 @@
|
||||
#include "../attest/Attestor.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <map>
|
||||
|
||||
#include "../caps.hpp"
|
||||
#include "../common/Json.hpp"
|
||||
|
||||
namespace molo::supply::attest {
|
||||
|
||||
bool Attestor::statement(const std::vector<ProvenanceBuilder::Subject>& subjects,
|
||||
std::string_view predicate_type, std::string_view predicate_json,
|
||||
std::string& out, std::string& error) {
|
||||
using common::Json;
|
||||
out.clear();
|
||||
if (predicate_type.empty()) {
|
||||
error = "predicate type must not be empty";
|
||||
return false;
|
||||
}
|
||||
if (subjects.size() > caps::kMaxSignedFiles) {
|
||||
error = "subject count over 32 signed-files cap";
|
||||
return false;
|
||||
}
|
||||
Json::Value predicate;
|
||||
if (!Json::parse(predicate_json, predicate, error)) {
|
||||
error = "predicate is not valid json: " + error;
|
||||
return false;
|
||||
}
|
||||
if (predicate.type != Json::Value::Type::Object) {
|
||||
error = "predicate must be a json object";
|
||||
return false;
|
||||
}
|
||||
std::vector<ProvenanceBuilder::Subject> sorted = subjects;
|
||||
std::sort(sorted.begin(), sorted.end(),
|
||||
[](const auto& a, const auto& b) { return a.path < b.path; });
|
||||
std::vector<std::string> rendered;
|
||||
for (const auto& s : sorted) {
|
||||
if (s.path.empty() || !Json::is_hex64(s.sha256)) {
|
||||
error = "subject needs a path and 64 hex sha256";
|
||||
return false;
|
||||
}
|
||||
std::map<std::string, std::string> subj;
|
||||
subj["digest"] = Json::object({{"sha256", Json::quote(s.sha256)}}, 3);
|
||||
subj["name"] = Json::quote(s.path);
|
||||
rendered.push_back(Json::object(subj, 2));
|
||||
}
|
||||
// Re-indent the embedded predicate so the whole statement stays canonical:
|
||||
// every predicate line after the opening brace shifts one level right.
|
||||
std::string predicate_indented;
|
||||
{
|
||||
std::string raw(predicate_json);
|
||||
std::size_t pos = 0;
|
||||
bool first_line = true;
|
||||
while (true) {
|
||||
std::size_t nl = raw.find('\n', pos);
|
||||
std::string line = (nl == std::string::npos) ? raw.substr(pos) : raw.substr(pos, nl - pos);
|
||||
if (!first_line) predicate_indented += " ";
|
||||
first_line = false;
|
||||
predicate_indented += line;
|
||||
if (nl == std::string::npos) break;
|
||||
predicate_indented += "\n";
|
||||
pos = nl + 1;
|
||||
}
|
||||
}
|
||||
std::map<std::string, std::string> root;
|
||||
root["_type"] = Json::quote(caps::kInTotoStatementType);
|
||||
root["predicate"] = predicate_indented;
|
||||
root["predicateType"] = Json::quote(std::string(predicate_type));
|
||||
root["subject"] = Json::array(rendered, 1);
|
||||
out = Json::object(root, 0) + "\n";
|
||||
if (out.size() > caps::kMaxSbomBytes) {
|
||||
out.clear();
|
||||
error = "statement over 1 MiB cap";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace molo::supply::attest
|
||||
@@ -0,0 +1,23 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
#include "../attest/ProvenanceBuilder.hpp"
|
||||
|
||||
namespace molo::supply::attest {
|
||||
|
||||
// in-toto Statement wrapper: binds subjects (path plus sha256 digest) to a
|
||||
// predicate document. Subjects sort by path for canonical output. The 33rd
|
||||
// subject is rejected (32 signed files cap).
|
||||
class Attestor {
|
||||
public:
|
||||
Attestor() = delete;
|
||||
|
||||
static bool statement(const std::vector<ProvenanceBuilder::Subject>& subjects,
|
||||
std::string_view predicate_type, std::string_view predicate_json,
|
||||
std::string& out, std::string& error);
|
||||
};
|
||||
|
||||
} // namespace molo::supply::attest
|
||||
@@ -0,0 +1,61 @@
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
#include "../caps.hpp"
|
||||
#include "../common/Json.hpp"
|
||||
|
||||
namespace molo::supply::attest {
|
||||
|
||||
// SLSA provenance predicate builder (predicate type
|
||||
// https://slsa.dev/provenance/v1, build type https://moloapp.dev/build/v1).
|
||||
// Header-only: builds a canonical JSON predicate object that Attestor wraps
|
||||
// into an in-toto Statement.
|
||||
class ProvenanceBuilder {
|
||||
public:
|
||||
struct Subject {
|
||||
std::string path;
|
||||
std::string sha256;
|
||||
};
|
||||
|
||||
ProvenanceBuilder() = delete;
|
||||
|
||||
static std::string build(std::string_view builder_id, std::string_view commit,
|
||||
const std::vector<std::string>& toolchain,
|
||||
const std::vector<Subject>& subjects,
|
||||
std::string_view invocation = "") {
|
||||
using common::Json;
|
||||
std::vector<Subject> sorted = subjects;
|
||||
std::sort(sorted.begin(), sorted.end(),
|
||||
[](const Subject& a, const Subject& b) { return a.path < b.path; });
|
||||
std::vector<std::string> materials;
|
||||
for (const auto& t : toolchain) materials.push_back(Json::quote(t));
|
||||
std::vector<std::string> resolved;
|
||||
for (const auto& s : sorted) {
|
||||
std::map<std::string, std::string> dep;
|
||||
dep["digest"] = Json::object({{"sha256", Json::quote(s.sha256)}}, 4);
|
||||
dep["uri"] = Json::quote(s.path);
|
||||
resolved.push_back(Json::object(dep, 3));
|
||||
}
|
||||
std::map<std::string, std::string> build_def;
|
||||
build_def["buildType"] = Json::quote(caps::kMoloBuildType);
|
||||
build_def["externalParameters"] =
|
||||
Json::object({{"commit", Json::quote(std::string(commit))},
|
||||
{"invocation", Json::quote(std::string(invocation))},
|
||||
{"materials", Json::array(materials, 3)}},
|
||||
2);
|
||||
build_def["resolvedDependencies"] = Json::array(resolved, 2);
|
||||
std::map<std::string, std::string> run_details;
|
||||
run_details["builder"] = Json::object({{"id", Json::quote(std::string(builder_id))}}, 2);
|
||||
std::map<std::string, std::string> predicate;
|
||||
predicate["buildDefinition"] = Json::object(build_def, 1);
|
||||
predicate["runDetails"] = Json::object(run_details, 1);
|
||||
return Json::object(predicate, 0);
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace molo::supply::attest
|
||||
@@ -0,0 +1,79 @@
|
||||
#include "../attest/Signer.hpp"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
|
||||
#if __has_include("cli/embed/sha256.hpp")
|
||||
#include "cli/embed/sha256.hpp"
|
||||
#elif __has_include("embed/sha256.hpp")
|
||||
#include "embed/sha256.hpp"
|
||||
#else
|
||||
#include "../adapters/cli/embed/sha256.hpp" // ADAPTER fallback for isolated builds
|
||||
#endif
|
||||
|
||||
namespace molo::supply::attest {
|
||||
|
||||
std::string Signer::quote_path(std::string_view path) {
|
||||
std::string out = "'";
|
||||
for (char c : path) {
|
||||
if (c == '\'') {
|
||||
out += "'\\''";
|
||||
} else {
|
||||
out.push_back(c);
|
||||
}
|
||||
}
|
||||
out += "'";
|
||||
return out;
|
||||
}
|
||||
|
||||
bool Signer::sign(const std::string& blob_path, const std::string& bundle_path,
|
||||
std::string& error) {
|
||||
if (blob_path.empty() || bundle_path.empty()) {
|
||||
error = "blob and bundle paths must not be empty";
|
||||
return false;
|
||||
}
|
||||
const char* fake = std::getenv("MOLO_FAKE_COSIGN");
|
||||
if (fake != nullptr && std::string(fake) == "1") {
|
||||
std::string digest;
|
||||
if (!molo::embed::Sha256::hex_of_file(blob_path, digest)) {
|
||||
error = "fake sign: cannot hash blob '" + blob_path + "'";
|
||||
return false;
|
||||
}
|
||||
std::FILE* f = std::fopen(bundle_path.c_str(), "wb");
|
||||
if (f == nullptr) {
|
||||
error = "fake sign: cannot write bundle '" + bundle_path + "'";
|
||||
return false;
|
||||
}
|
||||
std::string bundle = "{\"fakeBundle\":true,\"digest\":\"" + digest +
|
||||
"\",\"signature\":\"FAKE-" + digest.substr(0, 16) + "\"}\n";
|
||||
std::size_t wrote = std::fwrite(bundle.data(), 1, bundle.size(), f);
|
||||
bool ok = wrote == bundle.size() && std::fclose(f) == 0;
|
||||
if (!ok) error = "fake sign: failed writing bundle '" + bundle_path + "'";
|
||||
return ok;
|
||||
}
|
||||
std::string cmd = "cosign sign-blob --yes --bundle " + quote_path(bundle_path) + " " +
|
||||
quote_path(blob_path) + " 2>&1";
|
||||
std::FILE* pipe = ::popen(cmd.c_str(), "r");
|
||||
if (pipe == nullptr) {
|
||||
error = "cannot spawn cosign";
|
||||
return false;
|
||||
}
|
||||
std::string output;
|
||||
char chunk[1024];
|
||||
std::size_t n = 0;
|
||||
while ((n = std::fread(chunk, 1, sizeof(chunk), pipe)) > 0) {
|
||||
if (output.size() + n > 2048) {
|
||||
output.append(chunk, 2048 - output.size());
|
||||
break;
|
||||
}
|
||||
output.append(chunk, n);
|
||||
}
|
||||
int status = ::pclose(pipe);
|
||||
if (status != 0) {
|
||||
error = "cosign sign-blob failed (status " + std::to_string(status) + "): " + output;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace molo::supply::attest
|
||||
@@ -0,0 +1,21 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace molo::supply::attest {
|
||||
|
||||
// cosign sign-blob wrapper (keyless): runs
|
||||
// `cosign sign-blob --yes --bundle <bundle> <blob>` and reports failures with
|
||||
// capped output. This is the only supply-chain file allowed to spawn a shell.
|
||||
// Tests set MOLO_FAKE_COSIGN=1 for a deterministic offline fake bundle.
|
||||
class Signer {
|
||||
public:
|
||||
Signer() = delete;
|
||||
|
||||
static bool sign(const std::string& blob_path, const std::string& bundle_path,
|
||||
std::string& error);
|
||||
static std::string quote_path(std::string_view path);
|
||||
};
|
||||
|
||||
} // namespace molo::supply::attest
|
||||
@@ -0,0 +1,79 @@
|
||||
#include "../attest/Verify.hpp"
|
||||
|
||||
#include <cstdio>
|
||||
|
||||
#include "../caps.hpp"
|
||||
#include "../common/Json.hpp"
|
||||
|
||||
#if __has_include("cli/embed/sha256.hpp")
|
||||
#include "cli/embed/sha256.hpp"
|
||||
#elif __has_include("embed/sha256.hpp")
|
||||
#include "embed/sha256.hpp"
|
||||
#else
|
||||
#include "../adapters/cli/embed/sha256.hpp" // ADAPTER fallback for isolated builds
|
||||
#endif
|
||||
|
||||
namespace molo::supply::attest {
|
||||
|
||||
Verify::Result Verify::verify_files(
|
||||
const std::vector<std::pair<std::string, std::string>>& expected,
|
||||
const std::string& bundle_path, const policy::WolfPin::Pin* pin) {
|
||||
Result r;
|
||||
if (expected.empty()) {
|
||||
r.error = "no subjects to verify";
|
||||
return r;
|
||||
}
|
||||
if (expected.size() > caps::kMaxSignedFiles) {
|
||||
r.error = "subject count over 32 signed-files cap";
|
||||
return r;
|
||||
}
|
||||
std::FILE* bf = std::fopen(bundle_path.c_str(), "rb");
|
||||
if (bf == nullptr) {
|
||||
r.error = "cannot open bundle '" + bundle_path + "'";
|
||||
return r;
|
||||
}
|
||||
std::string bundle;
|
||||
char chunk[4096];
|
||||
std::size_t n = 0;
|
||||
bool bundle_ok = true;
|
||||
while ((n = std::fread(chunk, 1, sizeof(chunk), bf)) > 0) {
|
||||
if (bundle.size() + n > caps::kMaxBundleBytes) {
|
||||
bundle_ok = false;
|
||||
break;
|
||||
}
|
||||
bundle.append(chunk, n);
|
||||
}
|
||||
if (std::ferror(bf) != 0) bundle_ok = false;
|
||||
std::fclose(bf);
|
||||
if (!bundle_ok) {
|
||||
r.error = "cannot read bundle '" + bundle_path + "' (over 1 MiB cap or I/O error)";
|
||||
return r;
|
||||
}
|
||||
for (const auto& [path, want] : expected) {
|
||||
if (!common::Json::is_hex64(want)) {
|
||||
r.error = "subject '" + path + "' expected digest is not 64 hex";
|
||||
return r;
|
||||
}
|
||||
std::string actual;
|
||||
if (!molo::embed::Sha256::hex_of_file(path, actual)) {
|
||||
r.error = "cannot hash subject '" + path + "'";
|
||||
return r;
|
||||
}
|
||||
if (actual != want) {
|
||||
r.error = "hash mismatch for subject '" + path + "'";
|
||||
return r;
|
||||
}
|
||||
if (bundle.find(want) == std::string::npos) {
|
||||
r.error = "bundle does not cover subject '" + path + "'";
|
||||
return r;
|
||||
}
|
||||
if (pin != nullptr && path.find("wolfssl") != std::string::npos && want != pin->sha256) {
|
||||
r.error = "subject '" + path + "' does not match wolfssl pin";
|
||||
return r;
|
||||
}
|
||||
}
|
||||
r.ok = true;
|
||||
return r;
|
||||
}
|
||||
|
||||
} // namespace molo::supply::attest
|
||||
@@ -0,0 +1,27 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "../policy/WolfPin.hpp"
|
||||
|
||||
namespace molo::supply::attest {
|
||||
|
||||
// Offline release verifier: recomputes sha256 for every expected subject,
|
||||
// checks the signature bundle exists and covers every subject hash (chain),
|
||||
// and checks the wolfssl subject against the pin when one is provided.
|
||||
class Verify {
|
||||
public:
|
||||
struct Result {
|
||||
bool ok = false;
|
||||
std::string error;
|
||||
};
|
||||
|
||||
Verify() = delete;
|
||||
|
||||
static Result verify_files(const std::vector<std::pair<std::string, std::string>>& expected,
|
||||
const std::string& bundle_path, const policy::WolfPin::Pin* pin);
|
||||
};
|
||||
|
||||
} // namespace molo::supply::attest
|
||||
@@ -0,0 +1,33 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
|
||||
namespace molo::supply::caps {
|
||||
|
||||
// Static ceilings for the supply-chain part. Every automated path enforces
|
||||
// these; anything over a cap is rejected with a clear error, never truncated.
|
||||
inline constexpr std::size_t kMaxComponents = 64;
|
||||
inline constexpr std::size_t kMaxRelationships = 256;
|
||||
inline constexpr std::size_t kMaxSbomBytes = 1048576; // 1 MiB
|
||||
inline constexpr std::size_t kMaxToolchainEntries = 100;
|
||||
inline constexpr std::size_t kMaxToolchainBytes = 65536; // 64 KiB
|
||||
inline constexpr std::size_t kMaxSignedFiles = 32;
|
||||
inline constexpr std::size_t kMaxPinJsonBytes = 65536; // 64 KiB
|
||||
inline constexpr std::size_t kMaxAdvisoriesBytes = 262144; // 256 KiB
|
||||
inline constexpr std::size_t kMaxCommitChars = 128;
|
||||
inline constexpr std::size_t kMaxJsonDepth = 32;
|
||||
inline constexpr std::size_t kMaxJsonBytes = 4194304; // 4 MiB parser ceiling
|
||||
inline constexpr std::size_t kMaxOsvVulns = 64;
|
||||
inline constexpr std::size_t kOsvMaxQueries = 64;
|
||||
inline constexpr int kOsvTimeoutSeconds = 10;
|
||||
inline constexpr int kOsvMaxRetries = 1;
|
||||
inline constexpr long long kOverrideTtlSeconds = 604800; // 7 days
|
||||
inline constexpr double kBlockCvss = 9.0;
|
||||
inline constexpr std::size_t kMaxBundleBytes = 1048576; // 1 MiB
|
||||
|
||||
inline constexpr const char* kOsvQueryUrl = "https://api.osv.dev/v1/query";
|
||||
inline constexpr const char* kSlsaPredicateType = "https://slsa.dev/provenance/v1";
|
||||
inline constexpr const char* kMoloBuildType = "https://moloapp.dev/build/v1";
|
||||
inline constexpr const char* kInTotoStatementType = "https://in-toto.io/Statement/v1";
|
||||
|
||||
} // namespace molo::supply::caps
|
||||
@@ -0,0 +1,502 @@
|
||||
#include "../cli/SupplyCli.hpp"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <ctime>
|
||||
#include <map>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "../attest/Attestor.hpp"
|
||||
#include "../attest/ProvenanceBuilder.hpp"
|
||||
#include "../attest/Signer.hpp"
|
||||
#include "../attest/Verify.hpp"
|
||||
#include "../caps.hpp"
|
||||
#include "../common/Json.hpp"
|
||||
#include "../policy/DependencyPolicy.hpp"
|
||||
#include "../policy/WolfPin.hpp"
|
||||
#include "../sbom/CycloneDxEmitter.hpp"
|
||||
#include "../sbom/SbomCheck.hpp"
|
||||
#include "../sbom/SbomGenerator.hpp"
|
||||
#include "../sbom/SpdxEmitter.hpp"
|
||||
#include "../scan/OsvClient.hpp"
|
||||
#include "../scan/VulnHook.hpp"
|
||||
|
||||
#if __has_include("cli/cli/json_writer.hpp")
|
||||
#include "cli/cli/json_writer.hpp"
|
||||
#elif __has_include("cli/json_writer.hpp")
|
||||
#include "cli/json_writer.hpp"
|
||||
#else
|
||||
#include "../adapters/cli/cli/json_writer.hpp" // ADAPTER fallback for isolated builds
|
||||
#endif
|
||||
|
||||
#if __has_include("cli/version.hpp")
|
||||
#include "cli/version.hpp"
|
||||
#elif __has_include("version.hpp")
|
||||
#include "version.hpp"
|
||||
#else
|
||||
#include "../adapters/cli/version.hpp" // ADAPTER fallback for isolated builds
|
||||
#endif
|
||||
|
||||
#if __has_include("cli/embed/sha256.hpp")
|
||||
#include "cli/embed/sha256.hpp"
|
||||
#elif __has_include("embed/sha256.hpp")
|
||||
#include "embed/sha256.hpp"
|
||||
#else
|
||||
#include "../adapters/cli/embed/sha256.hpp" // ADAPTER fallback for isolated builds
|
||||
#endif
|
||||
|
||||
namespace molo::supply::cli {
|
||||
|
||||
namespace {
|
||||
|
||||
using molo::cli::ExitCode;
|
||||
using molo::cli::Output;
|
||||
using molo::cli::ParsedArgs;
|
||||
|
||||
bool wants_json(const ParsedArgs& args) { return args.global.format == "json"; }
|
||||
|
||||
std::string flag_or(const ParsedArgs& args, const std::string& name, const std::string& fallback) {
|
||||
auto it = args.flags.find(name);
|
||||
if (it == args.flags.end()) return fallback;
|
||||
return it->second;
|
||||
}
|
||||
|
||||
bool has_unknown_flag(const ParsedArgs& args, const std::vector<std::string>& known,
|
||||
std::string& bad) {
|
||||
for (const auto& [name, value] : args.flags) {
|
||||
(void)value;
|
||||
bool ok = false;
|
||||
for (const auto& k : known) {
|
||||
if (name == k) {
|
||||
ok = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!ok) {
|
||||
bad = name;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool read_file_capped(const std::string& path, std::string& text, std::size_t cap,
|
||||
std::string& error) {
|
||||
std::FILE* f = std::fopen(path.c_str(), "rb");
|
||||
if (f == nullptr) {
|
||||
error = "cannot open '" + path + "'";
|
||||
return false;
|
||||
}
|
||||
text.clear();
|
||||
char chunk[4096];
|
||||
std::size_t n = 0;
|
||||
bool ok = true;
|
||||
while ((n = std::fread(chunk, 1, sizeof(chunk), f)) > 0) {
|
||||
if (text.size() + n > cap) {
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
text.append(chunk, n);
|
||||
}
|
||||
if (std::ferror(f) != 0) ok = false;
|
||||
std::fclose(f);
|
||||
if (!ok) {
|
||||
error = "cannot read '" + path + "' (over cap or I/O error)";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool write_file(const std::string& path, const std::string& text, std::string& error) {
|
||||
std::FILE* f = std::fopen(path.c_str(), "wb");
|
||||
if (f == nullptr) {
|
||||
error = "cannot open '" + path + "' for writing";
|
||||
return false;
|
||||
}
|
||||
std::size_t wrote = std::fwrite(text.data(), 1, text.size(), f);
|
||||
bool ok = wrote == text.size() && std::fclose(f) == 0;
|
||||
if (!ok) error = "failed writing '" + path + "'";
|
||||
return ok;
|
||||
}
|
||||
|
||||
std::string join_path(const std::string& dir, const std::string& leaf) {
|
||||
if (leaf.empty()) return dir;
|
||||
if (!leaf.empty() && leaf[0] == '/') return leaf;
|
||||
if (dir.empty() || dir == ".") return leaf;
|
||||
if (dir.back() == '/') return dir + leaf;
|
||||
return dir + "/" + leaf;
|
||||
}
|
||||
|
||||
std::string trim(const std::string& s) {
|
||||
std::size_t b = 0;
|
||||
while (b < s.size() && (s[b] == ' ' || s[b] == '\t' || s[b] == '\n' || s[b] == '\r')) ++b;
|
||||
std::size_t e = s.size();
|
||||
while (e > b && (s[e - 1] == ' ' || s[e - 1] == '\t' || s[e - 1] == '\n' || s[e - 1] == '\r')) --e;
|
||||
return s.substr(b, e - b);
|
||||
}
|
||||
|
||||
void emit_status(Output& out, bool json, const std::string& status, const std::string& detail,
|
||||
std::size_t count) {
|
||||
if (json) {
|
||||
std::map<std::string, std::string> fields;
|
||||
fields["count"] = molo::cli::JsonWriter::number(static_cast<long long>(count));
|
||||
fields["detail"] = molo::cli::JsonWriter::quote(detail);
|
||||
fields["status"] = molo::cli::JsonWriter::quote(status);
|
||||
out.print(molo::cli::JsonWriter::object(fields));
|
||||
return;
|
||||
}
|
||||
out.print(status + ": " + detail);
|
||||
}
|
||||
|
||||
bool parse_subjects(const std::string& text, const std::string& dir,
|
||||
std::vector<std::pair<std::string, std::string>>& expected, std::string& error) {
|
||||
expected.clear();
|
||||
std::istringstream in(text);
|
||||
std::string line;
|
||||
while (std::getline(in, line)) {
|
||||
line = trim(line);
|
||||
if (line.empty() || line[0] == '#') continue;
|
||||
std::istringstream parts(line);
|
||||
std::string digest, path;
|
||||
if (!(parts >> digest >> path)) {
|
||||
error = "bad subjects line: '" + line + "'";
|
||||
return false;
|
||||
}
|
||||
if (path.size() > 1 && path[0] == '*') path = path.substr(1);
|
||||
if (expected.size() >= caps::kMaxSignedFiles) {
|
||||
error = "subject count over 32 signed-files cap";
|
||||
return false;
|
||||
}
|
||||
expected.emplace_back(join_path(dir, path), digest);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
long long now_unix() { return static_cast<long long>(std::time(nullptr)); }
|
||||
|
||||
} // namespace
|
||||
|
||||
ExitCode SupplyCli::run_verify(const ParsedArgs& args, Output& out) {
|
||||
const bool json = wants_json(args);
|
||||
if (args.global.show_help) {
|
||||
out.print("usage: molo verify [dir] [--manifest subjects.txt] [--bundle bundle.json] [--pin allow]");
|
||||
return ExitCode::Ok;
|
||||
}
|
||||
std::string bad;
|
||||
if (has_unknown_flag(args, {"manifest", "bundle", "pin"}, bad)) {
|
||||
out.error("unknown flag '--" + bad + "'");
|
||||
return ExitCode::Usage;
|
||||
}
|
||||
if (args.positionals.size() > 1) {
|
||||
out.error("verify takes at most one directory argument");
|
||||
return ExitCode::Usage;
|
||||
}
|
||||
const std::string dir = args.positionals.empty() ? "." : args.positionals[0];
|
||||
const std::string manifest_path = join_path(dir, flag_or(args, "manifest", "subjects.txt"));
|
||||
const std::string bundle_path = join_path(dir, flag_or(args, "bundle", "bundle.json"));
|
||||
|
||||
std::string text;
|
||||
std::string error;
|
||||
if (!read_file_capped(manifest_path, text, caps::kMaxSbomBytes, error)) {
|
||||
out.error(error);
|
||||
return ExitCode::Runtime;
|
||||
}
|
||||
std::vector<std::pair<std::string, std::string>> expected;
|
||||
if (!parse_subjects(text, dir, expected, error)) {
|
||||
out.error(error);
|
||||
return ExitCode::Runtime;
|
||||
}
|
||||
policy::WolfPin::Pin pin;
|
||||
const policy::WolfPin::Pin* pin_ptr = nullptr;
|
||||
std::string pin_flag = flag_or(args, "pin", "");
|
||||
if (!pin_flag.empty()) {
|
||||
if (!policy::WolfPin::load_file(join_path(dir, pin_flag), pin, error)) {
|
||||
out.error(error);
|
||||
return ExitCode::Runtime;
|
||||
}
|
||||
pin_ptr = &pin;
|
||||
}
|
||||
attest::Verify::Result r = attest::Verify::verify_files(expected, bundle_path, pin_ptr);
|
||||
if (!r.ok) {
|
||||
emit_status(out, json, "fail", r.error, expected.size());
|
||||
return ExitCode::Runtime;
|
||||
}
|
||||
emit_status(out, json, "ok", "verified " + std::to_string(expected.size()) + " subject(s)", expected.size());
|
||||
return ExitCode::Ok;
|
||||
}
|
||||
|
||||
ExitCode SupplyCli::run_check(const ParsedArgs& args, Output& out) {
|
||||
const bool json = wants_json(args);
|
||||
if (args.global.show_help) {
|
||||
out.print("usage: molo supply-check [dir] [--allow supply.allow.json] [--advisories advisories.json] [--exceptions exceptions.json] [--osv]");
|
||||
return ExitCode::Ok;
|
||||
}
|
||||
std::string bad;
|
||||
if (has_unknown_flag(args, {"allow", "advisories", "exceptions", "osv"}, bad)) {
|
||||
out.error("unknown flag '--" + bad + "'");
|
||||
return ExitCode::Usage;
|
||||
}
|
||||
if (args.positionals.size() > 1) {
|
||||
out.error("supply-check takes at most one directory argument");
|
||||
return ExitCode::Usage;
|
||||
}
|
||||
const std::string dir = args.positionals.empty() ? "." : args.positionals[0];
|
||||
std::string error;
|
||||
|
||||
policy::WolfPin::Pin pin;
|
||||
if (!policy::WolfPin::load_file(join_path(dir, flag_or(args, "allow", "supply.allow.json")), pin, error)) {
|
||||
out.error(error);
|
||||
return ExitCode::Runtime;
|
||||
}
|
||||
policy::DependencyPolicy manifest;
|
||||
{
|
||||
std::string allow_text;
|
||||
if (!read_file_capped(join_path(dir, flag_or(args, "allow", "supply.allow.json")), allow_text,
|
||||
caps::kMaxPinJsonBytes, error)) {
|
||||
out.error(error);
|
||||
return ExitCode::Runtime;
|
||||
}
|
||||
if (!manifest.parse(allow_text, error)) {
|
||||
out.error(error);
|
||||
return ExitCode::Runtime;
|
||||
}
|
||||
}
|
||||
out.debug(1, "pin ok: wolfssl " + pin.version + " with " + std::to_string(manifest.size()) + " extra dep(s)");
|
||||
|
||||
std::vector<scan::OsvClient::Vuln> findings;
|
||||
bool offline_unknown = false;
|
||||
if (args.flags.find("osv") != args.flags.end()) {
|
||||
scan::OsvClient client;
|
||||
std::vector<scan::OsvClient::Vuln> vulns;
|
||||
if (!client.query("wolfssl", pin.version, vulns, error)) {
|
||||
offline_unknown = true; // default transport is offline by design
|
||||
} else {
|
||||
findings = vulns;
|
||||
}
|
||||
}
|
||||
{
|
||||
std::string adv_text;
|
||||
if (!read_file_capped(join_path(dir, flag_or(args, "advisories", "advisories.json")), adv_text,
|
||||
caps::kMaxAdvisoriesBytes, error)) {
|
||||
out.error(error + " (offline source required)");
|
||||
return ExitCode::Runtime;
|
||||
}
|
||||
std::vector<scan::OsvClient::Vuln> from_file;
|
||||
if (!scan::VulnHook::parse_advisories(adv_text, from_file, error)) {
|
||||
out.error(error);
|
||||
return ExitCode::Runtime;
|
||||
}
|
||||
findings.insert(findings.end(), from_file.begin(), from_file.end());
|
||||
}
|
||||
std::vector<scan::VulnHook::Exception> exceptions;
|
||||
std::string exc_flag = flag_or(args, "exceptions", "");
|
||||
if (!exc_flag.empty()) {
|
||||
std::string exc_text;
|
||||
if (!read_file_capped(join_path(dir, exc_flag), exc_text, caps::kMaxAdvisoriesBytes, error)) {
|
||||
out.error(error);
|
||||
return ExitCode::Runtime;
|
||||
}
|
||||
if (!scan::VulnHook::parse_exceptions(exc_text, exceptions, error)) {
|
||||
out.error(error);
|
||||
return ExitCode::Runtime;
|
||||
}
|
||||
}
|
||||
|
||||
std::string reason;
|
||||
scan::VulnHook::Verdict verdict =
|
||||
scan::VulnHook::evaluate(findings, exceptions, now_unix(), offline_unknown, reason);
|
||||
if (verdict == scan::VulnHook::Verdict::Blocked) {
|
||||
emit_status(out, json, "blocked", reason, findings.size());
|
||||
return ExitCode::Runtime;
|
||||
}
|
||||
if (verdict == scan::VulnHook::Verdict::Disclosed) {
|
||||
out.warn(reason);
|
||||
emit_status(out, json, "disclosed", reason, findings.size());
|
||||
return ExitCode::Ok;
|
||||
}
|
||||
emit_status(out, json, "clean", reason, findings.size());
|
||||
return ExitCode::Ok;
|
||||
}
|
||||
|
||||
ExitCode SupplyCli::run_release(const ParsedArgs& args, Output& out) {
|
||||
const bool json = wants_json(args);
|
||||
if (args.global.show_help) {
|
||||
out.print("usage: molo release --commit <sha> --suite-stamp <file> [--dir .] [--allow supply.allow.json] [--advisories advisories.json] [--exceptions e.json] [--toolchain toolchain.txt] [--tag-file TAG]");
|
||||
return ExitCode::Ok;
|
||||
}
|
||||
std::string bad;
|
||||
if (has_unknown_flag(args, {"commit", "suite-stamp", "dir", "allow", "advisories", "exceptions",
|
||||
"toolchain", "tag-file"},
|
||||
bad)) {
|
||||
out.error("unknown flag '--" + bad + "'");
|
||||
return ExitCode::Usage;
|
||||
}
|
||||
const std::string dir = flag_or(args, "dir", ".");
|
||||
const std::string commit = flag_or(args, "commit", "");
|
||||
const std::string stamp_path = flag_or(args, "suite-stamp", "");
|
||||
std::string error;
|
||||
if (commit.empty() || stamp_path.empty()) {
|
||||
out.error("release needs --commit and --suite-stamp");
|
||||
return ExitCode::Usage;
|
||||
}
|
||||
|
||||
// Step 1: suite green (stamp file written by the base-tree test gate).
|
||||
{
|
||||
std::string stamp;
|
||||
if (!read_file_capped(join_path(dir, stamp_path), stamp, 1024, error) ||
|
||||
trim(stamp) != "PASS") {
|
||||
out.error("release step 1/6 suite: stamp is not PASS (" + error + ")");
|
||||
return ExitCode::Runtime;
|
||||
}
|
||||
out.progress("release 1/6 suite: green");
|
||||
}
|
||||
|
||||
// Step 2: sbom (generate, emit both formats, NTIA check).
|
||||
sbom::SbomDocument doc;
|
||||
std::string spdx_path = join_path(dir, "sbom.spdx.json");
|
||||
std::string cdx_path = join_path(dir, "sbom.cdx.json");
|
||||
{
|
||||
policy::WolfPin::Pin pin;
|
||||
if (!policy::WolfPin::load_file(join_path(dir, flag_or(args, "allow", "supply.allow.json")), pin, error)) {
|
||||
out.error("release step 2/6 sbom: " + error);
|
||||
return ExitCode::Runtime;
|
||||
}
|
||||
policy::DependencyPolicy manifest;
|
||||
{
|
||||
std::string allow_text;
|
||||
if (!read_file_capped(join_path(dir, flag_or(args, "allow", "supply.allow.json")),
|
||||
allow_text, caps::kMaxPinJsonBytes, error) ||
|
||||
!manifest.parse(allow_text, error)) {
|
||||
out.error("release step 2/6 sbom: " + error);
|
||||
return ExitCode::Runtime;
|
||||
}
|
||||
}
|
||||
std::vector<sbom::SbomToolchainEntry> toolchain;
|
||||
{
|
||||
std::string tool_text;
|
||||
if (read_file_capped(join_path(dir, flag_or(args, "toolchain", "toolchain.txt")), tool_text,
|
||||
caps::kMaxToolchainBytes, error)) {
|
||||
std::istringstream in(tool_text);
|
||||
std::string line;
|
||||
while (std::getline(in, line)) {
|
||||
line = trim(line);
|
||||
if (line.empty() || line[0] == '#') continue;
|
||||
auto at = line.find('@');
|
||||
if (at == std::string::npos) {
|
||||
out.error("release step 2/6 sbom: bad toolchain line '" + line + "'");
|
||||
return ExitCode::Runtime;
|
||||
}
|
||||
toolchain.push_back({line.substr(0, at), line.substr(at + 1)});
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!sbom::SbomGenerator::generate(commit, toolchain, pin, manifest, molo::kMoloVersion,
|
||||
sbom::SbomGenerator::utc_now(), doc, error)) {
|
||||
out.error("release step 2/6 sbom: " + error);
|
||||
return ExitCode::Runtime;
|
||||
}
|
||||
std::vector<std::string> missing;
|
||||
if (!sbom::SbomCheck::check_ntia(doc, missing, error) || !missing.empty()) {
|
||||
out.error("release step 2/6 sbom: NTIA check failed");
|
||||
return ExitCode::Runtime;
|
||||
}
|
||||
if (!sbom::SpdxEmitter::emit_file(doc, spdx_path, error)) {
|
||||
out.error("release step 2/6 sbom: " + error);
|
||||
return ExitCode::Runtime;
|
||||
}
|
||||
if (!sbom::CycloneDxEmitter::emit_file(doc, cdx_path, error)) {
|
||||
out.error("release step 2/6 sbom: " + error);
|
||||
return ExitCode::Runtime;
|
||||
}
|
||||
out.progress("release 2/6 sbom: spdx+cdx written");
|
||||
}
|
||||
|
||||
// Step 3: scan (offline advisories; blocked fails the release).
|
||||
{
|
||||
std::string adv_text;
|
||||
if (!read_file_capped(join_path(dir, flag_or(args, "advisories", "advisories.json")), adv_text,
|
||||
caps::kMaxAdvisoriesBytes, error)) {
|
||||
out.error("release step 3/6 scan: " + error);
|
||||
return ExitCode::Runtime;
|
||||
}
|
||||
std::vector<scan::OsvClient::Vuln> findings;
|
||||
if (!scan::VulnHook::parse_advisories(adv_text, findings, error)) {
|
||||
out.error("release step 3/6 scan: " + error);
|
||||
return ExitCode::Runtime;
|
||||
}
|
||||
std::vector<scan::VulnHook::Exception> exceptions;
|
||||
std::string exc_flag = flag_or(args, "exceptions", "");
|
||||
if (!exc_flag.empty()) {
|
||||
std::string exc_text;
|
||||
if (!read_file_capped(join_path(dir, exc_flag), exc_text, caps::kMaxAdvisoriesBytes, error) ||
|
||||
!scan::VulnHook::parse_exceptions(exc_text, exceptions, error)) {
|
||||
out.error("release step 3/6 scan: " + error);
|
||||
return ExitCode::Runtime;
|
||||
}
|
||||
}
|
||||
std::string reason;
|
||||
if (scan::VulnHook::evaluate(findings, exceptions, now_unix(), false, reason) ==
|
||||
scan::VulnHook::Verdict::Blocked) {
|
||||
out.error("release step 3/6 scan: " + reason);
|
||||
return ExitCode::Runtime;
|
||||
}
|
||||
out.progress("release 3/6 scan: " + reason);
|
||||
}
|
||||
|
||||
// Step 4: provenance plus attestation over the emitted SBOM files.
|
||||
std::string statement_path = join_path(dir, "provenance.json");
|
||||
{
|
||||
std::string digest_spdx, digest_cdx;
|
||||
if (!molo::embed::Sha256::hex_of_file(spdx_path, digest_spdx) ||
|
||||
!molo::embed::Sha256::hex_of_file(cdx_path, digest_cdx)) {
|
||||
out.error("release step 4/6 provenance: cannot hash sbom files");
|
||||
return ExitCode::Runtime;
|
||||
}
|
||||
std::vector<attest::ProvenanceBuilder::Subject> subjects = {
|
||||
{"sbom.spdx.json", digest_spdx},
|
||||
{"sbom.cdx.json", digest_cdx},
|
||||
};
|
||||
std::vector<std::string> tool_names;
|
||||
for (const auto& t : doc.toolchain) tool_names.push_back(t.name + "@" + t.version);
|
||||
std::string predicate = attest::ProvenanceBuilder::build(
|
||||
"https://moloapp.dev/builder/v1", commit, tool_names, subjects, "molo release");
|
||||
std::string statement;
|
||||
if (!attest::Attestor::statement(subjects, caps::kSlsaPredicateType, predicate, statement,
|
||||
error)) {
|
||||
out.error("release step 4/6 provenance: " + error);
|
||||
return ExitCode::Runtime;
|
||||
}
|
||||
if (!write_file(statement_path, statement, error)) {
|
||||
out.error("release step 4/6 provenance: " + error);
|
||||
return ExitCode::Runtime;
|
||||
}
|
||||
out.progress("release 4/6 provenance: written");
|
||||
}
|
||||
|
||||
// Step 5: sign the statement bundle.
|
||||
{
|
||||
std::string bundle_path = join_path(dir, "bundle.json");
|
||||
if (!attest::Signer::sign(statement_path, bundle_path, error)) {
|
||||
out.error("release step 5/6 sign: " + error);
|
||||
return ExitCode::Runtime;
|
||||
}
|
||||
out.progress("release 5/6 sign: bundle written");
|
||||
}
|
||||
|
||||
// Step 6: tag stamp.
|
||||
{
|
||||
std::string tag = std::string(molo::kMoloVersion) + " " + commit + "\n";
|
||||
if (!write_file(join_path(dir, flag_or(args, "tag-file", "TAG")), tag, error)) {
|
||||
out.error("release step 6/6 tag: " + error);
|
||||
return ExitCode::Runtime;
|
||||
}
|
||||
out.progress("release 6/6 tag: written");
|
||||
}
|
||||
|
||||
emit_status(out, json, "released", commit, 6);
|
||||
return ExitCode::Ok;
|
||||
}
|
||||
|
||||
} // namespace molo::supply::cli
|
||||
@@ -0,0 +1,44 @@
|
||||
#pragma once
|
||||
|
||||
#if __has_include("cli/cli/exit_code.hpp")
|
||||
#include "cli/cli/exit_code.hpp"
|
||||
#elif __has_include("cli/exit_code.hpp")
|
||||
#include "cli/exit_code.hpp"
|
||||
#else
|
||||
#include "../adapters/cli/cli/exit_code.hpp" // ADAPTER fallback for isolated builds
|
||||
#endif
|
||||
|
||||
#if __has_include("cli/cli/arg_parser.hpp")
|
||||
#include "cli/cli/arg_parser.hpp"
|
||||
#elif __has_include("cli/arg_parser.hpp")
|
||||
#include "cli/arg_parser.hpp"
|
||||
#else
|
||||
#include "../adapters/cli/cli/arg_parser.hpp" // ADAPTER fallback for isolated builds
|
||||
#endif
|
||||
|
||||
#if __has_include("cli/cli/output.hpp")
|
||||
#include "cli/cli/output.hpp"
|
||||
#elif __has_include("cli/output.hpp")
|
||||
#include "cli/output.hpp"
|
||||
#else
|
||||
#include "../adapters/cli/cli/output.hpp" // ADAPTER fallback for isolated builds
|
||||
#endif
|
||||
|
||||
namespace molo::supply::cli {
|
||||
|
||||
// Thin CLI handlers wired by CliApp::build_tree() in the base tree. Each
|
||||
// handler only parses args, delegates to the policy/sbom/scan/attest classes,
|
||||
// and renders through Output. No supply logic lives here.
|
||||
class SupplyCli {
|
||||
public:
|
||||
SupplyCli() = delete;
|
||||
|
||||
// `molo verify [dir]`: offline artifact check, exit 0/1/2.
|
||||
static molo::cli::ExitCode run_verify(const molo::cli::ParsedArgs& args, molo::cli::Output& out);
|
||||
// `molo supply-check [dir]`: pin plus allow-list plus advisory gate.
|
||||
static molo::cli::ExitCode run_check(const molo::cli::ParsedArgs& args, molo::cli::Output& out);
|
||||
// `molo release --commit <sha> --suite-stamp <file>`: ordered release gate.
|
||||
static molo::cli::ExitCode run_release(const molo::cli::ParsedArgs& args, molo::cli::Output& out);
|
||||
};
|
||||
|
||||
} // namespace molo::supply::cli
|
||||
@@ -0,0 +1,368 @@
|
||||
#include "../common/Json.hpp"
|
||||
|
||||
#include <cctype>
|
||||
#include <cstdio>
|
||||
|
||||
#include "../caps.hpp"
|
||||
|
||||
namespace molo::supply::common {
|
||||
|
||||
namespace {
|
||||
|
||||
class Parser {
|
||||
public:
|
||||
explicit Parser(std::string_view text) : text_(text) {}
|
||||
|
||||
bool run(Json::Value& out, std::string& error) {
|
||||
skip_ws();
|
||||
if (!parse_value(out, 0, error)) return false;
|
||||
skip_ws();
|
||||
if (pos_ != text_.size()) {
|
||||
error = "trailing characters at offset " + std::to_string(pos_);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private:
|
||||
bool parse_value(Json::Value& out, std::size_t depth, std::string& error) {
|
||||
if (depth > caps::kMaxJsonDepth) {
|
||||
error = "nesting over cap";
|
||||
return false;
|
||||
}
|
||||
if (pos_ >= text_.size()) {
|
||||
error = "unexpected end of input";
|
||||
return false;
|
||||
}
|
||||
char c = text_[pos_];
|
||||
if (c == '{') return parse_object(out, depth, error);
|
||||
if (c == '[') return parse_array(out, depth, error);
|
||||
if (c == '"') {
|
||||
out.type = Json::Value::Type::String;
|
||||
return parse_string(out.str, error);
|
||||
}
|
||||
if (c == 't' || c == 'f') return parse_bool(out, error);
|
||||
if (c == 'n') return parse_null(out, error);
|
||||
if (c == '-' || (c >= '0' && c <= '9')) return parse_number(out, error);
|
||||
error = std::string("unexpected character '") + c + "' at offset " + std::to_string(pos_);
|
||||
return false;
|
||||
}
|
||||
|
||||
bool parse_object(Json::Value& out, std::size_t depth, std::string& error) {
|
||||
++pos_; // consume '{'
|
||||
out.type = Json::Value::Type::Object;
|
||||
skip_ws();
|
||||
if (peek('}')) {
|
||||
++pos_;
|
||||
return true;
|
||||
}
|
||||
while (true) {
|
||||
skip_ws();
|
||||
if (pos_ >= text_.size() || text_[pos_] != '"') {
|
||||
error = "object key must be a string at offset " + std::to_string(pos_);
|
||||
return false;
|
||||
}
|
||||
std::string key;
|
||||
if (!parse_string(key, error)) return false;
|
||||
skip_ws();
|
||||
if (!peek(':')) {
|
||||
error = "expected ':' at offset " + std::to_string(pos_);
|
||||
return false;
|
||||
}
|
||||
++pos_;
|
||||
skip_ws();
|
||||
Json::Value v;
|
||||
if (!parse_value(v, depth + 1, error)) return false;
|
||||
out.fields[key] = v;
|
||||
skip_ws();
|
||||
if (peek(',')) {
|
||||
++pos_;
|
||||
continue;
|
||||
}
|
||||
if (peek('}')) {
|
||||
++pos_;
|
||||
return true;
|
||||
}
|
||||
error = "expected ',' or '}' at offset " + std::to_string(pos_);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool parse_array(Json::Value& out, std::size_t depth, std::string& error) {
|
||||
++pos_; // consume '['
|
||||
out.type = Json::Value::Type::Array;
|
||||
skip_ws();
|
||||
if (peek(']')) {
|
||||
++pos_;
|
||||
return true;
|
||||
}
|
||||
while (true) {
|
||||
skip_ws();
|
||||
Json::Value v;
|
||||
if (!parse_value(v, depth + 1, error)) return false;
|
||||
out.items.push_back(v);
|
||||
skip_ws();
|
||||
if (peek(',')) {
|
||||
++pos_;
|
||||
continue;
|
||||
}
|
||||
if (peek(']')) {
|
||||
++pos_;
|
||||
return true;
|
||||
}
|
||||
error = "expected ',' or ']' at offset " + std::to_string(pos_);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool parse_string(std::string& out, std::string& error) {
|
||||
++pos_; // consume opening quote
|
||||
while (pos_ < text_.size()) {
|
||||
char c = text_[pos_++];
|
||||
if (c == '"') return true;
|
||||
if (c != '\\') {
|
||||
out.push_back(c);
|
||||
continue;
|
||||
}
|
||||
if (pos_ >= text_.size()) break;
|
||||
char e = text_[pos_++];
|
||||
switch (e) {
|
||||
case '"': out.push_back('"'); break;
|
||||
case '\\': out.push_back('\\'); break;
|
||||
case '/': out.push_back('/'); break;
|
||||
case 'b': out.push_back('\b'); break;
|
||||
case 'f': out.push_back('\f'); break;
|
||||
case 'n': out.push_back('\n'); break;
|
||||
case 'r': out.push_back('\r'); break;
|
||||
case 't': out.push_back('\t'); break;
|
||||
case 'u': {
|
||||
if (pos_ + 4 > text_.size()) {
|
||||
error = "bad unicode escape";
|
||||
return false;
|
||||
}
|
||||
unsigned code = 0;
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
char h = text_[pos_++];
|
||||
code <<= 4;
|
||||
if (h >= '0' && h <= '9') code |= static_cast<unsigned>(h - '0');
|
||||
else if (h >= 'a' && h <= 'f') code |= static_cast<unsigned>(h - 'a' + 10);
|
||||
else if (h >= 'A' && h <= 'F') code |= static_cast<unsigned>(h - 'A' + 10);
|
||||
else {
|
||||
error = "bad unicode escape";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (code < 0x80) {
|
||||
out.push_back(static_cast<char>(code));
|
||||
} else if (code < 0x800) {
|
||||
out.push_back(static_cast<char>(0xC0 | (code >> 6)));
|
||||
out.push_back(static_cast<char>(0x80 | (code & 0x3F)));
|
||||
} else {
|
||||
out.push_back(static_cast<char>(0xE0 | (code >> 12)));
|
||||
out.push_back(static_cast<char>(0x80 | ((code >> 6) & 0x3F)));
|
||||
out.push_back(static_cast<char>(0x80 | (code & 0x3F)));
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
error = std::string("bad escape '\\") + e + "'";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
error = "unterminated string";
|
||||
return false;
|
||||
}
|
||||
|
||||
bool parse_bool(Json::Value& out, std::string& error) {
|
||||
if (consume("true")) {
|
||||
out.type = Json::Value::Type::Bool;
|
||||
out.boolean = true;
|
||||
return true;
|
||||
}
|
||||
if (consume("false")) {
|
||||
out.type = Json::Value::Type::Bool;
|
||||
out.boolean = false;
|
||||
return true;
|
||||
}
|
||||
error = "bad literal at offset " + std::to_string(pos_);
|
||||
return false;
|
||||
}
|
||||
|
||||
bool parse_null(Json::Value& out, std::string& error) {
|
||||
if (!consume("null")) {
|
||||
error = "bad literal at offset " + std::to_string(pos_);
|
||||
return false;
|
||||
}
|
||||
out.type = Json::Value::Type::Null;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool parse_number(Json::Value& out, std::string& error) {
|
||||
std::size_t start = pos_;
|
||||
if (peek('-')) ++pos_;
|
||||
if (pos_ >= text_.size()) {
|
||||
error = "bad number";
|
||||
return false;
|
||||
}
|
||||
if (text_[pos_] == '0') {
|
||||
++pos_;
|
||||
} else if (text_[pos_] >= '1' && text_[pos_] <= '9') {
|
||||
while (pos_ < text_.size() && text_[pos_] >= '0' && text_[pos_] <= '9') ++pos_;
|
||||
} else {
|
||||
error = "bad number";
|
||||
return false;
|
||||
}
|
||||
if (peek('.')) {
|
||||
++pos_;
|
||||
if (pos_ >= text_.size() || text_[pos_] < '0' || text_[pos_] > '9') {
|
||||
error = "bad number";
|
||||
return false;
|
||||
}
|
||||
while (pos_ < text_.size() && text_[pos_] >= '0' && text_[pos_] <= '9') ++pos_;
|
||||
}
|
||||
if (peek('e') || peek('E')) {
|
||||
++pos_;
|
||||
if (peek('+') || peek('-')) ++pos_;
|
||||
if (pos_ >= text_.size() || text_[pos_] < '0' || text_[pos_] > '9') {
|
||||
error = "bad number";
|
||||
return false;
|
||||
}
|
||||
while (pos_ < text_.size() && text_[pos_] >= '0' && text_[pos_] <= '9') ++pos_;
|
||||
}
|
||||
out.type = Json::Value::Type::Number;
|
||||
out.number = std::string(text_.substr(start, pos_ - start));
|
||||
return true;
|
||||
}
|
||||
|
||||
void skip_ws() {
|
||||
while (pos_ < text_.size()) {
|
||||
char c = text_[pos_];
|
||||
if (c == ' ' || c == '\t' || c == '\n' || c == '\r') {
|
||||
++pos_;
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool peek(char c) const { return pos_ < text_.size() && text_[pos_] == c; }
|
||||
|
||||
bool consume(std::string_view word) {
|
||||
if (text_.substr(pos_, word.size()) == word) {
|
||||
pos_ += word.size();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
std::string_view text_;
|
||||
std::size_t pos_ = 0;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
std::string Json::escape(std::string_view in) {
|
||||
std::string out;
|
||||
out.reserve(in.size() + 8);
|
||||
char buf[8];
|
||||
for (unsigned char c : in) {
|
||||
switch (c) {
|
||||
case '"': out += "\\\""; break;
|
||||
case '\\': out += "\\\\"; break;
|
||||
case '\b': out += "\\b"; break;
|
||||
case '\f': out += "\\f"; break;
|
||||
case '\n': out += "\\n"; break;
|
||||
case '\r': out += "\\r"; break;
|
||||
case '\t': out += "\\t"; break;
|
||||
default:
|
||||
if (c < 0x20) {
|
||||
std::snprintf(buf, sizeof(buf), "\\u%04x", c);
|
||||
out += buf;
|
||||
} else {
|
||||
out.push_back(static_cast<char>(c));
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string Json::quote(std::string_view in) { return "\"" + escape(in) + "\""; }
|
||||
|
||||
std::string Json::indent_str(int level) { return std::string(static_cast<std::size_t>(level) * 2, ' '); }
|
||||
|
||||
std::string Json::object(const std::map<std::string, std::string>& rendered, int indent) {
|
||||
if (rendered.empty()) return "{}";
|
||||
std::string out = "{\n";
|
||||
bool first = true;
|
||||
for (const auto& [key, value] : rendered) {
|
||||
if (!first) out += ",\n";
|
||||
first = false;
|
||||
out += indent_str(indent + 1) + quote(key) + ": " + value;
|
||||
}
|
||||
out += "\n" + indent_str(indent) + "}";
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string Json::array(const std::vector<std::string>& rendered, int indent) {
|
||||
if (rendered.empty()) return "[]";
|
||||
std::string out = "[\n";
|
||||
bool first = true;
|
||||
for (const auto& item : rendered) {
|
||||
if (!first) out += ",\n";
|
||||
first = false;
|
||||
out += indent_str(indent + 1) + item;
|
||||
}
|
||||
out += "\n" + indent_str(indent) + "]";
|
||||
return out;
|
||||
}
|
||||
|
||||
bool Json::parse(std::string_view text, Value& out, std::string& error) {
|
||||
if (text.size() > caps::kMaxJsonBytes) {
|
||||
error = "json input over 4 MiB cap";
|
||||
return false;
|
||||
}
|
||||
Parser parser(text);
|
||||
return parser.run(out, error);
|
||||
}
|
||||
|
||||
const Json::Value* Json::find(const Value& obj, std::string_view key) {
|
||||
if (obj.type != Value::Type::Object) return nullptr;
|
||||
auto it = obj.fields.find(std::string(key));
|
||||
if (it == obj.fields.end()) return nullptr;
|
||||
return &it->second;
|
||||
}
|
||||
|
||||
std::string Json::string_or(const Value& v, const std::string& fallback) {
|
||||
if (v.type == Value::Type::String) return v.str;
|
||||
if (v.type == Value::Type::Number) return v.number;
|
||||
return fallback;
|
||||
}
|
||||
|
||||
double Json::number_or(const Value& v, double fallback) {
|
||||
if (v.type == Value::Type::Number) {
|
||||
try {
|
||||
return std::stod(v.number);
|
||||
} catch (...) {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
if (v.type == Value::Type::String) {
|
||||
try {
|
||||
return std::stod(v.str);
|
||||
} catch (...) {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
bool Json::is_hex64(std::string_view s) {
|
||||
if (s.size() != 64) return false;
|
||||
for (char c : s) {
|
||||
bool hex = (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
|
||||
if (!hex) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace molo::supply::common
|
||||
@@ -0,0 +1,44 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace molo::supply::common {
|
||||
|
||||
// Minimal JSON parser plus canonical renderer (sorted keys, LF, 2 spaces).
|
||||
// Only dependency-free stdlib code; one shared home so no other supply file
|
||||
// parses or escapes JSON on its own.
|
||||
class Json {
|
||||
public:
|
||||
struct Value {
|
||||
enum class Type { Null, Bool, Number, String, Array, Object };
|
||||
Type type = Type::Null;
|
||||
bool boolean = false;
|
||||
std::string number;
|
||||
std::string str;
|
||||
std::vector<Value> items;
|
||||
std::map<std::string, Value> fields;
|
||||
};
|
||||
|
||||
Json() = delete;
|
||||
|
||||
static std::string escape(std::string_view in);
|
||||
static std::string quote(std::string_view in);
|
||||
static std::string indent_str(int level);
|
||||
|
||||
// Render an object from pre-rendered values. Keys sort via std::map.
|
||||
static std::string object(const std::map<std::string, std::string>& rendered, int indent);
|
||||
static std::string array(const std::vector<std::string>& rendered, int indent);
|
||||
|
||||
static bool parse(std::string_view text, Value& out, std::string& error);
|
||||
|
||||
static const Value* find(const Value& obj, std::string_view key);
|
||||
static std::string string_or(const Value& v, const std::string& fallback);
|
||||
static double number_or(const Value& v, double fallback);
|
||||
static bool is_hex64(std::string_view s);
|
||||
};
|
||||
|
||||
} // namespace molo::supply::common
|
||||
@@ -0,0 +1,92 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
#include "../caps.hpp"
|
||||
#include "../common/Json.hpp"
|
||||
|
||||
namespace molo::supply::policy {
|
||||
|
||||
// Parsed allow-list of third-party dependencies from supply.allow.json.
|
||||
// Reads the top-level "dependencies" array; the "wolfssl" pin object belongs
|
||||
// to WolfPin. Header-only: parsing is small and has no platform dependency.
|
||||
class DependencyPolicy {
|
||||
public:
|
||||
struct Entry {
|
||||
std::string name;
|
||||
std::string version;
|
||||
std::string sha256;
|
||||
std::string source;
|
||||
std::string license;
|
||||
};
|
||||
|
||||
bool parse(std::string_view text, std::string& error) {
|
||||
entries_.clear();
|
||||
if (text.size() > caps::kMaxPinJsonBytes) {
|
||||
error = "allow-list over 64 KiB cap";
|
||||
return false;
|
||||
}
|
||||
common::Json::Value root;
|
||||
if (!common::Json::parse(text, root, error)) return false;
|
||||
if (root.type != common::Json::Value::Type::Object) {
|
||||
error = "allow-list root must be an object";
|
||||
return false;
|
||||
}
|
||||
const common::Json::Value* deps = common::Json::find(root, "dependencies");
|
||||
if (deps == nullptr) return true; // no generic entries: wolfssl-only file
|
||||
if (deps->type != common::Json::Value::Type::Array) {
|
||||
error = "\"dependencies\" must be an array";
|
||||
return false;
|
||||
}
|
||||
for (const auto& item : deps->items) {
|
||||
if (entries_.size() >= caps::kMaxComponents) {
|
||||
error = "dependency count over 64 cap";
|
||||
return false;
|
||||
}
|
||||
if (item.type != common::Json::Value::Type::Object) {
|
||||
error = "dependency entry must be an object";
|
||||
return false;
|
||||
}
|
||||
Entry e;
|
||||
const common::Json::Value* v = nullptr;
|
||||
v = common::Json::find(item, "name");
|
||||
e.name = (v == nullptr) ? "" : common::Json::string_or(*v, "");
|
||||
v = common::Json::find(item, "version");
|
||||
e.version = (v == nullptr) ? "" : common::Json::string_or(*v, "");
|
||||
v = common::Json::find(item, "sha256");
|
||||
e.sha256 = (v == nullptr) ? "" : common::Json::string_or(*v, "");
|
||||
v = common::Json::find(item, "source");
|
||||
e.source = (v == nullptr) ? "" : common::Json::string_or(*v, "");
|
||||
v = common::Json::find(item, "license");
|
||||
e.license = (v == nullptr) ? "" : common::Json::string_or(*v, "");
|
||||
if (e.name.empty() || e.version.empty() || e.sha256.empty() || e.source.empty() ||
|
||||
e.license.empty()) {
|
||||
error = "dependency entry missing name/version/sha256/source/license";
|
||||
return false;
|
||||
}
|
||||
if (!common::Json::is_hex64(e.sha256)) {
|
||||
error = "dependency '" + e.name + "' sha256 is not 64 hex chars";
|
||||
return false;
|
||||
}
|
||||
entries_.push_back(e);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
const std::vector<Entry>& entries() const { return entries_; }
|
||||
std::size_t size() const { return entries_.size(); }
|
||||
|
||||
const Entry* find(const std::string& name) const {
|
||||
for (const auto& e : entries_) {
|
||||
if (e.name == name) return &e;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
private:
|
||||
std::vector<Entry> entries_;
|
||||
};
|
||||
|
||||
} // namespace molo::supply::policy
|
||||
@@ -0,0 +1,91 @@
|
||||
#include "../policy/WolfPin.hpp"
|
||||
|
||||
#include <cstdio>
|
||||
|
||||
#include "../caps.hpp"
|
||||
#include "../common/Json.hpp"
|
||||
|
||||
namespace molo::supply::policy {
|
||||
|
||||
bool WolfPin::parse_pin(std::string_view text, Pin& out, std::string& error) {
|
||||
out = Pin{};
|
||||
if (text.size() > caps::kMaxPinJsonBytes) {
|
||||
error = "pin json over 64 KiB cap";
|
||||
return false;
|
||||
}
|
||||
common::Json::Value root;
|
||||
if (!common::Json::parse(text, root, error)) return false;
|
||||
if (root.type != common::Json::Value::Type::Object) {
|
||||
error = "pin root must be an object";
|
||||
return false;
|
||||
}
|
||||
const common::Json::Value* node = common::Json::find(root, "wolfssl");
|
||||
if (node == nullptr || node->type != common::Json::Value::Type::Object) {
|
||||
error = "missing \"wolfssl\" pin object";
|
||||
return false;
|
||||
}
|
||||
const common::Json::Value* v = nullptr;
|
||||
v = common::Json::find(*node, "version");
|
||||
out.version = (v == nullptr) ? "" : common::Json::string_or(*v, "");
|
||||
v = common::Json::find(*node, "sha256");
|
||||
out.sha256 = (v == nullptr) ? "" : common::Json::string_or(*v, "");
|
||||
v = common::Json::find(*node, "source");
|
||||
out.source = (v == nullptr) ? "" : common::Json::string_or(*v, "");
|
||||
v = common::Json::find(*node, "license");
|
||||
out.license = (v == nullptr) ? "" : common::Json::string_or(*v, "");
|
||||
v = common::Json::find(*node, "receipt");
|
||||
out.receipt = (v == nullptr) ? "" : common::Json::string_or(*v, "");
|
||||
if (out.version.empty() || out.sha256.empty() || out.source.empty() || out.license.empty() ||
|
||||
out.receipt.empty()) {
|
||||
error = "wolfssl pin missing version/sha256/source/license/receipt";
|
||||
return false;
|
||||
}
|
||||
if (!common::Json::is_hex64(out.sha256)) {
|
||||
error = "wolfssl pin sha256 is not 64 hex chars";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool WolfPin::load_file(const std::string& path, Pin& out, std::string& error) {
|
||||
std::FILE* f = std::fopen(path.c_str(), "rb");
|
||||
if (f == nullptr) {
|
||||
error = "cannot open pin file '" + path + "'";
|
||||
return false;
|
||||
}
|
||||
std::string text;
|
||||
char chunk[4096];
|
||||
std::size_t n = 0;
|
||||
bool ok = true;
|
||||
while ((n = std::fread(chunk, 1, sizeof(chunk), f)) > 0) {
|
||||
if (text.size() + n > caps::kMaxPinJsonBytes) {
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
text.append(chunk, n);
|
||||
}
|
||||
if (std::ferror(f) != 0) ok = false;
|
||||
std::fclose(f);
|
||||
if (!ok) {
|
||||
error = "cannot read pin file '" + path + "' (over 64 KiB cap or I/O error)";
|
||||
return false;
|
||||
}
|
||||
return parse_pin(text, out, error);
|
||||
}
|
||||
|
||||
WolfPin::Check WolfPin::check(const Pin& pin, std::string_view version, std::string_view sha256) {
|
||||
if (version != pin.version) return Check::VersionMismatch;
|
||||
if (sha256 != pin.sha256) return Check::HashMismatch;
|
||||
return Check::Ok;
|
||||
}
|
||||
|
||||
const char* WolfPin::to_string(Check c) {
|
||||
switch (c) {
|
||||
case Check::Ok: return "ok";
|
||||
case Check::VersionMismatch: return "version-mismatch";
|
||||
case Check::HashMismatch: return "hash-mismatch";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
} // namespace molo::supply::policy
|
||||
@@ -0,0 +1,32 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace molo::supply::policy {
|
||||
|
||||
// The pinned wolfSSL release: the sole third-party dependency. Parsed from
|
||||
// the "wolfssl" object of supply.allow.json:
|
||||
// {"wolfssl": {"version": "X.Y.Z", "sha256": "<64hex>", "source": "...",
|
||||
// "license": "...", "receipt": "..."}}.
|
||||
class WolfPin {
|
||||
public:
|
||||
struct Pin {
|
||||
std::string version;
|
||||
std::string sha256;
|
||||
std::string source;
|
||||
std::string license;
|
||||
std::string receipt;
|
||||
};
|
||||
|
||||
enum class Check { Ok, VersionMismatch, HashMismatch };
|
||||
|
||||
WolfPin() = delete;
|
||||
|
||||
static bool parse_pin(std::string_view text, Pin& out, std::string& error);
|
||||
static bool load_file(const std::string& path, Pin& out, std::string& error);
|
||||
static Check check(const Pin& pin, std::string_view version, std::string_view sha256);
|
||||
static const char* to_string(Check c);
|
||||
};
|
||||
|
||||
} // namespace molo::supply::policy
|
||||
@@ -0,0 +1,98 @@
|
||||
#include "../sbom/CycloneDxEmitter.hpp"
|
||||
|
||||
#include <cstdio>
|
||||
#include <map>
|
||||
|
||||
#include "../caps.hpp"
|
||||
#include "../common/Json.hpp"
|
||||
|
||||
#if __has_include("cli/embed/sha256.hpp")
|
||||
#include "cli/embed/sha256.hpp"
|
||||
#elif __has_include("embed/sha256.hpp")
|
||||
#include "embed/sha256.hpp"
|
||||
#else
|
||||
#include "../adapters/cli/embed/sha256.hpp" // ADAPTER fallback for isolated builds
|
||||
#endif
|
||||
|
||||
namespace molo::supply::sbom {
|
||||
|
||||
namespace {
|
||||
|
||||
std::string component_json(const SbomComponent& c, int indent) {
|
||||
using common::Json;
|
||||
std::map<std::string, std::string> hash;
|
||||
hash["alg"] = Json::quote("SHA-256");
|
||||
hash["content"] = Json::quote(c.sha256);
|
||||
std::map<std::string, std::string> comp;
|
||||
comp["bom-ref"] = Json::quote(c.name + "@" + c.version);
|
||||
comp["hashes"] = Json::array({Json::object(hash, indent + 2)}, indent + 1);
|
||||
comp["licenses"] = Json::array({Json::object({{"license", Json::object({{"name", Json::quote(c.license)}}, indent + 3)}}, indent + 2)}, indent + 1);
|
||||
comp["name"] = Json::quote(c.name);
|
||||
comp["supplier"] = Json::object({{"name", Json::quote(c.supplier)}}, indent + 1);
|
||||
comp["type"] = Json::quote("library");
|
||||
comp["version"] = Json::quote(c.version);
|
||||
return Json::object(comp, indent);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool CycloneDxEmitter::emit_json(const SbomDocument& doc, std::string& out, std::string& error) {
|
||||
using common::Json;
|
||||
out.clear();
|
||||
if (doc.components.size() > caps::kMaxComponents) {
|
||||
error = "component count over 64 cap";
|
||||
return false;
|
||||
}
|
||||
std::vector<std::string> tools;
|
||||
for (const auto& t : doc.toolchain) {
|
||||
std::map<std::string, std::string> tool;
|
||||
tool["name"] = Json::quote(t.name);
|
||||
tool["version"] = Json::quote(t.version);
|
||||
tools.push_back(Json::object(tool, 3));
|
||||
}
|
||||
std::map<std::string, std::string> metadata;
|
||||
metadata["component"] = Json::object(
|
||||
{{"bom-ref", Json::quote("moloapp@" + doc.doc_version)},
|
||||
{"name", Json::quote("moloapp")},
|
||||
{"type", Json::quote("application")},
|
||||
{"version", Json::quote(doc.doc_version)}},
|
||||
2);
|
||||
metadata["timestamp"] = Json::quote(doc.created_iso8601);
|
||||
metadata["tools"] = Json::object({{"components", Json::array(tools, 3)}}, 2);
|
||||
|
||||
std::vector<std::string> components;
|
||||
for (const auto& c : doc.components) components.push_back(component_json(c, 2));
|
||||
|
||||
const std::string seed = molo::embed::Sha256::hex_of_string("moloapp-cdx:" + doc.commit);
|
||||
std::map<std::string, std::string> root;
|
||||
root["bomFormat"] = Json::quote("CycloneDX");
|
||||
root["components"] = Json::array(components, 1);
|
||||
root["metadata"] = Json::object(metadata, 1);
|
||||
root["serialNumber"] = Json::quote("urn:uuid:00000000-0000-4000-8000-" + seed.substr(0, 12));
|
||||
root["specVersion"] = Json::quote("1.6");
|
||||
root["version"] = "1";
|
||||
out = Json::object(root, 0) + "\n";
|
||||
if (out.size() > caps::kMaxSbomBytes) {
|
||||
out.clear();
|
||||
error = "CycloneDX output over 1 MiB cap";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CycloneDxEmitter::emit_file(const SbomDocument& doc, const std::string& path,
|
||||
std::string& error) {
|
||||
std::string text;
|
||||
if (!emit_json(doc, text, error)) return false;
|
||||
std::FILE* f = std::fopen(path.c_str(), "wb");
|
||||
if (f == nullptr) {
|
||||
error = "cannot open '" + path + "' for writing";
|
||||
return false;
|
||||
}
|
||||
std::size_t wrote = std::fwrite(text.data(), 1, text.size(), f);
|
||||
bool ok = wrote == text.size() && std::fclose(f) == 0;
|
||||
if (!ok) error = "failed writing '" + path + "'";
|
||||
return ok;
|
||||
}
|
||||
|
||||
} // namespace molo::supply::sbom
|
||||
@@ -0,0 +1,20 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
|
||||
#include "../sbom/Types.hpp"
|
||||
|
||||
namespace molo::supply::sbom {
|
||||
|
||||
// CycloneDX 1.6 JSON emitter. Renders the same (name, version, sha256)
|
||||
// triples as SpdxEmitter from the same document. Canonical form only: keys
|
||||
// sorted, LF line endings, 2-space indent, single trailing newline.
|
||||
class CycloneDxEmitter {
|
||||
public:
|
||||
CycloneDxEmitter() = delete;
|
||||
|
||||
static bool emit_json(const SbomDocument& doc, std::string& out, std::string& error);
|
||||
static bool emit_file(const SbomDocument& doc, const std::string& path, std::string& error);
|
||||
};
|
||||
|
||||
} // namespace molo::supply::sbom
|
||||
@@ -0,0 +1,23 @@
|
||||
#include "../sbom/SbomCheck.hpp"
|
||||
|
||||
#include "../common/Json.hpp"
|
||||
|
||||
namespace molo::supply::sbom {
|
||||
|
||||
bool SbomCheck::check_ntia(const SbomDocument& doc, std::vector<std::string>& missing,
|
||||
std::string& error) {
|
||||
missing.clear();
|
||||
error.clear();
|
||||
if (doc.commit.empty()) missing.push_back("document.commit");
|
||||
for (std::size_t i = 0; i < doc.components.size(); ++i) {
|
||||
const SbomComponent& c = doc.components[i];
|
||||
std::string base = "components[" + std::to_string(i) + "]";
|
||||
if (c.name.empty()) missing.push_back(base + ".name");
|
||||
if (c.version.empty()) missing.push_back(base + ".version");
|
||||
if (!common::Json::is_hex64(c.sha256)) missing.push_back(base + ".sha256");
|
||||
if (c.supplier.empty() && c.source.empty()) missing.push_back(base + ".supplier");
|
||||
}
|
||||
return missing.empty();
|
||||
}
|
||||
|
||||
} // namespace molo::supply::sbom
|
||||
@@ -0,0 +1,20 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "../sbom/Types.hpp"
|
||||
|
||||
namespace molo::supply::sbom {
|
||||
|
||||
// NTIA minimum-elements check: every component needs a supplier, a name, a
|
||||
// version and a unique identifier (sha256); the document needs a commit.
|
||||
class SbomCheck {
|
||||
public:
|
||||
SbomCheck() = delete;
|
||||
|
||||
static bool check_ntia(const SbomDocument& doc, std::vector<std::string>& missing,
|
||||
std::string& error);
|
||||
};
|
||||
|
||||
} // namespace molo::supply::sbom
|
||||
@@ -0,0 +1,122 @@
|
||||
#include "../sbom/SbomGenerator.hpp"
|
||||
|
||||
#include <chrono>
|
||||
#include <ctime>
|
||||
|
||||
#include "../caps.hpp"
|
||||
#include "../common/Json.hpp"
|
||||
|
||||
#if __has_include("cli/embed/sha256.hpp")
|
||||
#include "cli/embed/sha256.hpp"
|
||||
#elif __has_include("embed/sha256.hpp")
|
||||
#include "embed/sha256.hpp"
|
||||
#else
|
||||
#include "../adapters/cli/embed/sha256.hpp" // ADAPTER fallback for isolated builds
|
||||
#endif
|
||||
|
||||
namespace molo::supply::sbom {
|
||||
|
||||
bool SbomGenerator::generate(std::string_view commit,
|
||||
const std::vector<SbomToolchainEntry>& toolchain,
|
||||
const policy::WolfPin::Pin& pin,
|
||||
const policy::DependencyPolicy& manifest,
|
||||
std::string_view molo_version,
|
||||
std::string_view created_iso8601,
|
||||
SbomDocument& out,
|
||||
std::string& error) {
|
||||
out = SbomDocument{};
|
||||
if (commit.empty() || commit.size() > caps::kMaxCommitChars) {
|
||||
error = "commit must be 1..128 chars";
|
||||
return false;
|
||||
}
|
||||
if (molo_version.empty()) {
|
||||
error = "molo version must not be empty";
|
||||
return false;
|
||||
}
|
||||
if (created_iso8601.empty()) {
|
||||
error = "created timestamp must not be empty";
|
||||
return false;
|
||||
}
|
||||
if (toolchain.size() > caps::kMaxToolchainEntries) {
|
||||
error = "toolchain over 100 entries cap";
|
||||
return false;
|
||||
}
|
||||
std::size_t toolchain_bytes = 0;
|
||||
for (const auto& t : toolchain) {
|
||||
toolchain_bytes += t.name.size() + t.version.size();
|
||||
if (t.name.empty() || t.version.empty()) {
|
||||
error = "toolchain entry needs name and version";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (toolchain_bytes > caps::kMaxToolchainBytes) {
|
||||
error = "toolchain over 64 KiB cap";
|
||||
return false;
|
||||
}
|
||||
if (pin.version.empty() || !common::Json::is_hex64(pin.sha256)) {
|
||||
error = "wolfssl pin invalid";
|
||||
return false;
|
||||
}
|
||||
|
||||
out.doc_name = "moloapp-sbom";
|
||||
out.doc_version = std::string(molo_version);
|
||||
out.commit = std::string(commit);
|
||||
out.created_iso8601 = std::string(created_iso8601);
|
||||
out.toolchain = toolchain;
|
||||
|
||||
SbomComponent self;
|
||||
self.name = "moloapp";
|
||||
self.version = std::string(molo_version);
|
||||
self.sha256 =
|
||||
molo::embed::Sha256::hex_of_string("moloapp@" + std::string(molo_version) + "@" + out.commit);
|
||||
self.source = "https://moloapp.dev";
|
||||
self.license = "proprietary";
|
||||
self.supplier = "moloapp";
|
||||
out.components.push_back(self);
|
||||
|
||||
SbomComponent wolf;
|
||||
wolf.name = "wolfssl";
|
||||
wolf.version = pin.version;
|
||||
wolf.sha256 = pin.sha256;
|
||||
wolf.source = pin.source;
|
||||
wolf.license = pin.license;
|
||||
wolf.supplier = "wolfSSL Inc.";
|
||||
out.components.push_back(wolf);
|
||||
|
||||
for (const auto& e : manifest.entries()) {
|
||||
if (e.name == "wolfssl" || e.name == "moloapp") continue; // pin and self win
|
||||
if (out.components.size() >= caps::kMaxComponents) {
|
||||
error = "component count over 64 cap";
|
||||
return false;
|
||||
}
|
||||
SbomComponent c;
|
||||
c.name = e.name;
|
||||
c.version = e.version;
|
||||
c.sha256 = e.sha256;
|
||||
c.source = e.source;
|
||||
c.license = e.license;
|
||||
c.supplier = e.source;
|
||||
out.components.push_back(c);
|
||||
}
|
||||
if (1 + out.components.size() > caps::kMaxRelationships) {
|
||||
error = "relationship count over 256 cap";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string SbomGenerator::utc_now() {
|
||||
const auto now = std::chrono::system_clock::now();
|
||||
std::time_t t = std::chrono::system_clock::to_time_t(now);
|
||||
std::tm tm{};
|
||||
#if defined(_WIN32)
|
||||
gmtime_s(&tm, &t);
|
||||
#else
|
||||
gmtime_r(&t, &tm);
|
||||
#endif
|
||||
char buf[32];
|
||||
std::strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%SZ", &tm);
|
||||
return std::string(buf);
|
||||
}
|
||||
|
||||
} // namespace molo::supply::sbom
|
||||
@@ -0,0 +1,32 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
#include "../policy/DependencyPolicy.hpp"
|
||||
#include "../policy/WolfPin.hpp"
|
||||
#include "../sbom/Types.hpp"
|
||||
|
||||
namespace molo::supply::sbom {
|
||||
|
||||
// Pure SBOM builder: commit plus toolchain plus wolfSSL pin plus allow-list
|
||||
// manifest in, validated SbomDocument out. No I/O, no clock (callers pass the
|
||||
// timestamp; utc_now() is provided for CLI use).
|
||||
class SbomGenerator {
|
||||
public:
|
||||
SbomGenerator() = delete;
|
||||
|
||||
static bool generate(std::string_view commit,
|
||||
const std::vector<SbomToolchainEntry>& toolchain,
|
||||
const policy::WolfPin::Pin& pin,
|
||||
const policy::DependencyPolicy& manifest,
|
||||
std::string_view molo_version,
|
||||
std::string_view created_iso8601,
|
||||
SbomDocument& out,
|
||||
std::string& error);
|
||||
|
||||
static std::string utc_now();
|
||||
};
|
||||
|
||||
} // namespace molo::supply::sbom
|
||||
@@ -0,0 +1,97 @@
|
||||
#include "../sbom/SpdxEmitter.hpp"
|
||||
|
||||
#include <cstdio>
|
||||
#include <map>
|
||||
|
||||
#include "../caps.hpp"
|
||||
#include "../common/Json.hpp"
|
||||
|
||||
namespace molo::supply::sbom {
|
||||
|
||||
namespace {
|
||||
|
||||
std::string package_json(const SbomComponent& c, const std::string& id, int indent) {
|
||||
using common::Json;
|
||||
std::map<std::string, std::string> checksum;
|
||||
checksum["algorithm"] = Json::quote("SHA256");
|
||||
checksum["checksumValue"] = Json::quote(c.sha256);
|
||||
std::map<std::string, std::string> ext_ref;
|
||||
ext_ref["category"] = Json::quote("PACKAGE-MANAGER");
|
||||
ext_ref["locator"] = Json::quote(c.source);
|
||||
ext_ref["referenceType"] = Json::quote("purl");
|
||||
std::map<std::string, std::string> pkg;
|
||||
pkg["SPDXID"] = Json::quote(id);
|
||||
pkg["checksums"] = Json::array({Json::object(checksum, indent + 2)}, indent + 1);
|
||||
pkg["downloadLocation"] = Json::quote(c.source);
|
||||
pkg["externalRefs"] = Json::array({Json::object(ext_ref, indent + 2)}, indent + 1);
|
||||
pkg["licenseDeclared"] = Json::quote(c.license);
|
||||
pkg["name"] = Json::quote(c.name);
|
||||
pkg["supplier"] = Json::quote("Organization: " + c.supplier);
|
||||
pkg["versionInfo"] = Json::quote(c.version);
|
||||
return Json::object(pkg, indent);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool SpdxEmitter::emit_json(const SbomDocument& doc, std::string& out, std::string& error) {
|
||||
using common::Json;
|
||||
out.clear();
|
||||
if (doc.components.size() > caps::kMaxComponents) {
|
||||
error = "component count over 64 cap";
|
||||
return false;
|
||||
}
|
||||
std::map<std::string, std::string> creation;
|
||||
creation["created"] = Json::quote(doc.created_iso8601);
|
||||
creation["creators"] = Json::array({Json::quote("Tool: moloapp-" + doc.doc_version)}, 2);
|
||||
|
||||
std::vector<std::string> packages;
|
||||
std::vector<std::string> relationships;
|
||||
for (std::size_t i = 0; i < doc.components.size(); ++i) {
|
||||
const SbomComponent& c = doc.components[i];
|
||||
std::string id = "SPDXRef-Package-" + c.name;
|
||||
packages.push_back(package_json(c, id, 2));
|
||||
std::map<std::string, std::string> rel;
|
||||
rel["relatedSpdxElement"] = Json::quote(id);
|
||||
rel["relationshipType"] = Json::quote("CONTAINS");
|
||||
rel["spdxElementId"] = Json::quote("SPDXRef-DOCUMENT");
|
||||
relationships.push_back(Json::object(rel, 2));
|
||||
}
|
||||
if (1 + relationships.size() > caps::kMaxRelationships) {
|
||||
error = "relationship count over 256 cap";
|
||||
return false;
|
||||
}
|
||||
|
||||
std::map<std::string, std::string> root;
|
||||
root["SPDXID"] = Json::quote("SPDXRef-DOCUMENT");
|
||||
root["creationInfo"] = Json::object(creation, 1);
|
||||
root["dataLicense"] = Json::quote("CC0-1.0");
|
||||
root["documentDescribes"] = Json::array({Json::quote("SPDXRef-DOCUMENT")}, 1);
|
||||
root["documentNamespace"] = Json::quote("https://moloapp.dev/sbom/" + doc.commit);
|
||||
root["name"] = Json::quote(doc.doc_name);
|
||||
root["packages"] = Json::array(packages, 1);
|
||||
root["relationships"] = Json::array(relationships, 1);
|
||||
root["spdxVersion"] = Json::quote("SPDX-2.3");
|
||||
out = Json::object(root, 0) + "\n";
|
||||
if (out.size() > caps::kMaxSbomBytes) {
|
||||
out.clear();
|
||||
error = "SPDX output over 1 MiB cap";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool SpdxEmitter::emit_file(const SbomDocument& doc, const std::string& path, std::string& error) {
|
||||
std::string text;
|
||||
if (!emit_json(doc, text, error)) return false;
|
||||
std::FILE* f = std::fopen(path.c_str(), "wb");
|
||||
if (f == nullptr) {
|
||||
error = "cannot open '" + path + "' for writing";
|
||||
return false;
|
||||
}
|
||||
std::size_t wrote = std::fwrite(text.data(), 1, text.size(), f);
|
||||
bool ok = wrote == text.size() && std::fclose(f) == 0;
|
||||
if (!ok) error = "failed writing '" + path + "'";
|
||||
return ok;
|
||||
}
|
||||
|
||||
} // namespace molo::supply::sbom
|
||||
@@ -0,0 +1,19 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
|
||||
#include "../sbom/Types.hpp"
|
||||
|
||||
namespace molo::supply::sbom {
|
||||
|
||||
// SPDX 2.3 JSON emitter. Canonical form only: keys sorted, LF line endings,
|
||||
// 2-space indent, single trailing newline. Rejects output over the 1 MiB cap.
|
||||
class SpdxEmitter {
|
||||
public:
|
||||
SpdxEmitter() = delete;
|
||||
|
||||
static bool emit_json(const SbomDocument& doc, std::string& out, std::string& error);
|
||||
static bool emit_file(const SbomDocument& doc, const std::string& path, std::string& error);
|
||||
};
|
||||
|
||||
} // namespace molo::supply::sbom
|
||||
@@ -0,0 +1,33 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace molo::supply::sbom {
|
||||
|
||||
// Shared SBOM value types. Both emitters (SPDX, CycloneDX) render the same
|
||||
// document so the (name, version, sha256) triples always match.
|
||||
struct SbomComponent {
|
||||
std::string name;
|
||||
std::string version;
|
||||
std::string sha256;
|
||||
std::string source;
|
||||
std::string license;
|
||||
std::string supplier;
|
||||
};
|
||||
|
||||
struct SbomToolchainEntry {
|
||||
std::string name;
|
||||
std::string version;
|
||||
};
|
||||
|
||||
struct SbomDocument {
|
||||
std::string doc_name;
|
||||
std::string doc_version;
|
||||
std::string commit;
|
||||
std::string created_iso8601;
|
||||
std::vector<SbomToolchainEntry> toolchain;
|
||||
std::vector<SbomComponent> components;
|
||||
};
|
||||
|
||||
} // namespace molo::supply::sbom
|
||||
@@ -0,0 +1,130 @@
|
||||
#include "../scan/OsvClient.hpp"
|
||||
|
||||
#include <map>
|
||||
|
||||
#include "../caps.hpp"
|
||||
#include "../common/Json.hpp"
|
||||
|
||||
namespace molo::supply::scan {
|
||||
|
||||
OsvClient::OsvClient(Transport transport) : transport_(std::move(transport)) {}
|
||||
|
||||
std::string OsvClient::request_body(const std::string& package, const std::string& version) {
|
||||
using common::Json;
|
||||
std::map<std::string, std::string> pkg;
|
||||
pkg["ecosystem"] = Json::quote("OSS-Fuzz");
|
||||
pkg["name"] = Json::quote(package);
|
||||
std::map<std::string, std::string> root;
|
||||
root["package"] = Json::object(pkg, 1);
|
||||
root["version"] = Json::quote(version);
|
||||
return Json::object(root, 0);
|
||||
}
|
||||
|
||||
bool OsvClient::parse_response(const std::string& package, const std::string& text,
|
||||
std::vector<Vuln>& findings, std::string& error) {
|
||||
findings.clear();
|
||||
if (text.size() > caps::kMaxAdvisoriesBytes) {
|
||||
error = "osv response over 256 KiB cap";
|
||||
return false;
|
||||
}
|
||||
common::Json::Value root;
|
||||
if (!common::Json::parse(text, root, error)) return false;
|
||||
if (root.type != common::Json::Value::Type::Object) {
|
||||
error = "osv response root must be an object";
|
||||
return false;
|
||||
}
|
||||
const common::Json::Value* vulns = common::Json::find(root, "vulns");
|
||||
if (vulns == nullptr) return true; // no vulns key means clean
|
||||
if (vulns->type != common::Json::Value::Type::Array) {
|
||||
error = "\"vulns\" must be an array";
|
||||
return false;
|
||||
}
|
||||
for (const auto& item : vulns->items) {
|
||||
if (findings.size() >= caps::kMaxOsvVulns) {
|
||||
error = "osv vuln count over 64 cap";
|
||||
return false;
|
||||
}
|
||||
if (item.type != common::Json::Value::Type::Object) continue;
|
||||
Vuln v;
|
||||
v.package = package;
|
||||
const common::Json::Value* f = common::Json::find(item, "id");
|
||||
v.id = (f == nullptr) ? "" : common::Json::string_or(*f, "");
|
||||
f = common::Json::find(item, "summary");
|
||||
if (f == nullptr) f = common::Json::find(item, "details");
|
||||
v.summary = (f == nullptr) ? "" : common::Json::string_or(*f, "");
|
||||
const common::Json::Value* sev = common::Json::find(item, "severity");
|
||||
if (sev != nullptr && sev->type == common::Json::Value::Type::Array) {
|
||||
for (const auto& s : sev->items) {
|
||||
if (s.type != common::Json::Value::Type::Object) continue;
|
||||
const common::Json::Value* score = common::Json::find(s, "score");
|
||||
if (score != nullptr) {
|
||||
double d = common::Json::number_or(*score, 0.0);
|
||||
if (d > v.cvss) v.cvss = d;
|
||||
}
|
||||
}
|
||||
}
|
||||
const common::Json::Value* affected = common::Json::find(item, "affected");
|
||||
if (affected != nullptr && affected->type == common::Json::Value::Type::Array) {
|
||||
for (const auto& a : affected->items) {
|
||||
if (a.type != common::Json::Value::Type::Object) continue;
|
||||
const common::Json::Value* ranges = common::Json::find(a, "ranges");
|
||||
if (ranges == nullptr || ranges->type != common::Json::Value::Type::Array) continue;
|
||||
for (const auto& r : ranges->items) {
|
||||
if (r.type != common::Json::Value::Type::Object) continue;
|
||||
const common::Json::Value* events = common::Json::find(r, "events");
|
||||
if (events == nullptr || events->type != common::Json::Value::Type::Array) continue;
|
||||
for (const auto& e : events->items) {
|
||||
if (e.type != common::Json::Value::Type::Object) continue;
|
||||
const common::Json::Value* fixed = common::Json::find(e, "fixed");
|
||||
if (fixed != nullptr && v.fixed_version.empty()) {
|
||||
v.fixed_version = common::Json::string_or(*fixed, "");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (v.id.empty()) {
|
||||
error = "osv vuln entry missing id";
|
||||
return false;
|
||||
}
|
||||
findings.push_back(v);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool OsvClient::query(const std::string& package, const std::string& version,
|
||||
std::vector<Vuln>& findings, std::string& error) {
|
||||
findings.clear();
|
||||
if (package.empty() || version.empty()) {
|
||||
error = "package and version must not be empty";
|
||||
return false;
|
||||
}
|
||||
if (queries_made_ >= caps::kOsvMaxQueries) {
|
||||
error = "osv query count over 64 cap";
|
||||
return false;
|
||||
}
|
||||
const std::string body = request_body(package, version);
|
||||
std::string response;
|
||||
std::string last_error = "offline: no transport configured";
|
||||
for (int attempt = 0; attempt <= caps::kOsvMaxRetries; ++attempt) {
|
||||
++queries_made_;
|
||||
if (queries_made_ > caps::kOsvMaxQueries) {
|
||||
error = "osv query count over 64 cap";
|
||||
return false;
|
||||
}
|
||||
response.clear();
|
||||
std::string transport_error;
|
||||
bool ok = false;
|
||||
if (transport_) {
|
||||
ok = transport_(caps::kOsvQueryUrl, body, response, transport_error);
|
||||
} else {
|
||||
transport_error = "offline: no transport configured";
|
||||
}
|
||||
if (ok) return parse_response(package, response, findings, error);
|
||||
last_error = transport_error.empty() ? "transport failed" : transport_error;
|
||||
}
|
||||
error = last_error;
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace molo::supply::scan
|
||||
@@ -0,0 +1,46 @@
|
||||
#pragma once
|
||||
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace molo::supply::scan {
|
||||
|
||||
// Minimal OSV (https://api.osv.dev/v1/query) client. The HTTP transport is
|
||||
// injected so tests run offline with a fake; the default transport always
|
||||
// reports offline, so no socket code lives here. Base-tree wiring can inject
|
||||
// the framework HTTP client later. Capped: 64 queries per instance, 1 retry,
|
||||
// 10 s timeout is the transport contract (see spec.md).
|
||||
class OsvClient {
|
||||
public:
|
||||
struct Vuln {
|
||||
std::string id;
|
||||
std::string summary;
|
||||
std::string package;
|
||||
std::string fixed_version;
|
||||
double cvss = 0.0;
|
||||
};
|
||||
|
||||
// (url, request_body, response_out, error_out) -> true on HTTP 200.
|
||||
using Transport =
|
||||
std::function<bool(const std::string&, const std::string&, std::string&, std::string&)>;
|
||||
|
||||
explicit OsvClient(Transport transport = {});
|
||||
OsvClient(const OsvClient&) = delete;
|
||||
OsvClient& operator=(const OsvClient&) = delete;
|
||||
|
||||
bool query(const std::string& package, const std::string& version,
|
||||
std::vector<Vuln>& findings, std::string& error);
|
||||
|
||||
std::size_t queries_made() const { return queries_made_; }
|
||||
|
||||
static std::string request_body(const std::string& package, const std::string& version);
|
||||
static bool parse_response(const std::string& package, const std::string& text,
|
||||
std::vector<Vuln>& findings, std::string& error);
|
||||
|
||||
private:
|
||||
Transport transport_;
|
||||
std::size_t queries_made_ = 0;
|
||||
};
|
||||
|
||||
} // namespace molo::supply::scan
|
||||
@@ -0,0 +1,154 @@
|
||||
#include "../scan/VulnHook.hpp"
|
||||
|
||||
#include "../caps.hpp"
|
||||
#include "../common/Json.hpp"
|
||||
|
||||
namespace molo::supply::scan {
|
||||
|
||||
bool VulnHook::parse_advisories(std::string_view text, std::vector<OsvClient::Vuln>& out,
|
||||
std::string& error) {
|
||||
out.clear();
|
||||
if (text.size() > caps::kMaxAdvisoriesBytes) {
|
||||
error = "advisories over 256 KiB cap";
|
||||
return false;
|
||||
}
|
||||
common::Json::Value root;
|
||||
if (!common::Json::parse(text, root, error)) return false;
|
||||
if (root.type != common::Json::Value::Type::Object) {
|
||||
error = "advisories root must be an object";
|
||||
return false;
|
||||
}
|
||||
const common::Json::Value* list = common::Json::find(root, "advisories");
|
||||
if (list == nullptr) return true;
|
||||
if (list->type != common::Json::Value::Type::Array) {
|
||||
error = "\"advisories\" must be an array";
|
||||
return false;
|
||||
}
|
||||
for (const auto& item : list->items) {
|
||||
if (out.size() >= caps::kMaxOsvVulns) {
|
||||
error = "advisory count over 64 cap";
|
||||
return false;
|
||||
}
|
||||
if (item.type != common::Json::Value::Type::Object) {
|
||||
error = "advisory entry must be an object";
|
||||
return false;
|
||||
}
|
||||
OsvClient::Vuln v;
|
||||
const common::Json::Value* f = nullptr;
|
||||
f = common::Json::find(item, "id");
|
||||
v.id = (f == nullptr) ? "" : common::Json::string_or(*f, "");
|
||||
f = common::Json::find(item, "package");
|
||||
v.package = (f == nullptr) ? "" : common::Json::string_or(*f, "");
|
||||
f = common::Json::find(item, "summary");
|
||||
v.summary = (f == nullptr) ? "" : common::Json::string_or(*f, "");
|
||||
f = common::Json::find(item, "fixed");
|
||||
v.fixed_version = (f == nullptr) ? "" : common::Json::string_or(*f, "");
|
||||
f = common::Json::find(item, "cvss");
|
||||
v.cvss = (f == nullptr) ? 0.0 : common::Json::number_or(*f, 0.0);
|
||||
if (v.id.empty() || v.package.empty()) {
|
||||
error = "advisory entry missing id/package";
|
||||
return false;
|
||||
}
|
||||
out.push_back(v);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool VulnHook::parse_exceptions(std::string_view text, std::vector<Exception>& out,
|
||||
std::string& error) {
|
||||
out.clear();
|
||||
if (text.size() > caps::kMaxAdvisoriesBytes) {
|
||||
error = "exceptions over 256 KiB cap";
|
||||
return false;
|
||||
}
|
||||
common::Json::Value root;
|
||||
if (!common::Json::parse(text, root, error)) return false;
|
||||
if (root.type != common::Json::Value::Type::Object) {
|
||||
error = "exceptions root must be an object";
|
||||
return false;
|
||||
}
|
||||
const common::Json::Value* list = common::Json::find(root, "exceptions");
|
||||
if (list == nullptr) return true;
|
||||
if (list->type != common::Json::Value::Type::Array) {
|
||||
error = "\"exceptions\" must be an array";
|
||||
return false;
|
||||
}
|
||||
for (const auto& item : list->items) {
|
||||
if (out.size() >= caps::kMaxOsvVulns) {
|
||||
error = "exception count over 64 cap";
|
||||
return false;
|
||||
}
|
||||
if (item.type != common::Json::Value::Type::Object) {
|
||||
error = "exception entry must be an object";
|
||||
return false;
|
||||
}
|
||||
Exception e;
|
||||
const common::Json::Value* f = common::Json::find(item, "id");
|
||||
e.vuln_id = (f == nullptr) ? "" : common::Json::string_or(*f, "");
|
||||
f = common::Json::find(item, "reason");
|
||||
e.reason = (f == nullptr) ? "" : common::Json::string_or(*f, "");
|
||||
f = common::Json::find(item, "expires");
|
||||
e.expires_unix = (f == nullptr) ? 0 : static_cast<long long>(common::Json::number_or(*f, 0.0));
|
||||
if (e.vuln_id.empty() || e.expires_unix <= 0) {
|
||||
error = "exception entry missing id/expires";
|
||||
return false;
|
||||
}
|
||||
out.push_back(e);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool VulnHook::is_blocking(const OsvClient::Vuln& v) {
|
||||
if (v.cvss >= caps::kBlockCvss) return true;
|
||||
return v.package == "wolfssl" && !v.fixed_version.empty();
|
||||
}
|
||||
|
||||
VulnHook::Verdict VulnHook::evaluate(const std::vector<OsvClient::Vuln>& findings,
|
||||
const std::vector<Exception>& exceptions, long long now_unix,
|
||||
bool offline_unknown, std::string& reason) {
|
||||
reason.clear();
|
||||
if (offline_unknown && findings.empty()) {
|
||||
reason = "offline-unknown: cannot prove clean without scan data";
|
||||
return Verdict::Blocked;
|
||||
}
|
||||
auto covered = [&](const OsvClient::Vuln& v) -> bool {
|
||||
for (const auto& e : exceptions) {
|
||||
if (e.vuln_id == v.id && now_unix < e.expires_unix) return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
auto expired_match = [&](const OsvClient::Vuln& v) -> bool {
|
||||
for (const auto& e : exceptions) {
|
||||
if (e.vuln_id == v.id && now_unix >= e.expires_unix) return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
for (const auto& v : findings) {
|
||||
if (covered(v)) continue;
|
||||
if (expired_match(v)) {
|
||||
reason = "exception-expired:" + v.id;
|
||||
return Verdict::Blocked;
|
||||
}
|
||||
if (is_blocking(v)) {
|
||||
reason = "vuln-block:" + v.id;
|
||||
return Verdict::Blocked;
|
||||
}
|
||||
}
|
||||
if (findings.empty()) {
|
||||
reason = "allow: no findings";
|
||||
return Verdict::Clean;
|
||||
}
|
||||
reason = "disclosed: " + std::to_string(findings.size()) + " finding(s) below block threshold";
|
||||
return Verdict::Disclosed;
|
||||
}
|
||||
|
||||
const char* VulnHook::to_string(Verdict v) {
|
||||
switch (v) {
|
||||
case Verdict::Clean: return "clean";
|
||||
case Verdict::Disclosed: return "disclosed";
|
||||
case Verdict::Blocked: return "blocked";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
} // namespace molo::supply::scan
|
||||
@@ -0,0 +1,39 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
#include "../scan/OsvClient.hpp"
|
||||
|
||||
namespace molo::supply::scan {
|
||||
|
||||
// Release gate over vulnerability findings. Verdicts:
|
||||
// clean (no findings), disclosed (only sub-threshold findings, or every
|
||||
// finding covered by an unexpired exception), blocked (any CVSS >= 9.0
|
||||
// finding uncovered, any wolfssl finding with a fix uncovered, any matched
|
||||
// exception expired, or the scan state unknown while offline).
|
||||
class VulnHook {
|
||||
public:
|
||||
enum class Verdict { Clean, Disclosed, Blocked };
|
||||
|
||||
struct Exception {
|
||||
std::string vuln_id;
|
||||
long long expires_unix = 0;
|
||||
std::string reason;
|
||||
};
|
||||
|
||||
VulnHook() = delete;
|
||||
|
||||
static bool parse_advisories(std::string_view text, std::vector<OsvClient::Vuln>& out,
|
||||
std::string& error);
|
||||
static bool parse_exceptions(std::string_view text, std::vector<Exception>& out,
|
||||
std::string& error);
|
||||
static Verdict evaluate(const std::vector<OsvClient::Vuln>& findings,
|
||||
const std::vector<Exception>& exceptions, long long now_unix,
|
||||
bool offline_unknown, std::string& reason);
|
||||
static const char* to_string(Verdict v);
|
||||
static bool is_blocking(const OsvClient::Vuln& v);
|
||||
};
|
||||
|
||||
} // namespace molo::supply::scan
|
||||
@@ -0,0 +1,161 @@
|
||||
# MoloApp supply-chain part (src/supplychain/): specification
|
||||
|
||||
## 1. Purpose
|
||||
|
||||
Own the software supply chain for MoloApp releases: pinned dependencies,
|
||||
SBOM generation in two formats, vulnerability gating, SLSA provenance,
|
||||
signing, and offline verification. Ships three CLI leaves (`verify`,
|
||||
`supply-check`, `release`) whose handlers live here; the base tree only wires
|
||||
them into `CliApp::build_tree()` (see PATCHES.md).
|
||||
|
||||
## 2. Rules
|
||||
|
||||
- C++23, standard library plus OS syscalls only. No third-party code.
|
||||
- One class per file. Namespaces mirror directories under `molo::supply`.
|
||||
- Every limit is a static cap in `caps.hpp`. Over-cap input is rejected with
|
||||
a clear error, never silently cut.
|
||||
- Offline by default: `verify` and the advisory gate use no network. The OSV
|
||||
client ships with an offline stub transport; base-tree wiring may inject
|
||||
the framework HTTP client later.
|
||||
- Only `attest/Signer.cpp` may spawn a shell (the cosign wrapper).
|
||||
- stdout is primary output via `molo::cli::Output`; diagnostics go to stderr.
|
||||
- Canonical JSON everywhere: keys sorted, LF endings, 2-space indent, single
|
||||
trailing newline.
|
||||
|
||||
## 3. Static caps (caps.hpp)
|
||||
|
||||
| Cap | Value |
|
||||
|---|---|
|
||||
| Components per SBOM | 64 |
|
||||
| Relationships per SBOM | 256 |
|
||||
| SBOM / statement output | 1 MiB |
|
||||
| Toolchain entries / bytes | 100 / 64 KiB |
|
||||
| Signed files (subjects) | 32 |
|
||||
| Pin / allow-list JSON | 64 KiB |
|
||||
| Advisories / exceptions JSON | 256 KiB |
|
||||
| OSV queries / retries / timeout | 64 / 1 / 10 s |
|
||||
| Override TTL reference | 7 days (604800 s) |
|
||||
| Block CVSS threshold | 9.0 |
|
||||
|
||||
## 4. Components
|
||||
|
||||
### common/Json (Json.hpp, Json.cpp)
|
||||
|
||||
Shared JSON parser (depth cap 32, 4 MiB ceiling) plus canonical renderer
|
||||
(`object` from pre-rendered values, `array`, `quote`, `escape`) and small
|
||||
accessors (`find`, `string_or`, `number_or`, `is_hex64`). No other supply
|
||||
file parses or escapes JSON on its own.
|
||||
|
||||
### policy (DependencyPolicy.hpp, WolfPin.hpp/.cpp)
|
||||
|
||||
- `DependencyPolicy` parses the `dependencies` array of supply.allow.json.
|
||||
Each entry needs name, version, sha256 (64 hex), source, license.
|
||||
- `WolfPin` parses the `wolfssl` pin object (version, sha256, source,
|
||||
license, receipt) and checks candidate version/hash pairs with verdicts
|
||||
`ok`, `version-mismatch`, `hash-mismatch`. File reads cap at 64 KiB.
|
||||
|
||||
### sbom (Types.hpp, SbomGenerator, SpdxEmitter, CycloneDxEmitter, SbomCheck)
|
||||
|
||||
- `SbomGenerator::generate` is a pure function of (commit, toolchain, pin,
|
||||
manifest, molo version, created timestamp). Components are always
|
||||
`moloapp` (build id derived by hashing name/version/commit), `wolfssl`
|
||||
(from the pin), then manifest entries with `wolfssl`/`moloapp` dups
|
||||
dropped. `utc_now()` supplies CLI timestamps.
|
||||
- `SpdxEmitter` writes SPDX 2.3 JSON; `CycloneDxEmitter` writes CycloneDX 1.6
|
||||
JSON. Both render the same (name, version, sha256) triples from the same
|
||||
document; `test_cdx_equiv` proves triple equality. Output over 1 MiB is
|
||||
rejected.
|
||||
- `SbomCheck::check_ntia` enforces NTIA minimum elements: commit on the
|
||||
document; name, version, 64-hex sha256, and supplier/source on every
|
||||
component. Returns the list of missing `components[i].field` paths.
|
||||
|
||||
### scan (OsvClient.hpp/.cpp, VulnHook.hpp/.cpp)
|
||||
|
||||
- `OsvClient` posts to `https://api.osv.dev/v1/query` through an injected
|
||||
`Transport`. The default (empty) transport reports offline, so standalone
|
||||
builds and tests never touch the network. Parses `vulns` entries (id,
|
||||
summary/details, max severity score, first fixed version). One retry, 64
|
||||
queries per instance; the 10 s timeout is a contract on the injected
|
||||
transport.
|
||||
- `VulnHook` parses `advisories.json` (`advisories` array of
|
||||
id/package/cvss/fixed/summary) and `exceptions.json` (`exceptions` array of
|
||||
id/expires/reason, expires as unix seconds). `evaluate` returns:
|
||||
- `clean`: no findings and scan state known.
|
||||
- `disclosed`: only sub-threshold findings, or every finding covered by an
|
||||
unexpired exception.
|
||||
- `blocked`: any CVSS >= 9.0 finding uncovered, any wolfssl finding with a
|
||||
fix uncovered, any matched exception expired, or scan state unknown
|
||||
while offline.
|
||||
- Reason strings use the `allow:` / `disclosed:` / `vuln-block:` /
|
||||
`exception-expired:` / `offline-unknown:` prefixes so base-tree logging
|
||||
can key off them.
|
||||
|
||||
### attest (ProvenanceBuilder.hpp, Attestor.hpp/.cpp, Signer.hpp/.cpp, Verify.hpp/.cpp)
|
||||
|
||||
- `ProvenanceBuilder::build` returns a canonical SLSA predicate object
|
||||
(build type `https://moloapp.dev/build/v1`, builder id, commit,
|
||||
invocation, materials, resolved dependencies). Subjects sort by path.
|
||||
- `Attestor::statement` wraps a predicate into an in-toto Statement with
|
||||
predicate type `https://slsa.dev/provenance/v1`, re-indenting the embedded
|
||||
predicate so the whole statement stays canonical. The 33rd subject is
|
||||
rejected.
|
||||
- `Signer::sign` runs `cosign sign-blob --yes --bundle <bundle> <blob>`
|
||||
(keyless) with single-quote path escaping and 2 KiB capped failure output.
|
||||
`MOLO_FAKE_COSIGN=1` writes a deterministic offline fake bundle embedding
|
||||
the blob digest; tests use the fake.
|
||||
- `Verify::verify_files` recomputes sha256 for each expected subject via the
|
||||
embed seam, requires the bundle to contain every digest (chain), and
|
||||
requires any `wolfssl` subject to equal the pin when a pin is given.
|
||||
|
||||
### cli (SupplyCli.hpp/.cpp)
|
||||
|
||||
Thin `ExitCode` handlers, no supply logic:
|
||||
|
||||
- `run_verify`: `molo verify [dir] [--manifest subjects.txt]
|
||||
[--bundle bundle.json] [--pin allow]`. Exit 0 ok, 1 failure, 2 usage.
|
||||
Fully offline. `--format json` prints a status object.
|
||||
- `run_check`: `molo supply-check [dir] [--allow supply.allow.json]
|
||||
[--advisories advisories.json] [--exceptions e.json] [--osv]`. Pin plus
|
||||
allow-list plus advisory gate. `blocked` exits 1; `disclosed` warns and
|
||||
exits 0; missing advisory source exits 1 (offline sources are required).
|
||||
- `run_release`: `molo release --commit <sha> --suite-stamp <file>
|
||||
[--dir .] [--allow ...] [--advisories ...] [--exceptions ...]
|
||||
[--toolchain toolchain.txt] [--tag-file TAG]`. Six ordered steps: suite
|
||||
stamp is `PASS`; SBOM generate plus NTIA plus emit both formats; advisory
|
||||
scan (blocked fails); provenance plus attestation; cosign sign; tag stamp
|
||||
write. Any failure exits 1 naming the step.
|
||||
|
||||
## 5. Base-tree seams consumed
|
||||
|
||||
`molo::cli` (ExitCode, ParsedArgs, Output, JsonWriter::escape/quote/object),
|
||||
`molo::embed::Sha256` (hex_of_string/hex_of_file),
|
||||
`molo::kMoloVersion`. Each include prefers the base header via
|
||||
`__has_include` and falls back to the `adapters/` mirror for isolated
|
||||
builds. The fragment `src/supplychain.mk` never adds `adapters/` to the
|
||||
include path, so real builds cannot see the fallbacks.
|
||||
|
||||
The `molo::log::Logger` seam is intentionally not called: the seam handoff
|
||||
lists the class but not the `Level`/`fields` types, so call sites would be
|
||||
guesses. Verdict reason strings (section 4, VulnHook) are the logging
|
||||
contract; base-tree wiring logs them.
|
||||
|
||||
## 6. Tests (tests/src/supplychain/)
|
||||
|
||||
Plain `int main()` plus `CHECK`, no gtest: `test_pin`, `test_spdx`,
|
||||
`test_cdx_equiv`, `test_scan`, `test_provenance`, `test_verify`, with byte
|
||||
goldens under `golden/` (sbom pair, provenance, advisories input). Covered
|
||||
caps: 1 MiB SBOM reject, 33rd subject reject, expired exception blocks,
|
||||
offline unknown blocks signing, 65th OSV query rejected, pin oversize
|
||||
rejected. `MOLO_REGEN_GOLDEN=1` regenerates output goldens; advisories.json
|
||||
is a hand-written input fixture. SHA-256 self-checks against the independent
|
||||
`sha256("abc")` vector in `test_verify`.
|
||||
|
||||
## 7. Gaps
|
||||
|
||||
- No `plans/15-supply-chain.md` exists in this worktree (plans only go to
|
||||
10); this spec plus the seam handoff is the authority.
|
||||
- `Output::print/info/progress/warn/error/debug` and
|
||||
`JsonWriter::object(map<string,string>)` signatures are per the seam
|
||||
summary; PATCHES.md flags the assumption for the base-tree applier.
|
||||
- Real cosign and live OSV are integration concerns for the base tree; here
|
||||
they are covered by the fake bundle and injected fake transport.
|
||||
Reference in New Issue
Block a user