From 5266c31230145e246924ffb135126e3b81a47705 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Fri, 16 Oct 2026 04:02:02 -0500 Subject: [PATCH 1/2] feat(id): record world module build provenance --- .opencode/plans/phase-9-portable-platform.md | 5 +- ...-00-00Z_feature_world_module_provenance.md | 24 +++ pkgs/id/Cargo.lock | 1 + pkgs/id/Cargo.toml | 1 + pkgs/id/src/world.rs | 158 +++++++++++++++- pkgs/id/src/world_compile.rs | 175 +++++++++++++++++- pkgs/id/src/world_net.rs | 45 ++++- pkgs/id/src/world_session.rs | 39 +++- pkgs/id/src/world_store.rs | 2 + 9 files changed, 430 insertions(+), 20 deletions(-) create mode 100644 doc/2026-10-16T09-00-00Z_feature_world_module_provenance/2026-10-16T09-00-00Z_feature_world_module_provenance.md diff --git a/.opencode/plans/phase-9-portable-platform.md b/.opencode/plans/phase-9-portable-platform.md index 1234567dea..f6946a0ff6 100644 --- a/.opencode/plans/phase-9-portable-platform.md +++ b/.opencode/plans/phase-9-portable-platform.md @@ -17,7 +17,8 @@ The immediate slice (P9.1) is a backwards-compatible, validated cell-grid presen ## Status and current worktree scope - **P9.1 complete:** portable surface contract and SSH/web presenters are committed on `platform-portable-ui` (PR #214, stacked on #209). -- **P9.3a complete in this worktree:** server-wide source-only install policy, stacked on #214. Source compilation remains enabled and raw artifacts are refused. Compiler provenance, per-world profiles, and broader allowed-function ceilings remain open. +- **P9.3a complete in PR #215:** server-wide source-only install policy. Source compilation remains enabled and raw artifacts can be refused. +- **P9.3b implementation in progress:** source builds attach server-observed compiler/platform/source digests, target, and stable arguments to the install event; raw artifact installs are labeled as artifacts. Metadata survives restart/checkpoint and is available through the additive module-info field. This is not a trust attestation. Per-world execution profiles, human-readable compiler version, and broader allowed-function ceilings remain open. - **P9.2a complete in this worktree:** focusable browser surfaces encode common keys with terminal-compatible bytes and send them through the existing durable input event. SSH already forwards PTY bytes through that same event. - **P9.2b complete in PR #219:** bounded paste is an explicit input event; browser ResizeObserver and SSH PTY/window-change events set connection-local viewport context. Structured screens are cropped per connection without entering the journal. Roc apps still render at their declared dimensions; guest-aware reflow remains a future ABI follow-up. - **P9.4 first slice complete in this worktree:** pure-Roc `RocJson.roc` decode/encode and typed accessors are exported by the Roc world platform; lounge now decodes host events and encodes requests/records. Broader data/game/communication helpers remain planned. @@ -45,6 +46,8 @@ P9.2b record: [per-session viewport and paste policy](../../doc/2026-10-15T16-00 P9.4 first-slice record: [pure-Roc JSON module](../../doc/2026-10-15T09-27-28Z_feature_roc_json/2026-10-15T09-27-28Z_feature_roc_json.md). P9.5 record: [terminal buffer capture interface](../../doc/2026-10-15T16-30-00Z_feature_terminal_buffer_capture/2026-10-15T16-30-00Z_feature_terminal_buffer_capture.md). +P9.3b record: [observed world module provenance](../../doc/2026-10-16T09-00-00Z_feature_world_module_provenance/2026-10-16T09-00-00Z_feature_world_module_provenance.md). + ## P9.3a acceptance - Source-only is an explicit server option, off by default, and requires an enabled world plus a configured server-side Roc compiler/platform. diff --git a/doc/2026-10-16T09-00-00Z_feature_world_module_provenance/2026-10-16T09-00-00Z_feature_world_module_provenance.md b/doc/2026-10-16T09-00-00Z_feature_world_module_provenance/2026-10-16T09-00-00Z_feature_world_module_provenance.md new file mode 100644 index 0000000000..42811ea710 --- /dev/null +++ b/doc/2026-10-16T09-00-00Z_feature_world_module_provenance/2026-10-16T09-00-00Z_feature_world_module_provenance.md @@ -0,0 +1,24 @@ +# Observed world module provenance + +## Decision + +Record an optional, server-observed origin alongside each installed world module. A raw module upload is tagged `artifact`. A successful source build records a versioned provenance document containing domain-separated BLAKE3 digests of the configured Roc executable, staged platform tree, and submitted source files, together with the target and stable compiler arguments (excluding the ephemeral output path). + +The record is metadata, not an attestation. It does not prove that the compiler, platform, or source is trustworthy, and the server admin token is not an individual identity. It does not store source contents or credentials. The executable digest identifies the bytes observed at compile time; no claim is made about the compiler's supply chain or reproducibility. + +## Persistence and compatibility + +- Provenance is an optional field on the existing `program_installed` event and checkpoint. Old journal entries decode with no provenance, and `None` is omitted when serializing. +- Journal version remains 1 because this is an additive optional JSON field; checkpoints preserve the current module's value across compaction and restore. +- The existing module-info frame gains an optional provenance field. Existing clients can keep using the current tuple-returning API; `WorldClient::info_details` exposes the new field. +- A module installed through an older/direct API may remain unknown (`None`); it is never inferred to be a source build. Network raw-artifact installation is explicitly marked `artifact`. + +## Boundaries and follow-ups + +- Hashes are integrity identifiers only. There is no signature, remote verification, transparency log, per-user build identity, or compiler version string in this slice. +- The metadata records the source submitted to the configured compiler. The compiler still rewrites the platform reference to the staged platform copy before building. +- Per-world execution profiles and broader allowed-function ceilings remain separate policy work; this change does not relax Wasm imports or native OS sandboxing. + +## Validation + +Tests cover deterministic source/platform digests, optional-field backward compatibility, checkpoint persistence, source build metadata, and module-info reporting for an artifact install. diff --git a/pkgs/id/Cargo.lock b/pkgs/id/Cargo.lock index 59e8dfba93..ec20c129b0 100644 --- a/pkgs/id/Cargo.lock +++ b/pkgs/id/Cargo.lock @@ -2884,6 +2884,7 @@ dependencies = [ "anyhow", "axum", "base64 0.22.1", + "blake3", "cbor-core", "clap", "comrak", diff --git a/pkgs/id/Cargo.toml b/pkgs/id/Cargo.toml index d7ddda546c..b9819957fd 100644 --- a/pkgs/id/Cargo.toml +++ b/pkgs/id/Cargo.toml @@ -104,6 +104,7 @@ aes-gcm = { version = "0.11", default-features = false, features = [ "alloc", ], optional = true } base64 = { version = "0.22", optional = true } +blake3 = "1" qrcode = { version = "0.14.1", default-features = false, optional = true } hkdf = { version = "0.13", optional = true } sha2 = { version = "0.11", optional = true } diff --git a/pkgs/id/src/world.rs b/pkgs/id/src/world.rs index c6a40bb781..7605aa7a58 100644 --- a/pkgs/id/src/world.rs +++ b/pkgs/id/src/world.rs @@ -231,9 +231,40 @@ pub enum WorldEventKind { /// inputs after this event it reproduces the program state exactly. #[serde(default)] seed: u64, + /// Server-observed origin metadata. Absent on older journal entries. + #[serde(default, skip_serializing_if = "Option::is_none")] + provenance: Option, }, } +/// How the active module artifact entered the world. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "origin", content = "build", rename_all = "snake_case")] +pub enum ModuleProvenance { + /// A raw module artifact was installed; no compiler identity is asserted. + Artifact, + /// The server observed a successful source build. These hashes identify + /// inputs; they are not a signature or a trust attestation. + SourceBuild(SourceBuildProvenance), +} + +/// Bounded, deterministic metadata observed for one source compilation. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct SourceBuildProvenance { + /// Provenance record schema, independent of the world journal version. + pub schema_version: u8, + /// Domain-separated BLAKE3 digest of the compiler executable bytes. + pub compiler_blake3: String, + /// BLAKE3 digest of the platform tree, including relative paths. + pub platform_blake3: String, + /// BLAKE3 digest of the submitted source filenames and contents. + pub source_blake3: String, + /// Compiler target (`wasm32` or `x64musl`). + pub target: String, + /// Stable compiler arguments, excluding the temporary output path. + pub arguments: Vec, +} + /// Whether a world's directory may be read from other worlds. /// /// Writes never cross worlds, whatever the setting. @@ -420,6 +451,9 @@ pub enum JournalEntry { module_hash: String, /// Seed the program was initialized with. seed: u64, + /// Provenance of the active module, if it was recorded. + #[serde(default, skip_serializing_if = "Option::is_none")] + provenance: Option, /// The program's own serialization of its state. snapshot: String, /// Recent events kept for reconnect catch-up. @@ -466,6 +500,8 @@ pub struct RestoredProgram { /// State to restore before replaying, if the journal was compacted behind /// a checkpoint; otherwise the program starts from `init(seed)`. pub snapshot: Option, + /// Server-observed module origin, if this journal version recorded it. + pub provenance: Option, } /// A world rebuilt from its journal, before its program is re-instantiated. @@ -608,6 +644,9 @@ pub struct WorldSnapshot { pub world_id: String, /// Content hash of the active program, if this world executes one. pub active_module_hash: Option, + /// Provenance for the active module, when recorded. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub active_module_provenance: Option, /// Latest committed sequence at snapshot time. pub current_sequence: u64, /// Earliest event sequence present in this snapshot, or the current @@ -653,6 +692,7 @@ pub struct WorldCore { next_participant_id: u64, sequence: u64, active_module_hash: Option, + active_module_provenance: Option, active_seed: u64, /// What this world's program may ask the server for. pub(crate) ledger: crate::world_caps::CapLedger, @@ -698,6 +738,7 @@ impl WorldCore { next_participant_id: 1, sequence: 0, active_module_hash: None, + active_module_provenance: None, active_seed: 0, ledger: crate::world_caps::CapLedger::new(Default::default(), limits.grant_on_use), isolation: Isolation::default(), @@ -870,13 +911,19 @@ impl WorldCore { event.sequence ); match &event.kind { - WorldEventKind::ProgramInstalled { module_hash, seed } => { + WorldEventKind::ProgramInstalled { + module_hash, + seed, + provenance, + } => { core.active_module_hash = Some(module_hash.clone()); + core.active_module_provenance = provenance.clone(); core.active_seed = *seed; program = Some(RestoredProgram { module_hash: module_hash.clone(), seed: *seed, snapshot: None, + provenance: provenance.clone(), }); replay.clear(); } @@ -891,6 +938,7 @@ impl WorldCore { sequence, module_hash, seed, + provenance, snapshot, events, } => { @@ -911,11 +959,13 @@ impl WorldCore { core.events.pop_front(); } core.active_module_hash = Some(module_hash.clone()); + core.active_module_provenance = provenance.clone(); core.active_seed = seed; program = Some(RestoredProgram { module_hash, seed, snapshot: Some(snapshot), + provenance, }); } } @@ -997,6 +1047,7 @@ impl WorldCore { sequence: self.sequence, module_hash, seed: self.active_seed, + provenance: self.active_module_provenance.clone(), snapshot, events: self.events.iter().cloned().collect(), }); @@ -1538,6 +1589,7 @@ impl WorldCore { WorldSnapshot { world_id: self.world_id.clone(), active_module_hash: self.active_module_hash.clone(), + active_module_provenance: self.active_module_provenance.clone(), current_sequence: self.sequence, oldest_retained_sequence, events: events.into_iter().collect(), @@ -1624,6 +1676,7 @@ enum WorldCommand { InstallProgram { module_hash: String, seed: u64, + provenance: Option, program: Box, reply: oneshot::Sender>, }, @@ -2405,6 +2458,7 @@ impl WorldActor { WorldCommand::InstallProgram { module_hash, seed, + provenance, program: mut replacement, reply, } => { @@ -2422,7 +2476,11 @@ impl WorldActor { let candidate = WorldEvent { sequence: self.core.sequence.saturating_add(1), participant_id: 0, - kind: WorldEventKind::ProgramInstalled { module_hash, seed }, + kind: WorldEventKind::ProgramInstalled { + module_hash, + seed, + provenance: provenance.clone(), + }, }; let result = self .persist(JournalEntry::Committed { @@ -2434,6 +2492,7 @@ impl WorldActor { if let WorldEventKind::ProgramInstalled { module_hash, .. } = &event.kind { self.core.active_module_hash = Some(module_hash.clone()); } + self.core.active_module_provenance = provenance; self.core.active_seed = seed; self.program = replacement; self.program_healthy = true; @@ -3051,12 +3110,25 @@ impl WorldHandle { module_hash: String, seed: u64, program: Box, + ) -> Result { + self.install_program_with_provenance(module_hash, seed, None, program) + .await + } + + /// As [`Self::install_program`], preserving server-observed origin metadata. + pub async fn install_program_with_provenance( + &self, + module_hash: String, + seed: u64, + provenance: Option, + program: Box, ) -> Result { let (reply, response) = oneshot::channel(); self.commands .send(WorldCommand::InstallProgram { module_hash, seed, + provenance, program, reply, }) @@ -3173,6 +3245,88 @@ mod tests { .unwrap() } + fn sample_source_provenance() -> ModuleProvenance { + ModuleProvenance::SourceBuild(SourceBuildProvenance { + schema_version: 1, + compiler_blake3: "compiler".to_owned(), + platform_blake3: "platform".to_owned(), + source_blake3: "source".to_owned(), + target: "wasm32".to_owned(), + arguments: vec!["build".to_owned(), "main.roc".to_owned()], + }) + } + + #[test] + fn provenance_is_optional_and_old_install_events_keep_their_wire_shape() { + let old = serde_json::json!({ + "sequence": 1, + "participant_id": 0, + "kind": { "kind": "program_installed", "data": { "module_hash": "h", "seed": 3 } } + }); + let parsed: WorldEvent = serde_json::from_value(old.clone()).unwrap(); + assert!(matches!( + parsed.kind, + WorldEventKind::ProgramInstalled { + provenance: None, + .. + } + )); + assert_eq!(serde_json::to_value(parsed).unwrap(), old); + + let event = WorldEvent { + sequence: 1, + participant_id: 0, + kind: WorldEventKind::ProgramInstalled { + module_hash: "h".to_owned(), + seed: 3, + provenance: Some(sample_source_provenance()), + }, + }; + let encoded = serde_json::to_value(&event).unwrap(); + assert_eq!( + serde_json::from_value::(encoded).unwrap(), + event + ); + } + + #[test] + fn checkpoint_defaults_missing_provenance_and_round_trips_recorded_provenance() { + let old = serde_json::json!({ + "entry": "checkpoint", + "sequence": 0, + "module_hash": "h", + "seed": 1, + "snapshot": "s", + "events": [] + }); + let parsed: JournalEntry = serde_json::from_value(old.clone()).unwrap(); + assert!(matches!( + parsed, + JournalEntry::Checkpoint { + provenance: None, + .. + } + )); + assert_eq!(serde_json::to_value(parsed).unwrap(), old); + } + + #[test] + fn recorded_provenance_survives_checkpoint_compaction_and_restore() { + let provenance = sample_source_provenance(); + let mut core = world(8); + core.active_module_hash = Some("h".to_owned()); + core.active_module_provenance = Some(provenance.clone()); + core.active_seed = 7; + let entries = core.checkpoint_entries("state".to_owned()).unwrap(); + + let restored = WorldCore::restore("test-world", WorldLimits::default(), entries).unwrap(); + assert_eq!( + restored.core.active_module_provenance, + Some(provenance.clone()) + ); + assert_eq!(restored.program.unwrap().provenance, Some(provenance)); + } + /// A program driven by numeric inputs: each input switches its `wants` /// script, and every host event is recorded. Request ids embed the input /// count, so re-sending an input asks again. diff --git a/pkgs/id/src/world_compile.rs b/pkgs/id/src/world_compile.rs index 84009d60ab..0873e6d479 100644 --- a/pkgs/id/src/world_compile.rs +++ b/pkgs/id/src/world_compile.rs @@ -189,7 +189,7 @@ pub async fn compile( compiler: &Compiler, granted: &[String], timeout: Duration, -) -> Result<(Vec, String)> { +) -> Result<(Vec, String, crate::world::ModuleProvenance)> { use crate::world_session::MAX_WORLD_MODULE_BYTES; validate_spec(spec)?; @@ -206,8 +206,10 @@ pub async fn compile( } else { "wasm32" }; + let source_blake3 = digest_sources(&spec.files)?; let job = tempfile::tempdir().context("create compile job directory")?; copy_platform(&compiler.platform_dir, job.path())?; + let platform_blake3 = digest_tree(&job.path().join("platform"))?; for (name, content) in &spec.files { let path = job.path().join(sanitize_file_name(name)?); tokio::fs::write(&path, content) @@ -223,7 +225,9 @@ pub async fn compile( tokio::fs::write(&main_path, rewritten).await?; let output_path = job.path().join("out"); - let roc_bin = resolve_program(&compiler.roc_bin); + let roc_bin = std::fs::canonicalize(resolve_program(&compiler.roc_bin)) + .context("resolve Roc compiler executable")?; + let compiler_blake3 = digest_file(&roc_bin)?; let job_dir = job.path().to_owned(); let output = PathBuf::from(&output_path); // The compiler is a whole LLVM process; run it on a blocking thread and @@ -240,6 +244,11 @@ pub async fn compile( if target == "wasm32" { args.push(format!("--wasm-memory={WASM_MEMORY_BYTES}")); } + let stable_arguments: Vec = args + .iter() + .filter(|argument| !argument.starts_with("--output=")) + .cloned() + .collect(); command .current_dir(&job_dir) .args(&args) @@ -290,9 +299,9 @@ pub async fn compile( }; let captured_err = readers.1.join().unwrap_or_default(); let captured_out = readers.0.join().unwrap_or_default(); - Ok((status, captured_err, captured_out)) + Ok((status, captured_err, captured_out, stable_arguments)) }); - let (status, captured_err, _captured_out) = run + let (status, captured_err, _captured_out, arguments) = run .await .context("compile task")? .map_err(|error| error.context("compilation failed"))?; @@ -302,6 +311,15 @@ pub async fn compile( tail(&captured_err, MAX_CAPTURE_BYTES) ); } + let provenance = + crate::world::ModuleProvenance::SourceBuild(crate::world::SourceBuildProvenance { + schema_version: 1, + compiler_blake3, + platform_blake3, + source_blake3, + target: target.to_owned(), + arguments, + }); let wasm = tokio::fs::read(&output_path) .await @@ -317,7 +335,7 @@ pub async fn compile( crate::world_native::is_native_module(&wasm), "the compiler did not produce a native executable" ); - return Ok((wasm, tail(&captured_err, MAX_CAPTURE_BYTES))); + return Ok((wasm, tail(&captured_err, MAX_CAPTURE_BYTES), provenance)); } // Same policy as an upload: import-free and allowlisted. #[cfg(feature = "sandbox")] @@ -329,7 +347,92 @@ pub async fn compile( }, ) .context("the compiled module is not a valid world module")?; - Ok((wasm, tail(&captured_err, MAX_CAPTURE_BYTES))) + Ok((wasm, tail(&captured_err, MAX_CAPTURE_BYTES), provenance)) +} + +fn digest_file(path: &Path) -> Result { + let mut file = std::fs::File::open(path).with_context(|| format!("open {}", path.display()))?; + let mut hasher = blake3::Hasher::new(); + hasher.update(b"roc-compiler-binary-v1\0"); + let mut buffer = [0_u8; 64 * 1024]; + loop { + use std::io::Read as _; + let read = file.read(&mut buffer)?; + if read == 0 { + break; + } + hasher.update(&buffer[..read]); + } + Ok(hasher.finalize().to_hex().to_string()) +} + +fn digest_tree(root: &Path) -> Result { + fn visit(root: &Path, dir: &Path, hasher: &mut blake3::Hasher) -> Result<()> { + let mut entries = std::fs::read_dir(dir) + .with_context(|| format!("read {}", dir.display()))? + .collect::>>()?; + entries.sort_by_key(std::fs::DirEntry::file_name); + for entry in entries { + ensure!( + !entry.file_type()?.is_symlink(), + "no symlinks in the platform" + ); + let path = entry.path(); + if path.is_dir() { + let relative = path.strip_prefix(root)?; + let name = relative.to_string_lossy(); + let name_bytes = name.as_bytes(); + let name_len = u64::try_from(name_bytes.len()).context("platform path length")?; + hasher.update(b"D"); + hasher.update(&name_len.to_le_bytes()); + hasher.update(name_bytes); + visit(root, &path, hasher)?; + continue; + } + let relative = path.strip_prefix(root)?; + let name = relative.to_string_lossy(); + let name_bytes = name.as_bytes(); + let name_len = u64::try_from(name_bytes.len()).context("platform path length")?; + hasher.update(b"F"); + hasher.update(&name_len.to_le_bytes()); + hasher.update(name_bytes); + let mut file = std::fs::File::open(&path)?; + let file_len = file.metadata()?.len(); + hasher.update(&file_len.to_le_bytes()); + let mut buffer = [0_u8; 64 * 1024]; + loop { + use std::io::Read as _; + let read = file.read(&mut buffer)?; + if read == 0 { + break; + } + hasher.update(&buffer[..read]); + } + } + Ok(()) + } + + let mut hasher = blake3::Hasher::new(); + visit(root, root, &mut hasher)?; + Ok(hasher.finalize().to_hex().to_string()) +} + +fn digest_sources(files: &[(String, String)]) -> Result { + let mut sorted: Vec<_> = files.iter().collect(); + sorted.sort_by(|left, right| left.0.cmp(&right.0)); + let mut hasher = blake3::Hasher::new(); + hasher.update(b"roc-source-files-v1\0"); + for (name, content) in sorted { + let name = name.as_bytes(); + let content = content.as_bytes(); + let name_len = u64::try_from(name.len()).context("source filename length")?; + let content_len = u64::try_from(content.len()).context("source file length")?; + hasher.update(&name_len.to_le_bytes()); + hasher.update(name); + hasher.update(&content_len.to_le_bytes()); + hasher.update(content); + } + Ok(hasher.finalize().to_hex().to_string()) } /// Copy the platform pieces a compilation needs (its `.roc` modules, including @@ -465,6 +568,43 @@ mod tests { assert!(validate_spec(&spec(many)).is_err()); } + #[test] + fn source_digest_is_independent_of_file_order_but_tracks_names_and_contents() { + let first = vec![ + ("main.roc".to_owned(), "app [] {}".to_owned()), + ("lib.roc".to_owned(), "value = 1".to_owned()), + ]; + let reversed = vec![first[1].clone(), first[0].clone()]; + assert_eq!( + digest_sources(&first).unwrap(), + digest_sources(&reversed).unwrap() + ); + + let changed = vec![ + first[0].clone(), + ("lib.roc".to_owned(), "value = 2".to_owned()), + ]; + assert_ne!( + digest_sources(&first).unwrap(), + digest_sources(&changed).unwrap() + ); + } + + #[test] + fn platform_digest_is_stable_and_includes_relative_names() { + let root = tempfile::tempdir().unwrap(); + std::fs::create_dir_all(root.path().join("targets/wasm32")).unwrap(); + std::fs::write(root.path().join("platform.roc"), "platform").unwrap(); + std::fs::write(root.path().join("targets/wasm32/host.wasm"), b"host").unwrap(); + + let before = digest_tree(root.path()).unwrap(); + assert_eq!(before, digest_tree(root.path()).unwrap()); + std::fs::create_dir(root.path().join("empty")).unwrap(); + assert_ne!(before, digest_tree(root.path()).unwrap()); + std::fs::write(root.path().join("targets/wasm32/host.wasm"), b"other").unwrap(); + assert_ne!(before, digest_tree(root.path()).unwrap()); + } + #[test] fn the_platform_path_is_rewritten_to_the_staged_copy() { let main = "app [program] { pf: platform \"../roc-world/platform.roc\" }\n"; @@ -509,7 +649,7 @@ mod tests { )) .unwrap(); eprintln!("PROBE roc={}", compiler.roc_bin); - let (wasm, _diagnostics) = compile( + let (wasm, _diagnostics, provenance) = compile( &CompileSpec { files: vec![("main.roc".to_owned(), counter)], seed: 42, @@ -521,6 +661,15 @@ mod tests { ) .await .unwrap(); + let crate::world::ModuleProvenance::SourceBuild(build) = provenance else { + panic!("source compilation must return build provenance"); + }; + assert_eq!(build.schema_version, 1); + assert_eq!(build.target, "wasm32"); + assert_eq!(build.arguments[0], "build"); + assert_eq!(build.compiler_blake3.len(), 64); + assert_eq!(build.platform_blake3.len(), 64); + assert_eq!(build.source_blake3.len(), 64); // The compiled module behaves like the checked-in one. let runner = crate::sandbox::Sandbox::compile(&wasm, crate::sandbox::SandboxLimits::default()) @@ -556,7 +705,7 @@ mod tests { "/examples/roc-screen/main.roc" )) .unwrap(); - let (wasm, _diagnostics) = compile( + let (wasm, _diagnostics, provenance) = compile( &CompileSpec { files: vec![("main.roc".to_owned(), app)], seed: 7, @@ -568,6 +717,10 @@ mod tests { ) .await .unwrap(); + assert!(matches!( + provenance, + crate::world::ModuleProvenance::SourceBuild(_) + )); let runner = crate::sandbox::Sandbox::compile(&wasm, crate::sandbox::SandboxLimits::default()) .unwrap(); @@ -621,7 +774,7 @@ mod tests { "/examples/roc-counter/main.roc" )) .unwrap(); - let (native, _diagnostics) = compile( + let (native, _diagnostics, provenance) = compile( &CompileSpec { files: vec![("main.roc".to_owned(), counter)], seed: 42, @@ -633,6 +786,10 @@ mod tests { ) .await .unwrap(); + assert!(matches!( + provenance, + crate::world::ModuleProvenance::SourceBuild(_) + )); assert!(crate::world_native::is_native_module(&native)); let job = tempfile::tempdir().unwrap(); let path = job.path().join("counter"); diff --git a/pkgs/id/src/world_net.rs b/pkgs/id/src/world_net.rs index b158eacc31..c821200433 100644 --- a/pkgs/id/src/world_net.rs +++ b/pkgs/id/src/world_net.rs @@ -31,6 +31,19 @@ use crate::world_session::{ /// variants; removing or changing one needs `/id-world/2`. pub const WORLD_ALPN: &[u8] = b"/id-world/1"; +/// Public module state returned by a world's `info` frame. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct WorldModuleInfo { + /// World identifier. + pub world_id: String, + /// Hash of the active module, if any. + pub active_module_hash: Option, + /// Server-observed build origin, if recorded by this host. + pub active_module_provenance: Option, + /// Latest committed world sequence. + pub current_sequence: u64, +} + /// Concurrent sessions allowed on one connection. const MAX_SESSIONS_PER_CONNECTION: usize = 16; @@ -656,6 +669,17 @@ impl WorldClient { /// /// Fails if the capability is refused or the stream breaks. pub async fn info(&mut self, capability: &str) -> Result<(String, Option, u64)> { + let info = self.info_details(capability).await?; + Ok(( + info.world_id, + info.active_module_hash, + info.current_sequence, + )) + } + + /// Query module state, including observed build provenance where available. + /// Older hosts that do not send provenance continue to decode as `None`. + pub async fn info_details(&mut self, capability: &str) -> Result { self.send_json(&serde_json::json!({ "type": "info", "capability": capability, @@ -675,7 +699,18 @@ impl WorldClient { let current_sequence = reply["current_sequence"] .as_u64() .context("host omitted sequence")?; - Ok((world_id, active_module_hash, current_sequence)) + let active_module_provenance = reply + .get("active_module_provenance") + .filter(|value| !value.is_null()) + .map(|value| serde_json::from_value(value.clone())) + .transpose() + .context("host sent invalid module provenance")?; + Ok(WorldModuleInfo { + world_id, + active_module_hash, + active_module_provenance, + current_sequence, + }) } _ => bail!( "{}", @@ -1085,9 +1120,13 @@ mod tests { let mut query = WorldClient::connect(&client_ep, addr.clone()) .await .unwrap(); - let (_, active, _) = query.info(&capability).await.unwrap(); + let info = query.info_details(&capability).await.unwrap(); query.close(); - assert_eq!(active.as_deref(), Some(hash.as_str())); + assert_eq!(info.active_module_hash.as_deref(), Some(hash.as_str())); + assert_eq!( + info.active_module_provenance, + Some(crate::world::ModuleProvenance::Artifact) + ); let mut fetch = WorldClient::connect(&client_ep, addr.clone()) .await diff --git a/pkgs/id/src/world_session.rs b/pkgs/id/src/world_session.rs index dc33fec839..813f1ac55b 100644 --- a/pkgs/id/src/world_session.rs +++ b/pkgs/id/src/world_session.rs @@ -258,6 +258,8 @@ enum ServerFrame<'a> { ModuleInfo { world_id: String, active_module_hash: Option, + #[serde(skip_serializing_if = "Option::is_none")] + active_module_provenance: Option, current_sequence: u64, }, /// One page of structured records, with the sequence they were read at. @@ -613,7 +615,7 @@ impl WorldService { .await .map_err(|error| format!("compile failed: {error:#}"))? .granted; - let (wasm, diagnostics) = + let (wasm, diagnostics, provenance) = crate::world_compile::compile(spec, compiler, &granted, COMPILE_TIMEOUT) .await .map_err(|error| { @@ -625,7 +627,15 @@ impl WorldService { .try_reserve_module_upload() .map_err(|error| format!("install failed: {error:?}"))?; let (_, sequence) = self - .install_wasm_reserved(supplied_admin, wasm, spec.seed, &hash, permit, true) + .install_wasm_reserved( + supplied_admin, + wasm, + spec.seed, + &hash, + permit, + true, + Some(provenance), + ) .await .map_err(|error| format!("install failed: {error:?}"))?; Ok((hash, sequence, diagnostics)) @@ -773,8 +783,16 @@ impl WorldService { claimed_hash: &str, ) -> Result<(String, u64), InstallError> { let permit = self.try_reserve_module_upload()?; - self.install_wasm_reserved(supplied_admin, wasm, seed, claimed_hash, permit, false) - .await + self.install_wasm_reserved( + supplied_admin, + wasm, + seed, + claimed_hash, + permit, + false, + None, + ) + .await } #[cfg(feature = "sandbox")] @@ -786,6 +804,7 @@ impl WorldService { claimed_hash: &str, _permit: OwnedSemaphorePermit, compiled_from_source: bool, + provenance: Option, ) -> Result<(String, u64), InstallError> { self.authorize_admin(supplied_admin) .map_err(|error| match error { @@ -797,6 +816,9 @@ impl WorldService { if self.source_only && !compiled_from_source { return Err(InstallError::RawModuleDisabled); } + if compiled_from_source && provenance.is_none() { + return Err(InstallError::InvalidModule); + } if wasm.is_empty() || wasm.len() > MAX_WORLD_MODULE_BYTES { return Err(InstallError::InvalidUpload); } @@ -896,7 +918,12 @@ impl WorldService { }; let installed = self .world - .install_program(module_hash.clone(), seed, guest) + .install_program_with_provenance( + module_hash.clone(), + seed, + Some(provenance.unwrap_or(crate::world::ModuleProvenance::Artifact)), + guest, + ) .await .map_err(|_| InstallError::Unavailable)?; if !matches!( @@ -1455,6 +1482,7 @@ async fn query_session(service: &WorldService, io: &mut I, first: &ServerFrame::ModuleInfo { world_id: snapshot.world_id, active_module_hash: snapshot.active_module_hash, + active_module_provenance: snapshot.active_module_provenance, current_sequence: snapshot.current_sequence, }, ) @@ -1740,6 +1768,7 @@ async fn install_module_session( &actual_hash, upload_permit, false, + None, ) .await .map_err(|error| match error { diff --git a/pkgs/id/src/world_store.rs b/pkgs/id/src/world_store.rs index 70f5d77ec0..967eab2f0c 100644 --- a/pkgs/id/src/world_store.rs +++ b/pkgs/id/src/world_store.rs @@ -1047,6 +1047,7 @@ mod tests { kind: crate::world::WorldEventKind::ProgramInstalled { module_hash: "h".to_owned(), seed: 1, + provenance: None, }, }, }); @@ -1054,6 +1055,7 @@ mod tests { sequence: 1, module_hash: "h".to_owned(), seed: 1, + provenance: None, snapshot: "s".to_owned(), events: Vec::new(), }); From fd66aa094820c191dbe17d7688e92551c560fc1e Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Fri, 16 Oct 2026 04:11:24 -0500 Subject: [PATCH 2/2] docs(id): record world provenance design --- ...-30-00Z_feature_world_module_provenance.md | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 doc/2026-10-16T09-30-00Z_feature_world_module_provenance/2026-10-16T09-30-00Z_feature_world_module_provenance.md diff --git a/doc/2026-10-16T09-30-00Z_feature_world_module_provenance/2026-10-16T09-30-00Z_feature_world_module_provenance.md b/doc/2026-10-16T09-30-00Z_feature_world_module_provenance/2026-10-16T09-30-00Z_feature_world_module_provenance.md new file mode 100644 index 0000000000..68ad124f57 --- /dev/null +++ b/doc/2026-10-16T09-30-00Z_feature_world_module_provenance/2026-10-16T09-30-00Z_feature_world_module_provenance.md @@ -0,0 +1,30 @@ +# World module build provenance + +See the [Phase 9 plan](../../../../.opencode/plans/phase-9-portable-platform.md) and the [platform-level decision record](../../../../doc/2026-10-16T09-00-00Z_feature_world_module_provenance/2026-10-16T09-00-00Z_feature_world_module_provenance.md). + +## Intent + +P9.3 needs an auditable distinction between a module compiled from source by the server and a raw artifact uploaded by an administrator. The record must survive restart and compaction without claiming that a source build is trustworthy. It must not store source text, administrator credentials, or change the sandbox policy. + +## Initial design + +- Use an optional, versioned `ModuleProvenance` value: `artifact` or `source_build`. +- For source builds, capture domain-separated BLAKE3 digests for the configured compiler executable, staged platform tree, and submitted source files, plus target and the stable compiler argument vector. Exclude the temporary output path. +- Persist provenance on the existing program-install journal event and checkpoint. Optional fields with Serde defaults preserve old journal decoding; missing provenance remains unknown. +- Expose the value as an optional field in module info while retaining the existing tuple-based `WorldClient::info` API. +- Keep this as server-observed metadata, not a signature, human identity, source attestation, or reproducibility claim. + +## Rollout update + +The initial slice is implemented in `world_compile.rs`, `world.rs`, `world_session.rs`, and `world_net.rs`. The module event and checkpoint carry provenance through replay and compaction. Raw network artifact installs are explicitly labeled; older/direct installs without metadata remain `None`. `WorldClient::info_details` exposes the optional record without breaking `info` callers. + +Focused tests cover deterministic digesting, legacy event/checkpoint decoding, checkpoint restore, and module-info reporting. Full per-world runtime profiles, expanded capability ceilings, and a human-readable compiler version are intentionally separate follow-ups. + +## References + +- [Phase 9 plan](../../../../.opencode/plans/phase-9-portable-platform.md) +- [Platform-level provenance record](../../../../doc/2026-10-16T09-00-00Z_feature_world_module_provenance/2026-10-16T09-00-00Z_feature_world_module_provenance.md) +- `pkgs/id/src/world_compile.rs` +- `pkgs/id/src/world.rs` +- `pkgs/id/src/world_session.rs` +- `pkgs/id/src/world_net.rs`