From 644a637b108283e96ae4bb014e044dd9dc017328 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Fri, 2 Oct 2026 08:36:16 -0500 Subject: [PATCH 1/2] VC1 stage 4: import resolution in the Omega OSC compiler (oscv, omega.lock, receipt check) `import NAME;` in OSC now resolves only through omega.lock -> semantic id -> Verified Crumb Store -> receipt check -> transitive verified closure. Ten refusal codes, a fail-closed lock parser, a C reader of the aien-proof receipt wire contract (with BLAKE3), build and dev domains (dev output is tainted and never enters the store), and the closure digest folded into the build id. No skip switch, no environment variable, no unsafe import. src/omega_vcstore.c is untouched. cl_program.c and omega_discovery.c are not migrated (stage 6). make test-resolve: 147 checks (plain and ASan/UBSan), 55 mutants all killed. Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/host-suites-2.yml | 2 +- Makefile | 93 ++ docs/osc/OSC-VC1-IMPORT.md | 63 + src/compiler/osc_diag.c | 2 +- src/compiler/osc_diag.h | 2 + src/compiler/osc_front.c | 28 +- src/compiler/osc_front.h | 14 +- src/compiler/osc_lex.c | 6 +- src/compiler/osc_lex.h | 2 + src/compiler/osc_parse.c | 39 + src/compiler/osc_parse.h | 10 + src/omega_blake3.c | 154 ++ src/omega_blake3.h | 17 + src/omega_receipt.c | 695 ++++++++ src/omega_receipt.h | 70 + src/omega_resolve.c | 710 ++++++++ src/omega_resolve.h | 181 +++ src/omega_resolve_osc.c | 27 + src/omega_resolve_osc.h | 23 + src/oscv_main.c | 197 +++ tests/resolve/blake3_vectors.txt | 35 + ...a7a422c189024912ec4626347e860b5f44a8c.json | 42 + ...2292be29fc15da36d434944ad4521e69de5b3.json | 40 + ...7161c02196646b270d41078d8b16d4beaf765.json | 42 + tests/test_omega_resolve.c | 1448 +++++++++++++++++ 25 files changed, 3935 insertions(+), 7 deletions(-) create mode 100644 docs/osc/OSC-VC1-IMPORT.md create mode 100644 src/omega_blake3.c create mode 100644 src/omega_blake3.h create mode 100644 src/omega_receipt.c create mode 100644 src/omega_receipt.h create mode 100644 src/omega_resolve.c create mode 100644 src/omega_resolve.h create mode 100644 src/omega_resolve_osc.c create mode 100644 src/omega_resolve_osc.h create mode 100644 src/oscv_main.c create mode 100644 tests/resolve/blake3_vectors.txt create mode 100644 tests/resolve/receipts/54f597d22b3753e47d6bd7706b6a7a422c189024912ec4626347e860b5f44a8c.json create mode 100644 tests/resolve/receipts/7fdff014cb20a0af5b5a5b377532292be29fc15da36d434944ad4521e69de5b3.json create mode 100644 tests/resolve/receipts/8e885832de2e7123555c47803547161c02196646b270d41078d8b16d4beaf765.json create mode 100644 tests/test_omega_resolve.c diff --git a/.github/workflows/host-suites-2.yml b/.github/workflows/host-suites-2.yml index b9bf58d2f..589c1922d 100644 --- a/.github/workflows/host-suites-2.yml +++ b/.github/workflows/host-suites-2.yml @@ -261,7 +261,7 @@ jobs: with: fetch-depth: 0 - name: Crumbline learner conformance vectors - run: make PHYSICS_DIR=/nonexistent PHYSICS_LOCK_CHECK=0 test-crumbline test-library test-vcstore + run: make PHYSICS_DIR=/nonexistent PHYSICS_LOCK_CHECK=0 test-crumbline test-library test-vcstore test-resolve runtime: needs: changes diff --git a/Makefile b/Makefile index 32365fe7c..682fbdabd 100644 --- a/Makefile +++ b/Makefile @@ -1801,3 +1801,96 @@ test-vcstore: tests/test_omega_vcstore.c src/omega_vcstore.c src/omega_vcstore.h build_mutant load-name-id load-name-id ' (void)vcs_find(t, id, &di);'; \ build_mutant save-verify save-verify ' int rc = 0;' @echo "test-vcstore: PASS (all checks, all mutants killed)" + +# VC1-RESOLVE (VC1 stage 4): import resolution in the Omega OSC compiler. `import NAME;` resolves +# only through omega.lock -> semantic id -> Verified Crumb Store -> receipt check -> transitive +# verified closure (src/omega_resolve.c), with a C reader of the aien-proof receipt wire contract +# (src/omega_receipt.c, BLAKE3 in src/omega_blake3.c). oscv is the verified driver. Test inputs: +# tests/resolve/ (official BLAKE3 vectors, three receipts written by the Rust implementation). +# Mutation proof: each mutant is a copy of ONE source file with one tagged line (VC1R: in +# omega_resolve.c / omega_receipt.c, B3M: in omega_blake3.c) replaced; the test must exit 1 +# with "MUTANT KILLED by " for the check named here, every time. A mutant whose sed +# changed nothing, did not compile, or survived fails the build. CPU only; no physics; no chip. +.PHONY: test-resolve oscv +RESOLVE_FLAGS = -std=gnu11 -Wall -Wextra -Werror -D_GNU_SOURCE -O2 -Isrc -Isrc/compiler -Isrc/compiler/model +RESOLVE_DIR = $(OUT_DIR)/resolve-test +RESOLVE_OSC_LIB = $(filter-out src/compiler/oscc_main.c,$(wildcard src/compiler/*.c)) +RESOLVE_SRC = src/omega_resolve.c src/omega_receipt.c src/omega_blake3.c +RESOLVE_REST = src/omega_resolve_osc.c src/omega_vcstore.c $(RESOLVE_OSC_LIB) src/sha256.c +RESOLVE_HDRS = $(wildcard src/compiler/*.h) src/omega_resolve.h src/omega_receipt.h src/omega_blake3.h src/omega_resolve_osc.h src/omega_vcstore.h src/sha256.h +$(OUT_DIR)/compiler/oscv: src/oscv_main.c $(RESOLVE_SRC) $(RESOLVE_REST) $(RESOLVE_HDRS) + @mkdir -p $(OUT_DIR)/compiler + $(CC) $(RESOLVE_FLAGS) -o $@ src/oscv_main.c $(RESOLVE_SRC) $(RESOLVE_REST) +oscv: $(OUT_DIR)/compiler/oscv +test-resolve: tests/test_omega_resolve.c $(OUT_DIR)/compiler/oscv $(RESOLVE_SRC) $(RESOLVE_REST) $(RESOLVE_HDRS) + @mkdir -p $(RESOLVE_DIR) + $(CC) $(RESOLVE_FLAGS) -DOSCV_PATH='"$(OUT_DIR)/compiler/oscv"' -o $(RESOLVE_DIR)/test_omega_resolve tests/test_omega_resolve.c $(RESOLVE_SRC) $(RESOLVE_REST) + $(RESOLVE_DIR)/test_omega_resolve + $(CC) $(RESOLVE_FLAGS) -O1 -g -fsanitize=address,undefined -fno-sanitize-recover=all -DOSCV_PATH='"$(OUT_DIR)/compiler/oscv"' -o $(RESOLVE_DIR)/test_omega_resolve_asan tests/test_omega_resolve.c $(RESOLVE_SRC) $(RESOLVE_REST) + $(RESOLVE_DIR)/test_omega_resolve_asan + @set -eu; build_mutant() { name=$$1; tag=$$2; which=$$3; chk=$$4; repl=$$5; \ + case $$which in blake3) f=src/omega_blake3.c; pfx=B3M;; resolve) f=src/omega_resolve.c; pfx=VC1R;; receipt) f=src/omega_receipt.c; pfx=VC1R;; *) echo "bad mutant file $$which"; exit 1;; esac; \ + sed "/$$pfx:$$tag/c\\$$repl" $$f > $(RESOLVE_DIR)/mut_$$name.c; \ + if cmp -s $$f $(RESOLVE_DIR)/mut_$$name.c; then echo "mutant $$name: sed changed nothing"; exit 1; fi; \ + srcs=""; for s in $(RESOLVE_SRC); do if [ "$$s" = "$$f" ]; then srcs="$$srcs $(RESOLVE_DIR)/mut_$$name.c"; else srcs="$$srcs $$s"; fi; done; \ + $(CC) $(RESOLVE_FLAGS) -DOSCV_PATH='"$(OUT_DIR)/compiler/oscv"' -o $(RESOLVE_DIR)/mut_$$name tests/test_omega_resolve.c $$srcs $(RESOLVE_REST); \ + rc=0; $(RESOLVE_DIR)/mut_$$name $$name > $(RESOLVE_DIR)/mut_$$name.out 2>&1 || rc=$$?; \ + if [ $$rc -ne 1 ] || ! grep -q "^MUTANT $$name KILLED by $$chk\$$" $(RESOLVE_DIR)/mut_$$name.out; then \ + echo "mutant $$name NOT killed by $$chk (exit $$rc)"; tail -5 $(RESOLVE_DIR)/mut_$$name.out; exit 1; fi; \ + echo "mutant $$name: killed by $$chk (exit 1)"; }; \ + build_mutant b3-merge merge blake3 b3-official-vectors ' while ((total & 1) == 0 && sp > 1) {'; \ + build_mutant b3-root root blake3 b3-official-vectors ' cur.flags |= 0;'; \ + build_mutant profile-known profile-known resolve profile-unknown-refused ' if (!p) p = table;'; \ + build_mutant profile-version profile-version resolve profile-version-too-old-refused ' if (cmp < -1)'; \ + build_mutant lock-bytes-tab lock-bytes resolve lock-refuses-tab-in-comment ' if (text[i] == 13 || text[i] == 0) return lock_bad(err, 1, "CR or NUL byte");'; \ + build_mutant lock-bytes-cr lock-bytes resolve lock-refuses-cr-in-comment ' if (text[i] == 9 || text[i] == 0) return lock_bad(err, 1, "tab or NUL byte");'; \ + build_mutant lock-bytes-nul lock-bytes resolve lock-refuses-nul-in-comment ' if (text[i] == 9 || text[i] == 13) return lock_bad(err, 1, "tab or CR byte");'; \ + build_mutant lock-header lock-header resolve lock-refuses-wrong-header ' if (ll != 13) { free(ents); return lock_bad(err, line, "header"); }'; \ + build_mutant lock-unknown-line lock-unknown-line resolve lock-refuses-bad-name-start ' if (0) { free(ents); return lock_bad(err, line, "unknown line"); }'; \ + build_mutant lock-hex lock-hex resolve lock-refuses-uppercase-hex ' if (unhex32(h1, en.semantic) || unhex32(h2, en.receipt)) { memset(en.semantic, 1, 32); memset(en.receipt, 1, 32); }'; \ + build_mutant lock-order-duplicate lock-order resolve lock-refuses-duplicate-name ' if (n > 0 && strcmp(ents[n - 1].name, en.name) > 0) {'; \ + build_mutant lock-order-sorted lock-order resolve lock-refuses-unsorted ' if (n > 0 && strcmp(ents[n - 1].name, en.name) == 0) {'; \ + build_mutant missing-receipt missing-receipt resolve refuse-missing-receipt ' if (fr != 0) return fail(err, OMEGA_RES_UNVERIFIED_DEPENDENCY, 0, sid, "receipt unavailable");'; \ + build_mutant rule1-name rule1-name resolve refuse-receipt-file-holds-another-receipt ' if (0) {'; \ + build_mutant rule4-semantic rule4-semantic resolve refuse-receipt-does-not-name-program ' if (0) {'; \ + build_mutant rule4-source rule4-source resolve refuse-stale-receipt ' if (0) {'; \ + build_mutant rule3 rule3 resolve refuse-receipt-output-digest-is-not-evidence-root ' if (0) {'; \ + build_mutant rule5 rule5 resolve refuse-receipt-kind-is-not-profile ' if (0) {'; \ + build_mutant rule6 rule6 resolve refuse-receipt-has-extra-dependency ' if ((a != nrd || (a && memcmp(deps, rdeps, a * 32) != 0)) && 0) {'; \ + build_mutant rule2-pass rule2-pass resolve refuse-receipt-result-is-not-pass ' if (0) {'; \ + build_mutant rule2-assert rule2-assert resolve refuse-receipt-assertion-failed ' if (0) {'; \ + build_mutant rule2-testonly rule2-testonly resolve refuse-receipt-test-only-trust ' if (0) {'; \ + build_mutant rule2-tier rule2-tier resolve refuse-receipt-tier-below-profile ' if (!omega_tier_satisfies(need_rank, rcpt.tier_rank) && 0) {'; \ + build_mutant closure-receipt closure-receipt resolve closure-digest-matches-reference ' (void)e[i].receipt_id;'; \ + build_mutant cycle cycle resolve refuse-dependency-cycle ' if (0) return 0;'; \ + build_mutant lock-receipt lock-receipt resolve refuse-lock-pins-another-receipt ' if (0) {'; \ + build_mutant lock-receipt-visited visited-lock-receipt resolve refuse-lock-pins-another-receipt-for-visited-node ' if (0)'; \ + build_mutant genesis-gate genesis-gate resolve refuse-genesis-record-without-permission ' if (0) {'; \ + build_mutant taint-cap taint-cap resolve refuse-tainted-record-in-build-domain ' 0) {'; \ + build_mutant verified-needs-receipt verified-needs-receipt resolve refuse-missing-receipt ' if (0) {'; \ + build_mutant edge-contract edge-contract resolve refuse-edge-contract-mismatch ' if (memcmp(w->nodes[di].contract, req, 32) != 0 && 0) {'; \ + build_mutant boot-dep-verified boot-dep-verified resolve refuse-genesis-record-depending-on-verified ' if (0) {'; \ + build_mutant not-pinned not-pinned resolve refuse-not-pinned-without-lock ' if (0 && !omega_lock_find(lock, names[i]))'; \ + build_mutant undeclared undeclared resolve refuse-undeclared-lock-line-without-import ' if (!used && 0)'; \ + build_mutant closure-sort closure-sort resolve closure-sorted-ascending-by-semantic-id ' (void)cmp_entry;'; \ + build_mutant build-domain build-domain resolve build-id-matches-reference ' uint8_t db = (uint8_t)d & 0;'; \ + build_mutant build-closure build-closure resolve build-id-matches-reference ' (void)closure_digest;'; \ + build_mutant taint-mark taint-mark resolve artifact-dev-is-tainted-build-is-not ' m->tainted = 0;'; \ + build_mutant meta-taint-consistent meta-taint-consistent resolve artifact-refuses-dev-header-marked-untainted ' if (0)'; \ + build_mutant meta-build-id meta-build-id resolve artifact-refuses-edited-build-id ' if (0)'; \ + build_mutant admit-origin admit-origin resolve admit-refuses-record-from-tainted-origin ' if (origin && (origin->tainted || origin->domain == OMEGA_DOMAIN_DEV) && 0)'; \ + build_mutant admit-cap admit-cap resolve admit-refuses-taint-capability ' if (0) {'; \ + build_mutant admit-receipt admit-receipt resolve admit-refuses-mismatched-receipt ' rc = 0; (void)rr;'; \ + build_mutant genesis-dep genesis-dep resolve admit-genesis-refuses-verified-dependency ' if ((omega_vcstore_admission_kind(s, view->dependencies + 64 * (size_t)i, &k) != 0 || k != OMEGA_VCS_ADMISSION_BOOTSTRAP) && 0) {'; \ + build_mutant blob-digest blob-digest resolve refuse-blob-does-not-hash-to-digest ' if (0) {'; \ + build_mutant json-dup-key json-dup-key receipt receipt-refuses-duplicate-key ' if (0) { free(key); jfree(j); return jfail(p, "duplicate key"); }'; \ + build_mutant deny-unknown deny-unknown receipt receipt-refuses-unknown-field ' if (!all_known_key(root) && 0) { ef(&e, "receipt: unknown field%s", ""); goto done; }'; \ + build_mutant schema schema receipt receipt-refuses-unknown-schema ' if (strcmp(schema, SCHEMA) != 0 && 0) { ef(&e, "receipt: unknown receipt schema%s", ""); goto done; }'; \ + build_mutant version version receipt receipt-refuses-unknown-version ' if (r->version != 1 && 0) { ef(&e, "receipt: unsupported receipt version%s", ""); goto done; }'; \ + build_mutant feature feature receipt receipt-refuses-unknown-feature ' if (0) { ef(&e, "receipt: unknown required receipt feature%s", ""); goto done; }'; \ + build_mutant reserved reserved receipt receipt-refuses-reserved-field ' if (reserved[0] && 0) { ef(&e, "receipt: reserved field must be empty%s", ""); goto done; }'; \ + build_mutant env-class env-class receipt receipt-refuses-env-class-mismatch ' if (strcmp(r->env_class, r->tier) != 0 && 0) { ef(&e, "receipt: env_class contradicts tier%s", ""); goto done; }'; \ + build_mutant mutation-order mutation-order receipt receipt-refuses-observed-over-declared ' if (MUTS[r->observed_mutation].sev > MUTS[r->declared_mutation].sev && 0) { ef(&e, "receipt: observed mutation exceeds declared mutation%s", ""); goto done; }'; \ + build_mutant canon-sort canon-sort receipt receipt-canon-order-independent ' (void)cmp_str;'; \ + build_mutant id-compare id-compare receipt receipt-refuses-wrong-id ' if (0) {' + @echo "test-resolve: PASS (all checks, ASan/UBSan clean, all 55 mutants killed)" diff --git a/docs/osc/OSC-VC1-IMPORT.md b/docs/osc/OSC-VC1-IMPORT.md new file mode 100644 index 000000000..dfae035e4 --- /dev/null +++ b/docs/osc/OSC-VC1-IMPORT.md @@ -0,0 +1,63 @@ +# OSC import resolution (VC1 stage 4) + +Authority: ADR 0029 and aien-protocols `specs/verified-crumb/SPEC.md` (sections 5 to 8). This file records what the C +implementation does and where it stops. Code: `src/omega_resolve.c` (resolver, lock, identity), `src/omega_receipt.c` +(receipt reader), `src/omega_blake3.c`, `src/omega_resolve_osc.c` (front end adapter), `src/oscv_main.c` (`oscv` driver). +Tests: `make test-resolve`. + +## Grammar + +``` +unit := import* ( struct | fn )* +import := "import" NAME ";" +``` + +Imports come first. `import` is now a keyword (it was a reserved word). More than 64 imports is CAPACITY, a repeated +name is REDEFINED_NAME, an import after a struct or fn is SYNTAX. `osc_compile` (and `oscc`) refuses a unit with +imports (UNSUPPORTED). Only `osc_compile_imports` with a resolver hook accepts one, and the hook is called once per +compile even with zero imports (so a lock line with no import is caught). + +## Resolver flow (`omega_resolve_imports`) + +1. Declaration check, before any store access: every import needs a lock line (DEPENDENCY_NOT_PINNED); every lock line + needs an import (UNDECLARED_IMPORT). Direction chosen: an extra lock line is refused, not ignored. +2. Per node: lock line -> store get by semantic id -> identity (record id, optional blob digest, lock receipt equals + record receipt) -> kind (BOOTSTRAP needs `allow_genesis`) -> taint capability -> verifier profile and version -> + receipt check (SPEC 5.1 rules 1 to 6) -> edges (each dependency repeats the chain; contract ids must match; a node + already on the path is DEPENDENCY_CYCLE). +3. The closure is sorted by semantic id; its digest is `SHA-256("OMEGA.CLOSURE.V1" 0x00 || u32be n || n x (semantic_id || + receipt_id || kind))`. Any refusal returns no closure. + +Refusal codes: UNVERIFIED_DEPENDENCY, MISSING_RECEIPT, RECEIPT_HASH_MISMATCH, DEPENDENCY_NOT_PINNED, DEPENDENCY_CYCLE, +STALE_RECEIPT, UNDECLARED_IMPORT, TAINTED_ARTIFACT, UNKNOWN_VERIFIER_PROFILE, VERIFIER_TOO_OLD (enum in +`src/omega_resolve.h`). + +## Build identity + +`build_id = SHA-256("OSC1.BUILD.V1" 0x00 || ir_digest || domain byte || closure_digest)` in `omega_build_id`. That is +the one place the closure digest enters a build's identity. `oscv` prints it. + +## Domains + +`--domain build` (default) and `--domain dev` run the same checks; the domain never loosens one. omega-dev output +is TAINTED: its artifact header says `tainted 1`, its build id commits to the domain, and `omega_resolve_admit` refuses +to insert it (and refuses any record that lists the capability `omega-dev.taint`). A record listing that capability +can never satisfy an import in either domain. + +BOOTSTRAP (genesis) records satisfy an import only with `allow_genesis`. A BOOTSTRAP record may NOT depend on a +VERIFIED record (the audited base must be closed over itself); a VERIFIED record may depend on BOOTSTRAP. + +## No escape hatch + +No `unsafe import`, no skip switch, no environment variable. `make test-resolve` greps the compiler and resolver +sources for forbidden words and runs `oscv` with unknown switches and with environment variables set. + +## Limits (stated, not hidden) + +- Receipts are hashes, not signatures. The receipt reader recomputes the BLAKE3 id from the canonical bytes + (verified against three receipts written by the Rust implementation) but does not replicate ledger or lease store + bindings or chain walking of aien-proof. +- The program id is not recomputed from source; only the source digest is checked, and only when a blob store is given + (stage 6 supplies it). +- A dependency cycle cannot be built through the store API; it is refused when a tampered store holds one. +- `cl_program.c` and `omega_discovery.c` are not migrated here (stage 6). diff --git a/src/compiler/osc_diag.c b/src/compiler/osc_diag.c index 0d9a017b5..9ab762d3c 100644 --- a/src/compiler/osc_diag.c +++ b/src/compiler/osc_diag.c @@ -14,7 +14,7 @@ static const char *const kind_names[OSC_DIAG__COUNT] = { "CONDITIONAL_MOVE", "MUTABLE_ALIAS", "BORROW_OUTLIVES_OWNER", "STATIC_OUT_OF_BOUNDS", "IMMUTABLE_ASSIGN", "READ_ONLY_BORROW", "CONTRACT_INVALID", "CONTRACT_VIOLATION", "UNKNOWN_FIELD", "DUPLICATE_FIELD", "MISSING_FIELD", "UNDEFINED_TYPE", "RECURSIVE_STRUCT", "ARENA_ESCAPE", "ARENA_MOVE", "ARENA_CAPACITY", - "STALE_HANDLE", "WRONG_POOL", "POOL_CAPACITY", "GENERATION_EXHAUSTED"}; + "STALE_HANDLE", "WRONG_POOL", "POOL_CAPACITY", "GENERATION_EXHAUSTED", "IMPORT_REFUSED"}; const char *osc_diag_kind_name(int kind) { diff --git a/src/compiler/osc_diag.h b/src/compiler/osc_diag.h index 19b9683d2..5a0458daa 100644 --- a/src/compiler/osc_diag.h +++ b/src/compiler/osc_diag.h @@ -45,6 +45,8 @@ typedef enum { OSC_DIAG_WRONG_POOL, /* a handle of one pool is used with another pool (or copied across pools) */ OSC_DIAG_POOL_CAPACITY, /* pool K out of 1..16, or definite allocations exceed K live slots */ OSC_DIAG_GENERATION_EXHAUSTED, /* definite alloc/free cycles reuse a retired slot (generation would wrap) */ + /* VC1 stage 4 (docs/osc/OSC-VC1-IMPORT.md), appended */ + OSC_DIAG_IMPORT_REFUSED, /* an import did not resolve; transition = the resolver refusal code name */ OSC_DIAG__COUNT } OscDiagKind; diff --git a/src/compiler/osc_front.c b/src/compiler/osc_front.c index 5dc42d16d..f793f9117 100644 --- a/src/compiler/osc_front.c +++ b/src/compiler/osc_front.c @@ -10,7 +10,8 @@ #include #include -int osc_compile(const char *src, size_t len, OscUnit *out, OscDiag *diag, OscTrace *trace) +int osc_compile_imports(const char *src, size_t len, OscUnit *out, OscDiag *diag, OscTrace *trace, + OscImportResolver resolver, void *resolver_ctx) { memset(diag, 0, sizeof *diag); if (trace) { trace->n = 0; trace->overflow = 0; trace->refused = 0; trace->nfuncs = 0; } @@ -28,6 +29,26 @@ int osc_compile(const char *src, size_t len, OscUnit *out, OscDiag *diag, OscTra ast->toks = toks; ast->ntok = ntok; if (osc_parse(ast, diag)) goto out; + if (resolver) { + uint32_t bad = UINT32_MAX; + char why[160]; + why[0] = 0; + if (resolver(resolver_ctx, ast->imports, ast->nimports, &bad, why, sizeof why)) { + const OscImport *im = bad < ast->nimports ? &ast->imports[bad] : NULL; + char code[96]; + size_t cl = strcspn(why, ":"); + if (cl >= sizeof code) cl = sizeof code - 1; + memcpy(code, why, cl); + code[cl] = 0; + osc_diag_set(diag, OSC_DIAG_IMPORT_REFUSED, im ? im->line : 1, im ? im->col : 1, im ? im->name : "imports", 0, + NULL, code, "%s", why[0] ? why : "import refused"); + goto out; + } + } else if (ast->nimports) { + osc_diag_set(diag, OSC_DIAG_UNSUPPORTED, ast->imports[0].line, ast->imports[0].col, ast->imports[0].name, 0, + NULL, "import", "imports are resolved only by the verified driver (oscv); this entry point has no resolver"); + goto out; + } if (ast->nfns == 0) { osc_diag_set(diag, OSC_DIAG_UNSUPPORTED, 1, 1, "unit", 0, NULL, "empty unit", "a unit must define at least one function"); @@ -47,3 +68,8 @@ out: free(ast); return rc; } + +int osc_compile(const char *src, size_t len, OscUnit *out, OscDiag *diag, OscTrace *trace) +{ + return osc_compile_imports(src, len, out, diag, trace, NULL, NULL); +} diff --git a/src/compiler/osc_front.h b/src/compiler/osc_front.h index 6105df9b8..05b5ea70d 100644 --- a/src/compiler/osc_front.h +++ b/src/compiler/osc_front.h @@ -13,7 +13,19 @@ #include "osc_diag.h" #include "osc_ir.h" -/* 0 ok (out passed osc_ir_validate); -1 with *diag filled. +/* VC1 stage 4: import resolution hook. The front end parses `import NAME;` lines and, when a + * resolver is supplied, hands it ALL imports of the unit (possibly none) right after parsing. + * It returns 0 to accept, or nonzero with why = "CODE_NAME: plain text" (and *bad = the index of + * the import it refused, or UINT32_MAX when the refusal is about the unit as a whole). There is no + * default resolver and no way to turn the hook off: osc_compile (below) passes none and REFUSES a + * unit that has imports. The resolver is src/omega_resolve.c, linked only by the verified driver. */ +typedef int (*OscImportResolver)(void *ctx, const OscImport *imports, uint32_t n, uint32_t *bad, char *why, size_t why_cap); + +int osc_compile_imports(const char *src, size_t len, OscUnit *out, OscDiag *diag, OscTrace *trace_or_NULL, + OscImportResolver resolver, void *resolver_ctx); + +/* 0 ok (out passed osc_ir_validate); -1 with *diag filled. A unit with imports is refused here + * (UNSUPPORTED): only osc_compile_imports with a resolver can accept one. * trace_or_NULL receives the per-function ownership event trace (also on a * refusal: the refused event is the last one, flagged). */ int osc_compile(const char *src, size_t len, OscUnit *out, OscDiag *diag, OscTrace *trace_or_NULL); diff --git a/src/compiler/osc_lex.c b/src/compiler/osc_lex.c index abadc0b83..632323c35 100644 --- a/src/compiler/osc_lex.c +++ b/src/compiler/osc_lex.c @@ -13,7 +13,7 @@ static const struct { const char *w; int k; } keywords[] = { {"as", OT_AS}, {"true", OT_TRUE}, {"false", OT_FALSE}, {"u8", OT_U8}, {"u16", OT_U16}, {"u32", OT_U32}, {"u64", OT_U64}, {"i8", OT_I8}, {"i16", OT_I16}, {"i32", OT_I32}, {"i64", OT_I64}, {"bool", OT_BOOL}, {"struct", OT_STRUCT}, {"arena", OT_ARENA}, - {"pool", OT_POOL}, {"handle", OT_HANDLE}, + {"pool", OT_POOL}, {"handle", OT_HANDLE}, {"import", OT_IMPORT}, }; /* Reserved: destruction words (destruction has no surface syntax, III.8) and @@ -21,7 +21,7 @@ static const struct { const char *w; int k; } keywords[] = { static const char *const reserved[] = { "free", "drop", "delete", "dealloc", "effect", "cap", "capability", "mint", "revoke", "grant", "publish", "promote", "authority", "admin", - "syscall", "io", "print", "import", "extern", "unsafe", "asm", "loop", "match", "enum", + "syscall", "io", "print", "extern", "unsafe", "asm", "loop", "match", "enum", "var", "const", "self", "rec", "break", "continue", }; @@ -31,7 +31,7 @@ static const char *const kind_names[OT__COUNT] = { "ensures", "as", "true", "false", "u8", "u16", "u32", "u64", "i8", "i16", "i32", "i64", "bool", "(", ")", "{", "}", "[", "]", ",", ";", ":", "->", "..", "=", "+", "-", "*", "/", "%", "&", "|", "^", "~", "!", "&&", "||", "<<", ">>", "==", "!=", "<", "<=", ">", ">=", - "struct", ".", "arena", "pool", "handle", + "struct", ".", "arena", "pool", "handle", "import", }; const char *osc_tok_kind_name(int kind) diff --git a/src/compiler/osc_lex.h b/src/compiler/osc_lex.h index c74854656..cf6670eb5 100644 --- a/src/compiler/osc_lex.h +++ b/src/compiler/osc_lex.h @@ -31,6 +31,8 @@ typedef enum { OT_ARENA, /* OSC-3 item 2 (versioned handles), appended */ OT_POOL, OT_HANDLE, + /* VC1 stage 4: `import NAME;` (resolved only by the verified driver, src/omega_resolve.h), appended */ + OT_IMPORT, OT__COUNT } OscTokKind; diff --git a/src/compiler/osc_parse.c b/src/compiler/osc_parse.c index 19440785e..ff9f8bc65 100644 --- a/src/compiler/osc_parse.c +++ b/src/compiler/osc_parse.c @@ -1103,6 +1103,34 @@ static int parse_fn(P *p) return 0; } +static int parse_import(P *p) +{ + OscAst *a = p->ast; + const OscToken *kw = cur(p); + adv(p); + if (!at(p, OT_NAME)) return syntax(p, "NAME"); + const OscToken *nm = cur(p); + if (a->nimports >= OSC_MAX_IMPORTS) { + osc_diag_set(p->d, OSC_DIAG_CAPACITY, kw->line, kw->col, "unit", 0, NULL, "import capacity", + "more than %d imports", OSC_MAX_IMPORTS); + return -1; + } + OscImport *im = &a->imports[a->nimports]; + im->line = nm->line; + im->col = nm->col; + osc_tok_text(a->src, nm, im->name, sizeof im->name); + for (uint8_t k = 0; k < a->nimports; k++) + if (strcmp(a->imports[k].name, im->name) == 0) { + osc_diag_set(p->d, OSC_DIAG_REDEFINED_NAME, nm->line, nm->col, im->name, a->imports[k].line, NULL, + "import", "import '%s' is listed twice", im->name); + return -1; + } + adv(p); + if (expect(p, OT_SEMI)) return -1; + a->nimports++; + return 0; +} + int osc_parse(OscAst *ast, OscDiag *d) { P p = {ast, d, 0, 0}; @@ -1110,7 +1138,18 @@ int osc_parse(OscAst *ast, OscDiag *d) ast->nfns = 0; ast->nrel = 0; ast->nstructs = 0; + ast->nimports = 0; while (!at(&p, OT_EOF)) { + if (at(&p, OT_IMPORT)) { + if (ast->nstructs || ast->nfns) { + const OscToken *t = cur(&p); + osc_diag_set(d, OSC_DIAG_SYNTAX, t->line, t->col, "import", 0, NULL, "import position", + "imports must come before any struct or function"); + return -1; + } + if (parse_import(&p)) return -1; + continue; + } if (at(&p, OT_STRUCT)) { if (parse_struct(&p)) return -1; continue; } if (parse_fn(&p)) return -1; } diff --git a/src/compiler/osc_parse.h b/src/compiler/osc_parse.h index 12ca3ff8c..f9301c7ef 100644 --- a/src/compiler/osc_parse.h +++ b/src/compiler/osc_parse.h @@ -20,6 +20,12 @@ #define OSC_AST_MAX_REL 16384 /* release-list entries (checker) */ #define OSC_ARENA_MAX_CELLS OSC_MAX_ARRAY_LEN /* arena bound K: 1..64 cells (one pool slot) */ #define OSC_POOL_MAX_SLOTS 16 /* pool K: 1..16 slots (OSC-0B model slot capacity) */ +#define OSC_MAX_IMPORTS 64 /* `import NAME;` lines per unit (VC1 stage 4) */ + +typedef struct { + uint32_t line, col; /* of the NAME token */ + char name[OSC_LEX_NAME_MAX + 1]; +} OscImport; typedef enum { ON_NONE = 0, @@ -132,6 +138,10 @@ typedef struct { OscStruct structs[OSC_MAX_STRUCTS]; uint32_t struct_line[OSC_MAX_STRUCTS]; uint8_t nstructs; + /* VC1 stage 4: `import NAME;` lines, in source order (parser). Only the verified driver + * resolves them (osc_compile_imports); plain osc_compile refuses a unit that has any. */ + OscImport imports[OSC_MAX_IMPORTS]; + uint8_t nimports; } OscAst; /* Parse the token stream into ast (ast->src/toks/ntok must be set). 0 ok, -1 diff --git a/src/omega_blake3.c b/src/omega_blake3.c new file mode 100644 index 000000000..6e2f4baea --- /dev/null +++ b/src/omega_blake3.c @@ -0,0 +1,154 @@ +/* omega_blake3.c -- see omega_blake3.h. Follows the BLAKE3 reference construction: + * 1024-byte chunks of 64-byte blocks, a binary tree of parent nodes, the ROOT flag on the + * last compression only. Mutation tags (B3M:) mark lines make test-resolve breaks. */ +#include "omega_blake3.h" + +#include + +#define CHUNK_START 1u +#define CHUNK_END 2u +#define PARENT 4u +#define ROOT 8u +#define CHUNK_LEN 1024u +#define BLOCK_LEN 64u + +static const uint32_t IV[8] = { + 0x6A09E667u, 0xBB67AE85u, 0x3C6EF372u, 0xA54FF53Au, + 0x510E527Fu, 0x9B05688Cu, 0x1F83D9ABu, 0x5BE0CD19u +}; +static const uint8_t PERM[16] = { 2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8 }; + +static uint32_t rotr(uint32_t x, int n) { return (x >> n) | (x << (32 - n)); } + +static void g(uint32_t *s, int a, int b, int c, int d, uint32_t mx, uint32_t my) +{ + s[a] = s[a] + s[b] + mx; + s[d] = rotr(s[d] ^ s[a], 16); + s[c] = s[c] + s[d]; + s[b] = rotr(s[b] ^ s[c], 12); + s[a] = s[a] + s[b] + my; + s[d] = rotr(s[d] ^ s[a], 8); + s[c] = s[c] + s[d]; + s[b] = rotr(s[b] ^ s[c], 7); +} + +static void round_fn(uint32_t *s, const uint32_t *m) +{ + g(s, 0, 4, 8, 12, m[0], m[1]); + g(s, 1, 5, 9, 13, m[2], m[3]); + g(s, 2, 6, 10, 14, m[4], m[5]); + g(s, 3, 7, 11, 15, m[6], m[7]); + g(s, 0, 5, 10, 15, m[8], m[9]); + g(s, 1, 6, 11, 12, m[10], m[11]); + g(s, 2, 7, 8, 13, m[12], m[13]); + g(s, 3, 4, 9, 14, m[14], m[15]); +} + +/* out: the 16-word state after the final xor; words 0..7 are the chaining value */ +static void compress(const uint32_t cv[8], const uint8_t block[BLOCK_LEN], uint32_t block_len, + uint64_t counter, uint32_t flags, uint32_t out[16]) +{ + uint32_t m[16], t[16]; + for (int i = 0; i < 16; i++) + m[i] = (uint32_t)block[4 * i] | (uint32_t)block[4 * i + 1] << 8 | + (uint32_t)block[4 * i + 2] << 16 | (uint32_t)block[4 * i + 3] << 24; + uint32_t s[16] = { + cv[0], cv[1], cv[2], cv[3], cv[4], cv[5], cv[6], cv[7], + IV[0], IV[1], IV[2], IV[3], + (uint32_t)counter, (uint32_t)(counter >> 32), block_len, flags + }; + for (int r = 0; r < 7; r++) { + round_fn(s, m); + for (int i = 0; i < 16; i++) t[i] = m[PERM[i]]; + memcpy(m, t, sizeof m); + } + for (int i = 0; i < 8; i++) { + out[i] = s[i] ^ s[i + 8]; + out[i + 8] = s[i + 8] ^ cv[i]; + } +} + +/* The inputs of the last compression of a chunk or a parent: kept unfinished so the ROOT flag + * can still be added to whichever compression turns out to be the last. */ +typedef struct { + uint32_t cv[8]; + uint8_t block[BLOCK_LEN]; + uint32_t block_len; + uint64_t counter; + uint32_t flags; +} Node; + +static void node_cv(const Node *n, uint32_t out[8]) +{ + uint32_t st[16]; + compress(n->cv, n->block, n->block_len, n->counter, n->flags, st); + memcpy(out, st, 8 * sizeof(uint32_t)); +} + +/* the (unfinished) last compression of chunk number `counter` holding data[0..len) */ +static Node chunk_node(const uint8_t *data, size_t len, uint64_t counter) +{ + Node n; + memcpy(n.cv, IV, sizeof n.cv); + size_t nblocks = len ? (len + BLOCK_LEN - 1) / BLOCK_LEN : 1; + for (size_t b = 0; b + 1 < nblocks; b++) { + uint32_t fl = (b == 0) ? CHUNK_START : 0; + uint32_t st[16]; + compress(n.cv, data + b * BLOCK_LEN, BLOCK_LEN, counter, fl, st); + memcpy(n.cv, st, 8 * sizeof(uint32_t)); + } + size_t off = (nblocks - 1) * BLOCK_LEN, rem = len - off; + memset(n.block, 0, sizeof n.block); + if (rem) memcpy(n.block, data + off, rem); + n.block_len = (uint32_t)rem; + n.counter = counter; + n.flags = CHUNK_END | (nblocks == 1 ? CHUNK_START : 0); + return n; +} + +static Node parent_node(const uint32_t left[8], const uint32_t right[8]) +{ + Node n; + memcpy(n.cv, IV, sizeof n.cv); + for (int i = 0; i < 8; i++) { + for (int k = 0; k < 4; k++) { + n.block[4 * i + k] = (uint8_t)(left[i] >> (8 * k)); + n.block[32 + 4 * i + k] = (uint8_t)(right[i] >> (8 * k)); + } + } + n.block_len = BLOCK_LEN; + n.counter = 0; + n.flags = PARENT; + return n; +} + +void omega_blake3_hash(const uint8_t *data, size_t len, uint8_t out[32]) +{ + uint32_t stack[64][8]; + int sp = 0; + size_t nchunks = len ? (len + CHUNK_LEN - 1) / CHUNK_LEN : 1; + for (size_t c = 0; c + 1 < nchunks; c++) { + Node n = chunk_node(data + c * CHUNK_LEN, CHUNK_LEN, c); + uint32_t cv[8]; + node_cv(&n, cv); + uint64_t total = c + 1; + while ((total & 1) == 0) { /* B3M:merge */ + Node p = parent_node(stack[--sp], cv); + node_cv(&p, cv); + total >>= 1; + } + memcpy(stack[sp++], cv, sizeof cv); + } + size_t last = (nchunks - 1) * CHUNK_LEN; + Node cur = chunk_node(data + last, len - last, nchunks - 1); + while (sp > 0) { + uint32_t cv[8]; + node_cv(&cur, cv); + cur = parent_node(stack[--sp], cv); + } + cur.flags |= ROOT; /* B3M:root */ + uint32_t st[16]; + compress(cur.cv, cur.block, cur.block_len, cur.counter, cur.flags, st); + for (int i = 0; i < 8; i++) + for (int k = 0; k < 4; k++) out[4 * i + k] = (uint8_t)(st[i] >> (8 * k)); +} diff --git a/src/omega_blake3.h b/src/omega_blake3.h new file mode 100644 index 000000000..f2cd3d604 --- /dev/null +++ b/src/omega_blake3.h @@ -0,0 +1,17 @@ +#ifndef OMEGA_BLAKE3_H +#define OMEGA_BLAKE3_H + +/* omega_blake3: BLAKE3 default (unkeyed) hash, 32-byte output, one shot. VC1 stage 4. + * + * Why it exists: an aien-proof EvidenceReceiptV1 id is BLAKE3 over the receipt's canonical + * bytes (aien-protocols specs/evidence-receipt/SUBSET.md section 1), and the resolver must + * recompute that id itself (SPEC 5.1 rule 1). Portable C, no SIMD, no allocation, no state. + * Verified against the official BLAKE3 test vectors (tests/resolve/blake3_vectors.txt, from + * BLAKE3-team/BLAKE3 test_vectors/test_vectors.json, input = 0,1,..,250 repeating). */ + +#include +#include + +void omega_blake3_hash(const uint8_t *data, size_t len, uint8_t out[32]); + +#endif /* OMEGA_BLAKE3_H */ diff --git a/src/omega_receipt.c b/src/omega_receipt.c new file mode 100644 index 000000000..b92f0d2a7 --- /dev/null +++ b/src/omega_receipt.c @@ -0,0 +1,695 @@ +/* omega_receipt.c -- see omega_receipt.h. + * Lines tagged VC1R: are the ones `make test-resolve` deletes or weakens, one at a time + * (the mutation proof). */ +#include "omega_receipt.h" + +#include +#include +#include + +#include "omega_blake3.h" + +#define DOMAIN "AIEN_EVIDENCE_RECEIPT_V1" +#define SCHEMA "EvidenceReceiptV1" + +/* ---------------------------------------------------------------- small helpers */ +static void seterr(char *err, size_t cap, const char *fmt, const char *a) +{ + if (err && cap) snprintf(err, cap, fmt, a ? a : ""); +} + +static int hexval(int c) +{ + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + if (c >= 'A' && c <= 'F') return c - 'A' + 10; + return -1; +} +static int is_hex(const char *s) +{ + if (!*s) return 0; + for (; *s; s++) if (hexval((unsigned char)*s) < 0) return 0; + return 1; +} +static int is_lower_hex(const char *s) +{ + if (!*s) return 0; + for (; *s; s++) if (!((*s >= '0' && *s <= '9') || (*s >= 'a' && *s <= 'f'))) return 0; + return 1; +} +/* exactly 64 hex digits (any case) to 32 bytes */ +static int hex32(const char *s, uint8_t out[32]) +{ + if (strlen(s) != 64) return -1; + for (int i = 0; i < 32; i++) { + int hi = hexval((unsigned char)s[2 * i]), lo = hexval((unsigned char)s[2 * i + 1]); + if (hi < 0 || lo < 0) return -1; + out[i] = (uint8_t)(hi << 4 | lo); + } + return 0; +} + +/* ---------------------------------------------------------------- tiers, verdicts, mutations */ +static const struct { const char *name; int rank; } TIERS[] = { + {"TEST_ONLY_TRUST", 0}, {"HOST_TEST", 1}, {"QEMU", 2}, {"QEMU_SECURITY", 3}, + {"MACHINE1_READ_ONLY", 4}, {"MACHINE1_ATTENDED", 5}, {"MACHINE1_MUTATING", 6}, {"PRODUCTION", 7}, +}; +int omega_tier_rank(const char *tier) +{ + for (size_t i = 0; i < sizeof TIERS / sizeof TIERS[0]; i++) + if (strcmp(TIERS[i].name, tier) == 0) return TIERS[i].rank; + return -1; +} +int omega_tier_satisfies(int need, int have) +{ + if (need < 0 || have < 0) return 0; + if (have == 0) return need == 0; /* test-only trust satisfies only itself */ + if (need >= 4 && have < 4) return 0; /* physical needs physical (rank >= 4) */ + return have >= need; +} +static const char *const VERDICTS[] = { "PASS", "FAIL", "BLOCKED", "INCOMPLETE", "SKIPPED" }; +/* name, wire code, severity */ +static const struct { const char *name; uint8_t code, sev; } MUTS[] = { + {"NONE", 0, 0}, {"VOLATILE_ONLY", 1, 1}, {"REMOVABLE_MEDIA_ONLY", 2, 2}, + {"ONE_TIME_BOOT_SELECTION", 3, 3}, {"BOUNDED_TEST_REGION_WRITE", 4, 4}, + {"BOOT_CONFIGURATION_CHANGE", 5, 5}, {"TRUST_ROOT_CHANGE", 6, 6}, + {"TPM_POLICY_CHANGE", 7, 6}, {"DESTRUCTIVE_STORAGE", 8, 7}, +}; +#define N_MUTS (sizeof MUTS / sizeof MUTS[0]) + +/* ---------------------------------------------------------------- JSON DOM */ +typedef enum { J_NULL, J_BOOL, J_NUM, J_STR, J_ARR, J_OBJ } JK; +typedef struct J { + JK k; + int b; + uint64_t u; + int is_uint; + char *s; /* J_STR, NUL-terminated, no embedded NUL */ + struct J **v; /* J_ARR items, J_OBJ values */ + char **keys; /* J_OBJ */ + size_t n; +} J; + +typedef struct { const uint8_t *p; size_t n, i; int depth; char err[160]; } JP; + +static J *jnew(JK k) +{ + J *j = calloc(1, sizeof *j); + if (j) j->k = k; + return j; +} +static void jfree(J *j) +{ + if (!j) return; + free(j->s); + for (size_t i = 0; i < j->n; i++) { jfree(j->v ? j->v[i] : NULL); if (j->keys) free(j->keys[i]); } + free(j->v); + free(j->keys); + free(j); +} +static J *jfail(JP *p, const char *what) +{ + if (!p->err[0]) snprintf(p->err, sizeof p->err, "receipt JSON: %s at byte %zu", what, p->i); + return NULL; +} +static void jws(JP *p) +{ + while (p->i < p->n && (p->p[p->i] == ' ' || p->p[p->i] == '\t' || p->p[p->i] == '\n' || p->p[p->i] == '\r')) p->i++; +} +static int utf8_len(const uint8_t *s, size_t avail) +{ + if (s[0] < 0x80) return 1; + if (s[0] >= 0xC2 && s[0] <= 0xDF && avail >= 2 && (s[1] & 0xC0) == 0x80) return 2; + if (s[0] >= 0xE0 && s[0] <= 0xEF && avail >= 3 && (s[1] & 0xC0) == 0x80 && (s[2] & 0xC0) == 0x80) { + uint32_t cp = (uint32_t)(s[0] & 0x0F) << 12 | (uint32_t)(s[1] & 0x3F) << 6 | (s[2] & 0x3F); + if (cp >= 0x800 && !(cp >= 0xD800 && cp <= 0xDFFF)) return 3; + } + if (s[0] >= 0xF0 && s[0] <= 0xF4 && avail >= 4 && (s[1] & 0xC0) == 0x80 && (s[2] & 0xC0) == 0x80 && (s[3] & 0xC0) == 0x80) { + uint32_t cp = (uint32_t)(s[0] & 0x07) << 18 | (uint32_t)(s[1] & 0x3F) << 12 | (uint32_t)(s[2] & 0x3F) << 6 | (s[3] & 0x3F); + if (cp >= 0x10000 && cp <= 0x10FFFF) return 4; + } + return 0; +} +static int put_utf8(char *o, uint32_t cp) +{ + if (cp < 0x80) { o[0] = (char)cp; return 1; } + if (cp < 0x800) { o[0] = (char)(0xC0 | cp >> 6); o[1] = (char)(0x80 | (cp & 0x3F)); return 2; } + if (cp < 0x10000) { o[0] = (char)(0xE0 | cp >> 12); o[1] = (char)(0x80 | ((cp >> 6) & 0x3F)); o[2] = (char)(0x80 | (cp & 0x3F)); return 3; } + o[0] = (char)(0xF0 | cp >> 18); o[1] = (char)(0x80 | ((cp >> 12) & 0x3F)); + o[2] = (char)(0x80 | ((cp >> 6) & 0x3F)); o[3] = (char)(0x80 | (cp & 0x3F)); + return 4; +} +static int hex4(JP *p, uint32_t *out) +{ + if (p->i + 4 > p->n) return -1; + uint32_t v = 0; + for (int k = 0; k < 4; k++) { + int h = hexval(p->p[p->i + k]); + if (h < 0) return -1; + v = v << 4 | (uint32_t)h; + } + p->i += 4; + *out = v; + return 0; +} +/* p->i is just past the opening quote */ +static char *jstring(JP *p) +{ + size_t cap = 16, n = 0; + char *s = malloc(cap); + if (!s) { jfail(p, "out of memory"); return NULL; } + for (;;) { + if (p->i >= p->n) { free(s); jfail(p, "unterminated string"); return NULL; } + uint8_t c = p->p[p->i]; + if (n + 8 > cap) { cap *= 2; char *t = realloc(s, cap); if (!t) { free(s); jfail(p, "out of memory"); return NULL; } s = t; } + if (c == '"') { p->i++; s[n] = 0; return s; } + if (c < 0x20) { free(s); jfail(p, "control character in string"); return NULL; } + if (c == '\\') { + p->i++; + if (p->i >= p->n) { free(s); jfail(p, "bad escape"); return NULL; } + uint8_t e = p->p[p->i++]; + switch (e) { + case '"': s[n++] = '"'; break; + case '\\': s[n++] = '\\'; break; + case '/': s[n++] = '/'; break; + case 'b': s[n++] = '\b'; break; + case 'f': s[n++] = '\f'; break; + case 'n': s[n++] = '\n'; break; + case 'r': s[n++] = '\r'; break; + case 't': s[n++] = '\t'; break; + case 'u': { + uint32_t cp; + if (hex4(p, &cp)) { free(s); jfail(p, "bad \\u escape"); return NULL; } + if (cp >= 0xD800 && cp <= 0xDBFF) { + uint32_t lo; + if (p->i + 2 > p->n || p->p[p->i] != '\\' || p->p[p->i + 1] != 'u') { free(s); jfail(p, "lone surrogate"); return NULL; } + p->i += 2; + if (hex4(p, &lo) || lo < 0xDC00 || lo > 0xDFFF) { free(s); jfail(p, "bad surrogate pair"); return NULL; } + cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00); + } else if (cp >= 0xDC00 && cp <= 0xDFFF) { free(s); jfail(p, "lone surrogate"); return NULL; } + if (cp == 0) { free(s); jfail(p, "NUL in string"); return NULL; } + n += (size_t)put_utf8(s + n, cp); + break; + } + default: free(s); jfail(p, "bad escape"); return NULL; + } + continue; + } + int l = utf8_len(p->p + p->i, p->n - p->i); + if (!l) { free(s); jfail(p, "invalid UTF-8"); return NULL; } + memcpy(s + n, p->p + p->i, (size_t)l); + n += (size_t)l; + p->i += (size_t)l; + } +} +static J *jvalue(JP *p); +static J *jcontainer(JP *p, int is_obj) +{ + if (++p->depth > 6) return jfail(p, "nesting too deep"); + J *j = jnew(is_obj ? J_OBJ : J_ARR); + if (!j) return jfail(p, "out of memory"); + size_t cap = 0; + jws(p); + char close = is_obj ? '}' : ']'; + if (p->i < p->n && p->p[p->i] == close) { p->i++; p->depth--; return j; } + for (;;) { + jws(p); + char *key = NULL; + if (is_obj) { + if (p->i >= p->n || p->p[p->i] != '"') { jfree(j); return jfail(p, "expected object key"); } + p->i++; + key = jstring(p); + if (!key) { jfree(j); return NULL; } + for (size_t k = 0; k < j->n; k++) + if (strcmp(j->keys[k], key) == 0) { free(key); jfree(j); return jfail(p, "duplicate key"); } /* VC1R:json-dup-key */ + jws(p); + if (p->i >= p->n || p->p[p->i] != ':') { free(key); jfree(j); return jfail(p, "expected ':'"); } + p->i++; + } + J *v = jvalue(p); + if (!v) { free(key); jfree(j); return NULL; } + if (j->n == cap) { + cap = cap ? cap * 2 : 8; + J **nv = realloc(j->v, cap * sizeof *nv); + char **nk = is_obj ? realloc(j->keys, cap * sizeof *nk) : NULL; + if (nv) j->v = nv; + if (nk) j->keys = nk; + if (!nv || (is_obj && !nk)) { free(key); jfree(v); jfree(j); return jfail(p, "out of memory"); } + } + j->v[j->n] = v; + if (is_obj) j->keys[j->n] = key; + j->n++; + jws(p); + if (p->i < p->n && p->p[p->i] == ',') { p->i++; continue; } + if (p->i < p->n && p->p[p->i] == close) { p->i++; break; } + jfree(j); + return jfail(p, "expected ',' or closing bracket"); + } + p->depth--; + return j; +} +static J *jvalue(JP *p) +{ + jws(p); + if (p->i >= p->n) return jfail(p, "unexpected end"); + uint8_t c = p->p[p->i]; + if (c == '{') { p->i++; return jcontainer(p, 1); } + if (c == '[') { p->i++; return jcontainer(p, 0); } + if (c == '"') { + p->i++; + char *s = jstring(p); + if (!s) return NULL; + J *j = jnew(J_STR); + if (!j) { free(s); return jfail(p, "out of memory"); } + j->s = s; + return j; + } + if (p->n - p->i >= 4 && memcmp(p->p + p->i, "null", 4) == 0) { p->i += 4; return jnew(J_NULL); } + if (p->n - p->i >= 4 && memcmp(p->p + p->i, "true", 4) == 0) { p->i += 4; J *j = jnew(J_BOOL); if (j) j->b = 1; return j; } + if (p->n - p->i >= 5 && memcmp(p->p + p->i, "false", 5) == 0) { p->i += 5; return jnew(J_BOOL); } + if (c == '-' || (c >= '0' && c <= '9')) { + size_t s = p->i; + if (c == '-') p->i++; + size_t d0 = p->i; + while (p->i < p->n && p->p[p->i] >= '0' && p->p[p->i] <= '9') p->i++; + if (p->i == d0) return jfail(p, "bad number"); + if (p->p[d0] == '0' && p->i - d0 > 1) return jfail(p, "leading zero"); + int plain = (c != '-'); + if (p->i < p->n && (p->p[p->i] == '.' || p->p[p->i] == 'e' || p->p[p->i] == 'E')) { + plain = 0; + p->i++; + while (p->i < p->n && ((p->p[p->i] >= '0' && p->p[p->i] <= '9') || p->p[p->i] == '+' || p->p[p->i] == '-' || + p->p[p->i] == 'e' || p->p[p->i] == 'E' || p->p[p->i] == '.')) p->i++; + } + J *j = jnew(J_NUM); + if (!j) return jfail(p, "out of memory"); + if (plain) { + uint64_t v = 0; + int ok = (p->i - s) <= 20; + for (size_t k = s; ok && k < p->i; k++) { + uint64_t dgt = (uint64_t)(p->p[k] - '0'); + if (v > (UINT64_MAX - dgt) / 10) ok = 0; else v = v * 10 + dgt; + } + j->is_uint = ok; + j->u = v; + } + return j; + } + return jfail(p, "unexpected character"); +} + +static const J *oget(const J *o, const char *key) +{ + for (size_t i = 0; i < o->n; i++) if (strcmp(o->keys[i], key) == 0) return o->v[i]; + return NULL; +} + +/* ---------------------------------------------------------------- receipt extraction */ +typedef struct { char *err; size_t cap; } Er; +static int ef(Er *e, const char *fmt, const char *a) { seterr(e->err, e->cap, fmt, a); return -1; } + +static int want_str(Er *e, const J *o, const char *key, int required, char **out) +{ + const J *v = oget(o, key); + if (!v) { + if (required) return ef(e, "receipt: missing field %s", key); + *out = strdup(""); + return *out ? 0 : ef(e, "receipt: out of memory%s", ""); + } + if (v->k != J_STR) return ef(e, "receipt: field %s must be a string", key); + *out = strdup(v->s); + return *out ? 0 : ef(e, "receipt: out of memory%s", ""); +} +static int want_strlist(Er *e, const J *o, const char *key, int required, char ***out, size_t *n) +{ + const J *v = oget(o, key); + *out = NULL; *n = 0; + if (!v) return required ? ef(e, "receipt: missing field %s", key) : 0; + if (v->k != J_ARR) return ef(e, "receipt: field %s must be a list", key); + if (v->n > 4096) return ef(e, "receipt: field %s is too long", key); + if (v->n == 0) return 0; + char **a = calloc(v->n, sizeof *a); + if (!a) return ef(e, "receipt: out of memory%s", ""); + *out = a; *n = v->n; + for (size_t i = 0; i < v->n; i++) { + if (v->v[i]->k != J_STR) return ef(e, "receipt: list %s must hold strings", key); + a[i] = strdup(v->v[i]->s); + if (!a[i]) return ef(e, "receipt: out of memory%s", ""); + } + return 0; +} +static int want_bool(Er *e, const J *o, const char *key, int *out) +{ + const J *v = oget(o, key); + if (!v) return ef(e, "receipt: missing field %s", key); + if (v->k != J_BOOL) return ef(e, "receipt: field %s must be true or false", key); + *out = v->b; + return 0; +} +static int want_u64(Er *e, const J *o, const char *key, uint64_t *out) +{ + const J *v = oget(o, key); + if (!v) return ef(e, "receipt: missing field %s", key); + if (v->k != J_NUM || !v->is_uint) return ef(e, "receipt: field %s must be an unsigned integer", key); + *out = v->u; + return 0; +} +static int want_mut(Er *e, const J *o, const char *key, uint8_t *out) +{ + char *s = NULL; + if (want_str(e, o, key, 1, &s)) return -1; + int found = 0; + for (size_t i = 0; i < N_MUTS; i++) if (strcmp(MUTS[i].name, s) == 0) { *out = (uint8_t)i; found = 1; } + free(s); + return found ? 0 : ef(e, "receipt: unknown mutation in %s", key); +} + +void omega_receipt_free(OmegaReceipt *r) +{ + if (!r) return; + char **sv[] = { &r->kind, &r->tier, &r->repo, &r->commit, &r->toolchain, &r->procedure, &r->machine, + &r->env_class, &r->authority, &r->lease_resource }; + for (size_t i = 0; i < sizeof sv / sizeof sv[0]; i++) { free(*sv[i]); *sv[i] = NULL; } + char ***lv[] = { &r->input_artifacts, &r->output_artifacts, &r->dependencies, &r->external_refs, &r->required_features }; + size_t *nv[] = { &r->n_input, &r->n_output, &r->n_dependencies, &r->n_external, &r->n_features }; + for (size_t k = 0; k < 5; k++) { + if (*lv[k]) for (size_t i = 0; i < *nv[k]; i++) free((*lv[k])[i]); + free(*lv[k]); *lv[k] = NULL; *nv[k] = 0; + } + if (r->assertions) { + for (size_t i = 0; i < r->n_assertions; i++) { + free(r->assertions[i].id); free(r->assertions[i].expected); free(r->assertions[i].observed); + free(r->assertions[i].source); free(r->assertions[i].note); + } + free(r->assertions); + } + r->assertions = NULL; r->n_assertions = 0; +} + +static int cmp_str(const void *a, const void *b) { return strcmp(*(char *const *)a, *(char *const *)b); } + +static int check_digest_list(Er *e, const char *name, char **items, size_t n) +{ + for (size_t i = 0; i < n; i++) { + const char *it = items[i], *colon = strchr(it, ':'); + if (colon) { + size_t al = (size_t)(colon - it); + int ok = (al == 6 && memcmp(it, "blake3", 6) == 0) || (al == 6 && memcmp(it, "sha256", 6) == 0) || + (al == 6 && memcmp(it, "sha512", 6) == 0); + if (!ok) return ef(e, "receipt: unknown digest algorithm in %s", name); + const char *hx = colon + 1; + size_t hl = strlen(hx); + if (hl < 32 || hl % 2 || !is_hex(hx)) return ef(e, "receipt: bad digest hex in %s", name); + } else if (!(strlen(it) == 64 && is_hex(it))) { + return ef(e, "receipt: digest must be : or 64 hex digits in %s", name); + } + } + return 0; +} + +static int all_known_key(const J *o) +{ + static const char *const keys[] = { "schema", "version", "id", "kind", "tier", "result", "timestamp", "repo", "commit", + "dirty", "toolchain", "procedure", "machine", "env_class", "input_artifacts", "output_artifacts", "assertions", + "dependencies", "declared_mutation", "observed_mutation", "authority", "output_digest", "external_refs", "ledger", + "lease", "required_features", "reserved" }; + for (size_t i = 0; i < o->n; i++) { + int ok = 0; + for (size_t k = 0; k < sizeof keys / sizeof keys[0]; k++) if (strcmp(keys[k], o->keys[i]) == 0) ok = 1; + if (!ok) return 0; + } + return 1; +} + +int omega_receipt_parse(const uint8_t *json, size_t len, OmegaReceipt *r, char *err, size_t errcap) +{ + Er e = { err, errcap }; + memset(r, 0, sizeof *r); + if (!json || len == 0 || len > OMEGA_RECEIPT_MAX_BYTES) return ef(&e, "receipt: empty or oversize input%s", ""); + JP p = { json, len, 0, 0, { 0 } }; + J *root = jvalue(&p); + if (root) { jws(&p); if (p.i != p.n) { jfree(root); root = NULL; jfail(&p, "trailing bytes after the receipt"); } } + if (!root) return ef(&e, "%s", p.err); + int rc = -1; + char *schema = NULL, *idhex = NULL, *resultstr = NULL, *reserved = NULL, *odigest = NULL; + if (root->k != J_OBJ) { ef(&e, "receipt: top level must be an object%s", ""); goto done; } + if (!all_known_key(root)) { ef(&e, "receipt: unknown field%s", ""); goto done; } /* VC1R:deny-unknown */ + uint64_t ver = 0; + if (want_str(&e, root, "schema", 1, &schema) || want_u64(&e, root, "version", &ver) || + want_str(&e, root, "id", 1, &idhex) || want_str(&e, root, "kind", 1, &r->kind) || + want_str(&e, root, "tier", 1, &r->tier) || want_str(&e, root, "result", 1, &resultstr) || + want_u64(&e, root, "timestamp", &r->timestamp) || want_str(&e, root, "repo", 1, &r->repo) || + want_str(&e, root, "commit", 1, &r->commit) || want_bool(&e, root, "dirty", &r->dirty) || + want_str(&e, root, "toolchain", 1, &r->toolchain) || want_str(&e, root, "procedure", 1, &r->procedure) || + want_str(&e, root, "machine", 1, &r->machine) || want_str(&e, root, "env_class", 1, &r->env_class) || + want_strlist(&e, root, "input_artifacts", 1, &r->input_artifacts, &r->n_input) || + want_strlist(&e, root, "output_artifacts", 1, &r->output_artifacts, &r->n_output) || + want_strlist(&e, root, "dependencies", 1, &r->dependencies, &r->n_dependencies) || + want_mut(&e, root, "declared_mutation", &r->declared_mutation) || + want_mut(&e, root, "observed_mutation", &r->observed_mutation) || + want_str(&e, root, "authority", 0, &r->authority) || want_str(&e, root, "output_digest", 1, &odigest) || + want_strlist(&e, root, "external_refs", 0, &r->external_refs, &r->n_external) || + want_strlist(&e, root, "required_features", 0, &r->required_features, &r->n_features) || + want_str(&e, root, "reserved", 0, &reserved)) + goto done; + if (ver > 0xFFFFFFFFu) { ef(&e, "receipt: version out of range%s", ""); goto done; } + r->version = (uint32_t)ver; + /* ---- the validations of canonical_bytes, in its order ---- */ + if (strcmp(schema, SCHEMA) != 0) { ef(&e, "receipt: unknown receipt schema%s", ""); goto done; } /* VC1R:schema */ + if (r->version != 1) { ef(&e, "receipt: unsupported receipt version%s", ""); goto done; } /* VC1R:version */ + for (size_t i = 0; i < r->n_features; i++) + if (strcmp(r->required_features[i], "v1-base") != 0) { ef(&e, "receipt: unknown required receipt feature%s", ""); goto done; } /* VC1R:feature */ + if (reserved[0]) { ef(&e, "receipt: reserved field must be empty%s", ""); goto done; } /* VC1R:reserved */ + if (!r->kind[0]) { ef(&e, "receipt: kind must not be empty%s", ""); goto done; } + if (!r->repo[0]) { ef(&e, "receipt: repo must not be empty%s", ""); goto done; } + if (!((strlen(r->commit) == 40 || strlen(r->commit) == 64) && is_lower_hex(r->commit))) { + ef(&e, "receipt: commit must be 40 or 64 lowercase hex digits%s", ""); goto done; + } + if (!r->procedure[0]) { ef(&e, "receipt: procedure identity must not be empty%s", ""); goto done; } + if (!r->machine[0]) { ef(&e, "receipt: machine identity must not be empty%s", ""); goto done; } + r->tier_rank = omega_tier_rank(r->tier); + if (r->tier_rank < 0) { ef(&e, "receipt: unknown tier%s", ""); goto done; } + r->result = 255; + for (size_t i = 0; i < sizeof VERDICTS / sizeof VERDICTS[0]; i++) if (strcmp(VERDICTS[i], resultstr) == 0) r->result = (uint8_t)i; + if (r->result == 255) { ef(&e, "receipt: unknown result%s", ""); goto done; } + if (strcmp(r->env_class, r->tier) != 0) { ef(&e, "receipt: env_class contradicts tier%s", ""); goto done; } /* VC1R:env-class */ + if (check_digest_list(&e, "input_artifacts", r->input_artifacts, r->n_input) || + check_digest_list(&e, "output_artifacts", r->output_artifacts, r->n_output)) goto done; + if (hex32(odigest, r->output_digest)) { ef(&e, "receipt: output_digest must be 64 hex digits%s", ""); goto done; } + if (hex32(idhex, r->id)) { ef(&e, "receipt: id must be 64 hex digits%s", ""); goto done; } + /* assertions */ + const J *av = oget(root, "assertions"); + if (!av) { ef(&e, "receipt: missing field %s", "assertions"); goto done; } + if (av->k != J_ARR || av->n > 4096) { ef(&e, "receipt: assertions must be a list%s", ""); goto done; } + if (av->n) { + r->assertions = calloc(av->n, sizeof *r->assertions); + if (!r->assertions) { ef(&e, "receipt: out of memory%s", ""); goto done; } + r->n_assertions = av->n; + } + for (size_t i = 0; i < av->n; i++) { + const J *a = av->v[i]; + if (a->k != J_OBJ) { ef(&e, "receipt: an assertion must be an object%s", ""); goto done; } + for (size_t k = 0; k < a->n; k++) { + static const char *const ak[] = { "id", "expected", "observed", "pass", "source", "note" }; + int ok = 0; + for (size_t q = 0; q < 6; q++) if (strcmp(ak[q], a->keys[k]) == 0) ok = 1; + if (!ok) { ef(&e, "receipt: unknown assertion field%s", ""); goto done; } + } + OmegaReceiptAssertion *as = &r->assertions[i]; + if (want_str(&e, a, "id", 1, &as->id) || want_str(&e, a, "expected", 0, &as->expected) || + want_str(&e, a, "observed", 0, &as->observed) || want_bool(&e, a, "pass", &as->pass) || + want_str(&e, a, "source", 0, &as->source) || want_str(&e, a, "note", 0, &as->note)) + goto done; + } + if (r->n_assertions == 0 && r->result == OMEGA_RECEIPT_PASS) { ef(&e, "receipt: PASS receipts must carry at least one assertion%s", ""); goto done; } + for (size_t i = 0; i < r->n_assertions; i++) { + if (!r->assertions[i].id[0]) { ef(&e, "receipt: assertion id must not be empty%s", ""); goto done; } + for (size_t k = 0; k < i; k++) + if (strcmp(r->assertions[k].id, r->assertions[i].id) == 0) { ef(&e, "receipt: duplicate assertion id%s", ""); goto done; } + } + for (size_t i = 0; i < r->n_dependencies; i++) { + uint8_t tmp[32]; + if (hex32(r->dependencies[i], tmp)) { ef(&e, "receipt: dependency is not a 64 digit receipt hash%s", ""); goto done; } + } + if (MUTS[r->observed_mutation].sev > MUTS[r->declared_mutation].sev) { ef(&e, "receipt: observed mutation exceeds declared mutation%s", ""); goto done; } /* VC1R:mutation-order */ + { + int max = r->tier_rank == 4 ? 2 : r->tier_rank == 5 ? 5 : (r->tier_rank >= 6) ? 255 : 4; + if (MUTS[r->observed_mutation].sev > max) { ef(&e, "receipt: tier cannot claim that observed mutation%s", ""); goto done; } + if (r->tier_rank == 4 && r->observed_mutation >= 4) { ef(&e, "receipt: a read-only run cannot claim that mutation%s", ""); goto done; } + } + if (r->tier_rank == 7) { + size_t a = 0, b = strlen(r->authority); + while (a < b && (r->authority[a] == ' ' || r->authority[a] == '\t' || r->authority[a] == '\n' || r->authority[a] == '\r')) a++; + if (a == b) { ef(&e, "receipt: PRODUCTION receipts require an authority reference%s", ""); goto done; } + char *low = strdup(r->authority); + if (!low) { ef(&e, "receipt: out of memory%s", ""); goto done; } + for (char *c = low; *c; c++) if (*c >= 'A' && *c <= 'Z') *c = (char)(*c - 'A' + 'a'); + int bad = strstr(low, "test-only") || strstr(low, "test_only") || strstr(low, "testonly"); + free(low); + if (bad) { ef(&e, "receipt: a TEST_ONLY signer cannot produce a PRODUCTION receipt%s", ""); goto done; } + } + /* ledger and lease: null or an object (deny_unknown_fields) */ + const J *lg = oget(root, "ledger"); + if (lg && lg->k != J_NULL) { + if (lg->k != J_OBJ) { ef(&e, "receipt: ledger must be null or an object%s", ""); goto done; } + for (size_t k = 0; k < lg->n; k++) + if (strcmp(lg->keys[k], "index") && strcmp(lg->keys[k], "hash")) { ef(&e, "receipt: unknown ledger field%s", ""); goto done; } + char *h = NULL; + if (want_u64(&e, lg, "index", &r->ledger_index) || want_str(&e, lg, "hash", 1, &h)) goto done; + int bad = hex32(h, r->ledger_hash); + free(h); + if (bad) { ef(&e, "receipt: ledger hash must be 64 hex digits%s", ""); goto done; } + r->has_ledger = 1; + } + const J *ls = oget(root, "lease"); + if (ls && ls->k != J_NULL) { + if (ls->k != J_OBJ) { ef(&e, "receipt: lease must be null or an object%s", ""); goto done; } + for (size_t k = 0; k < ls->n; k++) + if (strcmp(ls->keys[k], "hold_id") && strcmp(ls->keys[k], "resource")) { ef(&e, "receipt: unknown lease field%s", ""); goto done; } + char *h = NULL; + if (want_str(&e, ls, "hold_id", 1, &h) || want_str(&e, ls, "resource", 1, &r->lease_resource)) { free(h); goto done; } + int bad = hex32(h, r->lease_hold); + free(h); + if (bad) { ef(&e, "receipt: lease hold_id must be 64 hex digits%s", ""); goto done; } + size_t a = 0, b = strlen(r->lease_resource); + while (a < b && (r->lease_resource[a] == ' ' || r->lease_resource[a] == '\t' || r->lease_resource[a] == '\n' || r->lease_resource[a] == '\r')) a++; + if (a == b) { ef(&e, "receipt: lease resource must not be empty%s", ""); goto done; } + r->has_lease = 1; + } + rc = 0; +done: + free(schema); free(idhex); free(resultstr); free(reserved); free(odigest); + jfree(root); + if (rc) omega_receipt_free(r); + return rc; +} + +/* ---------------------------------------------------------------- canonical bytes */ +typedef struct { uint8_t *p; size_t n, cap; int oom; } Buf; +static void bput(Buf *b, const void *d, size_t k) +{ + if (b->oom) return; + if (b->n + k > b->cap) { + size_t nc = (b->n + k) * 2 + 256; + uint8_t *t = realloc(b->p, nc); + if (!t) { b->oom = 1; return; } + b->p = t; b->cap = nc; + } + if (k) memcpy(b->p + b->n, d, k); + b->n += k; +} +static void bu8(Buf *b, uint8_t v) { bput(b, &v, 1); } +static void bu32(Buf *b, uint32_t v) { uint8_t t[4] = { (uint8_t)(v >> 24), (uint8_t)(v >> 16), (uint8_t)(v >> 8), (uint8_t)v }; bput(b, t, 4); } +static void bu64(Buf *b, uint64_t v) { bu32(b, (uint32_t)(v >> 32)); bu32(b, (uint32_t)v); } +static void bstr(Buf *b, const char *s) { size_t n = strlen(s); bu64(b, n); bput(b, s, n); } + +/* sorted, de-duplicated copy of the pointers (BTreeSet<&str>: byte order) */ +static char **sorted_unique(char **items, size_t n, size_t *out_n) +{ + char **c = malloc((n ? n : 1) * sizeof *c); + if (!c) return NULL; + if (n) memcpy(c, items, n * sizeof *c); + qsort(c, n, sizeof *c, cmp_str); /* VC1R:canon-sort */ + size_t m = 0; + for (size_t i = 0; i < n; i++) if (m == 0 || strcmp(c[m - 1], c[i]) != 0) c[m++] = c[i]; + *out_n = m; + return c; +} +static int cmp_assert(const void *a, const void *b) +{ + return strcmp(((const OmegaReceiptAssertion *)a)->id, ((const OmegaReceiptAssertion *)b)->id); +} + +int omega_receipt_canonical(const OmegaReceipt *r, uint8_t **out, size_t *len) +{ + Buf b = { 0 }; + bput(&b, DOMAIN, sizeof DOMAIN - 1); + bu32(&b, 1); + bstr(&b, r->kind); + bstr(&b, r->tier); + bu8(&b, r->result); + bstr(&b, r->repo); + bstr(&b, r->commit); + bu8(&b, (uint8_t)(r->dirty ? 1 : 0)); + bstr(&b, r->toolchain); + bstr(&b, r->procedure); + bstr(&b, r->machine); + bstr(&b, r->env_class); + size_t m; + char **s = sorted_unique(r->input_artifacts, r->n_input, &m); + if (!s) return -1; + bu32(&b, (uint32_t)m); + for (size_t i = 0; i < m; i++) bstr(&b, s[i]); + free(s); + s = sorted_unique(r->output_artifacts, r->n_output, &m); + if (!s) return -1; + bu32(&b, (uint32_t)m); + for (size_t i = 0; i < m; i++) bstr(&b, s[i]); + free(s); + OmegaReceiptAssertion *as = malloc((r->n_assertions ? r->n_assertions : 1) * sizeof *as); + if (!as) return -1; + if (r->n_assertions) memcpy(as, r->assertions, r->n_assertions * sizeof *as); + qsort(as, r->n_assertions, sizeof *as, cmp_assert); + bu32(&b, (uint32_t)r->n_assertions); + for (size_t i = 0; i < r->n_assertions; i++) { + bstr(&b, as[i].id); bstr(&b, as[i].expected); bstr(&b, as[i].observed); + bu8(&b, (uint8_t)(as[i].pass ? 1 : 0)); + bstr(&b, as[i].source); bstr(&b, as[i].note); + } + free(as); + s = sorted_unique(r->dependencies, r->n_dependencies, &m); + if (!s) return -1; + bu32(&b, (uint32_t)m); + for (size_t i = 0; i < m; i++) { + uint8_t raw[32]; + if (hex32(s[i], raw)) { free(s); free(b.p); return -1; } + bput(&b, raw, 32); + } + free(s); + bu8(&b, MUTS[r->declared_mutation].code); + bu8(&b, MUTS[r->observed_mutation].code); + bstr(&b, r->authority); + bput(&b, r->output_digest, 32); + s = sorted_unique(r->external_refs, r->n_external, &m); + if (!s) return -1; + bu32(&b, (uint32_t)m); + for (size_t i = 0; i < m; i++) bstr(&b, s[i]); + free(s); + if (r->has_ledger) { bu8(&b, 1); bu64(&b, r->ledger_index); bput(&b, r->ledger_hash, 32); } + else bu8(&b, 0); + if (r->has_lease) { bu8(&b, 1); bput(&b, r->lease_hold, 32); bstr(&b, r->lease_resource); } + else bu8(&b, 0); + bu64(&b, r->timestamp); + s = sorted_unique(r->required_features, r->n_features, &m); + if (!s) return -1; + bu32(&b, (uint32_t)m); + for (size_t i = 0; i < m; i++) bstr(&b, s[i]); + free(s); + bu32(&b, 0); + if (b.oom) { free(b.p); return -1; } + *out = b.p; + *len = b.n; + return 0; +} + +int omega_receipt_compute_id(const OmegaReceipt *r, uint8_t out[32]) +{ + uint8_t *c = NULL; + size_t n = 0; + if (omega_receipt_canonical(r, &c, &n)) return -1; + omega_blake3_hash(c, n, out); + free(c); + return 0; +} + +int omega_receipt_verify_bytes(const uint8_t *json, size_t len, OmegaReceipt *r, uint8_t out_id[32], char *err, size_t errcap) +{ + if (omega_receipt_parse(json, len, r, err, errcap)) return -1; + if (omega_receipt_compute_id(r, out_id)) { seterr(err, errcap, "receipt: cannot compute canonical identity%s", ""); omega_receipt_free(r); return -1; } + if (memcmp(out_id, r->id, 32) != 0) { /* VC1R:id-compare */ + seterr(err, errcap, "receipt id mismatch: the file claims one id, its canonical bytes hash to another%s", ""); + omega_receipt_free(r); + return -1; + } + return 0; +} diff --git a/src/omega_receipt.h b/src/omega_receipt.h new file mode 100644 index 000000000..22d333872 --- /dev/null +++ b/src/omega_receipt.h @@ -0,0 +1,70 @@ +#ifndef OMEGA_RECEIPT_H +#define OMEGA_RECEIPT_H + +/* omega_receipt: reader for the aien-proof EvidenceReceiptV1 wire contract (VC1 stage 4). + * + * Authority: aien-protocols specs/evidence-receipt/SUBSET.md (pinned source aien-sovereign-core + * 40dd373, crates/aien-proof/src/evidence.rs). This file is a second, independent reader of that + * contract in C: it parses the receipt JSON the way serde_json does for `Receipt` + * (deny_unknown_fields, the same required and defaulted fields), applies every validation that + * `canonical_bytes` applies, builds the canonical byte encoding (domain tag, big-endian integers, + * length-prefixed strings, sorted unique lists) and recomputes the id as BLAKE3 over those bytes. + * tests/resolve/receipts/ holds three receipts written by the Rust implementation; the C id must + * equal the Rust id for each. + * + * NOT replicated (stated, not hidden): the ledger and lease bindings of verify_with_store + * (ledger_bind.rs, lease.rs need the proof board store) and chain walking (the resolver walks the + * Verified Crumb closure itself and ties receipt dependencies to it, SPEC 5.1 rule 6). A receipt + * whose hash matches is only as trustworthy as the store it came from: receipts are not signed. + * + * Every function fails closed: any parse error, unknown field, bad enum, bad hex or oversize input + * is a nonzero return with a plain-text reason. */ + +#include +#include + +#define OMEGA_RECEIPT_MAX_BYTES (4u * 1024u * 1024u) + +typedef struct { char *id, *expected, *observed, *source, *note; int pass; } OmegaReceiptAssertion; + +typedef struct { + uint32_t version; + uint8_t id[32]; /* the "id" field, decoded (must equal the recomputed id) */ + char *kind, *tier, *repo, *commit, *toolchain, *procedure, *machine, *env_class, *authority; + uint8_t result; /* 0 PASS 1 FAIL 2 BLOCKED 3 INCOMPLETE 4 SKIPPED */ + int tier_rank; /* 0 TEST_ONLY_TRUST .. 7 PRODUCTION */ + int dirty; + uint64_t timestamp; + char **input_artifacts; size_t n_input; + char **output_artifacts; size_t n_output; + OmegaReceiptAssertion *assertions; size_t n_assertions; + char **dependencies; size_t n_dependencies; + uint8_t declared_mutation, observed_mutation; + uint8_t output_digest[32]; + char **external_refs; size_t n_external; + int has_ledger; uint64_t ledger_index; uint8_t ledger_hash[32]; + int has_lease; uint8_t lease_hold[32]; char *lease_resource; + char **required_features; size_t n_features; +} OmegaReceipt; + +#define OMEGA_RECEIPT_PASS 0 + +/* Parse and validate receipt JSON (everything canonical_bytes validates, plus serde's shape + * rules). 0 ok; -1 with err filled. On failure *r holds nothing to free. */ +int omega_receipt_parse(const uint8_t *json, size_t len, OmegaReceipt *r, char *err, size_t errcap); +void omega_receipt_free(OmegaReceipt *r); + +/* The canonical bytes (malloc'd, caller frees) and id = BLAKE3(canonical bytes). */ +int omega_receipt_canonical(const OmegaReceipt *r, uint8_t **out, size_t *len); +int omega_receipt_compute_id(const OmegaReceipt *r, uint8_t out[32]); + +/* Parse, recompute, and require the "id" field to equal the recomputed id (case-insensitive hex, + * as aien-proof verify_bytes). 0 ok with *r filled and out_id set; -1 with err. */ +int omega_receipt_verify_bytes(const uint8_t *json, size_t len, OmegaReceipt *r, uint8_t out_id[32], + char *err, size_t errcap); + +/* Tier rank by name (-1 unknown) and the aien-proof tier_satisfies rule (chain.rs:259). */ +int omega_tier_rank(const char *tier); +int omega_tier_satisfies(int need_rank, int have_rank); + +#endif /* OMEGA_RECEIPT_H */ diff --git a/src/omega_resolve.c b/src/omega_resolve.c new file mode 100644 index 000000000..38185bede --- /dev/null +++ b/src/omega_resolve.c @@ -0,0 +1,710 @@ +/* omega_resolve.c -- see omega_resolve.h. + * Lines tagged VC1R: are the ones `make test-resolve` deletes or weakens, one at a time + * (the mutation proof). */ +#include "omega_resolve.h" + +#include +#include +#include +#include +#include + +#include "omega_receipt.h" +#include "sha256.h" + +/* the shared codes must keep the store's numbers */ +#define SAME_CODE(n) ((int)OMEGA_RES_##n == (int)OMEGA_VCS_##n) +_Static_assert(SAME_CODE(UNVERIFIED_DEPENDENCY) && SAME_CODE(MISSING_RECEIPT) && SAME_CODE(RECEIPT_HASH_MISMATCH) && + SAME_CODE(DEPENDENCY_NOT_PINNED) && SAME_CODE(DEPENDENCY_CYCLE) && SAME_CODE(STALE_RECEIPT) && + SAME_CODE(UNDECLARED_IMPORT) && SAME_CODE(TAINTED_ARTIFACT) && SAME_CODE(UNKNOWN_VERIFIER_PROFILE), + "resolve codes must match the store reserved codes"); + +#define MAX_DEPTH 128 +#define MAX_FILE (4u * 1024u * 1024u) + +const char *omega_resolve_code_name(int code) +{ + switch (code) { + case OMEGA_RES_OK: return "OK"; + case OMEGA_RES_UNVERIFIED_DEPENDENCY: return "UNVERIFIED_DEPENDENCY"; + case OMEGA_RES_MISSING_RECEIPT: return "MISSING_RECEIPT"; + case OMEGA_RES_RECEIPT_HASH_MISMATCH: return "RECEIPT_HASH_MISMATCH"; + case OMEGA_RES_DEPENDENCY_NOT_PINNED: return "DEPENDENCY_NOT_PINNED"; + case OMEGA_RES_DEPENDENCY_CYCLE: return "DEPENDENCY_CYCLE"; + case OMEGA_RES_STALE_RECEIPT: return "STALE_RECEIPT"; + case OMEGA_RES_UNDECLARED_IMPORT: return "UNDECLARED_IMPORT"; + case OMEGA_RES_TAINTED_ARTIFACT: return "TAINTED_ARTIFACT"; + case OMEGA_RES_UNKNOWN_VERIFIER_PROFILE: return "UNKNOWN_VERIFIER_PROFILE"; + case OMEGA_RES_VERIFIER_TOO_OLD: return "VERIFIER_TOO_OLD"; + case OMEGA_RES_BAD_ARGUMENT: return "BAD_ARGUMENT"; + case OMEGA_RES_NOMEM: return "NOMEM"; + default: return "?"; + } +} +const char *omega_domain_name(OmegaDomain d) { return d == OMEGA_DOMAIN_DEV ? "dev" : d == OMEGA_DOMAIN_BUILD ? "build" : "?"; } + +static void hex(const uint8_t *in, size_t n, char *out) +{ + static const char h[] = "0123456789abcdef"; + for (size_t i = 0; i < n; i++) { out[2 * i] = h[in[i] >> 4]; out[2 * i + 1] = h[in[i] & 15]; } + out[2 * n] = 0; +} +static int unhex32(const char *s, uint8_t out[32]) +{ + for (int i = 0; i < 64; i++) if (!((s[i] >= '0' && s[i] <= '9') || (s[i] >= 'a' && s[i] <= 'f'))) return -1; + for (int i = 0; i < 32; i++) { + int hi = s[2 * i] <= '9' ? s[2 * i] - '0' : s[2 * i] - 'a' + 10; + int lo = s[2 * i + 1] <= '9' ? s[2 * i + 1] - '0' : s[2 * i + 1] - 'a' + 10; + out[i] = (uint8_t)(hi << 4 | lo); + } + return 0; +} +static int is_zero32(const uint8_t *p) { static const uint8_t z[32] = { 0 }; return memcmp(p, z, 32) == 0; } + +static int fail(OmegaResolveError *e, int code, int store_code, const char *subject, const char *fmt, ...) + __attribute__((format(printf, 5, 6))); +static int fail(OmegaResolveError *e, int code, int store_code, const char *subject, const char *fmt, ...) +{ + if (e) { + memset(e, 0, sizeof *e); + e->code = code; + e->store_code = store_code; + if (subject) snprintf(e->subject, sizeof e->subject, "%s", subject); + va_list ap; + va_start(ap, fmt); + vsnprintf(e->message, sizeof e->message, fmt, ap); + va_end(ap); + } + return code; +} + +/* ---------------------------------------------------------------- profiles */ +static const OmegaVerifierProfile DEFAULT_PROFILES[] = { + { "host-v1", "1.0.0", "HOST_TEST" }, + { "qemu-v1", "1.0.0", "QEMU" }, + { "production-v1", "1.0.0", "PRODUCTION" }, +}; +const OmegaVerifierProfile *omega_resolve_default_profiles(size_t *n) +{ + if (n) *n = sizeof DEFAULT_PROFILES / sizeof DEFAULT_PROFILES[0]; + return DEFAULT_PROFILES; +} + +#define MAX_VER_PARTS 8 +static int parse_version(const char *s, uint32_t out[MAX_VER_PARTS], int *n) +{ + *n = 0; + if (!*s) return -1; + for (;;) { + if (*n >= MAX_VER_PARTS) return -1; + uint32_t v = 0; + int digits = 0; + while (*s >= '0' && *s <= '9') { if (++digits > 9) return -1; v = v * 10 + (uint32_t)(*s - '0'); s++; } + if (!digits) return -1; + out[(*n)++] = v; + if (*s == '.') { s++; continue; } + if (*s == 0) return 0; + return -1; + } +} + +static const OmegaVerifierProfile *find_profile(const OmegaVerifierProfile *t, size_t n, const char *name) +{ + for (size_t i = 0; i < n; i++) if (strcmp(t[i].name, name) == 0) return &t[i]; + return NULL; +} + +int omega_resolve_check_profile(const OmegaVerifierProfile *table, size_t n, const char *profile, + const char *version, OmegaResolveError *err) +{ + if (!table && n == 0) table = omega_resolve_default_profiles(&n); + const OmegaVerifierProfile *p = table ? find_profile(table, n, profile) : NULL; + if (!p) return fail(err, OMEGA_RES_UNKNOWN_VERIFIER_PROFILE, 0, profile, "verifier profile '%s' is not in the profile table", profile); /* VC1R:profile-known */ + uint32_t have[MAX_VER_PARTS], need[MAX_VER_PARTS]; + int nh, nn; + if (parse_version(version, have, &nh) || parse_version(p->min_version, need, &nn)) + return fail(err, OMEGA_RES_VERIFIER_TOO_OLD, 0, profile, "verifier version '%s' is not a dotted number, so it cannot be shown to meet %s", version, p->min_version); + int cmp = 0; + for (int i = 0; i < MAX_VER_PARTS && cmp == 0; i++) { + uint32_t a = i < nh ? have[i] : 0, b = i < nn ? need[i] : 0; + cmp = a < b ? -1 : a > b ? 1 : 0; + } + if (cmp < 0) /* VC1R:profile-version */ + return fail(err, OMEGA_RES_VERIFIER_TOO_OLD, 0, profile, "verifier version %s is older than the minimum %s for profile %s", version, p->min_version, profile); + return 0; +} + +/* ---------------------------------------------------------------- lock */ +void omega_lock_free(OmegaLock *l) { if (l) { free(l->e); l->e = NULL; l->n = 0; } } +const OmegaLockEntry *omega_lock_find(const OmegaLock *l, const char *name) +{ + if (!l) return NULL; + for (size_t i = 0; i < l->n; i++) if (strcmp(l->e[i].name, name) == 0) return &l->e[i]; + return NULL; +} + +static int lock_bad(OmegaResolveError *e, size_t line, const char *why) +{ + char subj[32]; + snprintf(subj, sizeof subj, "omega.lock:%zu", line); + return fail(e, OMEGA_RES_DEPENDENCY_NOT_PINNED, 0, subj, "malformed omega.lock, line %zu: %s", line, why); +} + +int omega_lock_parse(const char *text, size_t len, OmegaLock *out, OmegaResolveError *err) +{ + out->e = NULL; out->n = 0; + if (!text || len == 0 || len > (1u << 20)) return lock_bad(err, 1, "empty or oversize file"); + for (size_t i = 0; i < len; i++) + if (text[i] == '\t' || text[i] == '\r' || text[i] == 0) return lock_bad(err, 1, "tab, CR or NUL byte (LF line endings only)"); /* VC1R:lock-bytes */ + if (text[len - 1] != '\n') return lock_bad(err, 1, "the last line must end with a line feed"); + size_t cap = 0, line = 0, pos = 0; + OmegaLockEntry *ents = NULL; + size_t n = 0; + int header = 0; + while (pos < len) { + size_t end = pos; + while (text[end] != '\n') end++; + const char *ln = text + pos; + size_t ll = end - pos; + pos = end + 1; + line++; + if (!header) { + if (ll != 13 || memcmp(ln, "omega.lock v1", 13) != 0) { free(ents); return lock_bad(err, line, "line 1 must be exactly 'omega.lock v1'"); } /* VC1R:lock-header */ + header = 1; + continue; + } + if (ll == 0 || ln[0] == '#') continue; + /* NAME */ + size_t k = 0; + if (!((ln[0] >= 'A' && ln[0] <= 'Z') || (ln[0] >= 'a' && ln[0] <= 'z') || ln[0] == '_')) { free(ents); return lock_bad(err, line, "unknown line (expected NAME = semantic HEX64 receipt HEX64)"); } /* VC1R:lock-unknown-line */ + while (k < ll && ((ln[k] >= 'A' && ln[k] <= 'Z') || (ln[k] >= 'a' && ln[k] <= 'z') || (ln[k] >= '0' && ln[k] <= '9') || + ln[k] == '_' || ln[k] == '.' || ln[k] == '-')) k++; + if (k > 128) { free(ents); return lock_bad(err, line, "name longer than 128 characters"); } + static const char mid[] = " = semantic ", mid2[] = " receipt "; + size_t need = k + (sizeof mid - 1) + 64 + (sizeof mid2 - 1) + 64; + if (ll != need || memcmp(ln + k, mid, sizeof mid - 1) != 0 || + memcmp(ln + k + sizeof mid - 1 + 64, mid2, sizeof mid2 - 1) != 0) { free(ents); return lock_bad(err, line, "unknown line (expected NAME = semantic HEX64 receipt HEX64)"); } + char h1[65], h2[65]; + memcpy(h1, ln + k + sizeof mid - 1, 64); h1[64] = 0; + memcpy(h2, ln + k + sizeof mid - 1 + 64 + sizeof mid2 - 1, 64); h2[64] = 0; + OmegaLockEntry en; + memset(&en, 0, sizeof en); + memcpy(en.name, ln, k); + if (unhex32(h1, en.semantic) || unhex32(h2, en.receipt)) { free(ents); return lock_bad(err, line, "digest must be 64 lowercase hex digits"); } /* VC1R:lock-hex */ + if (is_zero32(en.semantic) || is_zero32(en.receipt)) { free(ents); return lock_bad(err, line, "an all-zero digest pins nothing"); } + if (n > 0 && strcmp(ents[n - 1].name, en.name) >= 0) { /* VC1R:lock-order */ + int dup = strcmp(ents[n - 1].name, en.name) == 0; + free(ents); + return lock_bad(err, line, dup ? "duplicate name" : "names must be sorted ascending"); + } + if (n >= OMEGA_LOCK_MAX_ENTRIES) { free(ents); return lock_bad(err, line, "too many entries"); } + if (n == cap) { + cap = cap ? cap * 2 : 16; + OmegaLockEntry *t = realloc(ents, cap * sizeof *t); + if (!t) { free(ents); return fail(err, OMEGA_RES_NOMEM, 0, "omega.lock", "out of memory"); } + ents = t; + } + ents[n++] = en; + } + if (!header) return lock_bad(err, 1, "missing header"); + out->e = ents; + out->n = n; + return 0; +} + +/* ---------------------------------------------------------------- file sources */ +static int read_file(const char *path, size_t maxn, uint8_t **bytes, size_t *len) +{ + FILE *f = fopen(path, "rb"); + if (!f) return 1; + size_t cap = 4096, n = 0; + uint8_t *b = malloc(cap); + if (!b) { fclose(f); return -1; } + for (;;) { + size_t r = fread(b + n, 1, cap - n, f); + n += r; + if (n < cap) break; + if (cap >= maxn) { free(b); fclose(f); return -1; } + cap *= 2; + uint8_t *t = realloc(b, cap); + if (!t) { free(b); fclose(f); return -1; } + b = t; + } + int bad = ferror(f); + fclose(f); + if (bad || n > maxn) { free(b); return -1; } + *bytes = b; + *len = n; + return 0; +} +static int dir_fetch(void *dir, const uint8_t id[32], const char *ext, size_t maxn, uint8_t **bytes, size_t *len) +{ + if (!dir) return -1; + char hx[65], path[4096]; + hex(id, 32, hx); + if (snprintf(path, sizeof path, "%s/%s.%s", (const char *)dir, hx, ext) >= (int)sizeof path) return -1; + return read_file(path, maxn, bytes, len); +} +int omega_receipt_dir_fetch(void *dir, const uint8_t id[32], uint8_t **bytes, size_t *len) +{ + return dir_fetch(dir, id, "json", MAX_FILE, bytes, len); +} +int omega_blob_dir_fetch(void *dir, const uint8_t digest[32], uint8_t **bytes, size_t *len) +{ + return dir_fetch(dir, digest, "blob", 16u << 20, bytes, len); +} + +/* ---------------------------------------------------------------- receipt check (SPEC 5.1) */ +static int cmp32(const void *a, const void *b) { return memcmp(a, b, 32); } + +static int has_artifact(const OmegaReceipt *rc, const char *want) +{ + for (size_t i = 0; i < rc->n_input; i++) if (strcasecmp(rc->input_artifacts[i], want) == 0) return 1; + return 0; +} + +int omega_resolve_check_record_receipt(const OmegaResolver *r, const OmegaVcView *vc, OmegaResolveError *err) +{ + char sid[65], rid[65]; + hex(vc->semantic_id, 32, sid); + hex(vc->receipt_id, 32, rid); + char prof[OMEGA_VC_MAX_STRING + 1], ver[OMEGA_VC_MAX_STRING + 1]; + memcpy(prof, vc->verifier_profile.p, vc->verifier_profile.len); prof[vc->verifier_profile.len] = 0; + memcpy(ver, vc->verifier_version.p, vc->verifier_version.len); ver[vc->verifier_version.len] = 0; + /* 5: profile */ + int rc = omega_resolve_check_profile(r->profiles, r->n_profiles, prof, ver, err); + if (rc && err) snprintf(err->subject, sizeof err->subject, "%s", sid); + if (rc) return rc; + size_t nprof = r->n_profiles; + const OmegaVerifierProfile *tab = r->profiles ? r->profiles : omega_resolve_default_profiles(&nprof); + const OmegaVerifierProfile *pf = find_profile(tab, nprof, prof); + if (!pf) return fail(err, OMEGA_RES_UNKNOWN_VERIFIER_PROFILE, 0, sid, "verifier profile '%s' is not in the profile table", prof); + int need_rank = pf ? omega_tier_rank(pf->min_tier) : -1; + /* 6: the receipt itself */ + uint8_t *bytes = NULL; + size_t blen = 0; + int fr = r->fetch_receipt ? r->fetch_receipt(r->fetch_ctx, vc->receipt_id, &bytes, &blen) : 1; + if (fr != 0) return fail(err, OMEGA_RES_MISSING_RECEIPT, 0, sid, "receipt %s is %s", rid, fr == 1 ? "not in the receipt store" : "unreadable"); /* VC1R:missing-receipt */ + OmegaReceipt rcpt; + uint8_t got_id[32]; + char why[200]; + if (omega_receipt_verify_bytes(bytes, blen, &rcpt, got_id, why, sizeof why)) { + free(bytes); + return fail(err, OMEGA_RES_RECEIPT_HASH_MISMATCH, 0, sid, "receipt %s: %s", rid, why); + } + free(bytes); + rc = 0; + char want[80]; + uint8_t (*deps)[32] = NULL, (*rdeps)[32] = NULL; + size_t nd = 0, nrd = 0; + if (memcmp(got_id, vc->receipt_id, 32) != 0) { /* VC1R:rule1-name */ + rc = fail(err, OMEGA_RES_RECEIPT_HASH_MISMATCH, 0, sid, "the file stored under receipt %s holds another receipt", rid); + goto done; + } + /* rule 4: the receipt names this program (semantic id), then this source (digest) */ + snprintf(want, sizeof want, "sha256:%s", sid); + if (!has_artifact(&rcpt, want)) { /* VC1R:rule4-semantic */ + rc = fail(err, OMEGA_RES_RECEIPT_HASH_MISMATCH, 0, sid, "receipt %s does not name program %s", rid, sid); + goto done; + } + { + char dh[65]; + hex(vc->source_or_ir_digest, 32, dh); + snprintf(want, sizeof want, "sha256:%s", dh); + if (!has_artifact(&rcpt, want)) { /* VC1R:rule4-source */ + rc = fail(err, OMEGA_RES_STALE_RECEIPT, 0, sid, "receipt %s names the program but not its current source digest %s: it covers an older source", rid, dh); + goto done; + } + } + /* rule 3: output digest is the evidence root */ + if (memcmp(rcpt.output_digest, vc->evidence_root, 32) != 0) { /* VC1R:rule3 */ + rc = fail(err, OMEGA_RES_RECEIPT_HASH_MISMATCH, 0, sid, "receipt %s output_digest is not the record's evidence_root", rid); + goto done; + } + /* rule 5: receipt kind is the verifier profile */ + if (strcmp(rcpt.kind, prof) != 0) { /* VC1R:rule5 */ + rc = fail(err, OMEGA_RES_RECEIPT_HASH_MISMATCH, 0, sid, "receipt %s kind '%s' is not the verifier profile '%s'", rid, rcpt.kind, prof); + goto done; + } + /* rule 6: receipt dependencies == the receipt ids of the record's dependencies (as sets) */ + nd = vc->n_dependencies; + deps = malloc((nd ? nd : 1) * 32); + rdeps = malloc((rcpt.n_dependencies ? rcpt.n_dependencies : 1) * 32); + if (!deps || !rdeps) { rc = fail(err, OMEGA_RES_NOMEM, 0, sid, "out of memory"); goto done; } + for (size_t i = 0; i < nd; i++) { + if (omega_vcstore_receipt_of(r->store, vc->dependencies + 64 * i, deps[i]) != 0) { + rc = fail(err, OMEGA_RES_UNVERIFIED_DEPENDENCY, 0, sid, "a dependency of %s is not in the store", sid); + goto done; + } + } + for (size_t i = 0; i < rcpt.n_dependencies; i++) { + char *s = rcpt.dependencies[i]; + char low[65]; + size_t k = 0; + for (; s[k] && k < 64; k++) low[k] = (char)((s[k] >= 'A' && s[k] <= 'F') ? s[k] + 32 : s[k]); + low[k] = 0; + if (unhex32(low, rdeps[i])) { rc = fail(err, OMEGA_RES_RECEIPT_HASH_MISMATCH, 0, sid, "receipt %s has a malformed dependency", rid); goto done; } + } + qsort(deps, nd, 32, cmp32); + qsort(rdeps, rcpt.n_dependencies, 32, cmp32); + { + size_t a = 0, b = 0; + for (size_t i = 0; i < nd; i++) if (a == 0 || memcmp(deps[a - 1], deps[i], 32) != 0) memcpy(deps[a++], deps[i], 32); + for (size_t i = 0; i < rcpt.n_dependencies; i++) if (b == 0 || memcmp(rdeps[b - 1], rdeps[i], 32) != 0) memcpy(rdeps[b++], rdeps[i], 32); + nrd = b; + if (a != nrd || (a && memcmp(deps, rdeps, a * 32) != 0)) { /* VC1R:rule6 */ + rc = fail(err, OMEGA_RES_RECEIPT_HASH_MISMATCH, 0, sid, "receipt %s dependencies are not the receipts of the record's dependencies", rid); + goto done; + } + } + /* rule 2: a passing receipt of enough tier */ + if (rcpt.result != OMEGA_RECEIPT_PASS) { /* VC1R:rule2-pass */ + rc = fail(err, OMEGA_RES_UNVERIFIED_DEPENDENCY, 0, sid, "receipt %s does not record PASS", rid); + goto done; + } + for (size_t i = 0; i < rcpt.n_assertions; i++) + if (!rcpt.assertions[i].pass) { /* VC1R:rule2-assert */ + rc = fail(err, OMEGA_RES_UNVERIFIED_DEPENDENCY, 0, sid, "receipt %s says PASS but an assertion failed", rid); + goto done; + } + if (rcpt.tier_rank >= 4 && rcpt.tier_rank <= 6 && !rcpt.has_lease) { + rc = fail(err, OMEGA_RES_UNVERIFIED_DEPENDENCY, 0, sid, "receipt %s is a hardware receipt with no lease binding", rid); + goto done; + } + if (rcpt.tier_rank == 0) { /* VC1R:rule2-testonly */ + rc = fail(err, OMEGA_RES_UNVERIFIED_DEPENDENCY, 0, sid, "receipt %s is TEST_ONLY_TRUST, which satisfies no profile", rid); + goto done; + } + if (!omega_tier_satisfies(need_rank, rcpt.tier_rank)) { /* VC1R:rule2-tier */ + rc = fail(err, OMEGA_RES_UNVERIFIED_DEPENDENCY, 0, sid, "receipt %s tier %s is below the minimum %s of profile %s", rid, rcpt.tier, pf->min_tier, prof); + goto done; + } +done: + free(deps); + free(rdeps); + omega_receipt_free(&rcpt); + return rc; +} + +/* ---------------------------------------------------------------- closure */ +void omega_closure_free(OmegaClosure *c) { if (c) { free(c->entries); c->entries = NULL; c->n = 0; memset(c->digest, 0, 32); } } + +void omega_closure_digest(const OmegaClosureEntry *e, size_t n, uint8_t out[32]) +{ + sha256_ctx c; + sha256_init(&c); + static const uint8_t dom[] = "OMEGA.CLOSURE.V1"; + sha256_update(&c, dom, sizeof dom); /* includes the NUL after the tag */ + uint8_t cnt[4] = { (uint8_t)(n >> 24), (uint8_t)(n >> 16), (uint8_t)(n >> 8), (uint8_t)n }; + sha256_update(&c, cnt, 4); + for (size_t i = 0; i < n; i++) { + sha256_update(&c, e[i].semantic_id, 32); + sha256_update(&c, e[i].receipt_id, 32); /* VC1R:closure-receipt */ + sha256_update(&c, &e[i].admission_kind, 1); + } + sha256_final(&c, out); +} + +typedef struct { uint8_t id[32], receipt[32], contract[32]; uint8_t kind; int state; } WNode; +typedef struct { + const OmegaResolver *r; + WNode *nodes; + size_t n, cap; + OmegaResolveError *err; +} Walk; + +static long wfind(const Walk *w, const uint8_t id[32]) +{ + for (size_t i = 0; i < w->n; i++) if (memcmp(w->nodes[i].id, id, 32) == 0) return (long)i; + return -1; +} + +static int resolve_node(Walk *w, const uint8_t id[32], const uint8_t *lock_receipt, const char *name, size_t depth) +{ + const OmegaResolver *r = w->r; + char sid[65]; + hex(id, 32, sid); + const char *subj = name ? name : sid; + long at = wfind(w, id); + if (at >= 0) { + if (w->nodes[at].state == 1) return fail(w->err, OMEGA_RES_DEPENDENCY_CYCLE, 0, sid, "dependency cycle through %s", sid); /* VC1R:cycle */ + if (lock_receipt && memcmp(lock_receipt, w->nodes[at].receipt, 32) != 0) /* VC1R:visited-lock-receipt */ + return fail(w->err, OMEGA_RES_RECEIPT_HASH_MISMATCH, 0, subj, "the lock pins another receipt than the record carries for %s", sid); + return 0; + } + if (depth >= MAX_DEPTH) return fail(w->err, OMEGA_RES_UNVERIFIED_DEPENDENCY, 0, sid, "dependency chain deeper than %d", MAX_DEPTH); + OmegaVcRecord *rec = malloc(sizeof *rec); + if (!rec) return fail(w->err, OMEGA_RES_NOMEM, 0, sid, "out of memory"); + int rc = omega_vcstore_get(r->store, id, rec); + if (rc) { + int out = fail(w->err, OMEGA_RES_UNVERIFIED_DEPENDENCY, rc, subj, "%s is not an intact record in the Verified Crumb Store (store says %s)", sid, omega_vcstore_code_name(rc)); + free(rec); + return out; + } + const OmegaVcView *vc = &rec->vc; + rc = 0; + if (memcmp(vc->semantic_id, id, 32) != 0) { + rc = fail(w->err, OMEGA_RES_UNVERIFIED_DEPENDENCY, 0, subj, "the record fetched for %s names a different semantic id", sid); + goto out; + } + if (r->fetch_blob) { + uint8_t *bb = NULL; + size_t bl = 0; + uint8_t dg[32]; + int fr = r->fetch_blob(r->blob_ctx, vc->source_or_ir_digest, &bb, &bl); + if (fr != 0) { rc = fail(w->err, OMEGA_RES_UNVERIFIED_DEPENDENCY, 0, subj, "the source or IR named by %s is not available to recompute its digest", sid); goto out; } + sha256_hash(bb, bl, dg); + free(bb); + if (memcmp(dg, vc->source_or_ir_digest, 32) != 0) { /* VC1R:blob-digest */ + rc = fail(w->err, OMEGA_RES_UNVERIFIED_DEPENDENCY, 0, subj, "the stored source or IR of %s does not hash to its source_or_ir_digest", sid); + goto out; + } + } + if (lock_receipt && memcmp(lock_receipt, vc->receipt_id, 32) != 0) { /* VC1R:lock-receipt */ + rc = fail(w->err, OMEGA_RES_RECEIPT_HASH_MISMATCH, 0, subj, "the lock pins another receipt than the record carries for %s", sid); + goto out; + } + if (rec->admission_kind != OMEGA_VCS_ADMISSION_VERIFIED && rec->admission_kind != OMEGA_VCS_ADMISSION_BOOTSTRAP) { + rc = fail(w->err, OMEGA_RES_UNVERIFIED_DEPENDENCY, 0, subj, "%s has an unknown admission kind", sid); + goto out; + } + if (rec->admission_kind == OMEGA_VCS_ADMISSION_BOOTSTRAP && !r->allow_genesis) { /* VC1R:genesis-gate */ + rc = fail(w->err, OMEGA_RES_UNVERIFIED_DEPENDENCY, 0, subj, "%s is a genesis (bootstrap) record and genesis records are not permitted in this resolution", sid); + goto out; + } + for (uint32_t i = 0; i < vc->n_capabilities; i++) + if (vc->capabilities[i].len == sizeof OMEGA_TAINT_CAPABILITY - 1 && + memcmp(vc->capabilities[i].p, OMEGA_TAINT_CAPABILITY, sizeof OMEGA_TAINT_CAPABILITY - 1) == 0) { /* VC1R:taint-cap */ + rc = fail(w->err, OMEGA_RES_TAINTED_ARTIFACT, 0, subj, "%s lists the capability %s: an omega-dev output can never satisfy an import", sid, OMEGA_TAINT_CAPABILITY); + goto out; + } + if (rec->admission_kind == OMEGA_VCS_ADMISSION_VERIFIED) { /* VC1R:verified-needs-receipt */ + rc = omega_resolve_check_record_receipt(r, vc, w->err); + if (rc) { if (name) snprintf(w->err->subject, sizeof w->err->subject, "%s", name); goto out; } + } + if (w->n == w->cap) { + size_t nc = w->cap ? w->cap * 2 : 16; + WNode *t = realloc(w->nodes, nc * sizeof *t); + if (!t) { rc = fail(w->err, OMEGA_RES_NOMEM, 0, sid, "out of memory"); goto out; } + w->nodes = t; + w->cap = nc; + } + size_t me = w->n++; + memcpy(w->nodes[me].id, id, 32); + memcpy(w->nodes[me].receipt, vc->receipt_id, 32); + memcpy(w->nodes[me].contract, vc->contract_id, 32); + w->nodes[me].kind = rec->admission_kind; + w->nodes[me].state = 1; + for (uint32_t i = 0; i < vc->n_dependencies; i++) { + const uint8_t *dep = vc->dependencies + 64 * (size_t)i, *req = dep + 32; + rc = resolve_node(w, dep, NULL, NULL, depth + 1); + if (rc) goto out; + long di = wfind(w, dep); + if (di < 0) { rc = fail(w->err, OMEGA_RES_UNVERIFIED_DEPENDENCY, 0, sid, "internal: dependency vanished"); goto out; } + if (memcmp(w->nodes[di].contract, req, 32) != 0) { /* VC1R:edge-contract */ + char dh[65]; + hex(dep, 32, dh); + rc = fail(w->err, OMEGA_RES_UNVERIFIED_DEPENDENCY, 0, sid, "dependency %s of %s has a different contract than required", dh, sid); + goto out; + } + if (w->nodes[me].kind == OMEGA_VCS_ADMISSION_BOOTSTRAP && w->nodes[di].kind != OMEGA_VCS_ADMISSION_BOOTSTRAP) { /* VC1R:boot-dep-verified */ + rc = fail(w->err, OMEGA_RES_UNVERIFIED_DEPENDENCY, 0, sid, "genesis record %s depends on a non-genesis record: the audited base must be closed over itself", sid); + goto out; + } + } + w->nodes[me].state = 2; +out: + free(rec); + return rc; +} + +static int cmp_entry(const void *a, const void *b) { return memcmp(a, b, 32); } + +int omega_resolve_imports(const OmegaResolver *r, const OmegaLock *lock, const char *const *names, + size_t n_names, OmegaClosure *out, OmegaResolveError *err) +{ + out->entries = NULL; out->n = 0; + memset(out->digest, 0, 32); + if (!r || !r->store || (n_names && !names)) return fail(err, OMEGA_RES_BAD_ARGUMENT, 0, "resolver", "bad argument"); + OmegaLock empty = { NULL, 0 }; + if (!lock) lock = ∅ + for (size_t i = 0; i < n_names; i++) + for (size_t k = 0; k < i; k++) + if (strcmp(names[i], names[k]) == 0) return fail(err, OMEGA_RES_BAD_ARGUMENT, 0, names[i], "import '%s' is listed twice", names[i]); + /* declaration check: every import is pinned, every pin is imported */ + for (size_t i = 0; i < n_names; i++) + if (!omega_lock_find(lock, names[i])) /* VC1R:not-pinned */ + return fail(err, OMEGA_RES_DEPENDENCY_NOT_PINNED, 0, names[i], "import '%s' has no line in omega.lock", names[i]); + for (size_t i = 0; i < lock->n; i++) { + int used = 0; + for (size_t k = 0; k < n_names; k++) if (strcmp(names[k], lock->e[i].name) == 0) used = 1; + if (!used) /* VC1R:undeclared */ + return fail(err, OMEGA_RES_UNDECLARED_IMPORT, 0, lock->e[i].name, "omega.lock pins '%s' but the source never imports it", lock->e[i].name); + } + Walk w = { r, NULL, 0, 0, err }; + int rc = 0; + for (size_t i = 0; i < n_names && !rc; i++) { + const OmegaLockEntry *le = omega_lock_find(lock, names[i]); + if (!le) { rc = fail(err, OMEGA_RES_BAD_ARGUMENT, 0, names[i], "internal error: the pin for %s vanished after the declaration check", names[i]); break; } + rc = resolve_node(&w, le->semantic, le->receipt, names[i], 0); + } + if (rc) { free(w.nodes); return rc; } + OmegaClosureEntry *ents = malloc((w.n ? w.n : 1) * sizeof *ents); + if (!ents) { free(w.nodes); return fail(err, OMEGA_RES_NOMEM, 0, "closure", "out of memory"); } + for (size_t i = 0; i < w.n; i++) { + memcpy(ents[i].semantic_id, w.nodes[i].id, 32); + memcpy(ents[i].receipt_id, w.nodes[i].receipt, 32); + ents[i].admission_kind = w.nodes[i].kind; + } + free(w.nodes); + _Static_assert(offsetof(OmegaClosureEntry, semantic_id) == 0, "entries sort by their first 32 bytes"); + qsort(ents, w.n, sizeof *ents, cmp_entry); /* VC1R:closure-sort */ + out->entries = ents; + out->n = w.n; + omega_closure_digest(ents, w.n, out->digest); + return 0; +} + +/* ---------------------------------------------------------------- build identity and the taint mark */ +void omega_build_id(const uint8_t ir_digest[32], OmegaDomain d, const uint8_t closure_digest[32], uint8_t out[32]) +{ + sha256_ctx c; + sha256_init(&c); + static const uint8_t dom[] = "OSC1.BUILD.V1"; + sha256_update(&c, dom, sizeof dom); + sha256_update(&c, ir_digest, 32); + uint8_t db = (uint8_t)d; /* VC1R:build-domain */ + sha256_update(&c, &db, 1); + sha256_update(&c, closure_digest, 32); /* VC1R:build-closure */ + sha256_final(&c, out); +} + +void omega_artifact_meta_make(OmegaArtifactMeta *m, OmegaDomain d, const uint8_t ir_digest[32], const uint8_t closure_digest[32]) +{ + memset(m, 0, sizeof *m); + m->domain = d; + m->tainted = (uint8_t)(d == OMEGA_DOMAIN_DEV); /* VC1R:taint-mark */ + memcpy(m->ir_digest, ir_digest, 32); + memcpy(m->closure_digest, closure_digest, 32); + omega_build_id(ir_digest, d, closure_digest, m->build_id); +} + +int omega_artifact_meta_text(const OmegaArtifactMeta *m, char *buf, size_t cap) +{ + char a[65], b[65], c[65]; + hex(m->ir_digest, 32, a); hex(m->closure_digest, 32, b); hex(m->build_id, 32, c); + int n = snprintf(buf, cap, "OMEGA-ARTIFACT v1\ndomain %s\ntainted %d\nir_sha256 %s\nclosure_sha256 %s\nbuild_id %s\n", + omega_domain_name(m->domain), m->tainted ? 1 : 0, a, b, c); + return (n < 0 || (size_t)n >= cap) ? -1 : n; +} + +int omega_artifact_meta_parse(const char *text, size_t len, OmegaArtifactMeta *m, OmegaResolveError *err) +{ + memset(m, 0, sizeof *m); + if (!text || len == 0 || len > 4096 || text[len - 1] != '\n') return fail(err, OMEGA_RES_BAD_ARGUMENT, 0, "artifact", "malformed artifact header"); + char *t = malloc(len + 1); + if (!t) return fail(err, OMEGA_RES_NOMEM, 0, "artifact", "out of memory"); + memcpy(t, text, len); + t[len] = 0; + static const char *const keys[] = { "OMEGA-ARTIFACT v1", "domain ", "tainted ", "ir_sha256 ", "closure_sha256 ", "build_id " }; + char *line = t, *vals[6] = { 0 }; + int ok = 1; + for (int i = 0; i < 6 && ok; i++) { + char *nl = strchr(line, '\n'); + if (!nl) { ok = 0; break; } + *nl = 0; + size_t kl = strlen(keys[i]); + if (strncmp(line, keys[i], kl) != 0) { ok = 0; break; } + vals[i] = line + kl; + if (i == 0 && vals[i][0]) ok = 0; + line = nl + 1; + } + if (ok && *line) ok = 0; + uint8_t build[32]; + int domain = 0, tainted = -1; + if (ok) { + if (strcmp(vals[1], "dev") == 0) domain = OMEGA_DOMAIN_DEV; else if (strcmp(vals[1], "build") == 0) domain = OMEGA_DOMAIN_BUILD; else ok = 0; + if (strcmp(vals[2], "1") == 0) tainted = 1; else if (strcmp(vals[2], "0") == 0) tainted = 0; else ok = 0; + if (unhex32(vals[3], m->ir_digest) || unhex32(vals[4], m->closure_digest) || unhex32(vals[5], build)) ok = 0; + } + free(t); + if (!ok) return fail(err, OMEGA_RES_BAD_ARGUMENT, 0, "artifact", "malformed artifact header"); + m->domain = (OmegaDomain)domain; + m->tainted = (uint8_t)tainted; + if (tainted != (domain == OMEGA_DOMAIN_DEV)) /* VC1R:meta-taint-consistent */ + return fail(err, OMEGA_RES_TAINTED_ARTIFACT, 0, "artifact", "the taint mark does not match the domain: an omega-dev artifact is always tainted"); + omega_build_id(m->ir_digest, m->domain, m->closure_digest, m->build_id); + if (memcmp(m->build_id, build, 32) != 0) /* VC1R:meta-build-id */ + return fail(err, OMEGA_RES_TAINTED_ARTIFACT, 0, "artifact", "the build id does not match the header: the artifact was edited"); + return 0; +} + +/* ---------------------------------------------------------------- the one door into the store */ +static int map_store(OmegaResolveError *err, int vcs, const char *subject) +{ + int code = (vcs >= OMEGA_VCS_UNVERIFIED_DEPENDENCY && vcs <= OMEGA_VCS_UNKNOWN_VERIFIER_PROFILE) ? vcs : OMEGA_RES_UNVERIFIED_DEPENDENCY; + return fail(err, code, vcs, subject, "the store refused the record: %s", omega_vcstore_code_name(vcs)); +} + +static int has_taint_cap(const OmegaVcView *v) +{ + for (uint32_t i = 0; i < v->n_capabilities; i++) + if (v->capabilities[i].len == sizeof OMEGA_TAINT_CAPABILITY - 1 && + memcmp(v->capabilities[i].p, OMEGA_TAINT_CAPABILITY, sizeof OMEGA_TAINT_CAPABILITY - 1) == 0) return 1; + return 0; +} + +int omega_resolve_admit(const OmegaResolver *r, OmegaVcStore *s, const uint8_t *canonical, size_t len, + const uint8_t claimed_vc_id[32], const OmegaArtifactMeta *origin, OmegaResolveError *err) +{ + if (!r || !s || !canonical || !claimed_vc_id) return fail(err, OMEGA_RES_BAD_ARGUMENT, 0, "admit", "bad argument"); + if (origin && (origin->tainted || origin->domain == OMEGA_DOMAIN_DEV)) /* VC1R:admit-origin */ + return fail(err, OMEGA_RES_TAINTED_ARTIFACT, 0, "admit", "an omega-dev artifact is tainted and can never enter the store"); + OmegaVcView *view = malloc(sizeof *view); + if (!view) return fail(err, OMEGA_RES_NOMEM, 0, "admit", "out of memory"); + int rc = omega_vc_decode(canonical, len, view); + if (rc) { free(view); return map_store(err, rc, "admit"); } + char sid[65]; + hex(view->semantic_id, 32, sid); + if (has_taint_cap(view)) { /* VC1R:admit-cap */ + free(view); + return fail(err, OMEGA_RES_TAINTED_ARTIFACT, 0, sid, "the record lists %s and can never enter the store", OMEGA_TAINT_CAPABILITY); + } + OmegaResolver rr = *r; + rr.store = s; + rc = omega_resolve_check_record_receipt(&rr, view, err); /* VC1R:admit-receipt */ + free(view); + if (rc) return rc; + rc = omega_vcstore_insert(s, canonical, len, claimed_vc_id); + if (rc) return map_store(err, rc, sid); + return 0; +} + +int omega_resolve_admit_genesis(OmegaVcStore *s, const uint8_t *canonical, size_t len, + const uint8_t claimed_vc_id[32], const OmegaArtifactMeta *origin, OmegaResolveError *err) +{ + if (!s || !canonical || !claimed_vc_id) return fail(err, OMEGA_RES_BAD_ARGUMENT, 0, "genesis", "bad argument"); + if (origin && (origin->tainted || origin->domain == OMEGA_DOMAIN_DEV)) + return fail(err, OMEGA_RES_TAINTED_ARTIFACT, 0, "genesis", "an omega-dev artifact is tainted and can never enter the store"); + OmegaVcView *view = malloc(sizeof *view); + if (!view) return fail(err, OMEGA_RES_NOMEM, 0, "genesis", "out of memory"); + int rc = omega_vc_decode(canonical, len, view); + if (rc) { free(view); return map_store(err, rc, "genesis"); } + char sid[65]; + hex(view->semantic_id, 32, sid); + if (has_taint_cap(view)) { + free(view); + return fail(err, OMEGA_RES_TAINTED_ARTIFACT, 0, sid, "the record lists %s and can never enter the store", OMEGA_TAINT_CAPABILITY); + } + for (uint32_t i = 0; i < view->n_dependencies; i++) { + uint8_t k = 0; + if (omega_vcstore_admission_kind(s, view->dependencies + 64 * (size_t)i, &k) != 0 || k != OMEGA_VCS_ADMISSION_BOOTSTRAP) { /* VC1R:genesis-dep */ + free(view); + return fail(err, OMEGA_RES_UNVERIFIED_DEPENDENCY, 0, sid, "a genesis record may depend only on genesis records already in the store"); + } + } + free(view); + rc = omega_vcstore_insert_bootstrap(s, canonical, len, claimed_vc_id); + if (rc) return map_store(err, rc, sid); + return 0; +} diff --git a/src/omega_resolve.h b/src/omega_resolve.h new file mode 100644 index 000000000..1dc6843bf --- /dev/null +++ b/src/omega_resolve.h @@ -0,0 +1,181 @@ +#ifndef OMEGA_RESOLVE_H +#define OMEGA_RESOLVE_H + +/* omega_resolve: the Verified Crumb resolver (VC1 stage 4, ADR 0029 Decisions 3 to 5, + * aien-protocols specs/verified-crumb/SPEC.md sections 5 to 8). + * + * ONE CHAIN, every link must hold, any failure REFUSES and no partial closure is ever returned: + * + * import NAME -> omega.lock line -> semantic_id -> Verified Crumb Store -> receipt check + * -> transitive closure (every dependency repeats the chain, minus the lock) + * + * Per node, in this order (SPEC 6; the first failure wins): + * 1 lock name has a lock line, else DEPENDENCY_NOT_PINNED + * 2 store omega_vcstore_get(semantic_id); absent or integrity failure: UNVERIFIED_DEPENDENCY + * 3 identity key == record id; optional blob digest (below); lock receipt == record + * receipt_id, else RECEIPT_HASH_MISMATCH + * - kind BOOTSTRAP records satisfy an import only when allow_genesis is set, else + * UNVERIFIED_DEPENDENCY + * 4 taint capability "omega-dev.taint": TAINTED_ARTIFACT (both domains) + * 5 profile not in the table: UNKNOWN_VERIFIER_PROFILE; version below the minimum (or not a + * dotted number): VERIFIER_TOO_OLD + * 6 receipt absent: MISSING_RECEIPT; SPEC 5.1 rules 1,3,4,5,6 fail: RECEIPT_HASH_MISMATCH + * (rule 4 naming the semantic_id but another source digest: STALE_RECEIPT); + * then rule 2 (PASS, assertions pass, tier at least the profile minimum, never + * TEST_ONLY_TRUST): UNVERIFIED_DEPENDENCY + * 7 edges each dependency repeats 2 to 7; its contract_id must equal required_contract; + * a dependency already on the path: DEPENDENCY_CYCLE + * 9 closure the union, sorted ascending by semantic_id, with its digest + * Declaration check (before any store access): every import needs a lock line + * (DEPENDENCY_NOT_PINNED) and every lock line needs an import (UNDECLARED_IMPORT). + * + * DECISIONS (also in the PR body): + * - BOOTSTRAP records (the audited genesis set) carry an audit hash in receipt_id, not a + * receipt. When allow_genesis is set they skip steps 5 and 6 (the lock must still pin the + * audit hash). A BOOTSTRAP record may NOT depend on a VERIFIED record: the audited base must + * be closed over itself, so the resolver refuses it (UNVERIFIED_DEPENDENCY) and + * omega_resolve_admit_genesis refuses to insert it. A VERIFIED record may depend on BOOTSTRAP + * (the genesis set is where trust starts), and only resolves with allow_genesis. + * - omega-dev and omega-build run the SAME checks. The domain never loosens a check (ADR 0029 + * Decision 4: flags cannot change what is legal, only the closure can). It labels the output: + * an omega-dev artifact is TAINTED, its identity (build id) commits to that, and the resolver + * refuses to insert it into the store or to treat it as a dependency. + * - There is no skip switch, no environment variable and no fallback in this file or in the + * compiler. A test greps for them. + * + * LIMITS (stated, not hidden): receipts are hashes, not signatures (see omega_receipt.h); the + * blob check below is optional until stage 6 supplies the source/IR store; the receipt binding + * (rule 4) ties semantic_id and source digest, but the program id is not recomputed from source + * here (SPEC 6 step 3 first half is done only for the digest). */ + +#include +#include + +#include "omega_vcstore.h" + +/* Resolve refusals. 1..9 are ARCH-0029 Decision 9 in the ADR's order (same numbers as the + * reserved OMEGA_VCS_* codes), 10 is the VC1 addition of SPEC 6.1. */ +enum { + OMEGA_RES_OK = 0, + OMEGA_RES_UNVERIFIED_DEPENDENCY = 1, + OMEGA_RES_MISSING_RECEIPT, + OMEGA_RES_RECEIPT_HASH_MISMATCH, + OMEGA_RES_DEPENDENCY_NOT_PINNED, + OMEGA_RES_DEPENDENCY_CYCLE, + OMEGA_RES_STALE_RECEIPT, + OMEGA_RES_UNDECLARED_IMPORT, + OMEGA_RES_TAINTED_ARTIFACT, + OMEGA_RES_UNKNOWN_VERIFIER_PROFILE, + OMEGA_RES_VERIFIER_TOO_OLD, + /* not trust decisions */ + OMEGA_RES_BAD_ARGUMENT = 20, + OMEGA_RES_NOMEM +}; +const char *omega_resolve_code_name(int code); + +typedef struct { + int code; /* OMEGA_RES_* */ + int store_code; /* OMEGA_VCS_* when the store said no, else 0 */ + char subject[140]; /* import name, or hex semantic id */ + char message[240]; /* plain text */ +} OmegaResolveError; + +typedef enum { OMEGA_DOMAIN_BUILD = 1, OMEGA_DOMAIN_DEV = 2 } OmegaDomain; +const char *omega_domain_name(OmegaDomain d); + +/* ---- verifier profiles: profile name -> minimum verifier version and minimum receipt tier ---- */ +typedef struct { const char *name, *min_version, *min_tier; } OmegaVerifierProfile; +/* The static table the compiler uses (names and tiers match aien-closure profile_min_tier): + * host-v1 HOST_TEST, qemu-v1 QEMU, production-v1 PRODUCTION, each minimum version 1.0.0. + * There is no "accept any profile" entry. */ +const OmegaVerifierProfile *omega_resolve_default_profiles(size_t *n); +int omega_resolve_check_profile(const OmegaVerifierProfile *table, size_t n, const char *profile, + const char *version, OmegaResolveError *err); + +/* ---- omega.lock (SPEC 8) ---- */ +#define OMEGA_LOCK_MAX_ENTRIES 4096 +typedef struct { char name[129]; uint8_t semantic[32], receipt[32]; } OmegaLockEntry; +typedef struct { OmegaLockEntry *e; size_t n; } OmegaLock; +/* Fail-closed parser: any malformed lock is DEPENDENCY_NOT_PINNED. */ +int omega_lock_parse(const char *text, size_t len, OmegaLock *out, OmegaResolveError *err); +void omega_lock_free(OmegaLock *l); +const OmegaLockEntry *omega_lock_find(const OmegaLock *l, const char *name); + +/* ---- receipt and blob sources ---- */ +/* 0 = found (*bytes malloc'd, caller frees), 1 = absent, other = error (refused as missing) */ +typedef int (*OmegaReceiptFetch)(void *ctx, const uint8_t id[32], uint8_t **bytes, size_t *len); +typedef int (*OmegaBlobFetch)(void *ctx, const uint8_t digest[32], uint8_t **bytes, size_t *len); +/* ctx = const char *directory; reads /<64 lowercase hex>.json (receipts) or .blob (blobs) */ +int omega_receipt_dir_fetch(void *dir, const uint8_t id[32], uint8_t **bytes, size_t *len); +int omega_blob_dir_fetch(void *dir, const uint8_t digest[32], uint8_t **bytes, size_t *len); + +/* ---- the resolver ---- */ +typedef struct { + const OmegaVcStore *store; + OmegaDomain domain; + const OmegaVerifierProfile *profiles; /* NULL (with n_profiles 0): the default table */ + size_t n_profiles; + OmegaReceiptFetch fetch_receipt; /* required for any VERIFIED record */ + void *fetch_ctx; + OmegaBlobFetch fetch_blob; /* optional: when set, SHA-256 of the blob named by + source_or_ir_digest must equal that digest */ + void *blob_ctx; + int allow_genesis; /* BOOTSTRAP records may satisfy imports (stage 6) */ +} OmegaResolver; + +typedef struct { uint8_t semantic_id[32], receipt_id[32], admission_kind; } OmegaClosureEntry; +typedef struct { + OmegaClosureEntry *entries; /* sorted ascending by semantic_id */ + size_t n; + uint8_t digest[32]; /* omega_closure_digest of entries */ +} OmegaClosure; +void omega_closure_free(OmegaClosure *c); + +/* SHA-256("OMEGA.CLOSURE.V1" 0x00 || u32be n || n x (semantic_id || receipt_id || kind byte)). */ +void omega_closure_digest(const OmegaClosureEntry *e, size_t n, uint8_t out[32]); + +/* Resolve the imports of one compilation. names may be empty (n_names 0): the declaration check + * still runs, so a lock with entries and no imports is UNDECLARED_IMPORT. 0 or a refusal code + * with *err filled; on refusal *out is empty (never partial). */ +int omega_resolve_imports(const OmegaResolver *r, const OmegaLock *lock, const char *const *names, + size_t n_names, OmegaClosure *out, OmegaResolveError *err); + +/* SPEC 5.1 for one record: the receipt named by vc->receipt_id against profile, semantic id, + * source digest, evidence root and the receipt ids of the record's dependencies (read from the + * store). Steps 5 and 6 of the chain; exported for the admit path and tests. */ +int omega_resolve_check_record_receipt(const OmegaResolver *r, const OmegaVcView *vc, OmegaResolveError *err); + +/* ---- the one door into the store ---- */ +/* Build metadata of a compile: the domain, the taint mark and the identities. */ +typedef struct { + OmegaDomain domain; + uint8_t tainted; /* 1 exactly when domain is omega-dev */ + uint8_t ir_digest[32], closure_digest[32], build_id[32]; +} OmegaArtifactMeta; + +/* build_id = SHA-256("OSC1.BUILD.V1" 0x00 || ir_digest || domain byte || closure_digest). + * THE place the closure digest enters a build's identity: two builds of the same IR with + * different closures, or in different domains, have different build ids. */ +void omega_build_id(const uint8_t ir_digest[32], OmegaDomain d, const uint8_t closure_digest[32], uint8_t out[32]); +void omega_artifact_meta_make(OmegaArtifactMeta *m, OmegaDomain d, const uint8_t ir_digest[32], const uint8_t closure_digest[32]); +/* Text header, "OMEGA-ARTIFACT v1\ndomain dev\ntainted 1\nir_sha256 \nclosure_sha256 \nbuild_id \n". */ +int omega_artifact_meta_text(const OmegaArtifactMeta *m, char *buf, size_t cap); +/* Fail-closed parse: unknown line, wrong order, tainted mark inconsistent with the domain, or a + * build_id that does not recompute: refused (TAINTED_ARTIFACT for a mark/identity lie, + * BAD_ARGUMENT for malformed text). */ +int omega_artifact_meta_parse(const char *text, size_t len, OmegaArtifactMeta *m, OmegaResolveError *err); + +/* Insert a Verified Crumb into the store, only together with the receipt that qualifies it: + * origin (may be NULL when the record did not come from a compile) tainted: TAINTED_ARTIFACT; + * the record lists omega-dev.taint: TAINTED_ARTIFACT; then steps 5 and 6 above; then + * omega_vcstore_insert (VERIFIED). The store is unchanged on every refusal. */ +int omega_resolve_admit(const OmegaResolver *r, OmegaVcStore *s, const uint8_t *canonical, size_t len, + const uint8_t claimed_vc_id[32], const OmegaArtifactMeta *origin, OmegaResolveError *err); +/* Genesis loading (stage 6): same taint refusals, no receipt (audit hash), refuses any VERIFIED + * dependency, inserts with omega_vcstore_insert_bootstrap. */ +int omega_resolve_admit_genesis(OmegaVcStore *s, const uint8_t *canonical, size_t len, + const uint8_t claimed_vc_id[32], const OmegaArtifactMeta *origin, OmegaResolveError *err); + +#define OMEGA_TAINT_CAPABILITY "omega-dev.taint" + +#endif /* OMEGA_RESOLVE_H */ diff --git a/src/omega_resolve_osc.c b/src/omega_resolve_osc.c new file mode 100644 index 000000000..88713f7bc --- /dev/null +++ b/src/omega_resolve_osc.c @@ -0,0 +1,27 @@ +/* omega_resolve_osc.c -- see omega_resolve_osc.h. */ +#include "omega_resolve_osc.h" + +#include +#include +#include + +int omega_osc_import_hook(void *ctx, const OscImport *imports, uint32_t n, uint32_t *bad, char *why, size_t why_cap) +{ + OmegaOscImports *h = ctx; + const char **names = calloc(n ? n : 1, sizeof *names); + if (!names) { snprintf(why, why_cap, "NOMEM: out of memory"); return OMEGA_RES_NOMEM; } + for (uint32_t i = 0; i < n; i++) names[i] = imports[i].name; + omega_closure_free(&h->closure); + h->resolved = 0; + h->n_imports = n; + int rc = omega_resolve_imports(&h->resolver, h->lock, names, n, &h->closure, &h->err); + free(names); + if (rc) { + *bad = UINT32_MAX; + for (uint32_t i = 0; i < n; i++) if (strcmp(imports[i].name, h->err.subject) == 0) *bad = i; + snprintf(why, why_cap, "%s: %s", omega_resolve_code_name(h->err.code), h->err.message); + return rc; + } + h->resolved = 1; + return 0; +} diff --git a/src/omega_resolve_osc.h b/src/omega_resolve_osc.h new file mode 100644 index 000000000..b9aa4ec68 --- /dev/null +++ b/src/omega_resolve_osc.h @@ -0,0 +1,23 @@ +#ifndef OMEGA_RESOLVE_OSC_H +#define OMEGA_RESOLVE_OSC_H + +/* The adapter between the OSC front end's import hook (osc_front.h) and the resolver + * (omega_resolve.h). Lives in src/, not src/compiler/, so the plain compiler suite never links + * the resolver. Used by the verified driver (src/oscv_main.c) and by tests. */ + +#include "omega_resolve.h" +#include "osc_front.h" + +typedef struct { + OmegaResolver resolver; + const OmegaLock *lock; /* NULL = no lock file (an empty lock) */ + OmegaClosure closure; /* filled by a successful call; free with omega_closure_free */ + OmegaResolveError err; /* filled by a refused call */ + int resolved; /* 1 once a call succeeded */ + uint32_t n_imports; /* imports seen by the last call */ +} OmegaOscImports; + +/* An OscImportResolver. why = "CODE_NAME: message". */ +int omega_osc_import_hook(void *ctx, const OscImport *imports, uint32_t n, uint32_t *bad, char *why, size_t why_cap); + +#endif /* OMEGA_RESOLVE_OSC_H */ diff --git a/src/oscv_main.c b/src/oscv_main.c new file mode 100644 index 000000000..87e0f996a --- /dev/null +++ b/src/oscv_main.c @@ -0,0 +1,197 @@ +/* + * oscv_main.c -- `oscv`: the VERIFIED OSC driver (VC1 stage 4, ADR 0029). + * + * oscv [--domain dev|build] [--lock FILE] [--store FILE] [--receipts DIR] [--blobs DIR] + * [--allow-genesis] [--meta-out FILE] + * + * Compiles an OSC unit exactly as oscc does and ALSO resolves its `import NAME;` lines, only + * through omega.lock -> semantic id -> Verified Crumb Store -> receipt check -> closure. Defaults + * sit next to the source file: omega.lock, omega.vcstore, receipts/. There is no option that + * skips a check, and nothing is read from the environment. The only way to change what is legal + * is to change the closure. + * + * Output (success): ir_sha256= code_sha256= funcs= domain= tainted= imports= closure_entries= + * closure_sha256= build_id= (build_id folds the domain and the closure digest into the identity). + * Refusal: the oscc "error kind=..." lines, plus resolve_code= for an import refusal. + * Exit 0 ok, 1 refused, 2 usage or I/O. + * OSC-1 slice; not a general Omega compiler; no self-hosting. + */ +#include +#include +#include + +#include "omega_resolve.h" +#include "omega_resolve_osc.h" +#include "osc_cg.h" +#include "osc_front.h" +#include "sha256.h" + +static void hexs(const uint8_t *d, char *out) +{ + static const char h[] = "0123456789abcdef"; + for (int i = 0; i < 32; i++) { out[2 * i] = h[d[i] >> 4]; out[2 * i + 1] = h[d[i] & 15]; } + out[64] = 0; +} + +static char *slurp(const char *path, size_t *len, int *missing) +{ + FILE *fp = fopen(path, "rb"); + *missing = 0; + if (!fp) { *missing = 1; return NULL; } + size_t cap = 1 << 16, n = 0; + char *b = malloc(cap); + for (;;) { + if (!b) { fclose(fp); return NULL; } + n += fread(b + n, 1, cap - n, fp); + if (n < cap) break; + if (cap >= (1u << 24)) { fclose(fp); free(b); return NULL; } + cap *= 2; + char *t = realloc(b, cap); + if (!t) free(b); + b = t; + } + fclose(fp); + *len = n; + return b; +} + +static void join_dir(char *out, size_t cap, const char *file, const char *leaf) +{ + const char *slash = strrchr(file, '/'); + if (slash) snprintf(out, cap, "%.*s/%s", (int)(slash - file), file, leaf); + else snprintf(out, cap, "%s", leaf); +} + +static int refuse_resolve(const OmegaResolveError *e) +{ + printf("error kind=IMPORT_REFUSED line=0 col=0 object=%s origin_line=0 other= transition=%s\n", e->subject, omega_resolve_code_name(e->code)); + printf("message=%s\n", e->message); + printf("resolve_code=%s\n", omega_resolve_code_name(e->code)); + return 1; +} + +int main(int argc, char **argv) +{ + OmegaDomain domain = OMEGA_DOMAIN_BUILD; + const char *lockp = NULL, *storep = NULL, *recdir = NULL, *blobdir = NULL, *metaout = NULL, *file = NULL; + int allow_genesis = 0; + for (int i = 1; i < argc; i++) { + const char *a = argv[i]; + if (strcmp(a, "--domain") == 0 && i + 1 < argc) { + const char *v = argv[++i]; + if (strcmp(v, "dev") == 0) domain = OMEGA_DOMAIN_DEV; + else if (strcmp(v, "build") == 0) domain = OMEGA_DOMAIN_BUILD; + else { fprintf(stderr, "oscv: --domain must be dev or build\n"); return 2; } + } else if (strcmp(a, "--lock") == 0 && i + 1 < argc) lockp = argv[++i]; + else if (strcmp(a, "--store") == 0 && i + 1 < argc) storep = argv[++i]; + else if (strcmp(a, "--receipts") == 0 && i + 1 < argc) recdir = argv[++i]; + else if (strcmp(a, "--blobs") == 0 && i + 1 < argc) blobdir = argv[++i]; + else if (strcmp(a, "--meta-out") == 0 && i + 1 < argc) metaout = argv[++i]; + else if (strcmp(a, "--allow-genesis") == 0) allow_genesis = 1; + else if (a[0] == '-' || file) { fprintf(stderr, "oscv: unknown or repeated argument '%s'\n", a); return 2; } + else file = a; + } + if (!file) { + fprintf(stderr, "usage: oscv [--domain dev|build] [--lock F] [--store F] [--receipts D] [--blobs D] [--allow-genesis] [--meta-out F] \n"); + return 2; + } + char lockd[4096], stored[4096], recd[4096]; + if (!lockp) { join_dir(lockd, sizeof lockd, file, "omega.lock"); lockp = lockd; } + if (!storep) { join_dir(stored, sizeof stored, file, "omega.vcstore"); storep = stored; } + if (!recdir) { join_dir(recd, sizeof recd, file, "receipts"); recdir = recd; } + + size_t slen = 0; + int missing; + char *src = slurp(file, &slen, &missing); + if (!src) { fprintf(stderr, "oscv: cannot read %s\n", file); return 2; } + + OmegaResolveError err; + OmegaLock lock = { NULL, 0 }; + int have_lock = 0; + size_t llen = 0; + char *ltext = slurp(lockp, &llen, &missing); + if (ltext) { + if (omega_lock_parse(ltext, llen, &lock, &err)) { free(ltext); free(src); return refuse_resolve(&err); } + have_lock = 1; + } else if (!missing) { free(src); fprintf(stderr, "oscv: cannot read %s\n", lockp); return 2; } + free(ltext); + + OmegaVcStore store; + omega_vcstore_init(&store); + FILE *probe = fopen(storep, "rb"); + if (probe) { + fclose(probe); + int lrc = omega_vcstore_load(&store, storep); + if (lrc) { + memset(&err, 0, sizeof err); + err.code = OMEGA_RES_UNVERIFIED_DEPENDENCY; + err.store_code = lrc; + snprintf(err.subject, sizeof err.subject, "store"); + snprintf(err.message, sizeof err.message, "the Verified Crumb Store file is not intact (store says %s)", omega_vcstore_code_name(lrc)); + omega_vcstore_destroy(&store); omega_lock_free(&lock); free(src); + return refuse_resolve(&err); + } + } + + OmegaOscImports h; + memset(&h, 0, sizeof h); + h.resolver.store = &store; + h.resolver.domain = domain; + h.resolver.fetch_receipt = omega_receipt_dir_fetch; + h.resolver.fetch_ctx = (void *)recdir; + if (blobdir) { h.resolver.fetch_blob = omega_blob_dir_fetch; h.resolver.blob_ctx = (void *)blobdir; } + h.resolver.allow_genesis = allow_genesis; + h.lock = have_lock ? &lock : NULL; + + OscUnit *u = malloc(sizeof *u); + OscDiag d; + int rc = 1; + if (!u) { fprintf(stderr, "oscv: out of memory\n"); rc = 2; goto out; } + if (osc_compile_imports(src, slen, u, &d, NULL, omega_osc_import_hook, &h)) { + printf("error kind=%s line=%u col=%u object=%s origin_line=%u other=%s transition=%s\n", + osc_diag_kind_name(d.kind), d.line, d.col, d.object, d.origin_line, d.other, d.transition); + printf("message=%s\n", d.message); + if (d.kind == OSC_DIAG_IMPORT_REFUSED) printf("resolve_code=%s\n", d.transition); + goto out; + } + { + uint8_t dig[32], codedig[32]; + char hx[65], err2[160]; + OscCode code; + memset(&code, 0, sizeof code); + if (osc_ir_digest(u, dig) || osc_cg_compile(u, &code, err2, sizeof err2)) { + printf("error kind=backend message=%s\n", err2); + goto out; + } + sha256_hash(code.code, code.len, codedig); + OmegaArtifactMeta meta; + omega_artifact_meta_make(&meta, domain, dig, h.closure.digest); + hexs(dig, hx); + printf("ir_sha256=%s\n", hx); + hexs(codedig, hx); + printf("code_sha256=%s\n", hx); + printf("funcs=%u\n", (unsigned)u->nfuncs); + printf("domain=%s\n", omega_domain_name(domain)); + printf("tainted=%d\n", meta.tainted); + printf("imports=%u\n", (unsigned)h.n_imports); + printf("closure_entries=%zu\n", h.closure.n); + hexs(h.closure.digest, hx); + printf("closure_sha256=%s\n", hx); + hexs(meta.build_id, hx); + printf("build_id=%s\n", hx); + osc_cg_free(&code); + rc = 0; + if (metaout) { + char text[512]; + FILE *mf = omega_artifact_meta_text(&meta, text, sizeof text) > 0 ? fopen(metaout, "wb") : NULL; + if (!mf || fputs(text, mf) < 0 || fclose(mf)) { fprintf(stderr, "oscv: cannot write %s\n", metaout); rc = 2; } + } + } +out: + omega_closure_free(&h.closure); + omega_vcstore_destroy(&store); + omega_lock_free(&lock); + free(u); + free(src); + return rc; +} diff --git a/tests/resolve/blake3_vectors.txt b/tests/resolve/blake3_vectors.txt new file mode 100644 index 000000000..be7710824 --- /dev/null +++ b/tests/resolve/blake3_vectors.txt @@ -0,0 +1,35 @@ +0 af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262 +1 2d3adedff11b61f14c886e35afa036736dcd87a74d27b5c1510225d0f592e213 +2 7b7015bb92cf0b318037702a6cdd81dee41224f734684c2c122cd6359cb1ee63 +3 e1be4d7a8ab5560aa4199eea339849ba8e293d55ca0a81006726d184519e647f +4 f30f5ab28fe047904037f77b6da4fea1e27241c5d132638d8bedce9d40494f32 +5 b40b44dfd97e7a84a996a91af8b85188c66c126940ba7aad2e7ae6b385402aa2 +6 06c4e8ffb6872fad96f9aaca5eee1553eb62aed0ad7198cef42e87f6a616c844 +7 3f8770f387faad08faa9d8414e9f449ac68e6ff0417f673f602a646a891419fe +8 2351207d04fc16ade43ccab08600939c7c1fa70a5c0aaca76063d04c3228eaeb +63 e9bc37a594daad83be9470df7f7b3798297c3d834ce80ba85d6e207627b7db7b +64 4eed7141ea4a5cd4b788606bd23f46e212af9cacebacdc7d1f4c6dc7f2511b98 +65 de1e5fa0be70df6d2be8fffd0e99ceaa8eb6e8c93a63f2d8d1c30ecb6b263dee +127 d81293fda863f008c09e92fc382a81f5a0b4a1251cba1634016a0f86a6bd640d +128 f17e570564b26578c33bb7f44643f539624b05df1a76c81f30acd548c44b45ef +129 683aaae9f3c5ba37eaaf072aed0f9e30bac0865137bae68b1fde4ca2aebdcb12 +1023 10108970eeda3eb932baac1428c7a2163b0e924c9a9e25b35bba72b28f70bd11 +1024 42214739f095a406f3fc83deb889744ac00df831c10daa55189b5d121c855af7 +1025 d00278ae47eb27b34faecf67b4fe263f82d5412916c1ffd97c8cb7fb814b8444 +2048 e776b6028c7cd22a4d0ba182a8bf62205d2ef576467e838ed6f2529b85fba24a +2049 5f4d72f40d7a5f82b15ca2b2e44b1de3c2ef86c426c95c1af0b6879522563030 +3072 b98cb0ff3623be03326b373de6b9095218513e64f1ee2edd2525c7ad1e5cffd2 +3073 7124b49501012f81cc7f11ca069ec9226cecb8a2c850cfe644e327d22d3e1cd3 +4096 015094013f57a5277b59d8475c0501042c0b642e531b0a1c8f58d2163229e969 +4097 9b4052b38f1c5fc8b1f9ff7ac7b27cd242487b3d890d15c96a1c25b8aa0fb995 +5120 9cadc15fed8b5d854562b26a9536d9707cadeda9b143978f319ab34230535833 +5121 628bd2cb2004694adaab7bbd778a25df25c47b9d4155a55f8fbd79f2fe154cff +6144 3e2e5b74e048f3add6d21faab3f83aa44d3b2278afb83b80b3c35164ebeca205 +6145 f1323a8631446cc50536a9f705ee5cb619424d46887f3c376c695b70e0f0507f +7168 61da957ec2499a95d6b8023e2b0e604ec7f6b50e80a9678b89d2628e99ada77a +7169 a003fc7a51754a9b3c7fae0367ab3d782dccf28855a03d435f8cfe74605e7817 +8192 aae792484c8efe4f19e2ca7d371d8c467ffb10748d8a5a1ae579948f718a2a63 +8193 bab6c09cb8ce8cf459261398d2e7aef35700bf488116ceb94a36d0f5f1b7bc3b +16384 f875d6646de28985646f34ee13be9a576fd515f76b5b0a26bb324735041ddde4 +31744 62b6960e1a44bcc1eb1a611a8d6235b6b4b78f32e7abc4fb4c6cdcce94895c47 +102400 bc3e3d41a1146b069abffad3c0d44860cf664390afce4d9661f7902e7943e085 diff --git a/tests/resolve/receipts/54f597d22b3753e47d6bd7706b6a7a422c189024912ec4626347e860b5f44a8c.json b/tests/resolve/receipts/54f597d22b3753e47d6bd7706b6a7a422c189024912ec4626347e860b5f44a8c.json new file mode 100644 index 000000000..871a03bce --- /dev/null +++ b/tests/resolve/receipts/54f597d22b3753e47d6bd7706b6a7a422c189024912ec4626347e860b5f44a8c.json @@ -0,0 +1,42 @@ +{ + "schema": "EvidenceReceiptV1", + "version": 1, + "id": "54f597d22b3753e47d6bd7706b6a7a422c189024912ec4626347e860b5f44a8c", + "kind": "component-qualification", + "tier": "HOST_TEST", + "result": "PASS", + "timestamp": 1786000000, + "repo": "https://github.com/aien-dev/aien-sovereign-core", + "commit": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "dirty": false, + "toolchain": "rustc fixture", + "procedure": "cargo test -p alpha", + "machine": "host", + "env_class": "HOST_TEST", + "input_artifacts": [ + "blake3:b2e278b7503a88d38c307f96af9ba644c5d5c2af1b5ba521b4ae0ea934e01db8" + ], + "output_artifacts": [], + "assertions": [ + { + "id": "cargo_test_pass", + "expected": "pass", + "observed": "pass", + "pass": true, + "source": "cargo", + "note": "" + } + ], + "dependencies": [ + "8e885832de2e7123555c47803547161c02196646b270d41078d8b16d4beaf765" + ], + "declared_mutation": "NONE", + "observed_mutation": "NONE", + "authority": "", + "output_digest": "644a9bc57c6063e2ba4028fa73ed585170ae7db8ac7723d32be49c021a0225f5", + "external_refs": [], + "ledger": null, + "lease": null, + "required_features": [], + "reserved": "" +} diff --git a/tests/resolve/receipts/7fdff014cb20a0af5b5a5b377532292be29fc15da36d434944ad4521e69de5b3.json b/tests/resolve/receipts/7fdff014cb20a0af5b5a5b377532292be29fc15da36d434944ad4521e69de5b3.json new file mode 100644 index 000000000..3a968a12e --- /dev/null +++ b/tests/resolve/receipts/7fdff014cb20a0af5b5a5b377532292be29fc15da36d434944ad4521e69de5b3.json @@ -0,0 +1,40 @@ +{ + "schema": "EvidenceReceiptV1", + "version": 1, + "id": "7fdff014cb20a0af5b5a5b377532292be29fc15da36d434944ad4521e69de5b3", + "kind": "component-qualification", + "tier": "HOST_TEST", + "result": "PASS", + "timestamp": 1786000000, + "repo": "https://github.com/aien-dev/aien-sovereign-core", + "commit": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "dirty": false, + "toolchain": "rustc fixture", + "procedure": "cargo test -p gamma", + "machine": "host", + "env_class": "HOST_TEST", + "input_artifacts": [ + "blake3:d17162bc8434a689bdc83a101a396bb872c0aca59c6bd2e4d8adbbbce92eb19a" + ], + "output_artifacts": [], + "assertions": [ + { + "id": "cargo_test_pass", + "expected": "pass", + "observed": "pass", + "pass": true, + "source": "cargo", + "note": "" + } + ], + "dependencies": [], + "declared_mutation": "NONE", + "observed_mutation": "NONE", + "authority": "", + "output_digest": "039b3fa6c7a5987c410ffe6d58ab194dfc98840263841bc7c949bdd4497fd576", + "external_refs": [], + "ledger": null, + "lease": null, + "required_features": [], + "reserved": "" +} diff --git a/tests/resolve/receipts/8e885832de2e7123555c47803547161c02196646b270d41078d8b16d4beaf765.json b/tests/resolve/receipts/8e885832de2e7123555c47803547161c02196646b270d41078d8b16d4beaf765.json new file mode 100644 index 000000000..3753b88e1 --- /dev/null +++ b/tests/resolve/receipts/8e885832de2e7123555c47803547161c02196646b270d41078d8b16d4beaf765.json @@ -0,0 +1,42 @@ +{ + "schema": "EvidenceReceiptV1", + "version": 1, + "id": "8e885832de2e7123555c47803547161c02196646b270d41078d8b16d4beaf765", + "kind": "component-qualification", + "tier": "HOST_TEST", + "result": "PASS", + "timestamp": 1786000000, + "repo": "https://github.com/aien-dev/aien-sovereign-core", + "commit": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "dirty": false, + "toolchain": "rustc fixture", + "procedure": "cargo test -p beta", + "machine": "host", + "env_class": "HOST_TEST", + "input_artifacts": [ + "blake3:0e908df01d8f05dcd90f9767ee4f8212365c816e5099099491fcb035d0393fa0" + ], + "output_artifacts": [], + "assertions": [ + { + "id": "cargo_test_pass", + "expected": "pass", + "observed": "pass", + "pass": true, + "source": "cargo", + "note": "" + } + ], + "dependencies": [ + "7fdff014cb20a0af5b5a5b377532292be29fc15da36d434944ad4521e69de5b3" + ], + "declared_mutation": "NONE", + "observed_mutation": "NONE", + "authority": "", + "output_digest": "c607f0e66519ff41d34c1c8e2e312228c3cc358c0a5b75cef4b22cf8ed3875db", + "external_refs": [], + "ledger": null, + "lease": null, + "required_features": [], + "reserved": "" +} diff --git a/tests/test_omega_resolve.c b/tests/test_omega_resolve.c new file mode 100644 index 000000000..d74c235f4 --- /dev/null +++ b/tests/test_omega_resolve.c @@ -0,0 +1,1448 @@ +/* test_omega_resolve.c -- VC1 stage 4: import resolution in the Omega OSC compiler. + * + * Usage (run from the repository root): + * test_omega_resolve run every check; exit 0 only if all pass + * test_omega_resolve the binary was linked against a deliberately broken copy of + * src/omega_resolve.c, src/omega_receipt.c or src/omega_blake3.c + * (built by `make test-resolve`); run every check and require the + * mapped check to FAIL. Exit 1 = killed (what the Makefile + * asserts), 3 = survived, 2 = unknown mutant. + * + * What is NOT hardcoded: BLAKE3 outputs come from the official test vectors + * (tests/resolve/blake3_vectors.txt) and from three receipts written by the Rust implementation + * (tests/resolve/receipts, copied from aien-sovereign-core fixtures); Verified Crumbs are built by + * a test-side encoder that shares no code with the decoder; the closure digest and the build id + * are re-derived here by a second implementation of the formulas; every refusal code is provoked + * by a real compile of an OSC fixture program through the front end and the resolver. + * Receipts built here are emitted as JSON text and their ids are computed by the library under + * test, which is anchored by the Rust receipts above. + */ +#include +#include +#include +#include +#include +#include +#include + +#include "omega_blake3.h" +#include "omega_receipt.h" +#include "omega_resolve.h" +#include "omega_resolve_osc.h" +#include "omega_vcstore.h" +#include "osc_front.h" +#include "osc_cg.h" +#include "sha256.h" + +#ifndef OSCV_PATH +#define OSCV_PATH "build/compiler/oscv" +#endif + +static const char *g_mutant, *g_expect_check; +static int g_failed, g_expect_failed, g_total; + +static void check(const char *name, int ok) { + printf("%s %s\n", ok ? "PASS" : "FAIL", name); + g_total++; + if (!ok) { + g_failed++; + if (g_expect_check && strcmp(name, g_expect_check) == 0) g_expect_failed = 1; + } +} +static void setup_fail(const char *what) { + if (g_mutant && g_expect_failed) { printf("MUTANT %s KILLED by %s (a later fixture then failed: %s)\n", g_mutant, g_expect_check, what); exit(1); } + if (g_mutant) { printf("MUTANT %s SETUP-BROKEN before check %s ran (%s)\n", g_mutant, g_expect_check, what); exit(4); } + fprintf(stderr, "setup failed: %s\n", what); + exit(2); +} + +/* ---- byte and hex helpers ---- */ +typedef struct { uint8_t *p; size_t n, cap; } B; +static void bput(B *b, const void *d, size_t k) { + if (b->n + k > b->cap) { b->cap = (b->n + k) * 2 + 64; b->p = realloc(b->p, b->cap); if (!b->p) setup_fail("oom"); } + if (k) memcpy(b->p + b->n, d, k); + b->n += k; +} +static void bu32(B *b, uint32_t v) { uint8_t t[4] = { (uint8_t)(v >> 24), (uint8_t)(v >> 16), (uint8_t)(v >> 8), (uint8_t)v }; bput(b, t, 4); } +static void bu64(B *b, uint64_t v) { bu32(b, (uint32_t)(v >> 32)); bu32(b, (uint32_t)v); } +static void bstr(B *b, const char *s) { size_t n = strlen(s); bu64(b, n); bput(b, s, n); } + +static void hx(const uint8_t *d, char out[65]) { + static const char h[] = "0123456789abcdef"; + for (int i = 0; i < 32; i++) { out[2 * i] = h[d[i] >> 4]; out[2 * i + 1] = h[d[i] & 15]; } + out[64] = 0; +} +static void mkid(uint8_t out[32], uint8_t b0) { memset(out, 0x77, 32); out[0] = b0; } +static void con_of(const uint8_t sid[32], uint8_t out[32]) { memcpy(out, sid, 32); out[0] ^= 0x80; } + +/* ---- test-side Verified Crumb encoder (writes lists exactly as given) ---- */ +typedef struct { + uint32_t ver; + uint8_t sem[32], con[32], src[32], rcpt[32], root[32]; + uint8_t kind; + uint32_t n_dep; const uint8_t (*dep)[64]; + const char *prof, *pver; + uint32_t n_cap; const char *const *cap; +} Spec; +static void encode(B *o, const Spec *s) { + o->n = 0; + bput(o, "AIEN_VERIFIED_CRUMB_V1", 22); + bu32(o, s->ver); + bput(o, s->sem, 32); bput(o, s->con, 32); bput(o, &s->kind, 1); bput(o, s->src, 32); + bu32(o, 0); + bu32(o, s->n_dep); for (uint32_t i = 0; i < s->n_dep; i++) bput(o, s->dep[i], 64); + bput(o, s->rcpt, 32); bstr(o, s->prof); bstr(o, s->pver); bput(o, s->root, 32); + bu32(o, 0); + bu32(o, s->n_cap); for (uint32_t i = 0; i < s->n_cap; i++) bstr(o, s->cap[i]); +} + +/* ---- receipt JSON emitter ---- */ +typedef struct { + const char *kind, *tier, *env_class, *result, *schema, *decl_mut, *obs_mut, *procedure, *reserved, *feature; + int version; + const char *inputs[4]; int n_in; + const char *deps[4]; int n_dep; + char root[65]; + int assert_pass, extra_key, dup_key, lease; +} RJ; +static void rj_default(RJ *j) { + memset(j, 0, sizeof *j); + j->kind = "host-v1"; j->tier = "HOST_TEST"; j->env_class = NULL; j->result = "PASS"; + j->schema = "EvidenceReceiptV1"; j->decl_mut = "NONE"; j->obs_mut = "NONE"; + j->procedure = "fixture"; j->reserved = ""; j->feature = NULL; j->version = 1; j->assert_pass = 1; + memset(j->root, '6', 64); j->root[64] = 0; +} +static char *rj_emit(const RJ *j, const char *idhex, size_t *len) { + size_t cap = 16384, n = 0; + char *o = malloc(cap); + if (!o) setup_fail("oom"); +#define PF(...) do { n += (size_t)snprintf(o + n, cap - n, __VA_ARGS__); if (n >= cap - 64) setup_fail("receipt too long"); } while (0) + PF("{\n\"schema\": \"%s\",\n\"version\": %d,\n\"id\": \"%s\",\n\"kind\": \"%s\",\n", j->schema, j->version, idhex, j->kind); + if (j->dup_key) PF("\"kind\": \"%s\",\n", j->kind); + if (j->extra_key) PF("\"surprise\": 1,\n"); + PF("\"tier\": \"%s\",\n\"result\": \"%s\",\n\"timestamp\": 1786000000,\n", j->tier, j->result); + PF("\"repo\": \"fixture\",\n\"commit\": \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n\"dirty\": false,\n"); + PF("\"toolchain\": \"fixture\",\n\"procedure\": \"%s\",\n\"machine\": \"host\",\n\"env_class\": \"%s\",\n", j->procedure, j->env_class ? j->env_class : j->tier); + PF("\"input_artifacts\": ["); + for (int i = 0; i < j->n_in; i++) PF("%s\"%s\"", i ? ", " : "", j->inputs[i]); + PF("],\n\"output_artifacts\": [],\n\"assertions\": [{\"id\": \"fixture_check\", \"expected\": \"pass\", \"observed\": \"%s\", \"pass\": %s, \"source\": \"test\", \"note\": \"\"}],\n", + j->assert_pass ? "pass" : "fail", j->assert_pass ? "true" : "false"); + PF("\"dependencies\": ["); + for (int i = 0; i < j->n_dep; i++) PF("%s\"%s\"", i ? ", " : "", j->deps[i]); + PF("],\n\"declared_mutation\": \"%s\",\n\"observed_mutation\": \"%s\",\n\"authority\": \"\",\n\"output_digest\": \"%s\",\n\"external_refs\": [],\n\"ledger\": null,\n", + j->decl_mut, j->obs_mut, j->root); + if (j->lease) PF("\"lease\": {\"hold_id\": \"%s\", \"resource\": \"fixture-lease\"},\n", "1111111111111111111111111111111111111111111111111111111111111111"); + else PF("\"lease\": null,\n"); + if (j->feature) PF("\"required_features\": [\"%s\"],\n", j->feature); else PF("\"required_features\": [],\n"); + PF("\"reserved\": \"%s\"\n}\n", j->reserved); +#undef PF + *len = n; + return o; +} +/* emit with a placeholder id, let the library compute the id, emit again with the real id */ +static int rj_make(const RJ *j, uint8_t id[32], char **json, size_t *len) { + char zero[65]; memset(zero, '0', 64); zero[64] = 0; + size_t l0; char *t = rj_emit(j, zero, &l0); + OmegaReceipt r; char err[200]; + if (omega_receipt_parse((const uint8_t *)t, l0, &r, err, sizeof err)) { free(t); return -1; } + free(t); + int rc = omega_receipt_compute_id(&r, id); + omega_receipt_free(&r); + if (rc) return -1; + char h[65]; hx(id, h); + *json = rj_emit(j, h, len); + return 0; +} + +/* ---- in-memory receipt store ---- */ +typedef struct { uint8_t id[32]; char *p; size_t n; } Rb; +typedef struct { Rb *v; size_t n; } RTab; +static void tab_put(RTab *t, const uint8_t id[32], const char *p, size_t n) { + t->v = realloc(t->v, (t->n + 1) * sizeof *t->v); + if (!t->v) setup_fail("oom"); + memcpy(t->v[t->n].id, id, 32); + t->v[t->n].p = malloc(n + 1); + if (!t->v[t->n].p) setup_fail("oom"); + memcpy(t->v[t->n].p, p, n); + t->v[t->n].n = n; + t->n++; +} +static int tab_fetch(void *ctx, const uint8_t id[32], uint8_t **bytes, size_t *len) { + RTab *t = ctx; + for (size_t i = 0; i < t->n; i++) + if (memcmp(t->v[i].id, id, 32) == 0) { + *bytes = malloc(t->v[i].n + 1); + if (!*bytes) return 2; + memcpy(*bytes, t->v[i].p, t->v[i].n); + *len = t->v[i].n; + return 0; + } + return 1; +} + +/* ---- the world: a store, receipts, and a resolver over them ---- */ +typedef struct { + OmegaVcStore *st; + RTab rt; + uint8_t last_rid[32]; + int allow_genesis; +} W; +static void w_init(W *w) { + memset(w, 0, sizeof *w); + w->st = calloc(1, sizeof *w->st); + if (!w->st || omega_vcstore_init(w->st) != 0) setup_fail("store"); +} +static void w_free(W *w) { + omega_vcstore_destroy(w->st); free(w->st); + for (size_t i = 0; i < w->rt.n; i++) free(w->rt.v[i].p); + free(w->rt.v); +} + +typedef struct { + const char *prof, *ver, *tier, *result; + int assert_fail, skip_sid, stale_src, wrong_root, extra_rdep, wrong_kind, no_store, swap, taint, boot, lease; +} Opt; +static Opt opt0(void) { + Opt o; memset(&o, 0, sizeof o); + o.prof = "host-v1"; o.ver = "1.0.0"; o.tier = "HOST_TEST"; o.result = "PASS"; + return o; +} +static int ins_spec(OmegaVcStore *st, const Spec *sp, int boot) { + B b = { 0, 0, 0 }; + encode(&b, sp); + uint8_t id[32]; + omega_vc_compute_id(b.p, b.n, id); + int rc = boot ? omega_vcstore_insert_bootstrap(st, b.p, b.n, id) : omega_vcstore_insert(st, b.p, b.n, id); + free(b.p); + return rc; +} +static void spec_for(Spec *sp, uint8_t b0, const uint8_t (*deps)[32], uint32_t nd, uint8_t (*dbuf)[64]) { + memset(sp, 0, sizeof *sp); + sp->ver = 1; sp->kind = 1; + mkid(sp->sem, b0); con_of(sp->sem, sp->con); + memset(sp->src, 0x33, 32); sp->src[0] = b0; + memset(sp->root, 0x66, 32); sp->root[0] = b0; + memset(sp->rcpt, 0x55, 32); + for (uint32_t i = 0; i < nd; i++) { memcpy(dbuf[i], deps[i], 32); con_of(deps[i], dbuf[i] + 32); } + sp->n_dep = nd; sp->dep = (const uint8_t (*)[64])dbuf; + sp->prof = "host-v1"; sp->pver = "1.0.0"; +} +/* add one component; returns the insert result. Its receipt id is left in w->last_rid. */ +static int add_comp(W *w, uint8_t b0, const uint8_t (*deps)[32], uint32_t nd, const Opt *o) { + uint8_t dbuf[8][64]; + Spec sp; + spec_for(&sp, b0, deps, nd, dbuf); + sp.prof = o->prof; sp.pver = o->ver; + const char *taintcap[1] = { OMEGA_TAINT_CAPABILITY }; + if (o->taint) { sp.n_cap = 1; sp.cap = taintcap; } + if (o->boot) { + memset(sp.rcpt, 0xA0, 32); sp.rcpt[0] = b0; + memcpy(w->last_rid, sp.rcpt, 32); + return ins_spec(w->st, &sp, 1); + } + char sid_h[65], src_h[65], oth_h[65], root_h[65], inp[4][80], dep_h[8][65]; + hx(sp.sem, sid_h); hx(sp.src, src_h); + uint8_t other[32]; memset(other, 0x99, 32); hx(other, oth_h); + uint8_t root[32]; memcpy(root, sp.root, 32); if (o->wrong_root) root[5] ^= 1; + hx(root, root_h); + RJ j; rj_default(&j); + j.kind = o->wrong_kind ? "some-other-kind" : o->prof; + j.tier = o->tier; j.result = o->result; j.assert_pass = !o->assert_fail; j.lease = o->lease; + memcpy(j.root, root_h, 65); + if (!o->skip_sid) { snprintf(inp[j.n_in], 80, "sha256:%s", sid_h); j.inputs[j.n_in] = inp[j.n_in]; j.n_in++; } + snprintf(inp[j.n_in], 80, "sha256:%s", o->stale_src ? oth_h : src_h); j.inputs[j.n_in] = inp[j.n_in]; j.n_in++; + for (uint32_t i = 0; i < nd; i++) { + uint8_t r[32]; + if (omega_vcstore_receipt_of(w->st, deps[i], r) != 0) setup_fail("dependency not in store"); + hx(r, dep_h[j.n_dep]); j.deps[j.n_dep] = dep_h[j.n_dep]; j.n_dep++; + } + char extra[65]; memset(extra, 'a', 64); extra[64] = 0; + if (o->extra_rdep) j.deps[j.n_dep++] = extra; + uint8_t rid[32]; char *json; size_t jl; + if (rj_make(&j, rid, &json, &jl)) setup_fail("receipt fixture rejected by the library"); + memcpy(w->last_rid, rid, 32); + memcpy(sp.rcpt, rid, 32); + if (o->swap) { /* the file stored under rid holds another, internally valid receipt */ + RJ k = j; k.procedure = "swapped"; uint8_t rid2[32]; char *json2; size_t jl2; + if (rj_make(&k, rid2, &json2, &jl2)) setup_fail("swap receipt"); + tab_put(&w->rt, rid, json2, jl2); free(json2); + } else if (!o->no_store) tab_put(&w->rt, rid, json, jl); + free(json); + return ins_spec(w->st, &sp, 0); +} +/* replace the stored bytes of an existing object (tampering; mirrors test_omega_vcstore.c) */ +static void replace_obj(W *w, uint8_t b0, const Spec *sp) { + uint8_t sid[32]; mkid(sid, b0); + for (size_t i = 0; i < w->st->count; i++) + if (memcmp(w->st->objs[i].semantic_id, sid, 32) == 0) { + B b = { 0, 0, 0 }; + encode(&b, sp); + free(w->st->objs[i].bytes); + w->st->objs[i].bytes = b.p; w->st->objs[i].len = b.n; + omega_vc_compute_id(b.p, b.n, w->st->objs[i].vc_id); + return; + } + setup_fail("replace_obj: no such object"); +} + +/* ---- lock text and compiling a fixture through the real front end ---- */ +typedef struct { const char *name; uint8_t b0; int wrong_receipt; } Pin; +static char g_lock[8192]; +static const char *lock_text(const W *w, const Pin *pins, size_t n) { + size_t at = (size_t)snprintf(g_lock, sizeof g_lock, "omega.lock v1\n"); + for (size_t i = 0; i < n; i++) { + uint8_t sid[32], rid[32]; char a[65], b[65]; + mkid(sid, pins[i].b0); + if (omega_vcstore_receipt_of(w->st, sid, rid) != 0) memset(rid, 0x42, 32); + if (pins[i].wrong_receipt) rid[3] ^= 1; + hx(sid, a); hx(rid, b); + at += (size_t)snprintf(g_lock + at, sizeof g_lock - at, "%s = semantic %s receipt %s\n", pins[i].name, a, b); + } + return g_lock; +} +typedef struct { + OscUnit *u; + OscDiag dg; + OmegaOscImports h; + OmegaLock lock; + int rc, lock_rc; +} Run; +static const char *FN = "fn add(a: u32, b: u32) -> u32 { return a + b; }\n"; +static void run_compile(W *w, const char *src, OmegaDomain d, const char *locktext, Run *r) { + memset(r, 0, sizeof *r); + r->u = malloc(sizeof *r->u); + if (!r->u) setup_fail("oom"); + OmegaResolveError e; + if (locktext) { + r->lock_rc = omega_lock_parse(locktext, strlen(locktext), &r->lock, &e); + if (r->lock_rc) setup_fail("fixture lock did not parse"); + r->h.lock = &r->lock; + } + r->h.resolver.store = w->st; + r->h.resolver.domain = d; + r->h.resolver.fetch_receipt = tab_fetch; + r->h.resolver.fetch_ctx = &w->rt; + r->h.resolver.allow_genesis = w->allow_genesis; + r->rc = osc_compile_imports(src, strlen(src), r->u, &r->dg, NULL, omega_osc_import_hook, &r->h); +} +static void run_free(Run *r) { + omega_closure_free(&r->h.closure); + omega_lock_free(&r->lock); + free(r->u); +} +static int refused(const Run *r, const char *code, int code_enum) { + return r->rc != 0 && r->dg.kind == OSC_DIAG_IMPORT_REFUSED && strcmp(r->dg.transition, code) == 0 && r->h.err.code == code_enum; +} +static int refused_msg(const Run *r, const char *code, int code_enum, const char *needle) { + return refused(r, code, code_enum) && strstr(r->h.err.message, needle) != NULL; +} +static char g_src[512]; +static const char *src_imports(const char *const *names, size_t n) { + size_t at = 0; + g_src[0] = 0; + for (size_t i = 0; i < n; i++) at += (size_t)snprintf(g_src + at, sizeof g_src - at, "import %s;\n", names[i]); + snprintf(g_src + at, sizeof g_src - at, "%s", FN); + return g_src; +} +/* one component "foo" built with o, pinned correctly, imported by a fixture program */ +static int one_foo(const Opt *o, OmegaDomain d, Run *r, W *w) { + w_init(w); + if (add_comp(w, 0x51, NULL, 0, o) != 0) setup_fail("one_foo insert"); + Pin p[1] = { { "foo", 0x51, 0 } }; + const char *nm[1] = { "foo" }; + const char *lk = lock_text(w, p, 1); + run_compile(w, src_imports(nm, 1), d, lk, r); + return r->rc; +} + +/* ======================================================================== checks */ +static uint8_t *slurp_file(const char *path, size_t *n) { + FILE *f = fopen(path, "rb"); + if (!f) return NULL; + size_t cap = 1 << 14, k = 0; + uint8_t *b = malloc(cap); + for (;;) { + k += fread(b + k, 1, cap - k, f); + if (k < cap) break; + cap *= 2; b = realloc(b, cap); + } + fclose(f); + *n = k; + return b; +} + +/* ---- BLAKE3 ---- */ +static void t_blake3(void) { + FILE *f = fopen("tests/resolve/blake3_vectors.txt", "r"); + if (!f) setup_fail("tests/resolve/blake3_vectors.txt (run from the repository root)"); + size_t len; char want[80]; + int n = 0, bad = 0; + while (fscanf(f, "%zu %64s", &len, want) == 2) { + uint8_t *in = malloc(len + 1), out[32]; char got[65]; + if (!in) setup_fail("oom"); + for (size_t i = 0; i < len; i++) in[i] = (uint8_t)(i % 251); + omega_blake3_hash(in, len, out); + hx(out, got); + n++; + if (strcmp(got, want) != 0) bad++; + free(in); + } + fclose(f); + check("b3-official-vectors", n == 35 && bad == 0); +} + +/* ---- receipts ---- */ +static int rj_refused(const RJ *j) { + char zero[65]; memset(zero, '0', 64); zero[64] = 0; + size_t l; char *t = rj_emit(j, zero, &l); + OmegaReceipt r; char err[200]; + int rc = omega_receipt_parse((const uint8_t *)t, l, &r, err, sizeof err); + if (rc == 0) omega_receipt_free(&r); + free(t); + return rc != 0; +} +static void t_receipts(void) { + static const char *const files[3] = { "54f597d22b3753e47d6bd7706b6a7a422c189024912ec4626347e860b5f44a8c", + "7fdff014cb20a0af5b5a5b377532292be29fc15da36d434944ad4521e69de5b3", + "8e885832de2e7123555c47803547161c02196646b270d41078d8b16d4beaf765" }; + int ok = 0; + for (int i = 0; i < 3; i++) { + char path[256]; snprintf(path, sizeof path, "tests/resolve/receipts/%s.json", files[i]); + size_t n; uint8_t *b = slurp_file(path, &n); + if (!b) setup_fail("rust receipt fixture"); + OmegaReceipt r; uint8_t id[32]; char err[200], h[65]; + if (omega_receipt_verify_bytes(b, n, &r, id, err, sizeof err) == 0) { + hx(id, h); + if (strcmp(h, files[i]) == 0) ok++; + omega_receipt_free(&r); + } + free(b); + } + check("receipt-rust-ids", ok == 3); + + uint8_t x[32], y[32]; char xh[80], yh[80]; + memset(x, 1, 32); memset(y, 2, 32); + snprintf(xh, sizeof xh, "sha256:"); hx(x, xh + 7); + snprintf(yh, sizeof yh, "sha256:"); hx(y, yh + 7); + RJ a, b; rj_default(&a); rj_default(&b); + a.inputs[0] = xh; a.inputs[1] = yh; a.n_in = 2; + b.inputs[0] = yh; b.inputs[1] = xh; b.n_in = 2; + uint8_t ida[32], idb[32]; char *ja, *jb; size_t la, lb; + int mk = rj_make(&a, ida, &ja, &la) == 0 && rj_make(&b, idb, &jb, &lb) == 0; + RJ c = a; c.procedure = "another procedure"; uint8_t idc[32]; char *jc; size_t lc; + int mk2 = rj_make(&c, idc, &jc, &lc) == 0; + check("receipt-canon-order-independent", mk && mk2 && memcmp(ida, idb, 32) == 0 && memcmp(ida, idc, 32) != 0); + + /* a receipt whose id field is not the hash of its content */ + if (!mk) setup_fail("receipt fixture"); + { + char h[65]; hx(ida, h); + OmegaReceipt r; uint8_t id[32]; char err[200]; + int good = omega_receipt_verify_bytes((const uint8_t *)ja, la, &r, id, err, sizeof err); + if (good == 0) omega_receipt_free(&r); + h[0] = h[0] == '0' ? '1' : '0'; + char *bad = rj_emit(&a, h, &lb); + int rc = omega_receipt_verify_bytes((const uint8_t *)bad, lb, &r, id, err, sizeof err); + if (rc == 0) omega_receipt_free(&r); + free(bad); + check("receipt-refuses-wrong-id", good == 0 && rc != 0); + } + RJ j; + rj_default(&j); j.dup_key = 1; check("receipt-refuses-duplicate-key", rj_refused(&j)); + rj_default(&j); j.extra_key = 1; check("receipt-refuses-unknown-field", rj_refused(&j)); + rj_default(&j); j.schema = "EvidenceReceiptV2"; check("receipt-refuses-unknown-schema", rj_refused(&j)); + rj_default(&j); j.version = 2; check("receipt-refuses-unknown-version", rj_refused(&j)); + rj_default(&j); j.feature = "v2-extension"; check("receipt-refuses-unknown-feature", rj_refused(&j)); + rj_default(&j); j.reserved = "x"; check("receipt-refuses-reserved-field", rj_refused(&j)); + rj_default(&j); j.env_class = "QEMU"; check("receipt-refuses-env-class-mismatch", rj_refused(&j)); + rj_default(&j); j.obs_mut = "VOLATILE_ONLY"; check("receipt-refuses-observed-over-declared", rj_refused(&j)); + rj_default(&j); j.decl_mut = "VOLATILE_ONLY"; j.obs_mut = "VOLATILE_ONLY"; + check("receipt-control-valid-variant-parses", !rj_refused(&j)); + free(ja); free(jb); free(jc); + + int tab_ok = 1; + for (int need = -1; need <= 7; need++) + for (int have = -1; have <= 7; have++) { + int want = need >= 0 && have >= 0 && have >= need; + if (omega_tier_satisfies(need, have) != want) tab_ok = 0; + } + check("tier-satisfies-table", tab_ok && omega_tier_rank("PRODUCTION") == 7 && omega_tier_rank("HOST_TEST") == 1 && + omega_tier_rank("TEST_ONLY_TRUST") == 0 && omega_tier_rank("nonsense") == -1); +} + +/* ---- profiles ---- */ +static void t_profiles(void) { + size_t n; const OmegaVerifierProfile *t = omega_resolve_default_profiles(&n); + OmegaResolveError e; + check("profile-table-contents", n == 3 && strcmp(t[0].name, "host-v1") == 0 && strcmp(t[0].min_tier, "HOST_TEST") == 0 && + strcmp(t[1].name, "qemu-v1") == 0 && strcmp(t[1].min_tier, "QEMU") == 0 && + strcmp(t[2].name, "production-v1") == 0 && strcmp(t[2].min_tier, "PRODUCTION") == 0); + check("profile-known-accepted", omega_resolve_check_profile(t, n, "host-v1", "1.0.0", &e) == 0); + int rc = omega_resolve_check_profile(t, n, "mystery-v9", "1.0.0", &e); + check("profile-unknown-refused", rc == OMEGA_RES_UNKNOWN_VERIFIER_PROFILE && e.code == rc); + rc = omega_resolve_check_profile(t, n, "", "1.0.0", &e); + check("profile-empty-name-refused", rc == OMEGA_RES_UNKNOWN_VERIFIER_PROFILE); + static const char *const old[] = { "0.9.9", "0.99.99", "0", "0.0.0", "", "abc", "1.0.0-rc", "1..0", "1.0.", ".1", "1.0.x" }; + int old_ok = 1; + for (size_t i = 0; i < sizeof old / sizeof old[0]; i++) + if (omega_resolve_check_profile(t, n, "host-v1", old[i], &e) != OMEGA_RES_VERIFIER_TOO_OLD) old_ok = 0; + check("profile-version-too-old-refused", old_ok); + static const char *const fine[] = { "1.0.0", "1.0.1", "1.1", "1.0", "1", "2.0.0", "10.0.0", "1.0.0.0" }; + int fine_ok = 1; + for (size_t i = 0; i < sizeof fine / sizeof fine[0]; i++) + if (omega_resolve_check_profile(t, n, "host-v1", fine[i], &e) != 0) fine_ok = 0; + check("profile-version-boundaries-accepted", fine_ok); +} + +/* ---- the lock ---- */ +static const char *H1 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; +static const char *H2 = "bbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; +static int lock_refused(const char *text, size_t len) { + OmegaLock l; OmegaResolveError e; + int rc = omega_lock_parse(text, len, &l, &e); + if (rc == 0) { omega_lock_free(&l); return 0; } + return rc == OMEGA_RES_DEPENDENCY_NOT_PINNED && e.code == rc; +} +static void t_lock(void) { + char buf[1024]; + OmegaLock l; OmegaResolveError e; + snprintf(buf, sizeof buf, "omega.lock v1\nalpha = semantic %s receipt %s\nbeta.x-1_y = semantic %s receipt %s\n", H1, H2, H2, H1); + int rc = omega_lock_parse(buf, strlen(buf), &l, &e); + int ok = rc == 0 && l.n == 2 && strcmp(l.e[0].name, "alpha") == 0 && l.e[0].semantic[0] == 0xaa && l.e[0].receipt[0] == 0xbb && + omega_lock_find(&l, "beta.x-1_y") != NULL && omega_lock_find(&l, "gamma") == NULL && omega_lock_find(&l, "alph") == NULL; + if (rc == 0) omega_lock_free(&l); + check("lock-parses-valid", ok); + rc = omega_lock_parse("omega.lock v1\n", 14, &l, &e); + check("lock-parses-empty", rc == 0 && l.n == 0); + if (rc == 0) omega_lock_free(&l); + + snprintf(buf, sizeof buf, "omega.lock v2\nalpha = semantic %s receipt %s\n", H1, H2); + check("lock-refuses-wrong-header", lock_refused(buf, strlen(buf))); + check("lock-refuses-empty-file", lock_refused("", 0)); + check("lock-refuses-missing-final-newline", lock_refused("omega.lock v1", 13)); + snprintf(buf, sizeof buf, "omega.lock v1\nalpha = semantic %s receipt %s", H1, H2); + check("lock-refuses-no-trailing-lf", lock_refused(buf, strlen(buf))); + snprintf(buf, sizeof buf, "omega.lock v1\nalpha = semantic %s receipt %s\n", H1, H2); + { char t[1024]; size_t k = strlen(buf); memcpy(t, buf, k + 1); t[22] = '\t'; + check("lock-refuses-tab", lock_refused(t, k)); } + { char t[1024]; size_t k = strlen(buf); memcpy(t, buf, k + 1); t[k - 1] = '\r'; t[k] = '\n'; t[k + 1] = 0; + check("lock-refuses-cr", lock_refused(t, k + 1)); } + { char t[1024]; size_t k = strlen(buf); memcpy(t, buf, k + 1); t[k - 1] = 0; t[k] = '\n'; + check("lock-refuses-nul", lock_refused(t, k + 1)); } + { const char *c1 = "omega.lock v1\n# a\tcomment\n"; check("lock-refuses-tab-in-comment", lock_refused(c1, strlen(c1))); + const char *c2 = "omega.lock v1\r\n"; check("lock-refuses-crlf-header", lock_refused(c2, strlen(c2))); + const char *c3 = "omega.lock v1\n# a comment\r\n"; check("lock-refuses-cr-in-comment", lock_refused(c3, strlen(c3))); + static const char c4[] = "omega.lock v1\n# a\0comment\n"; check("lock-refuses-nul-in-comment", lock_refused(c4, sizeof c4 - 1)); } + check("lock-refuses-unknown-line", lock_refused("omega.lock v1\nhello world\n", 26)); + snprintf(buf, sizeof buf, "omega.lock v1\n# a comment\n\nalpha = semantic %s receipt %s\n\n# another\n", H1, H2); + rc = omega_lock_parse(buf, strlen(buf), &l, &e); + check("lock-allows-comment-and-blank-lines", rc == 0 && l.n == 1); + if (rc == 0) omega_lock_free(&l); + check("lock-refuses-indented-comment", lock_refused("omega.lock v1\n # not a comment\n", 30)); + snprintf(buf, sizeof buf, "omega.lock v1\nalpha = semantic %s receipt %s\n", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", H2); + check("lock-refuses-all-uppercase-hex", lock_refused(buf, strlen(buf))); + snprintf(buf, sizeof buf, "omega.lock v1\nalpha = semantic %.63sA receipt %s\n", H1, H2); + check("lock-refuses-uppercase-hex", lock_refused(buf, strlen(buf))); + snprintf(buf, sizeof buf, "omega.lock v1\nalpha = semantic %s receipt %.63sg\n", H1, H2); + check("lock-refuses-non-hex-character", lock_refused(buf, strlen(buf))); + snprintf(buf, sizeof buf, "omega.lock v1\nalpha = semantic %.63s receipt %s\n", H1, H2); + check("lock-refuses-short-hex", lock_refused(buf, strlen(buf))); + snprintf(buf, sizeof buf, "omega.lock v1\nalpha = semantic %s0 receipt %s\n", H1, H2); + check("lock-refuses-long-hex", lock_refused(buf, strlen(buf))); + snprintf(buf, sizeof buf, "omega.lock v1\nalpha = semantic %s receipt %s\n", "0000000000000000000000000000000000000000000000000000000000000000", H2); + check("lock-refuses-zero-digest", lock_refused(buf, strlen(buf))); + snprintf(buf, sizeof buf, "omega.lock v1\nbeta = semantic %s receipt %s\nalpha = semantic %s receipt %s\n", H1, H2, H1, H2); + check("lock-refuses-unsorted", lock_refused(buf, strlen(buf))); + snprintf(buf, sizeof buf, "omega.lock v1\nalpha = semantic %s receipt %s\nalpha = semantic %s receipt %s\n", H1, H2, H2, H1); + check("lock-refuses-duplicate-name", lock_refused(buf, strlen(buf))); + snprintf(buf, sizeof buf, "omega.lock v1\nalpha = semantic %s receipt %s\n", H1, H2); + check("lock-refuses-extra-space", lock_refused(buf, strlen(buf))); + snprintf(buf, sizeof buf, "omega.lock v1\nalpha = semantic %s receipt %s \n", H1, H2); + check("lock-refuses-trailing-space", lock_refused(buf, strlen(buf))); + snprintf(buf, sizeof buf, "omega.lock v1\nalpha = receipt %s semantic %s\n", H1, H2); + check("lock-refuses-swapped-keywords", lock_refused(buf, strlen(buf))); + snprintf(buf, sizeof buf, "omega.lock v1\n1alpha = semantic %s receipt %s\n", H1, H2); + check("lock-refuses-bad-name-start", lock_refused(buf, strlen(buf))); + snprintf(buf, sizeof buf, "omega.lock v1\nal/pha = semantic %s receipt %s\n", H1, H2); + check("lock-refuses-bad-name-char", lock_refused(buf, strlen(buf))); + snprintf(buf, sizeof buf, "omega.lock v1\nalpha = semantic %s\n", H1); + check("lock-refuses-missing-receipt-field", lock_refused(buf, strlen(buf))); +} + +/* ---- OSC front end: the `import` grammar ---- */ +static int stub_hook(void *ctx, const OscImport *imps, uint32_t n, uint32_t *bad, char *why, size_t cap) { + (void)bad; (void)why; (void)cap; + uint32_t *c = ctx; + c[0]++; c[1] = n; + c[2] = (n > 0 && strcmp(imps[0].name, "foo") == 0) ? 1 : 0; + return 0; +} +static int refuse_second_hook(void *ctx, const OscImport *imps, uint32_t n, uint32_t *bad, char *why, size_t cap) { + (void)ctx; (void)imps; + *bad = n - 1; + snprintf(why, cap, "TEST_CODE: nope"); + return -1; +} +static int front(const char *src, OscImportResolver h, void *ctx, OscDiag *d) { + OscUnit *u = malloc(sizeof *u); + if (!u) setup_fail("oom"); + int rc = osc_compile_imports(src, strlen(src), u, d, NULL, h, ctx); + free(u); + return rc; +} +static void t_frontend(void) { + OscDiag d; uint32_t c[3] = { 0, 0, 0 }; + char s[8192]; + snprintf(s, sizeof s, "import foo;\nimport bar;\n%s", FN); + int rc = front(s, stub_hook, c, &d); + check("osc-import-grammar-accepted", rc == 0 && c[0] == 1 && c[1] == 2 && c[2] == 1); + c[0] = 0; + rc = front(FN, stub_hook, c, &d); + check("osc-resolver-runs-with-zero-imports", rc == 0 && c[0] == 1 && c[1] == 0); + snprintf(s, sizeof s, "import foo\n%s", FN); + rc = front(s, stub_hook, c, &d); + check("osc-import-needs-semicolon", rc != 0 && d.kind == OSC_DIAG_SYNTAX); + snprintf(s, sizeof s, "%simport foo;\n", FN); + rc = front(s, stub_hook, c, &d); + check("osc-import-after-function-refused", rc != 0 && d.kind == OSC_DIAG_SYNTAX); + snprintf(s, sizeof s, "import foo;\nimport foo;\n%s", FN); + rc = front(s, stub_hook, c, &d); + check("osc-import-duplicate-refused", rc != 0 && d.kind == OSC_DIAG_REDEFINED_NAME); + snprintf(s, sizeof s, "import 7;\n%s", FN); + rc = front(s, stub_hook, c, &d); + check("osc-import-number-refused", rc != 0 && d.kind == OSC_DIAG_SYNTAX); + snprintf(s, sizeof s, "import fn;\n%s", FN); + rc = front(s, stub_hook, c, &d); + check("osc-import-keyword-refused", rc != 0 && d.kind == OSC_DIAG_SYNTAX); + { + size_t at = 0; + for (int i = 0; i < 65; i++) at += (size_t)snprintf(s + at, sizeof s - at, "import m%d;\n", i); + snprintf(s + at, sizeof s - at, "%s", FN); + rc = front(s, stub_hook, c, &d); + check("osc-too-many-imports-refused", rc != 0 && d.kind == OSC_DIAG_CAPACITY); + } + snprintf(s, sizeof s, "import foo;\n%s", FN); + OscUnit *u = malloc(sizeof *u); + if (!u) setup_fail("oom"); + rc = osc_compile(s, strlen(s), u, &d, NULL); + check("osc-plain-compile-refuses-imports", rc != 0 && d.kind == OSC_DIAG_UNSUPPORTED); + rc = osc_compile_imports(s, strlen(s), u, &d, NULL, NULL, NULL); + check("osc-no-resolver-refuses-imports", rc != 0 && d.kind == OSC_DIAG_UNSUPPORTED); + uint8_t d1[32], d2[32]; + OscUnit *u2 = malloc(sizeof *u2); + if (!u2) setup_fail("oom"); + c[0] = 0; + int r1 = osc_compile(FN, strlen(FN), u, &d, NULL); + int r2 = osc_compile_imports(FN, strlen(FN), u2, &d, NULL, stub_hook, c); + int g = r1 == 0 && r2 == 0 && osc_ir_digest(u, d1) == 0 && osc_ir_digest(u2, d2) == 0; + check("osc-no-import-unit-identical-to-plain-compile", g && memcmp(d1, d2, 32) == 0); + free(u); free(u2); + snprintf(s, sizeof s, "import foo;\nimport bar;\n%s", FN); + rc = front(s, refuse_second_hook, NULL, &d); + check("osc-hook-refusal-points-at-the-import", rc != 0 && d.kind == OSC_DIAG_IMPORT_REFUSED && d.line == 2 && + strcmp(d.transition, "TEST_CODE") == 0); +} + +/* ---- reference formulas (independent of the library under test) ---- */ +static void ref_closure_digest(const OmegaClosureEntry *e, size_t n, uint8_t out[32]) { + B b = { 0, 0, 0 }; + bput(&b, "OMEGA.CLOSURE.V1", 16); + uint8_t z = 0; bput(&b, &z, 1); + bu32(&b, (uint32_t)n); + for (size_t i = 0; i < n; i++) { bput(&b, e[i].semantic_id, 32); bput(&b, e[i].receipt_id, 32); bput(&b, &e[i].admission_kind, 1); } + sha256_hash(b.p, b.n, out); + free(b.p); +} +static void ref_build_id(const uint8_t ir[32], int dom, const uint8_t cl[32], uint8_t out[32]) { + B b = { 0, 0, 0 }; + bput(&b, "OSC1.BUILD.V1", 13); + uint8_t z = 0, d = (uint8_t)dom; bput(&b, &z, 1); + bput(&b, ir, 32); bput(&b, &d, 1); bput(&b, cl, 32); + sha256_hash(b.p, b.n, out); + free(b.p); +} +static int ir_of(const Run *r, uint8_t out[32]) { return osc_ir_digest(r->u, out); } + +/* ---- the refusal codes, each from a real compile ---- */ +static void t_refusals(void) { + W w; Run r; Opt o; + + /* the good path first: a record that passes every check resolves */ + o = opt0(); + one_foo(&o, OMEGA_DOMAIN_BUILD, &r, &w); + check("resolve-accepts-verified-record", r.rc == 0 && r.h.resolved && r.h.closure.n == 1 && r.h.n_imports == 1); + run_free(&r); w_free(&w); + + /* UNVERIFIED_DEPENDENCY: the pinned id is not in the store */ + w_init(&w); + { Opt a = opt0(); add_comp(&w, 0x51, NULL, 0, &a); } + { Pin p[1] = { { "foo", 0x77, 0 } }; const char *nm[1] = { "foo" }; + run_compile(&w, src_imports(nm, 1), OMEGA_DOMAIN_BUILD, lock_text(&w, p, 1), &r); } + check("refuse-unverified-id-not-in-store", refused(&r, "UNVERIFIED_DEPENDENCY", OMEGA_RES_UNVERIFIED_DEPENDENCY)); + run_free(&r); w_free(&w); + + /* MISSING_RECEIPT: the record names a receipt that is not in the receipt store */ + o = opt0(); o.no_store = 1; + one_foo(&o, OMEGA_DOMAIN_BUILD, &r, &w); + check("refuse-missing-receipt", refused(&r, "MISSING_RECEIPT", OMEGA_RES_MISSING_RECEIPT)); + run_free(&r); w_free(&w); + + /* RECEIPT_HASH_MISMATCH, one cause per check */ + o = opt0(); o.swap = 1; + one_foo(&o, OMEGA_DOMAIN_BUILD, &r, &w); + check("refuse-receipt-file-holds-another-receipt", refused(&r, "RECEIPT_HASH_MISMATCH", OMEGA_RES_RECEIPT_HASH_MISMATCH)); + run_free(&r); w_free(&w); + o = opt0(); o.skip_sid = 1; + one_foo(&o, OMEGA_DOMAIN_BUILD, &r, &w); + check("refuse-receipt-does-not-name-program", refused(&r, "RECEIPT_HASH_MISMATCH", OMEGA_RES_RECEIPT_HASH_MISMATCH)); + run_free(&r); w_free(&w); + o = opt0(); o.wrong_root = 1; + one_foo(&o, OMEGA_DOMAIN_BUILD, &r, &w); + check("refuse-receipt-output-digest-is-not-evidence-root", refused(&r, "RECEIPT_HASH_MISMATCH", OMEGA_RES_RECEIPT_HASH_MISMATCH)); + run_free(&r); w_free(&w); + o = opt0(); o.wrong_kind = 1; + one_foo(&o, OMEGA_DOMAIN_BUILD, &r, &w); + check("refuse-receipt-kind-is-not-profile", refused(&r, "RECEIPT_HASH_MISMATCH", OMEGA_RES_RECEIPT_HASH_MISMATCH)); + run_free(&r); w_free(&w); + o = opt0(); o.extra_rdep = 1; + one_foo(&o, OMEGA_DOMAIN_BUILD, &r, &w); + check("refuse-receipt-has-extra-dependency", refused(&r, "RECEIPT_HASH_MISMATCH", OMEGA_RES_RECEIPT_HASH_MISMATCH)); + run_free(&r); w_free(&w); + + /* the lock pins another receipt than the record carries */ + w_init(&w); + o = opt0(); add_comp(&w, 0x51, NULL, 0, &o); + { Pin p[1] = { { "foo", 0x51, 1 } }; const char *nm[1] = { "foo" }; + run_compile(&w, src_imports(nm, 1), OMEGA_DOMAIN_BUILD, lock_text(&w, p, 1), &r); } + check("refuse-lock-pins-another-receipt", refused(&r, "RECEIPT_HASH_MISMATCH", OMEGA_RES_RECEIPT_HASH_MISMATCH)); + run_free(&r); w_free(&w); + + /* the same, but the pinned name was already reached as a dependency of an earlier import */ + w_init(&w); + o = opt0(); add_comp(&w, 0x61, NULL, 0, &o); + { uint8_t d[1][32]; mkid(d[0], 0x61); add_comp(&w, 0x62, d, 1, &o); } + { Pin p[2] = { { "alpha", 0x62, 0 }, { "beta", 0x61, 1 } }; const char *nm[2] = { "alpha", "beta" }; + run_compile(&w, src_imports(nm, 2), OMEGA_DOMAIN_BUILD, lock_text(&w, p, 2), &r); } + check("refuse-lock-pins-another-receipt-for-visited-node", refused(&r, "RECEIPT_HASH_MISMATCH", OMEGA_RES_RECEIPT_HASH_MISMATCH)); + run_free(&r); + { Pin p[2] = { { "alpha", 0x62, 0 }, { "beta", 0x61, 0 } }; const char *nm[2] = { "alpha", "beta" }; + run_compile(&w, src_imports(nm, 2), OMEGA_DOMAIN_BUILD, lock_text(&w, p, 2), &r); } + check("accept-visited-node-with-the-right-pin", r.rc == 0 && r.h.closure.n == 2); + run_free(&r); w_free(&w); + + /* STALE_RECEIPT: the receipt covers an older source digest */ + o = opt0(); o.stale_src = 1; + one_foo(&o, OMEGA_DOMAIN_BUILD, &r, &w); + check("refuse-stale-receipt", refused(&r, "STALE_RECEIPT", OMEGA_RES_STALE_RECEIPT)); + run_free(&r); w_free(&w); + + /* DEPENDENCY_NOT_PINNED / UNDECLARED_IMPORT, both directions */ + w_init(&w); + o = opt0(); add_comp(&w, 0x51, NULL, 0, &o); + { const char *nm[1] = { "foo" }; run_compile(&w, src_imports(nm, 1), OMEGA_DOMAIN_BUILD, NULL, &r); } + check("refuse-not-pinned-without-lock", refused(&r, "DEPENDENCY_NOT_PINNED", OMEGA_RES_DEPENDENCY_NOT_PINNED)); + run_free(&r); + { const char *nm[2] = { "foo", "bar" }; Pin p[1] = { { "foo", 0x51, 0 } }; + run_compile(&w, src_imports(nm, 2), OMEGA_DOMAIN_BUILD, lock_text(&w, p, 1), &r); } + check("refuse-not-pinned-second-import", refused(&r, "DEPENDENCY_NOT_PINNED", OMEGA_RES_DEPENDENCY_NOT_PINNED) && strcmp(r.h.err.subject, "bar") == 0); + run_free(&r); + { Pin p[1] = { { "foo", 0x51, 0 } }; + run_compile(&w, FN, OMEGA_DOMAIN_BUILD, lock_text(&w, p, 1), &r); } + check("refuse-undeclared-lock-line-without-import", refused(&r, "UNDECLARED_IMPORT", OMEGA_RES_UNDECLARED_IMPORT) && strcmp(r.h.err.subject, "foo") == 0); + run_free(&r); + { const char *nm[1] = { "foo" }; Pin p[2] = { { "bar", 0x51, 0 }, { "foo", 0x51, 0 } }; + run_compile(&w, src_imports(nm, 1), OMEGA_DOMAIN_BUILD, lock_text(&w, p, 2), &r); } + check("refuse-undeclared-extra-lock-line", refused(&r, "UNDECLARED_IMPORT", OMEGA_RES_UNDECLARED_IMPORT) && strcmp(r.h.err.subject, "bar") == 0); + run_free(&r); + { run_compile(&w, FN, OMEGA_DOMAIN_BUILD, NULL, &r); } + check("accept-no-imports-no-lock", r.rc == 0 && r.h.closure.n == 0); + run_free(&r); w_free(&w); + + /* TAINTED_ARTIFACT: a record carrying the dev taint capability, in either domain */ + o = opt0(); o.taint = 1; + one_foo(&o, OMEGA_DOMAIN_BUILD, &r, &w); + check("refuse-tainted-record-in-build-domain", refused(&r, "TAINTED_ARTIFACT", OMEGA_RES_TAINTED_ARTIFACT)); + run_free(&r); w_free(&w); + one_foo(&o, OMEGA_DOMAIN_DEV, &r, &w); + check("refuse-tainted-record-in-dev-domain", refused(&r, "TAINTED_ARTIFACT", OMEGA_RES_TAINTED_ARTIFACT)); + run_free(&r); w_free(&w); + + /* UNKNOWN_VERIFIER_PROFILE and VERIFIER_TOO_OLD, from a real record */ + o = opt0(); o.prof = "mystery-v9"; + one_foo(&o, OMEGA_DOMAIN_BUILD, &r, &w); + check("refuse-unknown-verifier-profile", refused(&r, "UNKNOWN_VERIFIER_PROFILE", OMEGA_RES_UNKNOWN_VERIFIER_PROFILE)); + run_free(&r); w_free(&w); + o = opt0(); o.ver = "0.9.0"; + one_foo(&o, OMEGA_DOMAIN_BUILD, &r, &w); + check("refuse-verifier-too-old", refused(&r, "VERIFIER_TOO_OLD", OMEGA_RES_VERIFIER_TOO_OLD)); + run_free(&r); w_free(&w); + + /* UNVERIFIED_DEPENDENCY from the receipt's own content (SPEC 5.1 rule 2) */ + o = opt0(); o.result = "FAIL"; + one_foo(&o, OMEGA_DOMAIN_BUILD, &r, &w); + check("refuse-receipt-result-is-not-pass", refused(&r, "UNVERIFIED_DEPENDENCY", OMEGA_RES_UNVERIFIED_DEPENDENCY)); + run_free(&r); w_free(&w); + o = opt0(); o.assert_fail = 1; + one_foo(&o, OMEGA_DOMAIN_BUILD, &r, &w); + check("refuse-receipt-assertion-failed", refused(&r, "UNVERIFIED_DEPENDENCY", OMEGA_RES_UNVERIFIED_DEPENDENCY)); + run_free(&r); w_free(&w); + o = opt0(); o.tier = "TEST_ONLY_TRUST"; + one_foo(&o, OMEGA_DOMAIN_BUILD, &r, &w); + check("refuse-receipt-test-only-trust", refused_msg(&r, "UNVERIFIED_DEPENDENCY", OMEGA_RES_UNVERIFIED_DEPENDENCY, "satisfies no profile")); + run_free(&r); w_free(&w); + o = opt0(); o.prof = "production-v1"; + one_foo(&o, OMEGA_DOMAIN_BUILD, &r, &w); + check("refuse-receipt-tier-below-profile", refused_msg(&r, "UNVERIFIED_DEPENDENCY", OMEGA_RES_UNVERIFIED_DEPENDENCY, "below the minimum")); + run_free(&r); w_free(&w); + o = opt0(); o.prof = "qemu-v1"; + one_foo(&o, OMEGA_DOMAIN_BUILD, &r, &w); + check("refuse-host-receipt-for-qemu-profile", refused_msg(&r, "UNVERIFIED_DEPENDENCY", OMEGA_RES_UNVERIFIED_DEPENDENCY, "below the minimum")); + run_free(&r); w_free(&w); + o = opt0(); o.prof = "qemu-v1"; o.tier = "QEMU"; + one_foo(&o, OMEGA_DOMAIN_BUILD, &r, &w); + check("accept-qemu-receipt-for-qemu-profile", r.rc == 0 && r.h.closure.n == 1); + run_free(&r); w_free(&w); + o = opt0(); o.prof = "host-v1"; o.tier = "QEMU"; + one_foo(&o, OMEGA_DOMAIN_BUILD, &r, &w); + check("accept-higher-tier-receipt", r.rc == 0); + run_free(&r); w_free(&w); + o = opt0(); o.prof = "host-v1"; o.tier = "MACHINE1_READ_ONLY"; + one_foo(&o, OMEGA_DOMAIN_BUILD, &r, &w); + check("refuse-hardware-receipt-without-lease", refused_msg(&r, "UNVERIFIED_DEPENDENCY", OMEGA_RES_UNVERIFIED_DEPENDENCY, "lease")); + run_free(&r); w_free(&w); + o = opt0(); o.prof = "host-v1"; o.tier = "MACHINE1_READ_ONLY"; o.lease = 1; + one_foo(&o, OMEGA_DOMAIN_BUILD, &r, &w); + check("accept-hardware-receipt-with-lease", r.rc == 0); + run_free(&r); w_free(&w); + + /* blob check (optional source/IR store of stage 6): a blob that does not hash to the digest */ + { + w_init(&w); + o = opt0(); add_comp(&w, 0x51, NULL, 0, &o); + Pin p[1] = { { "foo", 0x51, 0 } }; const char *nm[1] = { "foo" }; + const char *lk = lock_text(&w, p, 1); + char dir[] = "/tmp/omega-resolve-blobs-XXXXXX"; + if (!mkdtemp(dir)) setup_fail("mkdtemp"); + uint8_t src[32]; memset(src, 0x33, 32); src[0] = 0x51; + char hh[65], path[300]; hx(src, hh); + snprintf(path, sizeof path, "%s/%s.blob", dir, hh); + FILE *f = fopen(path, "wb"); fputs("not the source", f); fclose(f); + (void)src_imports(nm, 1); + memset(&r, 0, sizeof r); + r.u = malloc(sizeof *r.u); + OmegaResolveError le; omega_lock_parse(lk, strlen(lk), &r.lock, &le); + r.h.lock = &r.lock; r.h.resolver.store = w.st; r.h.resolver.domain = OMEGA_DOMAIN_BUILD; + r.h.resolver.fetch_receipt = tab_fetch; r.h.resolver.fetch_ctx = &w.rt; + r.h.resolver.fetch_blob = omega_blob_dir_fetch; r.h.resolver.blob_ctx = dir; + r.rc = osc_compile_imports(g_src, strlen(g_src), r.u, &r.dg, NULL, omega_osc_import_hook, &r.h); + check("refuse-blob-does-not-hash-to-digest", refused(&r, "UNVERIFIED_DEPENDENCY", OMEGA_RES_UNVERIFIED_DEPENDENCY)); + run_free(&r); + /* a blob that does hash to the digest passes */ + uint8_t blobdig[32]; const char *content = "the real source"; + sha256_hash((const uint8_t *)content, strlen(content), blobdig); + /* record 0x52 whose source_or_ir_digest is the digest of the blob we write */ + { + uint8_t dbuf[1][64]; Spec sp; spec_for(&sp, 0x52, NULL, 0, dbuf); + memcpy(sp.src, blobdig, 32); + char sid_h[65], src_h[65], root_h[65], inp0[80], inp1[80]; hx(sp.sem, sid_h); hx(sp.src, src_h); hx(sp.root, root_h); + RJ j; rj_default(&j); + snprintf(inp0, sizeof inp0, "sha256:%s", sid_h); snprintf(inp1, sizeof inp1, "sha256:%s", src_h); + j.inputs[0] = inp0; j.inputs[1] = inp1; j.n_in = 2; memcpy(j.root, root_h, 65); + uint8_t rid[32]; char *json; size_t jl; + if (rj_make(&j, rid, &json, &jl)) setup_fail("blob receipt"); + memcpy(sp.rcpt, rid, 32); tab_put(&w.rt, rid, json, jl); free(json); + if (ins_spec(w.st, &sp, 0) != 0) setup_fail("blob record"); + snprintf(path, sizeof path, "%s/%s.blob", dir, src_h); + f = fopen(path, "wb"); fputs(content, f); fclose(f); + } + Pin p2[1] = { { "foo", 0x52, 0 } }; + const char *lk2 = lock_text(&w, p2, 1); + memset(&r, 0, sizeof r); + r.u = malloc(sizeof *r.u); + omega_lock_parse(lk2, strlen(lk2), &r.lock, &le); + r.h.lock = &r.lock; r.h.resolver.store = w.st; r.h.resolver.domain = OMEGA_DOMAIN_BUILD; + r.h.resolver.fetch_receipt = tab_fetch; r.h.resolver.fetch_ctx = &w.rt; + r.h.resolver.fetch_blob = omega_blob_dir_fetch; r.h.resolver.blob_ctx = dir; + r.rc = osc_compile_imports(g_src, strlen(g_src), r.u, &r.dg, NULL, omega_osc_import_hook, &r.h); + check("accept-blob-that-hashes-to-digest", r.rc == 0); + run_free(&r); w_free(&w); + char cmd[400]; snprintf(cmd, sizeof cmd, "rm -rf %s", dir); + if (system(cmd) != 0) setup_fail("cleanup"); + } +} + +/* ---- graphs: closure, cycle, edges, genesis ---- */ +static void t_graphs(void) { + W w; Run r; Opt o = opt0(); + + /* the diamond: root needs b and c, both need d */ + w_init(&w); + { uint8_t d[1][32], rr[2][32]; + add_comp(&w, 0x10, NULL, 0, &o); + mkid(d[0], 0x10); + add_comp(&w, 0x20, d, 1, &o); add_comp(&w, 0x30, d, 1, &o); + mkid(rr[0], 0x20); mkid(rr[1], 0x30); + add_comp(&w, 0x40, rr, 2, &o); } + Pin pr[1] = { { "root", 0x40, 0 } }; const char *nr[1] = { "root" }; + run_compile(&w, src_imports(nr, 1), OMEGA_DOMAIN_BUILD, lock_text(&w, pr, 1), &r); + int ok = r.rc == 0 && r.h.closure.n == 4; + OmegaClosureEntry want[4]; + static const uint8_t ids[4] = { 0x10, 0x20, 0x30, 0x40 }; + for (int i = 0; i < 4 && ok; i++) { + mkid(want[i].semantic_id, ids[i]); + omega_vcstore_receipt_of(w.st, want[i].semantic_id, want[i].receipt_id); + want[i].admission_kind = 1; + if (memcmp(r.h.closure.entries[i].semantic_id, want[i].semantic_id, 32) || memcmp(r.h.closure.entries[i].receipt_id, want[i].receipt_id, 32) || + r.h.closure.entries[i].admission_kind != 1) ok = 0; + } + uint8_t rd[32]; + if (ok) ref_closure_digest(want, 4, rd); + check("closure-diamond-has-each-node-once-in-id-order", ok); + check("closure-digest-matches-reference", ok && memcmp(rd, r.h.closure.digest, 32) == 0); + { + OmegaClosureEntry tweak[4]; memcpy(tweak, want, sizeof tweak); + tweak[2].receipt_id[0] ^= 1; + uint8_t td[32]; ref_closure_digest(tweak, 4, td); + tweak[2].receipt_id[0] ^= 1; tweak[2].admission_kind = 2; + uint8_t td2[32]; ref_closure_digest(tweak, 4, td2); + check("closure-digest-binds-receipt-ids-and-kinds", ok && memcmp(td, rd, 32) != 0 && memcmp(td2, rd, 32) != 0); + } + run_free(&r); + + /* resolution order differs from id order: names alpha -> 0x90, zeta -> 0x10 */ + w_free(&w); w_init(&w); + add_comp(&w, 0x90, NULL, 0, &o); add_comp(&w, 0x10, NULL, 0, &o); + { Pin p[2] = { { "alpha", 0x90, 0 }, { "zeta", 0x10, 0 } }; const char *nm[2] = { "alpha", "zeta" }; + run_compile(&w, src_imports(nm, 2), OMEGA_DOMAIN_BUILD, lock_text(&w, p, 2), &r); } + int sorted = r.rc == 0 && r.h.closure.n == 2 && memcmp(r.h.closure.entries[0].semantic_id, r.h.closure.entries[1].semantic_id, 32) < 0 && + r.h.closure.entries[0].semantic_id[0] == 0x10; + check("closure-sorted-ascending-by-semantic-id", sorted); + run_free(&r); w_free(&w); + + /* DEPENDENCY_CYCLE: only a tampered store can hold one (insert refuses it), shown with genesis records */ + w_init(&w); w.allow_genesis = 1; + { Opt b = opt0(); b.boot = 1; uint8_t d[1][32]; + add_comp(&w, 0x71, NULL, 0, &b); + mkid(d[0], 0x71); add_comp(&w, 0x72, d, 1, &b); + uint8_t db[1][64]; uint8_t dep72[1][32]; mkid(dep72[0], 0x72); + Spec sp; spec_for(&sp, 0x71, dep72, 1, db); + memset(sp.rcpt, 0xA0, 32); sp.rcpt[0] = 0x71; + replace_obj(&w, 0x71, &sp); } + { Pin p[1] = { { "cyc", 0x71, 0 } }; const char *nm[1] = { "cyc" }; + run_compile(&w, src_imports(nm, 1), OMEGA_DOMAIN_BUILD, lock_text(&w, p, 1), &r); } + check("refuse-dependency-cycle", refused(&r, "DEPENDENCY_CYCLE", OMEGA_RES_DEPENDENCY_CYCLE)); + run_free(&r); w_free(&w); + + /* an edge whose required contract differs from the dependency's contract */ + w_init(&w); + add_comp(&w, 0x81, NULL, 0, &o); + { uint8_t d[1][32]; mkid(d[0], 0x81); add_comp(&w, 0x82, d, 1, &o); + uint8_t db[1][64]; Spec sp; spec_for(&sp, 0x82, d, 1, db); + db[0][32] ^= 0x01; /* required_contract now wrong */ + omega_vcstore_receipt_of(w.st, sp.sem, sp.rcpt); + replace_obj(&w, 0x82, &sp); } + { Pin p[1] = { { "top", 0x82, 0 } }; const char *nm[1] = { "top" }; + run_compile(&w, src_imports(nm, 1), OMEGA_DOMAIN_BUILD, lock_text(&w, p, 1), &r); } + check("refuse-edge-contract-mismatch", refused(&r, "UNVERIFIED_DEPENDENCY", OMEGA_RES_UNVERIFIED_DEPENDENCY) && strstr(r.h.err.message, "contract") != NULL); + run_free(&r); w_free(&w); + + /* genesis (BOOTSTRAP) records */ + { Opt b = opt0(); b.boot = 1; + w_init(&w); + add_comp(&w, 0x91, NULL, 0, &b); + Pin p[1] = { { "base", 0x91, 0 } }; const char *nm[1] = { "base" }; + const char *lk = lock_text(&w, p, 1); + run_compile(&w, src_imports(nm, 1), OMEGA_DOMAIN_BUILD, lk, &r); + check("refuse-genesis-record-without-permission", refused_msg(&r, "UNVERIFIED_DEPENDENCY", OMEGA_RES_UNVERIFIED_DEPENDENCY, "genesis")); + run_free(&r); + w.allow_genesis = 1; + run_compile(&w, src_imports(nm, 1), OMEGA_DOMAIN_BUILD, lk, &r); + check("accept-genesis-record-with-permission", r.rc == 0 && r.h.closure.n == 1 && r.h.closure.entries[0].admission_kind == 2); + run_free(&r); + /* a verified record on top of a genesis record needs the permission too */ + uint8_t d[1][32]; mkid(d[0], 0x91); + add_comp(&w, 0x92, d, 1, &o); + Pin p2[1] = { { "top", 0x92, 0 } }; const char *nm2[1] = { "top" }; + const char *lk2 = lock_text(&w, p2, 1); + run_compile(&w, src_imports(nm2, 1), OMEGA_DOMAIN_BUILD, lk2, &r); + check("accept-verified-on-genesis-with-permission", r.rc == 0 && r.h.closure.n == 2); + run_free(&r); + w.allow_genesis = 0; + run_compile(&w, src_imports(nm2, 1), OMEGA_DOMAIN_BUILD, lk2, &r); + check("refuse-verified-on-genesis-without-permission", refused(&r, "UNVERIFIED_DEPENDENCY", OMEGA_RES_UNVERIFIED_DEPENDENCY)); + run_free(&r); + /* a genesis record may NOT depend on a verified record */ + w.allow_genesis = 1; + mkid(d[0], 0x92); + add_comp(&w, 0x93, d, 1, &b); + Pin p3[1] = { { "bad", 0x93, 0 } }; const char *nm3[1] = { "bad" }; + run_compile(&w, src_imports(nm3, 1), OMEGA_DOMAIN_BUILD, lock_text(&w, p3, 1), &r); + check("refuse-genesis-record-depending-on-verified", refused_msg(&r, "UNVERIFIED_DEPENDENCY", OMEGA_RES_UNVERIFIED_DEPENDENCY, "closed over itself")); + run_free(&r); w_free(&w); + } +} + +/* ---- admission into the store ---- */ +static int take(W *w, uint8_t b0, uint8_t **bytes, size_t *len, uint8_t id[32]) { + uint8_t sid[32]; mkid(sid, b0); + for (size_t i = 0; i < w->st->count; i++) + if (memcmp(w->st->objs[i].semantic_id, sid, 32) == 0) { + *bytes = malloc(w->st->objs[i].len); if (!*bytes) return -1; + memcpy(*bytes, w->st->objs[i].bytes, w->st->objs[i].len); + *len = w->st->objs[i].len; + memcpy(id, w->st->objs[i].vc_id, 32); + return 0; + } + return -1; +} +static OmegaResolver resolver_of(W *dst, RTab *rt) { + OmegaResolver r; memset(&r, 0, sizeof r); + r.store = dst->st; r.domain = OMEGA_DOMAIN_BUILD; r.fetch_receipt = tab_fetch; r.fetch_ctx = rt; + return r; +} +static void t_admit(void) { + OmegaResolveError e; + /* source world: builds the records and receipts, a second empty store is the target */ + { + W src, dst; Opt o = opt0(); + w_init(&src); w_init(&dst); + add_comp(&src, 0x51, NULL, 0, &o); + uint8_t *b; size_t n; uint8_t id[32]; + if (take(&src, 0x51, &b, &n, id)) setup_fail("take"); + OmegaResolver r = resolver_of(&dst, &src.rt); + int rc = omega_resolve_admit(&r, dst.st, b, n, id, NULL, &e); + uint8_t kind = 0; uint8_t sid[32]; mkid(sid, 0x51); + check("admit-verified-record-with-receipt", rc == 0 && omega_vcstore_count(dst.st) == 1 && + omega_vcstore_admission_kind(dst.st, sid, &kind) == 0 && kind == OMEGA_VCS_ADMISSION_VERIFIED); + /* wrong claimed id */ + uint8_t bad[32]; memcpy(bad, id, 32); bad[0] ^= 1; + W dst2; w_init(&dst2); OmegaResolver r2 = resolver_of(&dst2, &src.rt); + rc = omega_resolve_admit(&r2, dst2.st, b, n, bad, NULL, &e); + check("admit-refuses-wrong-claimed-id", rc != 0 && omega_vcstore_count(dst2.st) == 0); + /* dev-domain origin */ + OmegaArtifactMeta m; uint8_t ir[32], cl[32]; memset(ir, 1, 32); memset(cl, 2, 32); + omega_artifact_meta_make(&m, OMEGA_DOMAIN_DEV, ir, cl); + rc = omega_resolve_admit(&r2, dst2.st, b, n, id, &m, &e); + check("admit-refuses-record-from-tainted-origin", rc == OMEGA_RES_TAINTED_ARTIFACT && omega_vcstore_count(dst2.st) == 0); + omega_artifact_meta_make(&m, OMEGA_DOMAIN_BUILD, ir, cl); + rc = omega_resolve_admit(&r2, dst2.st, b, n, id, &m, &e); + check("admit-accepts-record-from-build-origin", rc == 0 && omega_vcstore_count(dst2.st) == 1); + free(b); w_free(&dst2); w_free(&dst); w_free(&src); + } + { /* a record carrying the dev taint capability never enters */ + W src, dst; Opt o = opt0(); o.taint = 1; + w_init(&src); w_init(&dst); + add_comp(&src, 0x52, NULL, 0, &o); + uint8_t *b; size_t n; uint8_t id[32]; + if (take(&src, 0x52, &b, &n, id)) setup_fail("take"); + OmegaResolver r = resolver_of(&dst, &src.rt); + int rc = omega_resolve_admit(&r, dst.st, b, n, id, NULL, &e); + check("admit-refuses-taint-capability", rc == OMEGA_RES_TAINTED_ARTIFACT && omega_vcstore_count(dst.st) == 0); + rc = omega_resolve_admit_genesis(dst.st, b, n, id, NULL, &e); + check("admit-genesis-refuses-taint-capability", rc == OMEGA_RES_TAINTED_ARTIFACT && omega_vcstore_count(dst.st) == 0); + free(b); w_free(&dst); w_free(&src); + } + { /* admission demands the receipt to qualify the record */ + static const char *const why[3] = { "no receipt", "receipt does not match the record", "receipt records FAIL" }; + for (int k = 0; k < 3; k++) { + W src, dst; Opt o = opt0(); + if (k == 0) o.no_store = 1; + if (k == 1) o.wrong_root = 1; + if (k == 2) o.result = "FAIL"; + w_init(&src); w_init(&dst); + add_comp(&src, 0x53, NULL, 0, &o); + uint8_t *b; size_t n; uint8_t id[32]; + if (take(&src, 0x53, &b, &n, id)) setup_fail("take"); + OmegaResolver r = resolver_of(&dst, &src.rt); + int rc = omega_resolve_admit(&r, dst.st, b, n, id, NULL, &e); + char nm[80]; snprintf(nm, sizeof nm, "admit-refuses-%s", k == 0 ? "missing-receipt" : k == 1 ? "mismatched-receipt" : "failing-receipt"); + (void)why; + check(nm, rc != 0 && omega_vcstore_count(dst.st) == 0); + free(b); w_free(&dst); w_free(&src); + } + } + { /* genesis loading: no receipt, but it may depend only on genesis records */ + W src, dst; Opt b = opt0(); b.boot = 1; Opt v = opt0(); + w_init(&src); w_init(&dst); + add_comp(&src, 0x61, NULL, 0, &b); + uint8_t *g; size_t gn; uint8_t gid[32]; + if (take(&src, 0x61, &g, &gn, gid)) setup_fail("take"); + int rc = omega_resolve_admit_genesis(dst.st, g, gn, gid, NULL, &e); + uint8_t kind = 0; uint8_t sid[32]; mkid(sid, 0x61); + check("admit-genesis-records-bootstrap-kind", rc == 0 && omega_vcstore_admission_kind(dst.st, sid, &kind) == 0 && kind == OMEGA_VCS_ADMISSION_BOOTSTRAP); + /* depends on a genesis record already loaded: fine */ + uint8_t d[1][32]; mkid(d[0], 0x61); + add_comp(&src, 0x62, d, 1, &b); + uint8_t *g2; size_t g2n; uint8_t g2id[32]; + if (take(&src, 0x62, &g2, &g2n, g2id)) setup_fail("take"); + rc = omega_resolve_admit_genesis(dst.st, g2, g2n, g2id, NULL, &e); + check("admit-genesis-may-depend-on-genesis", rc == 0 && omega_vcstore_count(dst.st) == 2); + /* depends on a verified record: refused */ + add_comp(&dst, 0x63, NULL, 0, &v); /* verified record in the target store */ + add_comp(&src, 0x63, NULL, 0, &v); + mkid(d[0], 0x63); + add_comp(&src, 0x64, d, 1, &b); + uint8_t *g3; size_t g3n; uint8_t g3id[32]; + if (take(&src, 0x64, &g3, &g3n, g3id)) setup_fail("take"); + size_t before = omega_vcstore_count(dst.st); + rc = omega_resolve_admit_genesis(dst.st, g3, g3n, g3id, NULL, &e); + check("admit-genesis-refuses-verified-dependency", rc == OMEGA_RES_UNVERIFIED_DEPENDENCY && omega_vcstore_count(dst.st) == before); + OmegaArtifactMeta m; uint8_t ir[32], cl[32]; memset(ir, 1, 32); memset(cl, 2, 32); + omega_artifact_meta_make(&m, OMEGA_DOMAIN_DEV, ir, cl); + rc = omega_resolve_admit_genesis(dst.st, g, gn, gid, &m, &e); + check("admit-genesis-refuses-tainted-origin", rc == OMEGA_RES_TAINTED_ARTIFACT); + free(g); free(g2); free(g3); w_free(&dst); w_free(&src); + } +} + +/* ---- build identity, domains, artifact header ---- */ +static void t_identity(void) { + uint8_t ir[32], cl[32], got[32], ref[32]; + memset(ir, 0x11, 32); memset(cl, 0x22, 32); + int ok = 1; + for (int dom = 1; dom <= 2; dom++) { + omega_build_id(ir, (OmegaDomain)dom, cl, got); + ref_build_id(ir, dom, cl, ref); + if (memcmp(got, ref, 32) != 0) ok = 0; + } + check("build-id-matches-reference", ok); + uint8_t b1[32], b2[32], b3[32], b4[32]; + omega_build_id(ir, OMEGA_DOMAIN_BUILD, cl, b1); + memset(cl, 0x23, 32); omega_build_id(ir, OMEGA_DOMAIN_BUILD, cl, b2); + memset(cl, 0x22, 32); omega_build_id(ir, OMEGA_DOMAIN_DEV, cl, b3); + memset(ir, 0x12, 32); omega_build_id(ir, OMEGA_DOMAIN_BUILD, cl, b4); + check("build-id-changes-with-closure-domain-and-ir", memcmp(b1, b2, 32) && memcmp(b1, b3, 32) && memcmp(b1, b4, 32) && memcmp(b2, b3, 32)); + + memset(ir, 0x11, 32); + OmegaArtifactMeta m, p; OmegaResolveError e; char text[600]; + omega_artifact_meta_make(&m, OMEGA_DOMAIN_DEV, ir, cl); + OmegaArtifactMeta mb; omega_artifact_meta_make(&mb, OMEGA_DOMAIN_BUILD, ir, cl); + check("artifact-dev-is-tainted-build-is-not", m.tainted == 1 && mb.tainted == 0 && m.domain == OMEGA_DOMAIN_DEV); + int tl = omega_artifact_meta_text(&m, text, sizeof text); + check("artifact-header-round-trips", tl > 0 && omega_artifact_meta_parse(text, (size_t)tl, &p, &e) == 0 && + p.domain == OMEGA_DOMAIN_DEV && p.tainted == 1 && memcmp(p.build_id, m.build_id, 32) == 0 && strstr(text, "tainted 1\n") != NULL); + char t2[800]; memcpy(t2, text, (size_t)tl + 1); + char *at = strstr(t2, "tainted 1"); + if (at) at[8] = '0'; + check("artifact-refuses-dev-header-marked-untainted", at && omega_artifact_meta_parse(t2, (size_t)tl, &p, &e) == OMEGA_RES_TAINTED_ARTIFACT); + memcpy(t2, text, (size_t)tl + 1); + at = strstr(t2, "domain dev"); + if (at) memcpy(at, "domain bui", 10), memmove(at + 10, at + 10, 0); + /* a header edited to the other domain: the mark and the build id no longer fit */ + check("artifact-refuses-edited-domain", at && omega_artifact_meta_parse(t2, (size_t)tl, &p, &e) != 0); + memcpy(t2, text, (size_t)tl + 1); + t2[tl - 2] = t2[tl - 2] == '0' ? '1' : '0'; + check("artifact-refuses-edited-build-id", omega_artifact_meta_parse(t2, (size_t)tl, &p, &e) == OMEGA_RES_TAINTED_ARTIFACT); + snprintf(t2, sizeof t2, "%sextra line\n", text); + check("artifact-refuses-extra-line", omega_artifact_meta_parse(t2, strlen(t2), &p, &e) != 0); + check("artifact-refuses-truncated-header", omega_artifact_meta_parse(text, (size_t)tl - 3, &p, &e) != 0); + + /* through real compiles: same IR, different closure or domain, different build id */ + W w1, w2; Run r1, r2, r3; Opt o = opt0(); + one_foo(&o, OMEGA_DOMAIN_BUILD, &r1, &w1); + w_init(&w2); + add_comp(&w2, 0x52, NULL, 0, &o); /* a different record behind the same name */ + { Pin pn[1] = { { "foo", 0x52, 0 } }; const char *nm[1] = { "foo" }; + run_compile(&w2, src_imports(nm, 1), OMEGA_DOMAIN_BUILD, lock_text(&w2, pn, 1), &r2); } + { Pin pn[1] = { { "foo", 0x51, 0 } }; const char *nm[1] = { "foo" }; + W w3; w_init(&w3); add_comp(&w3, 0x51, NULL, 0, &o); + run_compile(&w3, src_imports(nm, 1), OMEGA_DOMAIN_DEV, lock_text(&w3, pn, 1), &r3); + uint8_t i1[32], i2[32], i3[32], bb1[32], bb2[32], bb3[32]; + int g = r1.rc == 0 && r2.rc == 0 && r3.rc == 0 && ir_of(&r1, i1) == 0 && ir_of(&r2, i2) == 0 && ir_of(&r3, i3) == 0; + if (g) { + omega_build_id(i1, OMEGA_DOMAIN_BUILD, r1.h.closure.digest, bb1); + omega_build_id(i2, OMEGA_DOMAIN_BUILD, r2.h.closure.digest, bb2); + omega_build_id(i3, OMEGA_DOMAIN_DEV, r3.h.closure.digest, bb3); + } + check("identity-same-ir-different-closure-differs", g && memcmp(i1, i2, 32) == 0 && memcmp(r1.h.closure.digest, r2.h.closure.digest, 32) != 0 && memcmp(bb1, bb2, 32) != 0); + check("identity-same-ir-same-closure-dev-vs-build-differs", g && memcmp(i1, i3, 32) == 0 && memcmp(r1.h.closure.digest, r3.h.closure.digest, 32) == 0 && memcmp(bb1, bb3, 32) != 0); + check("dev-domain-resolves-and-marks-tainted", g && r3.h.resolved); + run_free(&r3); w_free(&w3); + } + run_free(&r1); run_free(&r2); w_free(&w1); w_free(&w2); +} + +/* ---- no escape hatch ---- */ +static const char *const FORBIDDEN[] = { "unsafe import", "unsafe_import", "skip-verify", "skip_verify", "SKIP_VERIFY", "no-verify", "no_verify", + "--insecure", "getenv", "secure_getenv", "putenv" }; +#define N_FORBIDDEN (sizeof FORBIDDEN / sizeof FORBIDDEN[0]) +static int scan_buf(const char *buf, size_t n, const char **hit) { + for (size_t i = 0; i < N_FORBIDDEN; i++) { + size_t k = strlen(FORBIDDEN[i]); + for (size_t a = 0; a + k <= n; a++) + if (memcmp(buf + a, FORBIDDEN[i], k) == 0) { *hit = FORBIDDEN[i]; return 1; } + } + return 0; +} +static int scan_file(const char *path, const char **hit) { + size_t n; uint8_t *b = slurp_file(path, &n); + if (!b) setup_fail("cannot read a scanned source file"); + int r = scan_buf((const char *)b, n, hit); + free(b); + return r; +} +static void t_no_escape(void) { + static const char *const files[] = { "src/omega_resolve.c", "src/omega_resolve.h", "src/omega_receipt.c", "src/omega_receipt.h", + "src/omega_blake3.c", "src/omega_blake3.h", "src/omega_resolve_osc.c", "src/omega_resolve_osc.h", "src/oscv_main.c" }; + const char *hit = NULL; + int found = 0, nfiles = 0; + for (size_t i = 0; i < sizeof files / sizeof files[0]; i++) { nfiles++; if (scan_file(files[i], &hit)) { found = 1; printf("note: %s contains \"%s\"\n", files[i], hit); } } + DIR *d = opendir("src/compiler"); + if (!d) setup_fail("src/compiler"); + struct dirent *de; + while ((de = readdir(d))) { + size_t l = strlen(de->d_name); + if (l < 3 || (strcmp(de->d_name + l - 2, ".c") && strcmp(de->d_name + l - 2, ".h"))) continue; + char path[300]; snprintf(path, sizeof path, "src/compiler/%s", de->d_name); + nfiles++; + if (scan_file(path, &hit)) { found = 1; printf("note: %s contains \"%s\"\n", path, hit); } + } + closedir(d); + check("no-escape-hatch-in-compiler-and-resolver-sources", !found && nfiles > 20); + const char *h2; + int control = 1; + for (size_t i = 0; i < N_FORBIDDEN; i++) { + char probe[128]; snprintf(probe, sizeof probe, "int x; /* %s */", FORBIDDEN[i]); + if (!scan_buf(probe, strlen(probe), &h2)) control = 0; + } + check("no-escape-scanner-detects-every-forbidden-word", control && !scan_buf("clean text", 10, &h2)); +} + +/* ---- the real driver, end to end ---- */ +static int sh(const char *cmd, char *out, size_t cap) { + FILE *p = popen(cmd, "r"); + if (!p) return -1; + size_t n = fread(out, 1, cap - 1, p); + out[n] = 0; + int st = pclose(p); + return st == -1 ? -1 : (st >> 8) & 0xff; +} +static int wfile(const char *path, const void *d, size_t n) { + FILE *f = fopen(path, "wb"); + if (!f) return -1; + int rc = fwrite(d, 1, n, f) == n ? 0 : -1; + return fclose(f) == 0 && rc == 0 ? 0 : -1; +} +static int kv(const char *out, const char *key, char *val, size_t cap) { + size_t k = strlen(key); + const char *p = out; + while (p && *p) { + if (strncmp(p, key, k) == 0 && p[k] == '=') { + const char *e = strchr(p + k + 1, '\n'); + size_t l = e ? (size_t)(e - (p + k + 1)) : strlen(p + k + 1); + if (l >= cap) l = cap - 1; + memcpy(val, p + k + 1, l); val[l] = 0; + return 0; + } + p = strchr(p, '\n'); if (p) p++; + } + return -1; +} +static void write_receipts(const W *w, const char *dir) { + char path[700], h[65]; + for (size_t i = 0; i < w->rt.n; i++) { + hx(w->rt.v[i].id, h); + snprintf(path, sizeof path, "%.200s/%s.json", dir, h); + if (wfile(path, w->rt.v[i].p, w->rt.v[i].n)) setup_fail("write receipt"); + } +} +static void t_cli(void) { + if (access(OSCV_PATH, X_OK) != 0) setup_fail("build/compiler/oscv is missing (make test-resolve builds it)"); + char dir[] = "/tmp/omega-resolve-cli-XXXXXX"; + if (!mkdtemp(dir)) setup_fail("mkdtemp"); + char path[700], rdir[700], cmd[2400], out[4096], v[200]; + snprintf(rdir, sizeof rdir, "%s/receipts", dir); + if (mkdir(rdir, 0700)) setup_fail("mkdir"); + W w; w_init(&w); Opt o = opt0(); + add_comp(&w, 0x51, NULL, 0, &o); + Opt t = opt0(); t.taint = 1; add_comp(&w, 0x52, NULL, 0, &t); + write_receipts(&w, rdir); + snprintf(path, sizeof path, "%s/omega.vcstore", dir); + if (omega_vcstore_save(w.st, path)) setup_fail("save store"); + Pin pin[1] = { { "foo", 0x51, 0 } }; + const char *lk = lock_text(&w, pin, 1); + snprintf(path, sizeof path, "%s/omega.lock", dir); + wfile(path, lk, strlen(lk)); + char src[400]; snprintf(src, sizeof src, "import foo;\n%s", FN); + snprintf(path, sizeof path, "%s/a.osc", dir); + wfile(path, src, strlen(src)); + snprintf(path, sizeof path, "%s/plain.osc", dir); + wfile(path, FN, strlen(FN)); + + /* expected identities, derived in this process */ + uint8_t ir[32], cd[32], bid[32], biddev[32]; char irh[65], cdh[65], bidh[65], biddevh[65]; + Run r; { const char *nm[1] = { "foo" }; run_compile(&w, src_imports(nm, 1), OMEGA_DOMAIN_BUILD, lk, &r); } + if (r.rc != 0 || ir_of(&r, ir)) setup_fail("cli expectation compile"); + memcpy(cd, r.h.closure.digest, 32); + omega_build_id(ir, OMEGA_DOMAIN_BUILD, cd, bid); omega_build_id(ir, OMEGA_DOMAIN_DEV, cd, biddev); + hx(ir, irh); hx(cd, cdh); hx(bid, bidh); hx(biddev, biddevh); + run_free(&r); + + snprintf(cmd, sizeof cmd, "%s %s/a.osc 2>&1", OSCV_PATH, dir); + int rc = sh(cmd, out, sizeof out); + int ok = rc == 0; + ok = ok && kv(out, "ir_sha256", v, sizeof v) == 0 && strcmp(v, irh) == 0; + ok = ok && kv(out, "closure_sha256", v, sizeof v) == 0 && strcmp(v, cdh) == 0; + ok = ok && kv(out, "build_id", v, sizeof v) == 0 && strcmp(v, bidh) == 0; + check("cli-build-resolves-with-expected-identity", ok); + snprintf(cmd, sizeof cmd, "%s --domain dev %s/a.osc 2>&1", OSCV_PATH, dir); + rc = sh(cmd, out, sizeof out); + ok = rc == 0 && kv(out, "build_id", v, sizeof v) == 0 && strcmp(v, biddevh) == 0 && strcmp(v, bidh) != 0 && + kv(out, "tainted", v, sizeof v) == 0 && strcmp(v, "1") == 0; + check("cli-dev-domain-is-tainted-with-its-own-build-id", ok); + snprintf(cmd, sizeof cmd, "%s %s/a.osc 2>&1", OSCV_PATH, dir); + sh(cmd, out, sizeof out); + kv(out, "tainted", v, sizeof v); + check("cli-build-domain-is-not-tainted", strcmp(v, "0") == 0); + /* meta header file */ + snprintf(cmd, sizeof cmd, "%s --domain dev --meta-out %s/meta.txt %s/a.osc 2>&1", OSCV_PATH, dir, dir); + rc = sh(cmd, out, sizeof out); + snprintf(path, sizeof path, "%s/meta.txt", dir); + size_t mn; uint8_t *mb = slurp_file(path, &mn); + OmegaArtifactMeta pm; OmegaResolveError e; + check("cli-meta-header-is-parsable-and-tainted", rc == 0 && mb && omega_artifact_meta_parse((const char *)mb, mn, &pm, &e) == 0 && pm.tainted == 1 && memcmp(pm.build_id, biddev, 32) == 0); + free(mb); + /* no-import unit: identical to the plain compiler's identity */ + snprintf(cmd, sizeof cmd, "%s --lock %s/missing.lock %s/plain.osc 2>&1", OSCV_PATH, dir, dir); + rc = sh(cmd, out, sizeof out); + OscUnit *u = malloc(sizeof *u); OscDiag dg; uint8_t pir[32]; char pirh[65]; + int pc = osc_compile(FN, strlen(FN), u, &dg, NULL) == 0 && osc_ir_digest(u, pir) == 0; + hx(pir, pirh); + free(u); + check("cli-plain-unit-has-the-plain-compilers-ir-digest", rc == 0 && pc && kv(out, "ir_sha256", v, sizeof v) == 0 && strcmp(v, pirh) == 0); + /* refusals */ + snprintf(path, sizeof path, "%s/none.lock", dir); + snprintf(cmd, sizeof cmd, "%s --lock %s/missing.lock %s/a.osc 2>&1", OSCV_PATH, dir, dir); + rc = sh(cmd, out, sizeof out); + check("cli-refuses-import-without-lock", rc == 1 && strstr(out, "resolve_code=DEPENDENCY_NOT_PINNED") != NULL && strstr(out, "ir_sha256") == NULL); + snprintf(path, sizeof path, "%s/tainted.osc", dir); + snprintf(src, sizeof src, "import foo;\n%s", FN); wfile(path, src, strlen(src)); + { Pin pt[1] = { { "foo", 0x52, 0 } }; const char *lt = lock_text(&w, pt, 1); + snprintf(path, sizeof path, "%s/t.lock", dir); wfile(path, lt, strlen(lt)); } + snprintf(cmd, sizeof cmd, "%s --lock %s/t.lock %s/a.osc 2>&1", OSCV_PATH, dir, dir); + rc = sh(cmd, out, sizeof out); + check("cli-refuses-tainted-record", rc == 1 && strstr(out, "resolve_code=TAINTED_ARTIFACT") != NULL); + snprintf(cmd, sizeof cmd, "%s --lock %s/t.lock --domain dev %s/a.osc 2>&1", OSCV_PATH, dir, dir); + rc = sh(cmd, out, sizeof out); + check("cli-refuses-tainted-record-in-dev-domain-too", rc == 1 && strstr(out, "resolve_code=TAINTED_ARTIFACT") != NULL); + snprintf(path, sizeof path, "%s/u.osc", dir); + wfile(path, FN, strlen(FN)); + snprintf(cmd, sizeof cmd, "%s %s/u.osc 2>&1", OSCV_PATH, dir); + rc = sh(cmd, out, sizeof out); + check("cli-refuses-lock-line-with-no-import", rc == 1 && strstr(out, "resolve_code=UNDECLARED_IMPORT") != NULL); + /* a bad receipt file */ + snprintf(path, sizeof path, "%s/rcpt2", dir); + if (mkdir(path, 0700)) setup_fail("mkdir"); + snprintf(cmd, sizeof cmd, "%s --receipts %s/rcpt2 %s/a.osc 2>&1", OSCV_PATH, dir, dir); + rc = sh(cmd, out, sizeof out); + check("cli-refuses-missing-receipt", rc == 1 && strstr(out, "resolve_code=MISSING_RECEIPT") != NULL); + /* a store file that does not load is refused, never treated as empty */ + snprintf(path, sizeof path, "%s/omega.vcstore", dir); + { size_t sn; uint8_t *sb = slurp_file(path, &sn); sb[sn / 2] ^= 1; snprintf(path, sizeof path, "%s/broken.vcstore", dir); wfile(path, sb, sn); free(sb); } + snprintf(cmd, sizeof cmd, "%s --store %s/broken.vcstore %s/a.osc 2>&1", OSCV_PATH, dir, dir); + rc = sh(cmd, out, sizeof out); + check("cli-refuses-a-damaged-store-file", rc == 1 && strstr(out, "resolve_code=UNVERIFIED_DEPENDENCY") != NULL); + /* no switch, no environment variable relaxes anything */ + snprintf(cmd, sizeof cmd, "%s --skip-verify %s/a.osc 2>&1", OSCV_PATH, dir); + rc = sh(cmd, out, sizeof out); + check("cli-has-no-skip-switch", rc == 2); + snprintf(cmd, sizeof cmd, "%s --insecure %s/a.osc 2>&1", OSCV_PATH, dir); + rc = sh(cmd, out, sizeof out); + check("cli-has-no-insecure-switch", rc == 2); + snprintf(cmd, sizeof cmd, "OMEGA_SKIP_VERIFY=1 SKIP_VERIFY=1 OMEGA_UNSAFE=1 %s --lock %s/missing.lock %s/a.osc 2>&1", OSCV_PATH, dir, dir); + rc = sh(cmd, out, sizeof out); + check("cli-ignores-environment-variables", rc == 1 && strstr(out, "resolve_code=DEPENDENCY_NOT_PINNED") != NULL); + snprintf(cmd, sizeof cmd, "%s --domain prod %s/a.osc 2>&1", OSCV_PATH, dir); + rc = sh(cmd, out, sizeof out); + check("cli-refuses-unknown-domain", rc == 2); + /* plain oscc-style refusal of an import, no resolver in the loop is covered in t_frontend */ + snprintf(cmd, sizeof cmd, "rm -rf %s", dir); + if (system(cmd) != 0) setup_fail("cleanup"); + w_free(&w); +} + +/* ======================================================================== main */ +static const struct { const char *mutant, *check; } MUTANTS[] = { + { "b3-merge", "b3-official-vectors" }, + { "b3-root", "b3-official-vectors" }, + { "profile-known", "profile-unknown-refused" }, + { "profile-version", "profile-version-too-old-refused" }, + { "lock-bytes-tab", "lock-refuses-tab-in-comment" }, + { "lock-bytes-cr", "lock-refuses-cr-in-comment" }, + { "lock-bytes-nul", "lock-refuses-nul-in-comment" }, + { "lock-header", "lock-refuses-wrong-header" }, + { "lock-unknown-line", "lock-refuses-bad-name-start" }, + { "lock-hex", "lock-refuses-uppercase-hex" }, + { "lock-order-duplicate", "lock-refuses-duplicate-name" }, + { "lock-order-sorted", "lock-refuses-unsorted" }, + { "missing-receipt", "refuse-missing-receipt" }, + { "rule1-name", "refuse-receipt-file-holds-another-receipt" }, + { "rule4-semantic", "refuse-receipt-does-not-name-program" }, + { "rule4-source", "refuse-stale-receipt" }, + { "rule3", "refuse-receipt-output-digest-is-not-evidence-root" }, + { "rule5", "refuse-receipt-kind-is-not-profile" }, + { "rule6", "refuse-receipt-has-extra-dependency" }, + { "rule2-pass", "refuse-receipt-result-is-not-pass" }, + { "rule2-assert", "refuse-receipt-assertion-failed" }, + { "rule2-testonly", "refuse-receipt-test-only-trust" }, + { "rule2-tier", "refuse-receipt-tier-below-profile" }, + { "closure-receipt", "closure-digest-matches-reference" }, + { "cycle", "refuse-dependency-cycle" }, + { "lock-receipt", "refuse-lock-pins-another-receipt" }, + { "lock-receipt-visited", "refuse-lock-pins-another-receipt-for-visited-node" }, + { "genesis-gate", "refuse-genesis-record-without-permission" }, + { "taint-cap", "refuse-tainted-record-in-build-domain" }, + { "verified-needs-receipt", "refuse-missing-receipt" }, + { "edge-contract", "refuse-edge-contract-mismatch" }, + { "boot-dep-verified", "refuse-genesis-record-depending-on-verified" }, + { "not-pinned", "refuse-not-pinned-without-lock" }, + { "undeclared", "refuse-undeclared-lock-line-without-import" }, + { "closure-sort", "closure-sorted-ascending-by-semantic-id" }, + { "build-domain", "build-id-matches-reference" }, + { "build-closure", "build-id-matches-reference" }, + { "taint-mark", "artifact-dev-is-tainted-build-is-not" }, + { "meta-taint-consistent", "artifact-refuses-dev-header-marked-untainted" }, + { "meta-build-id", "artifact-refuses-edited-build-id" }, + { "admit-origin", "admit-refuses-record-from-tainted-origin" }, + { "admit-cap", "admit-refuses-taint-capability" }, + { "admit-receipt", "admit-refuses-mismatched-receipt" }, + { "genesis-dep", "admit-genesis-refuses-verified-dependency" }, + { "blob-digest", "refuse-blob-does-not-hash-to-digest" }, + { "json-dup-key", "receipt-refuses-duplicate-key" }, + { "deny-unknown", "receipt-refuses-unknown-field" }, + { "schema", "receipt-refuses-unknown-schema" }, + { "version", "receipt-refuses-unknown-version" }, + { "feature", "receipt-refuses-unknown-feature" }, + { "reserved", "receipt-refuses-reserved-field" }, + { "env-class", "receipt-refuses-env-class-mismatch" }, + { "mutation-order", "receipt-refuses-observed-over-declared" }, + { "canon-sort", "receipt-canon-order-independent" }, + { "id-compare", "receipt-refuses-wrong-id" }, +}; +#define N_MUT (sizeof MUTANTS / sizeof MUTANTS[0]) + +int main(int argc, char **argv) { + if (argc > 1) { + g_mutant = argv[1]; + for (size_t i = 0; i < N_MUT; i++) if (strcmp(MUTANTS[i].mutant, g_mutant) == 0) g_expect_check = MUTANTS[i].check; + if (!g_expect_check) { fprintf(stderr, "unknown mutant %s\n", g_mutant); return 2; } + } + t_blake3(); + t_receipts(); + t_profiles(); + t_lock(); + t_frontend(); + t_refusals(); + t_graphs(); + t_admit(); + t_identity(); + t_no_escape(); + t_cli(); + if (g_mutant) { + if (g_expect_failed) { printf("MUTANT %s KILLED by %s\n", g_mutant, g_expect_check); return 1; } + printf("MUTANT %s SURVIVED (check %s did not fail; %d other checks failed)\n", g_mutant, g_expect_check, g_failed); + return 3; + } + printf("%d checks, %d failed\n", g_total, g_failed); + return g_failed ? 1 : 0; +} From 6b099f62b6972d61cf4935a81b02de827f8028e5 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Fri, 2 Oct 2026 09:09:50 -0500 Subject: [PATCH 2/2] VC1-RESOLVE round 2: remove oscv --allow-genesis, fix fuzz keyword clash, test four guards - oscv no longer has any genesis switch; the resolver field stays for stage 6. Source scan, option allow-list and CLI tests prove BOOTSTRAP-only stores are UNVERIFIED_DEPENDENCY in both domains with no way round it. - tests/compiler/test_osc_compiler.c: fuzz loop variable i collided with the type keyword i8 at depth 8 (unit 93); renamed to v. Test side only. - New tests and mapped mutants for chain depth limit, duplicate import names through the API, PRODUCTION authority rules, and PASS needs an assertion (161 checks, 64 mutants, all killed). - docs: genesis field not reachable from oscv; --blobs is optional. Co-Authored-By: Claude Sonnet 5.5 --- Makefile | 13 ++- docs/osc/OSC-VC1-IMPORT.md | 7 +- src/omega_receipt.c | 8 +- src/omega_resolve.c | 4 +- src/oscv_main.c | 11 ++- tests/compiler/test_osc_compiler.c | 4 +- tests/test_omega_resolve.c | 138 +++++++++++++++++++++++++++-- 7 files changed, 162 insertions(+), 23 deletions(-) diff --git a/Makefile b/Makefile index 682fbdabd..8272bfabb 100644 --- a/Makefile +++ b/Makefile @@ -1892,5 +1892,14 @@ test-resolve: tests/test_omega_resolve.c $(OUT_DIR)/compiler/oscv $(RESOLVE_SRC) build_mutant env-class env-class receipt receipt-refuses-env-class-mismatch ' if (strcmp(r->env_class, r->tier) != 0 && 0) { ef(&e, "receipt: env_class contradicts tier%s", ""); goto done; }'; \ build_mutant mutation-order mutation-order receipt receipt-refuses-observed-over-declared ' if (MUTS[r->observed_mutation].sev > MUTS[r->declared_mutation].sev && 0) { ef(&e, "receipt: observed mutation exceeds declared mutation%s", ""); goto done; }'; \ build_mutant canon-sort canon-sort receipt receipt-canon-order-independent ' (void)cmp_str;'; \ - build_mutant id-compare id-compare receipt receipt-refuses-wrong-id ' if (0) {' - @echo "test-resolve: PASS (all checks, ASan/UBSan clean, all 55 mutants killed)" + build_mutant id-compare id-compare receipt receipt-refuses-wrong-id ' if (0) {'; \ + build_mutant max-depth-removed max-depth resolve refuse-dependency-chain-too-deep ' if (0 && depth >= MAX_DEPTH) return fail(w->err, OMEGA_RES_UNVERIFIED_DEPENDENCY, 0, sid, "dependency chain deeper than %d", MAX_DEPTH);'; \ + build_mutant max-depth-one-too-many max-depth resolve refuse-dependency-chain-too-deep ' if (depth > MAX_DEPTH) return fail(w->err, OMEGA_RES_UNVERIFIED_DEPENDENCY, 0, sid, "dependency chain deeper than %d", MAX_DEPTH);'; \ + build_mutant max-depth-one-too-few max-depth resolve accept-dependency-chain-at-the-limit ' if (depth >= MAX_DEPTH - 1) return fail(w->err, OMEGA_RES_UNVERIFIED_DEPENDENCY, 0, sid, "dependency chain deeper than %d", MAX_DEPTH);'; \ + build_mutant dup-import dup-import resolve refuse-duplicate-import-names-through-the-api ' if (0) return fail(err, OMEGA_RES_BAD_ARGUMENT, 0, names[i], "import listed twice");'; \ + build_mutant pass-needs-assertion pass-needs-assertion receipt receipt-refuses-pass-without-assertion ' if (r->n_assertions == 0 && r->result == OMEGA_RECEIPT_PASS && 0) { ef(&e, "receipt: PASS receipts must carry at least one assertion%s", ""); goto done; }'; \ + build_mutant prod-authority-empty prod-authority receipt receipt-refuses-production-blank-authority ' if (a == b && 0) { ef(&e, "receipt: PRODUCTION receipts require an authority reference%s", ""); goto done; }'; \ + build_mutant prod-authority-trim prod-authority receipt receipt-refuses-production-blank-authority ' if (b == 0) { ef(&e, "receipt: PRODUCTION receipts require an authority reference%s", ""); goto done; }'; \ + build_mutant prod-spelling prod-spelling receipt receipt-refuses-production-test-only-authority ' int bad = strstr(low, "test-only") || strstr(low, "testonly");'; \ + build_mutant prod-bad-refused prod-bad-refused receipt receipt-refuses-production-test-only-authority ' if (bad && 0) { ef(&e, "receipt: a TEST_ONLY signer cannot produce a PRODUCTION receipt%s", ""); goto done; }' + @echo "test-resolve: PASS (all checks, ASan/UBSan clean, all 64 mutants killed)" diff --git a/docs/osc/OSC-VC1-IMPORT.md b/docs/osc/OSC-VC1-IMPORT.md index dfae035e4..0da14d676 100644 --- a/docs/osc/OSC-VC1-IMPORT.md +++ b/docs/osc/OSC-VC1-IMPORT.md @@ -44,11 +44,16 @@ is TAINTED: its artifact header says `tainted 1`, its build id commits to the do to insert it (and refuses any record that lists the capability `omega-dev.taint`). A record listing that capability can never satisfy an import in either domain. -BOOTSTRAP (genesis) records satisfy an import only with `allow_genesis`. A BOOTSTRAP record may NOT depend on a +BOOTSTRAP (genesis) records satisfy an import only with `allow_genesis`. That is a field inside the resolver library. +The `oscv` driver has no option, file or environment variable that sets it (the old `--allow-genesis` flag was removed), so a store +that holds only BOOTSTRAP records always yields UNVERIFIED_DEPENDENCY in both domains. The stage 6 genesis loader will be the +only caller that sets the field. A BOOTSTRAP record may NOT depend on a VERIFIED record (the audited base must be closed over itself); a VERIFIED record may depend on BOOTSTRAP. ## No escape hatch +`oscv --blobs` is optional: leaving it out skips only the recheck of source digests against stored blobs. + No `unsafe import`, no skip switch, no environment variable. `make test-resolve` greps the compiler and resolver sources for forbidden words and runs `oscv` with unknown switches and with environment variables set. diff --git a/src/omega_receipt.c b/src/omega_receipt.c index b92f0d2a7..b0ec34f99 100644 --- a/src/omega_receipt.c +++ b/src/omega_receipt.c @@ -501,7 +501,7 @@ int omega_receipt_parse(const uint8_t *json, size_t len, OmegaReceipt *r, char * want_str(&e, a, "source", 0, &as->source) || want_str(&e, a, "note", 0, &as->note)) goto done; } - if (r->n_assertions == 0 && r->result == OMEGA_RECEIPT_PASS) { ef(&e, "receipt: PASS receipts must carry at least one assertion%s", ""); goto done; } + if (r->n_assertions == 0 && r->result == OMEGA_RECEIPT_PASS) { ef(&e, "receipt: PASS receipts must carry at least one assertion%s", ""); goto done; } /* VC1R:pass-needs-assertion */ for (size_t i = 0; i < r->n_assertions; i++) { if (!r->assertions[i].id[0]) { ef(&e, "receipt: assertion id must not be empty%s", ""); goto done; } for (size_t k = 0; k < i; k++) @@ -520,13 +520,13 @@ int omega_receipt_parse(const uint8_t *json, size_t len, OmegaReceipt *r, char * if (r->tier_rank == 7) { size_t a = 0, b = strlen(r->authority); while (a < b && (r->authority[a] == ' ' || r->authority[a] == '\t' || r->authority[a] == '\n' || r->authority[a] == '\r')) a++; - if (a == b) { ef(&e, "receipt: PRODUCTION receipts require an authority reference%s", ""); goto done; } + if (a == b) { ef(&e, "receipt: PRODUCTION receipts require an authority reference%s", ""); goto done; } /* VC1R:prod-authority */ char *low = strdup(r->authority); if (!low) { ef(&e, "receipt: out of memory%s", ""); goto done; } for (char *c = low; *c; c++) if (*c >= 'A' && *c <= 'Z') *c = (char)(*c - 'A' + 'a'); - int bad = strstr(low, "test-only") || strstr(low, "test_only") || strstr(low, "testonly"); + int bad = strstr(low, "test-only") || strstr(low, "test_only") || strstr(low, "testonly"); /* VC1R:prod-spelling */ free(low); - if (bad) { ef(&e, "receipt: a TEST_ONLY signer cannot produce a PRODUCTION receipt%s", ""); goto done; } + if (bad) { ef(&e, "receipt: a TEST_ONLY signer cannot produce a PRODUCTION receipt%s", ""); goto done; } /* VC1R:prod-bad-refused */ } /* ledger and lease: null or an object (deny_unknown_fields) */ const J *lg = oget(root, "ledger"); diff --git a/src/omega_resolve.c b/src/omega_resolve.c index 38185bede..adcd36c8b 100644 --- a/src/omega_resolve.c +++ b/src/omega_resolve.c @@ -432,7 +432,7 @@ static int resolve_node(Walk *w, const uint8_t id[32], const uint8_t *lock_recei return fail(w->err, OMEGA_RES_RECEIPT_HASH_MISMATCH, 0, subj, "the lock pins another receipt than the record carries for %s", sid); return 0; } - if (depth >= MAX_DEPTH) return fail(w->err, OMEGA_RES_UNVERIFIED_DEPENDENCY, 0, sid, "dependency chain deeper than %d", MAX_DEPTH); + if (depth >= MAX_DEPTH) return fail(w->err, OMEGA_RES_UNVERIFIED_DEPENDENCY, 0, sid, "dependency chain deeper than %d", MAX_DEPTH); /* VC1R:max-depth */ OmegaVcRecord *rec = malloc(sizeof *rec); if (!rec) return fail(w->err, OMEGA_RES_NOMEM, 0, sid, "out of memory"); int rc = omega_vcstore_get(r->store, id, rec); @@ -530,7 +530,7 @@ int omega_resolve_imports(const OmegaResolver *r, const OmegaLock *lock, const c if (!lock) lock = ∅ for (size_t i = 0; i < n_names; i++) for (size_t k = 0; k < i; k++) - if (strcmp(names[i], names[k]) == 0) return fail(err, OMEGA_RES_BAD_ARGUMENT, 0, names[i], "import '%s' is listed twice", names[i]); + if (strcmp(names[i], names[k]) == 0) return fail(err, OMEGA_RES_BAD_ARGUMENT, 0, names[i], "import '%s' is listed twice", names[i]); /* VC1R:dup-import */ /* declaration check: every import is pinned, every pin is imported */ for (size_t i = 0; i < n_names; i++) if (!omega_lock_find(lock, names[i])) /* VC1R:not-pinned */ diff --git a/src/oscv_main.c b/src/oscv_main.c index 87e0f996a..8a4674ef1 100644 --- a/src/oscv_main.c +++ b/src/oscv_main.c @@ -2,12 +2,13 @@ * oscv_main.c -- `oscv`: the VERIFIED OSC driver (VC1 stage 4, ADR 0029). * * oscv [--domain dev|build] [--lock FILE] [--store FILE] [--receipts DIR] [--blobs DIR] - * [--allow-genesis] [--meta-out FILE] + * [--meta-out FILE] * * Compiles an OSC unit exactly as oscc does and ALSO resolves its `import NAME;` lines, only * through omega.lock -> semantic id -> Verified Crumb Store -> receipt check -> closure. Defaults * sit next to the source file: omega.lock, omega.vcstore, receipts/. There is no option that - * skips a check, and nothing is read from the environment. The only way to change what is legal + * skips a check (--blobs is optional: leaving it out skips only the source digest recheck, which + * stage 6 makes mandatory), and nothing is read from the environment. There is no genesis option. The only way to change what is legal * is to change the closure. * * Output (success): ir_sha256= code_sha256= funcs= domain= tainted= imports= closure_entries= @@ -74,7 +75,6 @@ int main(int argc, char **argv) { OmegaDomain domain = OMEGA_DOMAIN_BUILD; const char *lockp = NULL, *storep = NULL, *recdir = NULL, *blobdir = NULL, *metaout = NULL, *file = NULL; - int allow_genesis = 0; for (int i = 1; i < argc; i++) { const char *a = argv[i]; if (strcmp(a, "--domain") == 0 && i + 1 < argc) { @@ -87,12 +87,11 @@ int main(int argc, char **argv) else if (strcmp(a, "--receipts") == 0 && i + 1 < argc) recdir = argv[++i]; else if (strcmp(a, "--blobs") == 0 && i + 1 < argc) blobdir = argv[++i]; else if (strcmp(a, "--meta-out") == 0 && i + 1 < argc) metaout = argv[++i]; - else if (strcmp(a, "--allow-genesis") == 0) allow_genesis = 1; else if (a[0] == '-' || file) { fprintf(stderr, "oscv: unknown or repeated argument '%s'\n", a); return 2; } else file = a; } if (!file) { - fprintf(stderr, "usage: oscv [--domain dev|build] [--lock F] [--store F] [--receipts D] [--blobs D] [--allow-genesis] [--meta-out F] \n"); + fprintf(stderr, "usage: oscv [--domain dev|build] [--lock F] [--store F] [--receipts D] [--blobs D] [--meta-out F] \n"); return 2; } char lockd[4096], stored[4096], recd[4096]; @@ -140,7 +139,7 @@ int main(int argc, char **argv) h.resolver.fetch_receipt = omega_receipt_dir_fetch; h.resolver.fetch_ctx = (void *)recdir; if (blobdir) { h.resolver.fetch_blob = omega_blob_dir_fetch; h.resolver.blob_ctx = (void *)blobdir; } - h.resolver.allow_genesis = allow_genesis; + /* genesis (BOOTSTRAP) records are never permitted here: no option, file or variable turns that on */ h.lock = have_lock ? &lock : NULL; OscUnit *u = malloc(sizeof *u); diff --git a/tests/compiler/test_osc_compiler.c b/tests/compiler/test_osc_compiler.c index 308f4829a..59bc0cfb9 100644 --- a/tests/compiler/test_osc_compiler.c +++ b/tests/compiler/test_osc_compiler.c @@ -1655,10 +1655,10 @@ static int df_block(unsigned d, unsigned lo, int inloop) } else if (k < 14 && d < 2 && !inloop) { /* loop-local owner moved on one path */ unsigned iv = df_id++, lb = df_no; df_ind(d); - DFC("for i%u in 0 .. 3 {\n", iv); + DFC("for v%u in 0 .. 3 {\n", iv); unsigned w = df_new("w", 0); df_ind(d + 1); - DFC("let %s: own [u32; 3] = alloc((i%u as u32) + ((c & 3) as u32));\n", df_o[w].name, iv); + DFC("let %s: own [u32; 3] = alloc((v%u as u32) + ((c & 3) as u32));\n", df_o[w].name, iv); df_block(d + 1, lb, 1); df_no = lb; df_ind(d); diff --git a/tests/test_omega_resolve.c b/tests/test_omega_resolve.c index d74c235f4..efb280b22 100644 --- a/tests/test_omega_resolve.c +++ b/tests/test_omega_resolve.c @@ -103,13 +103,14 @@ typedef struct { const char *inputs[4]; int n_in; const char *deps[4]; int n_dep; char root[65]; - int assert_pass, extra_key, dup_key, lease; + int assert_pass, extra_key, dup_key, lease, no_assertion; + const char *authority; } RJ; static void rj_default(RJ *j) { memset(j, 0, sizeof *j); j->kind = "host-v1"; j->tier = "HOST_TEST"; j->env_class = NULL; j->result = "PASS"; j->schema = "EvidenceReceiptV1"; j->decl_mut = "NONE"; j->obs_mut = "NONE"; - j->procedure = "fixture"; j->reserved = ""; j->feature = NULL; j->version = 1; j->assert_pass = 1; + j->procedure = "fixture"; j->authority = ""; j->reserved = ""; j->feature = NULL; j->version = 1; j->assert_pass = 1; memset(j->root, '6', 64); j->root[64] = 0; } static char *rj_emit(const RJ *j, const char *idhex, size_t *len) { @@ -125,12 +126,14 @@ static char *rj_emit(const RJ *j, const char *idhex, size_t *len) { PF("\"toolchain\": \"fixture\",\n\"procedure\": \"%s\",\n\"machine\": \"host\",\n\"env_class\": \"%s\",\n", j->procedure, j->env_class ? j->env_class : j->tier); PF("\"input_artifacts\": ["); for (int i = 0; i < j->n_in; i++) PF("%s\"%s\"", i ? ", " : "", j->inputs[i]); - PF("],\n\"output_artifacts\": [],\n\"assertions\": [{\"id\": \"fixture_check\", \"expected\": \"pass\", \"observed\": \"%s\", \"pass\": %s, \"source\": \"test\", \"note\": \"\"}],\n", - j->assert_pass ? "pass" : "fail", j->assert_pass ? "true" : "false"); + PF("],\n\"output_artifacts\": [],\n"); + if (j->no_assertion) PF("\"assertions\": [],\n"); + else PF("\"assertions\": [{\"id\": \"fixture_check\", \"expected\": \"pass\", \"observed\": \"%s\", \"pass\": %s, \"source\": \"test\", \"note\": \"\"}],\n", + j->assert_pass ? "pass" : "fail", j->assert_pass ? "true" : "false"); PF("\"dependencies\": ["); for (int i = 0; i < j->n_dep; i++) PF("%s\"%s\"", i ? ", " : "", j->deps[i]); - PF("],\n\"declared_mutation\": \"%s\",\n\"observed_mutation\": \"%s\",\n\"authority\": \"\",\n\"output_digest\": \"%s\",\n\"external_refs\": [],\n\"ledger\": null,\n", - j->decl_mut, j->obs_mut, j->root); + PF("],\n\"declared_mutation\": \"%s\",\n\"observed_mutation\": \"%s\",\n\"authority\": \"%s\",\n\"output_digest\": \"%s\",\n\"external_refs\": [],\n\"ledger\": null,\n", + j->decl_mut, j->obs_mut, j->authority, j->root); if (j->lease) PF("\"lease\": {\"hold_id\": \"%s\", \"resource\": \"fixture-lease\"},\n", "1111111111111111111111111111111111111111111111111111111111111111"); else PF("\"lease\": null,\n"); if (j->feature) PF("\"required_features\": [\"%s\"],\n", j->feature); else PF("\"required_features\": [],\n"); @@ -458,6 +461,19 @@ static void t_receipts(void) { rj_default(&j); j.obs_mut = "VOLATILE_ONLY"; check("receipt-refuses-observed-over-declared", rj_refused(&j)); rj_default(&j); j.decl_mut = "VOLATILE_ONLY"; j.obs_mut = "VOLATILE_ONLY"; check("receipt-control-valid-variant-parses", !rj_refused(&j)); + rj_default(&j); j.no_assertion = 1; check("receipt-refuses-pass-without-assertion", rj_refused(&j)); + rj_default(&j); j.no_assertion = 1; j.result = "FAIL"; check("receipt-control-fail-without-assertion-parses", !rj_refused(&j)); + rj_default(&j); j.tier = "PRODUCTION"; j.kind = "production-v1"; j.authority = "release-key-1"; + check("receipt-control-production-with-authority-parses", !rj_refused(&j)); + { + int blank = 1, testonly = 1; + static const char *const blanks[] = { "", " ", " ", "\t" }; + static const char *const marks[] = { "TEST-ONLY signer", "a test_only key", "TestOnly", "test-only", "TEST_ONLY" }; + for (size_t i = 0; i < sizeof blanks / sizeof blanks[0]; i++) { rj_default(&j); j.tier = "PRODUCTION"; j.kind = "production-v1"; j.authority = blanks[i]; if (!rj_refused(&j)) blank = 0; } + for (size_t i = 0; i < sizeof marks / sizeof marks[0]; i++) { rj_default(&j); j.tier = "PRODUCTION"; j.kind = "production-v1"; j.authority = marks[i]; if (!rj_refused(&j)) testonly = 0; } + check("receipt-refuses-production-blank-authority", blank); + check("receipt-refuses-production-test-only-authority", testonly); + } free(ja); free(jb); free(jc); int tab_ok = 1; @@ -1095,6 +1111,47 @@ static void t_admit(void) { } } +/* ---- guards: chain depth, duplicate imports through the API ---- */ +static void build_chain(W *w, int n) { + Opt o = opt0(); + for (int k = 1; k <= n; k++) { + uint8_t d[1][32]; + if (k > 1) mkid(d[0], (uint8_t)(k - 1)); + if (add_comp(w, (uint8_t)k, k > 1 ? d : NULL, k > 1 ? 1 : 0, &o) != 0) setup_fail("chain insert"); + } +} +static void t_guards(void) { + W w; Run r; + w_init(&w); build_chain(&w, 128); + { Pin p[1] = { { "top", 128, 0 } }; const char *nm[1] = { "top" }; + run_compile(&w, src_imports(nm, 1), OMEGA_DOMAIN_BUILD, lock_text(&w, p, 1), &r); } + check("accept-dependency-chain-at-the-limit", r.rc == 0 && r.h.closure.n == 128); + run_free(&r); w_free(&w); + w_init(&w); build_chain(&w, 129); + { Pin p[1] = { { "top", 129, 0 } }; const char *nm[1] = { "top" }; + run_compile(&w, src_imports(nm, 1), OMEGA_DOMAIN_BUILD, lock_text(&w, p, 1), &r); } + check("refuse-dependency-chain-too-deep", refused_msg(&r, "UNVERIFIED_DEPENDENCY", OMEGA_RES_UNVERIFIED_DEPENDENCY, "deeper than") && r.h.closure.n == 0); + run_free(&r); w_free(&w); + + /* the same import name listed twice, straight into the resolver (the parser cannot produce it) */ + w_init(&w); + { Opt o = opt0(); add_comp(&w, 0x51, NULL, 0, &o); } + { Pin p[1] = { { "foo", 0x51, 0 } }; + OmegaLock lock; OmegaResolveError e; OmegaClosure cl; + const char *lk = lock_text(&w, p, 1); + if (omega_lock_parse(lk, strlen(lk), &lock, &e)) setup_fail("lock"); + OmegaResolver rv = resolver_of(&w, &w.rt); + const char *twice[2] = { "foo", "foo" }; + memset(&cl, 0, sizeof cl); + int rc = omega_resolve_imports(&rv, &lock, twice, 2, &cl, &e); + check("refuse-duplicate-import-names-through-the-api", rc == OMEGA_RES_BAD_ARGUMENT && cl.n == 0 && cl.entries == NULL); + const char *once[1] = { "foo" }; + rc = omega_resolve_imports(&rv, &lock, once, 1, &cl, &e); + check("accept-single-import-name-through-the-api", rc == 0 && cl.n == 1); + omega_closure_free(&cl); omega_lock_free(&lock); } + w_free(&w); +} + /* ---- build identity, domains, artifact header ---- */ static void t_identity(void) { uint8_t ir[32], cl[32], got[32], ref[32]; @@ -1199,6 +1256,35 @@ static void t_no_escape(void) { } closedir(d); check("no-escape-hatch-in-compiler-and-resolver-sources", !found && nfiles > 20); + /* the driver and its adapter: no genesis switch, and no option beyond the allow-list */ + { + static const char *const cli_files[] = { "src/oscv_main.c", "src/omega_resolve_osc.c", "src/omega_resolve_osc.h" }; + static const char *const cli_words[] = { "allow-genesis", "allow_genesis" }; + static const char *const allowed[] = { "--domain", "--lock", "--store", "--receipts", "--blobs", "--meta-out" }; + int clean = 1, opts_ok = 1, n_opts = 0; + for (size_t f = 0; f < sizeof cli_files / sizeof cli_files[0]; f++) { + size_t n; uint8_t *b = slurp_file(cli_files[f], &n); + if (!b) setup_fail("cannot read a driver source"); + for (size_t w = 0; w < sizeof cli_words / sizeof cli_words[0]; w++) { + size_t k = strlen(cli_words[w]); + for (size_t a = 0; a + k <= n; a++) if (memcmp(b + a, cli_words[w], k) == 0) clean = 0; + } + if (strcmp(cli_files[f], "src/oscv_main.c") == 0) + for (size_t a = 0; a + 3 <= n; a++) + if (b[a] == '"' && b[a + 1] == '-' && b[a + 2] == '-') { + size_t e = a + 1; + while (e < n && b[e] != '"' && b[e] != ' ') e++; + int known = 0; + for (size_t o = 0; o < sizeof allowed / sizeof allowed[0]; o++) + if (strlen(allowed[o]) == e - (a + 1) && memcmp(allowed[o], b + a + 1, e - (a + 1)) == 0) known = 1; + n_opts++; + if (!known) opts_ok = 0; + } + free(b); + } + check("no-genesis-switch-in-the-driver-sources", clean); + check("driver-options-are-exactly-the-allow-list", opts_ok && n_opts >= 6); + } const char *h2; int control = 1; for (size_t i = 0; i < N_FORBIDDEN; i++) { @@ -1352,6 +1438,36 @@ static void t_cli(void) { snprintf(cmd, sizeof cmd, "OMEGA_SKIP_VERIFY=1 SKIP_VERIFY=1 OMEGA_UNSAFE=1 %s --lock %s/missing.lock %s/a.osc 2>&1", OSCV_PATH, dir, dir); rc = sh(cmd, out, sizeof out); check("cli-ignores-environment-variables", rc == 1 && strstr(out, "resolve_code=DEPENDENCY_NOT_PINNED") != NULL); + /* genesis: no switch, no way round it from the driver */ + snprintf(cmd, sizeof cmd, "%s --allow-genesis %s/a.osc 2>&1", OSCV_PATH, dir); + rc = sh(cmd, out, sizeof out); + check("cli-refuses-allow-genesis-as-unknown-option", rc == 2 && strstr(out, "unknown or repeated argument") != NULL && strstr(out, "ir_sha256") == NULL); + snprintf(cmd, sizeof cmd, "%s --allow_genesis %s/a.osc 2>&1", OSCV_PATH, dir); + rc = sh(cmd, out, sizeof out); + check("cli-refuses-allow_genesis-spelling-too", rc == 2); + { + W g; w_init(&g); + Opt b = opt0(); b.boot = 1; + add_comp(&g, 0x91, NULL, 0, &b); + Pin gp[1] = { { "base", 0x91, 0 } }; + const char *glk = lock_text(&g, gp, 1); + snprintf(path, sizeof path, "%s/g.vcstore", dir); + if (omega_vcstore_save(g.st, path)) setup_fail("save genesis store"); + snprintf(path, sizeof path, "%s/g.lock", dir); wfile(path, glk, strlen(glk)); + snprintf(src, sizeof src, "import base;\n%s", FN); + snprintf(path, sizeof path, "%s/g.osc", dir); wfile(path, src, strlen(src)); + static const char *const flags[3] = { "", "--domain dev", "--domain build" }; + static const char *const envs[2] = { "", "OMEGA_ALLOW_GENESIS=1 ALLOW_GENESIS=1 " }; + int all = 1; + for (int f = 0; f < 3; f++) + for (int e2 = 0; e2 < 2; e2++) { + snprintf(cmd, sizeof cmd, "%s%s %s --store %s/g.vcstore --lock %s/g.lock --receipts %s %s/g.osc 2>&1", envs[e2], OSCV_PATH, flags[f], dir, dir, rdir, dir); + rc = sh(cmd, out, sizeof out); + if (!(rc == 1 && strstr(out, "resolve_code=UNVERIFIED_DEPENDENCY") != NULL && strstr(out, "genesis") != NULL && strstr(out, "build_id") == NULL)) all = 0; + } + check("cli-genesis-only-store-is-refused-in-every-mode", all); + w_free(&g); + } snprintf(cmd, sizeof cmd, "%s --domain prod %s/a.osc 2>&1", OSCV_PATH, dir); rc = sh(cmd, out, sizeof out); check("cli-refuses-unknown-domain", rc == 2); @@ -1418,6 +1534,15 @@ static const struct { const char *mutant, *check; } MUTANTS[] = { { "mutation-order", "receipt-refuses-observed-over-declared" }, { "canon-sort", "receipt-canon-order-independent" }, { "id-compare", "receipt-refuses-wrong-id" }, + { "max-depth-removed", "refuse-dependency-chain-too-deep" }, + { "max-depth-one-too-many", "refuse-dependency-chain-too-deep" }, + { "max-depth-one-too-few", "accept-dependency-chain-at-the-limit" }, + { "dup-import", "refuse-duplicate-import-names-through-the-api" }, + { "pass-needs-assertion", "receipt-refuses-pass-without-assertion" }, + { "prod-authority-empty", "receipt-refuses-production-blank-authority" }, + { "prod-authority-trim", "receipt-refuses-production-blank-authority" }, + { "prod-spelling", "receipt-refuses-production-test-only-authority" }, + { "prod-bad-refused", "receipt-refuses-production-test-only-authority" }, }; #define N_MUT (sizeof MUTANTS / sizeof MUTANTS[0]) @@ -1435,6 +1560,7 @@ int main(int argc, char **argv) { t_refusals(); t_graphs(); t_admit(); + t_guards(); t_identity(); t_no_escape(); t_cli();