use crate::{compat, receipt};
use anyhow::{Context, Result, ensure};
use serde_json::{Value, json};
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::Path;
const GEOMETRY: &[&str] = &[
"profile",
"memory64",
"pointer_width",
"page_size",
"address_limit",
"platform_format",
"stack_bytes",
"hot_control_base",
"hot_control_bytes",
"static_data_base",
"static_limit",
"control_base",
"bootstrap_address",
"initial_memory_bytes",
"typed_root",
];
const MANIFEST_SUFFIX: &str = ".manifest.json";
fn digest(value: &str) -> bool {
value.len() == 64
&& value
.bytes()
.all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
}
pub(crate) fn verified_bytes(file: &receipt::FileRecord) -> Result<Vec<u8>> {
let contents = fs::read(&file.path).with_context(|| format!("read {}", file.path.display()))?;
receipt::verify_bytes(file, &contents)?;
Ok(contents)
}
fn verified_document(file: &receipt::FileRecord) -> Result<Value> {
let contents = compat::read_document_bytes(&file.path)?;
receipt::verify_bytes(file, &contents)?;
compat::parse_document(&contents).with_context(|| format!("parse {}", file.path.display()))
}
fn strings(value: &Value, purpose: &str) -> Result<Vec<String>> {
serde_json::from_value(value.clone()).with_context(|| format!("invalid {purpose}"))
}
fn check_completion(
marker: &Path,
name: &str,
manifest_hash: &str,
outputs: &BTreeMap<String, receipt::FileRecord>,
) -> Result<()> {
let mut expected: BTreeMap<_, _> = outputs
.iter()
.map(|(name, row)| (name.as_str(), row.sha256.as_str()))
.collect();
ensure!(
expected.insert(name, manifest_hash).is_none(),
"manifest listed as its own output"
);
ensure!(
marker.is_file(),
"missing completion marker: {}",
marker.display()
);
let bytes = compat::read_document_bytes(marker)?;
let contents = std::str::from_utf8(&bytes).context("completion marker must be UTF-8")?;
let mut actual = BTreeMap::new();
for line in contents.lines() {
let (hash, name) = line
.split_once(" ")
.with_context(|| format!("invalid completion marker: {}", marker.display()))?;
ensure!(
digest(hash),
"invalid completion marker: {}",
marker.display()
);
ensure!(
receipt::safe_name(name) && actual.insert(name, hash).is_none(),
"unsafe or duplicate completion entry: {name}"
);
}
ensure!(
actual == expected,
"incomplete or stale artifact publication: {}",
marker.display()
);
Ok(())
}
pub(crate) struct Artifact {
pub(crate) completed: CompletedOutputs,
wasm_sha256: String,
compiler: Value,
path_remaps: Vec<String>,
}
impl Artifact {
fn summary(&self) -> Value {
json!({
"manifest": self.completed.manifest_record.path,
"wasm_sha256": self.wasm_sha256,
"compiler": self.compiler,
})
}
}
pub(crate) struct CompletedOutputs {
pub(crate) manifest_record: receipt::FileRecord,
pub(crate) manifest: Value,
stem: String,
outputs: BTreeMap<String, receipt::FileRecord>,
}
impl CompletedOutputs {
pub(crate) fn output(&self, suffix: &str) -> Result<&receipt::FileRecord> {
let name = format!("{}.{suffix}", self.stem);
self.outputs
.get(&name)
.with_context(|| format!("missing completed artifact output: {name}"))
}
pub(crate) fn optional_output(&self, suffix: &str) -> Option<&receipt::FileRecord> {
self.outputs.get(&format!("{}.{suffix}", self.stem))
}
}
pub(crate) fn completed_outputs(path: &Path, allow_relocated: bool) -> Result<CompletedOutputs> {
let path = path
.canonicalize()
.with_context(|| format!("resolve {}", path.display()))?;
let name = path
.file_name()
.and_then(|p| p.to_str())
.context("missing manifest filename")?;
let stem = name
.strip_suffix(MANIFEST_SUFFIX)
.context("expected canonical *.manifest.json")?;
ensure!(
receipt::safe_name(stem),
"invalid artifact filename stem: {stem:?}"
);
let directory = path.parent().context("missing artifact directory")?;
ensure!(
path.is_file(),
"not a regular manifest file: {}",
path.display()
);
let bytes = compat::read_document_bytes(&path)?;
let value =
compat::parse_document(&bytes).with_context(|| format!("parse {}", path.display()))?;
let build = &value["canonicalBuild"];
ensure!(
value["format"] == receipt::FORMAT
&& value["implementation"] == "cdk-rsx"
&& value["sourceUnchangedDuringBuild"] == true
&& build["source_unchanged_during_build"] == true
&& build["runtime"] == "typed-root",
"not a complete canonical typed-root build: {}",
path.display()
);
let records: Vec<receipt::FileRecord> = serde_json::from_value(value["outputs"].clone())
.context("missing or invalid artifact outputs")?;
ensure!(!records.is_empty(), "missing artifact outputs");
let mut outputs = BTreeMap::new();
for mut expected in records {
let name = expected
.path
.file_name()
.and_then(|name| name.to_str())
.context("invalid artifact output name")?;
ensure!(
expected.path.is_absolute()
&& (allow_relocated || expected.path.parent() == Some(directory))
&& receipt::safe_name(name),
"artifact outputs must share their manifest directory: {}",
expected.path.display()
);
let name = name.to_owned();
if allow_relocated {
expected.path = directory.join(&name);
}
ensure!(
receipt::record(&expected.path)? == expected,
"pinned input changed: {}",
expected.path.display()
);
ensure!(
outputs.insert(name, expected).is_none(),
"duplicate artifact output"
);
}
let sha256 = receipt::hash_bytes(&bytes);
check_completion(
&directory.join(format!("{stem}.SHA256SUMS")),
name,
&sha256,
&outputs,
)?;
let stem = stem.to_owned();
Ok(CompletedOutputs {
manifest_record: receipt::FileRecord {
path,
bytes: bytes.len() as u64,
sha256,
},
manifest: value,
stem,
outputs,
})
}
pub(crate) fn artifact(path: &Path, verify_sources: bool) -> Result<Artifact> {
let completed = completed_outputs(path, false)?;
let path = &completed.manifest_record.path;
let value = &completed.manifest;
let build = &value["canonicalBuild"];
let (wasm, raw) = (completed.output("wasm")?, completed.output("raw.wasm")?);
ensure!(
value["wasmSha256"] == wasm.sha256 && build["raw_wasm_sha256"] == raw.sha256,
"Wasm role/hash mismatch"
);
let compatibility = &build["compatibility"];
ensure!(
compatibility["status"] == "approved",
"build uses unapproved candidate identities or lacks compatibility provenance: {}",
path.display()
);
let aliases = compat::validate_aliases(&compatibility["aliases"])?;
ensure!(
compatibility["aliases_sha256"] == receipt::hash_bytes(&compat::canonical_bytes(&aliases)),
"build alias payload hash mismatch"
);
let target = build["target"].as_str().context("missing Wasm target")?;
ensure!(
matches!(target, "wasm64-unknown-unknown" | "wasm32-unknown-unknown"),
"unsupported target: {target}"
);
let context = compatibility["context"]
.as_str()
.context("missing exact build context")?;
ensure!(digest(context), "missing exact build context");
let inventory = |wasm_file: &receipt::FileRecord, suffix: &str| -> Result<Value> {
let recorded = compat::validate_inventory(
&verified_document(completed.output(suffix)?)?,
&aliases,
context,
target,
)?;
let from_wasm = cdk_rsx_wasm::compatibility(&verified_bytes(wasm_file)?)?;
ensure!(
recorded == from_wasm,
"policy inventory differs from Wasm: {}",
wasm_file.path.display()
);
Ok(recorded)
};
let installed = inventory(wasm, "policies.json")?;
ensure!(
installed == inventory(raw, "raw.policies.json")?,
"raw/prepared policy inventories differ"
);
let memory = verified_document(completed.output("memory.json")?)?;
ensure!(
GEOMETRY.iter().all(|key| memory.get(key).is_some()),
"missing target geometry facts"
);
let sources: Vec<receipt::FileRecord> = serde_json::from_value(value["sources"].clone())
.context("missing frozen source closure")?;
let mut source_paths = BTreeSet::new();
ensure!(
!sources.is_empty()
&& sources.iter().all(|row| row.path.is_absolute()
&& digest(&row.sha256)
&& source_paths.insert(&row.path)),
"missing, invalid or duplicate frozen source inputs"
);
if verify_sources {
for expected in &sources {
ensure!(
receipt::record(&expected.path)? == *expected,
"build source changed: {}",
expected.path.display()
);
}
}
let mut build_features = strings(&build["features"], "build receipt features")?;
let mut manifest_features = strings(&value["features"], "artifact manifest features")?;
build_features.sort_unstable();
manifest_features.sort_unstable();
ensure!(
value["package"].is_string()
&& value["package"] == build["package"]
&& build_features == manifest_features,
"package/features disagree with build receipt"
);
let scope = format!("compiler/{target}");
let mut scopes = BTreeSet::new();
let mut compiler = None;
for row in installed["entries"]
.as_array()
.context("missing policy inventory rows")?
{
let found = row["scope"].as_str().context("missing policy scope")?;
ensure!(
scopes.insert(found),
"one exact policy per scope is required: {found}"
);
if found == scope {
compiler = Some(json!({
"scope": scope,
"identity": row["identity"],
"raw": row["raw"],
}));
}
}
let path_remaps = strings(&build["rustflags"], "recorded Rust flags")?
.into_iter()
.filter(|flag| flag.starts_with("--remap-path-prefix="))
.collect();
let wasm_sha256 = wasm.sha256.clone();
Ok(Artifact {
completed,
wasm_sha256,
compiler: compiler.context("missing compiler policy")?,
path_remaps,
})
}
pub fn verify(path: &Path) -> Result<Value> {
Ok(artifact(path, true)?.summary())
}
pub fn preflight(baseline: &Path, candidate: &Path) -> Result<Value> {
let baseline = artifact(baseline, false).context("invalid KEEP baseline")?;
let candidate = artifact(candidate, false).context("invalid KEEP candidate")?;
Ok(compare(&baseline, &candidate))
}
pub(crate) fn compare(baseline: &Artifact, candidate: &Artifact) -> Value {
let (status, next_check) = if baseline.compiler["scope"] != candidate.compiler["scope"] {
(
"target-mismatch",
"Build the candidate for the installed Wasm target.",
)
} else if baseline.compiler["identity"] != candidate.compiler["identity"] {
(
"compiler-policy-mismatch",
"Compare recorded path remaps, Rust flags, pinned toolchains and SDK dependency closures. For a path-only change, rebuild the candidate at the original build paths.",
)
} else {
(
"compiler-policy-match",
"If the root changed, check that the candidate declares the installed root as a predecessor. Rehearse KEEP with populated state.",
)
};
let mut result = json!({
"baseline": baseline.summary(),
"candidate": candidate.summary(),
"status": status,
"next_check": next_check,
});
if baseline.path_remaps != candidate.path_remaps {
result["path_remaps"] = json!({
"baseline": baseline.path_remaps,
"candidate": candidate.path_remaps,
});
}
result
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
fn image(stem: &str, raw: &str) -> Artifact {
Artifact {
completed: CompletedOutputs {
manifest_record: receipt::FileRecord {
path: PathBuf::from(format!("/{stem}.manifest.json")),
bytes: 0,
sha256: "0".repeat(64),
},
manifest: Value::Null,
stem: stem.into(),
outputs: BTreeMap::new(),
},
wasm_sha256: "1".repeat(64),
compiler: json!({"scope": "compiler/wasm64-unknown-unknown",
"identity": "2".repeat(64), "raw": raw}),
path_remaps: Vec::new(),
}
}
#[test]
fn compares_effective_identity_and_reports_changed_remaps() {
let baseline = image("old", &"2".repeat(64));
let mut candidate = image("new", &"3".repeat(64));
let report = compare(&baseline, &candidate);
assert_eq!(report["status"], "compiler-policy-match");
assert_ne!(
report["baseline"]["compiler"]["raw"],
report["candidate"]["compiler"]["raw"]
);
assert!(report.get("path_remaps").is_none());
candidate.compiler["identity"] = json!("3".repeat(64));
let remap = "--remap-path-prefix=/elsewhere/app=/workspace";
candidate.path_remaps.push(remap.into());
let report = compare(&baseline, &candidate);
assert_eq!(report["status"], "compiler-policy-mismatch");
assert_eq!(
report["path_remaps"],
json!({"baseline": [], "candidate": [remap]})
);
candidate.compiler["scope"] = json!("compiler/wasm32-unknown-unknown");
assert_eq!(compare(&baseline, &candidate)["status"], "target-mismatch");
}
}