diff --git a/pkgs/id/crates/id-worlds/src/program_bundle.rs b/pkgs/id/crates/id-worlds/src/program_bundle.rs index b6c62ac83c..c1a6b9038e 100644 --- a/pkgs/id/crates/id-worlds/src/program_bundle.rs +++ b/pkgs/id/crates/id-worlds/src/program_bundle.rs @@ -16,7 +16,8 @@ //! //! Everything here is a pure function over bytes: export, verify and fork //! need no server, registry or network (invariant 1, "sideloading always -//! works"). Importing a verified bundle into a world is the next slice. +//! works"). `WorldService::install_bundle` (under the `sandbox` feature) +//! sideloads a verified bundle into a world and records its provenance. //! //! # File layout //! @@ -224,6 +225,18 @@ impl BundleError { } } +/// Why a sideloaded bundle was not installed into a world. +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum BundleInstallError { + /// The bundle itself failed verification; the error names the check. + #[error(transparent)] + Bundle(BundleError), + /// The bundle verified, but the world refused the install exactly as it + /// would refuse the same signed upload. + #[error("the verified bundle was not installed: {0:?}")] + Install(crate::world_session::InstallError), +} + /// A bundle whose framing, manifest, lineage, ABI, content hash and both /// signatures have all verified. The only way to hold one is through /// [`ProgramBundle::decode`], [`export`] or [`fork`]. @@ -318,6 +331,27 @@ impl ProgramBundle { &self.payload } + /// The verified bundle signature, lower-case hex. + #[must_use] + pub fn bundle_signature(&self) -> &str { + &self.seal.bundle_signature + } + + /// The install record a world keeps for this bundle (design D4). The + /// policy is pinned: an update is a new install decision. + #[must_use] + pub fn provenance(&self) -> crate::world::BundleProvenance { + crate::world::BundleProvenance { + schema_version: 1, + program: self.identity(), + abi: self.manifest.abi.clone(), + lineage: self.manifest.lineage.clone(), + licence: self.manifest.licence.clone(), + bundle_signature: self.seal.bundle_signature.clone(), + policy: crate::world::InstallPolicy::Pinned, + } + } + /// The F12.17 signature to present when installing the payload into a /// world with a publisher trust list. #[must_use] diff --git a/pkgs/id/crates/id-worlds/src/world/journal.rs b/pkgs/id/crates/id-worlds/src/world/journal.rs index a0bbb662bb..65ae1e778d 100644 --- a/pkgs/id/crates/id-worlds/src/world/journal.rs +++ b/pkgs/id/crates/id-worlds/src/world/journal.rs @@ -727,10 +727,18 @@ pub const JOURNAL_VERSION_SIGNED_PLAY: u32 = 9; /// the journal at the header check. pub const JOURNAL_VERSION_PORTALS: u32 = 10; +/// Header version of a journal that records a program-bundle install. +/// +/// That is a `ProgramInstalled` event, or a checkpoint, whose provenance is +/// [`ModuleProvenance::Bundle`] (#8280). Version-10 binaries cannot parse +/// that provenance and would fail mid-replay, so they must refuse the +/// journal at the header check. +pub const JOURNAL_VERSION_PROGRAM_BUNDLE: u32 = 11; + /// Newest journal version this binary can read. Journals with a higher /// header version are refused at the header check, before any entry is /// applied. -pub const MAX_JOURNAL_VERSION: u32 = JOURNAL_VERSION_PORTALS; +pub const MAX_JOURNAL_VERSION: u32 = JOURNAL_VERSION_PROGRAM_BUNDLE; /// The header version a journal must carry once it contains `entry`: version 2 /// for execution-profile entries, version 3 for region-handoff entries, @@ -738,8 +746,60 @@ pub const MAX_JOURNAL_VERSION: u32 = JOURNAL_VERSION_PORTALS; /// for checkpoints with open-presence metadata, and version 6 for checkpoint /// part entries. Checkpoints combine the requirements of their transfers, /// retained events, profile and presence field. +/// +/// Any entry that records a program-bundle install additionally requires +/// [`JOURNAL_VERSION_PROGRAM_BUNDLE`]. #[must_use] pub fn journal_version_required_by(entry: &JournalEntry) -> u32 { + let kind = entry_kind_version(entry); + if records_bundle_install(entry) { + kind.max(JOURNAL_VERSION_PROGRAM_BUNDLE) + } else { + kind + } +} + +/// Whether `event` installs a program from a bundle. +const fn is_bundle_install(event: &WorldEvent) -> bool { + matches!( + &event.kind, + WorldEventKind::ProgramInstalled { + provenance: Some(provenance), + .. + } if provenance.is_bundle() + ) +} + +/// Whether `entry` carries bundle provenance anywhere a reader must parse it. +fn records_bundle_install(entry: &JournalEntry) -> bool { + match entry { + JournalEntry::Committed { event } | JournalEntry::System { event } => { + is_bundle_install(event) + } + JournalEntry::EntityExported { source_event, .. } => is_bundle_install(source_event), + JournalEntry::EntityImported { + destination_event, .. + } => is_bundle_install(destination_event), + JournalEntry::CheckpointEventsPart { events, .. } + | JournalEntry::CheckpointAdminPart { events, .. } => events.iter().any(is_bundle_install), + JournalEntry::Checkpoint { + provenance, + events, + admin_history, + .. + } => { + provenance.as_ref().is_some_and(ModuleProvenance::is_bundle) + || events.iter().any(is_bundle_install) + || admin_history + .as_ref() + .is_some_and(|history| history.events.iter().any(is_bundle_install)) + } + _ => false, + } +} + +/// The version `entry`'s own kind and fields require, before provenance. +fn entry_kind_version(entry: &JournalEntry) -> u32 { // A persisted budget always requires the budget version, on top of any // version the entry kind itself already requires. let budget_version = |profile: Option<&crate::world_limits::WorldExecutionProfile>| { diff --git a/pkgs/id/crates/id-worlds/src/world/mod.rs b/pkgs/id/crates/id-worlds/src/world/mod.rs index 11c2b7be44..c25caf36bb 100644 --- a/pkgs/id/crates/id-worlds/src/world/mod.rs +++ b/pkgs/id/crates/id-worlds/src/world/mod.rs @@ -83,10 +83,11 @@ pub(crate) use journal::JournalAdminHistory; pub use journal::{ CoordinatorJournalEntry, JOURNAL_VERSION, JOURNAL_VERSION_CHECKPOINT_PARTS, JOURNAL_VERSION_EXECUTION_PROFILE, JOURNAL_VERSION_OPEN_PRESENCE, JOURNAL_VERSION_PORTALS, - JOURNAL_VERSION_REGION_HANDOFF, JOURNAL_VERSION_SCHEDULE_RECURRENCE, - JOURNAL_VERSION_SIGNED_PLAY, JOURNAL_VERSION_WORLD_BUDGET, JOURNAL_VERSION_WRITE_LEASE, - JournalEntry, JournalSignedMove, JournalSnapshot, JournalSnapshotSource, MAX_JOURNAL_VERSION, - TrustBasis, TrustDecision, WorldJournal, journal_version_required_by, + JOURNAL_VERSION_PROGRAM_BUNDLE, JOURNAL_VERSION_REGION_HANDOFF, + JOURNAL_VERSION_SCHEDULE_RECURRENCE, JOURNAL_VERSION_SIGNED_PLAY, JOURNAL_VERSION_WORLD_BUDGET, + JOURNAL_VERSION_WRITE_LEASE, JournalEntry, JournalSignedMove, JournalSnapshot, + JournalSnapshotSource, MAX_JOURNAL_VERSION, TrustBasis, TrustDecision, WorldJournal, + journal_version_required_by, }; pub use metrics::{ HistogramSnapshot, MetricsSnapshot, RegionWrites, WorldMetrics, WriteLocalitySnapshot, @@ -339,6 +340,54 @@ pub enum ModuleProvenance { /// The module was forked from another world: the world's state and module /// were copied at the fork point, with the origin recorded. Fork(ForkProvenance), + /// The module was sideloaded from a verified program bundle (#8280, + /// design D4): the install record names the bundle's identity, ABI, + /// lineage and signature. Journals carrying it need + /// [`JOURNAL_VERSION_PROGRAM_BUNDLE`]. + Bundle(BundleProvenance), +} + +impl ModuleProvenance { + /// Whether this provenance is a program-bundle install, which an older + /// binary cannot read. + #[must_use] + pub const fn is_bundle(&self) -> bool { + matches!(self, Self::Bundle(_)) + } +} + +/// How a bundle install follows later versions of its program (D4). Only +/// pinned exists today: an update is a new install decision. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum InstallPolicy { + /// Exactly this content hash; nothing changes without a new install. + #[default] + Pinned, +} + +/// The install record of a sideloaded program bundle (#8280). +/// +/// It keeps what the verified bundle stated with the install event, so the +/// world's history says which program, by whom, forked from what, is +/// running. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct BundleProvenance { + /// Provenance record schema, independent of the world journal version. + pub schema_version: u8, + /// The program's D1 identity; its content hash is the module hash. + pub program: crate::program_bundle::ProgramIdentity, + /// The guest ABI the bundle declared. + pub abi: crate::program_bundle::AbiDescriptor, + /// Ancestors, oldest first; empty for an original. + pub lineage: Vec, + /// The author's licence statement, if any. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub licence: Option, + /// The verified bundle signature, lower-case hex. + pub bundle_signature: String, + /// How this install follows later versions. + pub policy: InstallPolicy, } /// Provenance recorded when one world is forked from another (F12.2). It diff --git a/pkgs/id/crates/id-worlds/src/world/tests.rs b/pkgs/id/crates/id-worlds/src/world/tests.rs index a86ac3ef53..c40507a2f4 100644 --- a/pkgs/id/crates/id-worlds/src/world/tests.rs +++ b/pkgs/id/crates/id-worlds/src/world/tests.rs @@ -1674,11 +1674,12 @@ mod tests { "{entry:?}" ); } - // The max-version pin moved to version 10 with portal grants - // (F12.14 wiring, code#1068), after version 9 for signed play - // (#4346) and version 8 for recurring schedules (#1355); - // the lease entries still require exactly 7. - assert_eq!(MAX_JOURNAL_VERSION, JOURNAL_VERSION_PORTALS); + // The max-version pin moved to version 11 with program-bundle + // installs (#8280), after version 10 for portal grants (F12.14 + // wiring, code#1068), version 9 for signed play (#4346) and + // version 8 for recurring schedules (#1355); the lease entries + // still require exactly 7. + assert_eq!(MAX_JOURNAL_VERSION, JOURNAL_VERSION_PROGRAM_BUNDLE); // A checkpoint carrying a non-bootstrap lease also requires // version 7; one without a lease keeps its existing version. let mut lease = WriteLease::bootstrap(); @@ -2706,6 +2707,101 @@ mod tests { assert_eq!(restored.program.unwrap().provenance, Some(provenance)); } + fn sample_bundle_provenance() -> ModuleProvenance { + let author = ed25519_dalek::SigningKey::from_bytes(&[7; 32]); + let bundle = crate::program_bundle::export( + b"bundle payload".to_vec(), + crate::program_bundle::ProgramSpec { + name: "chess", + version: 1, + licence: None, + }, + &author, + ) + .unwrap(); + ModuleProvenance::Bundle(bundle.provenance()) + } + + fn install_event(provenance: Option) -> WorldEvent { + WorldEvent { + sequence: 1, + participant_id: 0, + kind: WorldEventKind::ProgramInstalled { + module_hash: "h".to_owned(), + seed: 1, + provenance, + trust: None, + }, + } + } + + /// #8280: an older binary cannot parse bundle provenance, so every entry + /// that carries it raises the header to the program-bundle version, and + /// nothing else does. + #[test] + fn bundle_provenance_requires_the_program_bundle_journal_version() { + let bundle = sample_bundle_provenance(); + let committed = |provenance| JournalEntry::Committed { + event: install_event(provenance), + }; + assert_eq!( + journal_version_required_by(&committed(Some(bundle.clone()))), + JOURNAL_VERSION_PROGRAM_BUNDLE + ); + assert_eq!( + journal_version_required_by(&committed(Some(ModuleProvenance::Artifact))), + JOURNAL_VERSION + ); + assert_eq!( + journal_version_required_by(&committed(None)), + JOURNAL_VERSION + ); + let part = JournalEntry::CheckpointEventsPart { + sequence: 1, + part_index: 0, + part_count: 1, + events: vec![install_event(Some(bundle))], + }; + assert_eq!( + journal_version_required_by(&part), + JOURNAL_VERSION_PROGRAM_BUNDLE + ); + let plain_part = JournalEntry::CheckpointEventsPart { + sequence: 1, + part_index: 0, + part_count: 1, + events: vec![install_event(None)], + }; + assert_eq!( + journal_version_required_by(&plain_part), + JOURNAL_VERSION_CHECKPOINT_PARTS + ); + } + + #[test] + fn bundle_provenance_survives_checkpoint_compaction_and_restore() { + let provenance = sample_bundle_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(); + assert!( + entries.iter().any(|entry| matches!( + entry, + JournalEntry::Created { version, .. } if *version == JOURNAL_VERSION_PROGRAM_BUNDLE + )), + "the compacted header carries the program-bundle version: {entries:?}" + ); + + 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/crates/id-worlds/src/world_session/service.rs b/pkgs/id/crates/id-worlds/src/world_session/service.rs index 8f7c0a0c1c..4db30c97e2 100644 --- a/pkgs/id/crates/id-worlds/src/world_session/service.rs +++ b/pkgs/id/crates/id-worlds/src/world_session/service.rs @@ -537,6 +537,51 @@ impl WorldService { .await } + /// Sideload a program bundle file (#8280, design D2/D4), fully offline. + /// + /// The bundle is verified first (framing, manifest, ABI, lineage, + /// content hash and both signatures), then its payload installs through + /// the same path as a signed upload: the admin check, the source-only + /// policy and the module trust list apply unchanged, with the bundle's + /// F12.17 module signature presented to the trust gate. The install + /// event records the bundle's identity, lineage, signature and pinned + /// policy as [`crate::world::ModuleProvenance::Bundle`]. + /// + /// # Errors + /// + /// [`BundleInstallError::Bundle`] naming the failed check when the file + /// does not verify, or [`BundleInstallError::Install`] when the world + /// refuses the verified payload. + #[cfg(feature = "sandbox")] + pub async fn install_bundle( + &self, + supplied_admin: Option<&str>, + bundle: &[u8], + seed: u64, + ) -> Result<(String, u64), crate::program_bundle::BundleInstallError> { + use crate::program_bundle::{BundleInstallError, ProgramBundle}; + + let bundle = ProgramBundle::decode(bundle).map_err(BundleInstallError::Bundle)?; + let signature = bundle.module_signature(); + let provenance = crate::world::ModuleProvenance::Bundle(bundle.provenance()); + let hash = bundle.manifest().content_hash.clone(); + let permit = self + .try_reserve_module_upload() + .map_err(BundleInstallError::Install)?; + self.install_wasm_reserved( + supplied_admin, + bundle.payload().to_vec(), + seed, + &hash, + permit, + false, + Some(provenance), + Some(&signature), + ) + .await + .map_err(BundleInstallError::Install) + } + #[cfg(feature = "sandbox")] pub(super) async fn install_wasm_reserved( &self, diff --git a/pkgs/id/crates/id-worlds/src/world_session/tests.rs b/pkgs/id/crates/id-worlds/src/world_session/tests.rs index 751dc8db86..f36a38b8cf 100644 --- a/pkgs/id/crates/id-worlds/src/world_session/tests.rs +++ b/pkgs/id/crates/id-worlds/src/world_session/tests.rs @@ -3366,6 +3366,117 @@ mod tests { ); } + /// #8280 slice 2: a bundle exported and forked offline sideloads into a + /// fresh trust-listed world, runs, and the install record matches the + /// bundle; tampered and untrusted bundles install nothing. + #[cfg(feature = "sandbox")] + #[tokio::test] + async fn sideloaded_bundle_installs_with_its_identity_lineage_and_signature() { + use crate::program_bundle::{BundleInstallError, ProgramSpec, export, fork}; + use iroh_blobs::store::mem::MemStore; + + let wasm = include_bytes!("../../../../examples/roc-counter/counter.wasm").to_vec(); + let original_author = SigningKey::from_bytes(&[41; 32]); + let forker = SigningKey::from_bytes(&[42; 32]); + let spec = |name| ProgramSpec { + name, + version: 1, + licence: Some("MIT"), + }; + let parent = export(wasm.clone(), spec("counter"), &original_author).unwrap(); + let bundle = fork(&parent, wasm.clone(), spec("counter-plus"), &forker).unwrap(); + let file = bundle.to_bytes(); + + let journal = CapturingJournal::default(); + let world = WorldHandle::spawn_durable( + WorldCore::new("sideload", WorldLimits::default()).unwrap(), + Box::new(NoProgram), + Some(Box::new(journal.clone())), + ); + let service = WorldService::new(world, Some("admin".to_owned())) + .with_blob_store(MemStore::new().into()) + .with_module_trust_keys(vec![forker.verifying_key().to_bytes()]); + + let mut tampered = file.clone(); + let last = tampered.len() - 1; + tampered[last] ^= 1; + match service.install_bundle(Some("admin"), &tampered, 5).await { + Err(BundleInstallError::Bundle(error)) => { + assert_eq!(error.check(), "content_hash", "{error}"); + } + other => panic!("a tampered bundle must fail verification: {other:?}"), + } + assert_eq!( + service + .install_bundle(Some("admin"), &parent.to_bytes(), 5) + .await, + Err(BundleInstallError::Install(InstallError::UntrustedModule)), + "the trust list still governs whose bundles install" + ); + assert_eq!( + service.install_bundle(Some("wrong"), &file, 5).await, + Err(BundleInstallError::Install(InstallError::Unauthorized)) + ); + let installs = |entries: &[crate::world::JournalEntry]| { + entries + .iter() + .filter(|entry| { + matches!( + entry, + crate::world::JournalEntry::Committed { event } + if matches!(event.kind, crate::world::WorldEventKind::ProgramInstalled { .. }) + ) + }) + .count() + }; + assert_eq!(installs(&journal.entries()), 0, "refusals install nothing"); + + let (hash, _) = service + .install_bundle(Some("admin"), &file, 5) + .await + .expect("a verified bundle from a trusted author installs offline"); + assert_eq!(hash, bundle.identity().content_hash); + + let entries = journal.entries(); + let recorded = entries + .iter() + .find_map(|entry| match entry { + crate::world::JournalEntry::Committed { event } => match &event.kind { + crate::world::WorldEventKind::ProgramInstalled { + module_hash, + provenance: Some(crate::world::ModuleProvenance::Bundle(provenance)), + trust, + .. + } => Some(( + module_hash.clone(), + provenance.clone(), + trust.clone(), + entry, + )), + _ => None, + }, + _ => None, + }) + .expect("the install event records bundle provenance"); + let (module_hash, provenance, trust, entry) = recorded; + assert_eq!(module_hash, hash); + assert_eq!(provenance, bundle.provenance()); + assert_eq!(provenance.program, bundle.identity()); + assert_eq!(provenance.lineage, vec![parent.identity()]); + assert_eq!(provenance.bundle_signature, bundle.bundle_signature()); + assert_eq!(provenance.policy, crate::world::InstallPolicy::Pinned); + let trust = trust.expect("the trust decision rides on the install event"); + assert_eq!(trust.basis, crate::world::TrustBasis::SignatureVerified); + assert_eq!( + trust.publisher.as_deref(), + Some(provenance.program.author.as_str()) + ); + assert_eq!( + crate::world::journal_version_required_by(entry), + crate::world::JOURNAL_VERSION_PROGRAM_BUNDLE + ); + } + #[cfg(feature = "sandbox")] #[tokio::test] async fn joined_guest_install_is_actor_denied_and_journals_nothing() {