Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 35 additions & 1 deletion pkgs/id/crates/id-worlds/src/program_bundle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
//!
Expand Down Expand Up @@ -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`].
Expand Down Expand Up @@ -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]
Expand Down
62 changes: 61 additions & 1 deletion pkgs/id/crates/id-worlds/src/world/journal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -727,19 +727,79 @@ 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,
/// version 4 for entries persisting a per-world total memory budget, version 5
/// 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>| {
Expand Down
57 changes: 53 additions & 4 deletions pkgs/id/crates/id-worlds/src/world/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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<crate::program_bundle::ProgramIdentity>,
/// The author's licence statement, if any.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub licence: Option<String>,
/// 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
Expand Down
106 changes: 101 additions & 5 deletions pkgs/id/crates/id-worlds/src/world/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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<ModuleProvenance>) -> 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.
Expand Down
45 changes: 45 additions & 0 deletions pkgs/id/crates/id-worlds/src/world_session/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Loading