diff --git a/pkgs/id/contract/shell-contract.v1.json b/pkgs/id/contract/shell-contract.v1.json index c6bd4ca2ca..c891ffcac8 100644 --- a/pkgs/id/contract/shell-contract.v1.json +++ b/pkgs/id/contract/shell-contract.v1.json @@ -1,7 +1,7 @@ { "contract": "id-shell", "version": 1, - "revision": 2, + "revision": 3, "description": "The client-server frame protocol every id shell (terminal, web, native) speaks to a world host. Version 1 is the protocol behind the /id-world/1 ALPN. A shell sends only frames and fields named here; it ignores server frame types and fields it does not know. Additive changes bump `revision`; removing or changing a frame or field needs version 2 and a new ALPN. A new frame kind waits for the journal format work (F11.12, #227).", "max_frame_bytes": 1048576, "routing_fields": ["world"], @@ -80,6 +80,12 @@ "opens": "query", "fields": { "capability": "string", "module_hash": "string" } }, + "download_module_admin": { + "class": "admin", + "phases": ["opening"], + "opens": "closed", + "fields": { "admin_token": "string", "module_hash": "string" } + }, "caps": { "class": "query", "phases": ["opening", "joined"], diff --git a/pkgs/id/src/commands/world.rs b/pkgs/id/src/commands/world.rs index 05181a7cb7..6bf77adcdb 100644 --- a/pkgs/id/src/commands/world.rs +++ b/pkgs/id/src/commands/world.rs @@ -463,8 +463,8 @@ pub async fn cmd_world(command: WorldCommand) -> Result<()> { no_relay, } => { let manifest = parse_manifest_file(&file)?; - let (endpoint, mut client) = connect(&node, &addrs, no_relay, world.as_deref()).await?; - let state = current_world_state(&mut client, &capability, None).await?; + let (endpoint, client) = connect(&node, &addrs, no_relay, world.as_deref()).await?; + let state = current_world_state(&client, &capability, None).await?; client.close(); endpoint.close().await; print!("{}", crate::world_manifest::diff(&manifest, &state)); @@ -481,8 +481,8 @@ pub async fn cmd_world(command: WorldCommand) -> Result<()> { no_relay, } => { let manifest = parse_manifest_file(&file)?; - let (endpoint, mut client) = connect(&node, &addrs, no_relay, world.as_deref()).await?; - let state = current_world_state(&mut client, &capability, Some(&admin_token)).await?; + let (endpoint, client) = connect(&node, &addrs, no_relay, world.as_deref()).await?; + let state = current_world_state(&client, &capability, Some(&admin_token)).await?; let steps = crate::world_manifest::plan(&manifest, &state); if steps.is_empty() { println!("no drift"); @@ -497,7 +497,7 @@ pub async fn cmd_world(command: WorldCommand) -> Result<()> { ); if !dry_run { let applied = - apply_steps(&mut client, &admin_token, &capability, &steps).await?; + apply_steps(&client, &admin_token, &capability, &steps).await?; if applied == steps.len() { println!("applied {} step(s)", applied); } else { @@ -872,17 +872,34 @@ fn parse_manifest_file(file: &std::path::Path) -> Result, ) -> Result { - let info = client.info_details(capability).await?; - let caps: crate::world_caps::CapsReport = - serde_json::from_value(client.caps(capability).await?) - .context("host returned a malformed capability report")?; - let profile: crate::world_limits::WorldExecutionProfile = - serde_json::from_value(client.execution_profile(None, Some(capability)).await?) - .context("host returned a malformed execution profile")?; + // One fresh session per read: admin and query frames are served one + // operation per stream, so sequencing these reads on one stream would + // talk to a session the host already finished. + let info = client + .fresh_session() + .await? + .info_details(capability) + .await?; + let caps: crate::world_caps::CapsReport = serde_json::from_value( + client + .fresh_session() + .await? + .caps(capability) + .await?, + ) + .context("host returned a malformed capability report")?; + let profile: crate::world_limits::WorldExecutionProfile = serde_json::from_value( + client + .fresh_session() + .await? + .execution_profile(None, Some(capability)) + .await?, + ) + .context("host returned a malformed execution profile")?; // The report carries the world's own ceiling as a list; an unrestricted // ceiling is the whole catalog, which we fold back to "no ceiling". let ceiling = if caps.ceiling @@ -894,7 +911,11 @@ async fn current_world_state( } else { Some(caps.ceiling.clone()) }; - let (seed, schedules) = client.manifest_state(admin_token, Some(capability)).await?; + let (seed, schedules) = client + .fresh_session() + .await? + .manifest_state(admin_token, Some(capability)) + .await?; Ok(crate::world_manifest::WorldState { module_hash: info.active_module_hash, seed: seed.unwrap_or(0), @@ -929,19 +950,58 @@ fn step_is_applied(step: &crate::world_manifest::ApplyStep) -> bool { /// set/cancel — each journaled by the host. Returns how many of the steps /// were actually applied, so the caller's summary cannot claim credit for /// any step whose apply path is missing (#818). +/// +/// The steps run in an order that makes the plan's result reachable, not +/// strictly in plan order (#807): schedule cancels first, so a manifest +/// that replaces ids at the pending-schedule capacity frees the slots its +/// additions need; the execution profile next, so a module installed in +/// the same apply is instantiated under the manifest's profile, not the +/// previous one (a profile applies on the next install); grants and +/// ceiling next, so a module compiled in the same apply may import the +/// capabilities the manifest grants; then the module install; schedule +/// additions last. +/// +/// Each operation runs on a fresh session (see +/// [`WorldClient::fresh_session`]): the host serves admin frames one +/// operation per stream, so a second operation on the same stream would +/// write to a session that no longer has a receiver. +/// Order steps for reachability (see [`apply_steps`]): cancellations +/// first, then profile, grants and ceiling, then the module install, +/// and schedule additions last. The sort is stable, so steps of the +/// same kind keep their plan order. +fn ordered_steps<'a>( + steps: &'a [crate::world_manifest::ApplyStep], +) -> Vec<&'a crate::world_manifest::ApplyStep> { + use crate::world_manifest::ApplyStep; + fn rank(step: &ApplyStep) -> u8 { + match step { + ApplyStep::CancelSchedule { .. } => 0, + ApplyStep::SetProfile { .. } => 1, + ApplyStep::SetGrants { .. } => 2, + ApplyStep::SetCeiling { .. } => 3, + ApplyStep::InstallModule { .. } => 4, + ApplyStep::ScheduleAt { .. } => 5, + } + } + let mut ordered: Vec<&ApplyStep> = steps.iter().collect(); + ordered.sort_by_key(|step| rank(step)); + ordered +} + async fn apply_steps( - client: &mut WorldClient, + client: &WorldClient, admin_token: &str, capability: &str, steps: &[crate::world_manifest::ApplyStep], ) -> Result { use crate::world_manifest::ApplyStep; let applied = steps.iter().filter(|step| step_is_applied(step)).count(); - for step in steps { + let ordered = ordered_steps(steps); + for step in ordered { match step { ApplyStep::SetGrants { grants } => { let current: crate::world_caps::CapsReport = - serde_json::from_value(client.caps(capability).await?) + serde_json::from_value(client.fresh_session().await?.caps(capability).await?) .context("host returned a malformed capability report")?; let to_revoke: Vec = current .granted @@ -956,6 +1016,8 @@ async fn apply_steps( .collect(); if !to_grant.is_empty() || !to_revoke.is_empty() { client + .fresh_session() + .await? .update_caps(admin_token, &to_grant, &to_revoke) .await?; } @@ -967,29 +1029,29 @@ async fn apply_steps( .into_iter() .collect::>() }); - client.set_caps_ceiling(admin_token, &names).await?; + client.fresh_session().await?.set_caps_ceiling(admin_token, &names).await?; } ApplyStep::SetProfile { profile } => { - client.set_execution_profile(admin_token, *profile).await?; + client.fresh_session().await?.set_execution_profile(admin_token, *profile).await?; } ApplyStep::InstallModule { hash, source, seed } => { if let Some(source) = source { let sources = read_compile_sources(source)?; - client.compile(admin_token, sources, *seed, false).await?; + client.fresh_session().await?.compile(admin_token, sources, *seed, false).await?; } else if let Some(hash) = hash { // The module is already on the host: fetch its bytes by // hash and install them under the manifest's seed. - let wasm = client.download_module(capability, hash).await?; - client.install_wasm(admin_token, &wasm, *seed).await?; + let wasm = client.fresh_session().await?.download_module_admin(admin_token, hash).await?; + client.fresh_session().await?.install_wasm(admin_token, &wasm, *seed).await?; } else { anyhow::bail!("install_module step names neither a hash nor a source"); } } ApplyStep::ScheduleAt { id, at_ms } => { - client.set_schedule(admin_token, id, *at_ms).await?; + client.fresh_session().await?.set_schedule(admin_token, id, *at_ms).await?; } ApplyStep::CancelSchedule { id } => { - client.cancel_schedule(admin_token, id).await?; + client.fresh_session().await?.cancel_schedule(admin_token, id).await?; } } } @@ -1669,6 +1731,49 @@ mod tests { assert_eq!(applied, steps.len()); } + /// The execution order is what makes a plan reachable (#807): a + /// cancellation frees the schedule slot an addition needs, and the + /// profile, grants and ceiling all land before the module step that + /// compiles or installs under them. + #[test] + fn apply_steps_run_in_reachability_order() { + use crate::world_manifest::ApplyStep; + let steps = [ + ApplyStep::ScheduleAt { + id: "new".to_owned(), + at_ms: 5, + }, + ApplyStep::InstallModule { + hash: None, + source: Some(std::path::PathBuf::from("main.roc")), + seed: 0, + }, + ApplyStep::SetCeiling { ceiling: None }, + ApplyStep::SetGrants { grants: vec![] }, + ApplyStep::SetProfile { + profile: crate::world_limits::WorldExecutionProfile::default(), + }, + ApplyStep::CancelSchedule { + id: "old".to_owned(), + }, + ]; + let kinds: Vec<&str> = super::ordered_steps(&steps) + .iter() + .map(|step| step.kind()) + .collect(); + assert_eq!( + kinds, + [ + "cancel_schedule", + "set_profile", + "set_grants", + "set_ceiling", + "install_module", + "schedule_at" + ] + ); + } + /// A manifest `module_source` that names a directory compiles its /// `main.roc` plus the sibling `.roc` files (and nothing else); a plain /// file compiles alone, always sent as `main.roc`. @@ -1755,7 +1860,7 @@ mod tests { .join("\n"); assert_eq!( check_contract(&good).unwrap(), - "3 frames conform to shell contract v1.2" + "3 frames conform to shell contract v1.3" ); let bad = [ r#"{"from": "client", "frame": {"type": "chat", "text": "too early"}}"#, diff --git a/pkgs/id/src/meta_client.rs b/pkgs/id/src/meta_client.rs index 9faadc0aac..3cce77d766 100644 --- a/pkgs/id/src/meta_client.rs +++ b/pkgs/id/src/meta_client.rs @@ -53,9 +53,9 @@ pub fn expect_ok(resp: MetaResponse) -> Result { /// limit instead. Any other read failure passes through unchanged. pub fn capped_response_error(err: ReadToEndError) -> anyhow::Error { match err { - ReadToEndError::TooLong => anyhow::anyhow!( - "response too large: exceeds the {MAX_RESPONSE_BYTES}-byte limit" - ), + ReadToEndError::TooLong => { + anyhow::anyhow!("response too large: exceeds the {MAX_RESPONSE_BYTES}-byte limit") + } other => other.into(), } } diff --git a/pkgs/id/src/world/actor.rs b/pkgs/id/src/world/actor.rs index 2e9ad3b67c..d525a9e821 100644 --- a/pkgs/id/src/world/actor.rs +++ b/pkgs/id/src/world/actor.rs @@ -1308,15 +1308,24 @@ impl WorldActor { if self.core.schedules.get(&id) == Some(&at_ms) { return Ok(self.core.schedules.clone()); } - if self.core.schedules.contains_key(&id) { + // Validate the replacement before anything is persisted: + // a refusal (say, past the horizon) must leave the + // existing schedule standing, in the journal as in + // memory (#807). + let replacing = self.core.schedules.contains_key(&id); + self.core.check_schedule_replacing( + &id, + at_ms, + self.core.clock().now_ms(), + replacing, + )?; + if replacing { // Journal the cancel before the replacement set: // replay refuses two pending sets for one id. self.persist(JournalEntry::ScheduleCancelled { id: id.clone() })?; self.core.schedules.remove(&id); self.overdue_at_open.remove(&id); } - self.core - .check_schedule(&id, at_ms, self.core.clock().now_ms())?; self.persist(JournalEntry::ScheduleSet { id: id.clone(), at_ms, diff --git a/pkgs/id/src/world/core.rs b/pkgs/id/src/world/core.rs index f540337dee..4ee5325c15 100644 --- a/pkgs/id/src/world/core.rs +++ b/pkgs/id/src/world/core.rs @@ -588,13 +588,30 @@ impl WorldCore { /// A malformed id, a duplicate pending id, a full schedule, or a time past /// the horizon. pub(crate) fn check_schedule(&self, id: &str, at_ms: u64, now_ms: u64) -> Result<()> { + self.check_schedule_replacing(id, at_ms, now_ms, false) + } + + /// Like [`Self::check_schedule`], but for a set that replaces the pending + /// schedule with the same id: the entry being replaced counts as already + /// cancelled, so it is neither a duplicate nor a use of the capacity. + /// Callers validate with this BEFORE persisting the replacement's + /// cancellation, so a refused replacement (say, past the horizon) leaves + /// the existing schedule standing (#807). + pub(crate) fn check_schedule_replacing( + &self, + id: &str, + at_ms: u64, + now_ms: u64, + replacing: bool, + ) -> Result<()> { crate::world_caps::validate_schedule_id(id)?; ensure!( - !self.schedules.contains_key(id), + replacing || !self.schedules.contains_key(id), "schedule {id:?} is already pending; cancel it before scheduling it again" ); + let pending = self.schedules.len() - usize::from(replacing); ensure!( - self.schedules.len() < crate::world_caps::MAX_PENDING_SCHEDULES, + pending < crate::world_caps::MAX_PENDING_SCHEDULES, "world already has {} pending schedules", crate::world_caps::MAX_PENDING_SCHEDULES ); diff --git a/pkgs/id/src/world/tests.rs b/pkgs/id/src/world/tests.rs index 0a1a33bad4..43a520ce73 100644 --- a/pkgs/id/src/world/tests.rs +++ b/pkgs/id/src/world/tests.rs @@ -3347,6 +3347,45 @@ mod schedule_tests { assert!(error.to_string().contains("pending schedules"), "{error}"); } + #[test] + fn a_replacement_is_validated_as_a_replacement_not_as_an_addition() { + // #807: the admin set that replaces a pending schedule validates + // against the map as it will be after the replacement - the entry + // being replaced is neither a duplicate nor a use of the capacity - + // so validation can run before the cancellation is persisted, and a + // refusal (here, past the horizon) leaves the original standing. + let now = 1_000_000_000_000u64; + let horizon = crate::world_caps::MAX_SCHEDULE_HORIZON_MS; + let mut core = world(8); + core.schedules.insert("taken".to_owned(), now + 5); + assert!( + core.check_schedule_replacing("taken", now + 9, now, true) + .is_ok(), + "replacing a pending id is not a duplicate" + ); + let error = core + .check_schedule_replacing("taken", now + horizon + 1, now, true) + .unwrap_err(); + assert!(error.to_string().contains("days past"), "{error}"); + assert_eq!( + core.schedules["taken"], + now + 5, + "the refused replacement overwrites nothing" + ); + + let mut full = world(8); + for index in 0..crate::world_caps::MAX_PENDING_SCHEDULES { + full.schedules.insert(format!("s{index}"), now); + } + assert!( + full.check_schedule_replacing("s0", now + 9, now, true) + .is_ok(), + "a replacement at capacity fits: it frees its own slot" + ); + let error = full.check_schedule("one-more", now, now).unwrap_err(); + assert!(error.to_string().contains("pending schedules"), "{error}"); + } + #[tokio::test] async fn an_ungranted_schedule_is_refused_and_counted() { let (mut actor, _clock, token, journal) = scheduling_actor("sched-refused", &[], false); diff --git a/pkgs/id/src/world_net.rs b/pkgs/id/src/world_net.rs index 6b63f9bce4..2015a4dfc0 100644 --- a/pkgs/id/src/world_net.rs +++ b/pkgs/id/src/world_net.rs @@ -216,6 +216,19 @@ impl WorldClient { }) } + /// Open another session on this client's connection, addressed to the + /// same world as this client. Admin frames are served one operation per + /// stream (the session ends with the reply), so a caller performing + /// several operations in sequence - `id world apply` is one - opens a + /// fresh session per operation instead of reusing a finished stream. + /// + /// # Errors + /// + /// Fails if the host refuses another stream on this connection. + pub async fn fresh_session(&self) -> Result { + self.open_session(self.world.as_deref()).await + } + /// Address this client's frames to `world` instead of the host's default. #[must_use] pub fn with_world(mut self, world: Option<&str>) -> Self { @@ -1068,12 +1081,48 @@ impl WorldClient { capability: &str, expected_hash: &str, ) -> Result> { - self.send_json(&serde_json::json!({ - "type": "download_module", - "capability": capability, - "module_hash": expected_hash, - })) - .await?; + self.download_module_with( + serde_json::json!({ + "type": "download_module", + "capability": capability, + "module_hash": expected_hash, + }), + expected_hash, + ) + .await + } + + /// Download a stored module by hash as an admin, whether or not it is + /// the active module (#807). The host serves only modules it holds in + /// its blob store; a hash it never installed is refused. + /// + /// # Errors + /// + /// Fails on a bad admin token, a hash the host does not hold, a hash + /// mismatch, oversize or a truncated transfer. + pub async fn download_module_admin( + &mut self, + admin_token: &str, + expected_hash: &str, + ) -> Result> { + self.download_module_with( + serde_json::json!({ + "type": "download_module_admin", + "admin_token": admin_token, + "module_hash": expected_hash, + }), + expected_hash, + ) + .await + } + + /// Send one module-download frame and read the transfer it starts. + async fn download_module_with( + &mut self, + frame: serde_json::Value, + expected_hash: &str, + ) -> Result> { + self.send_json(&frame).await?; let begin = self .recv_json() .await? @@ -1451,6 +1500,79 @@ mod tests { ep.close().await; } + /// #807: `id world apply`'s hash path - download a stored module as + /// admin, then install the bytes - sequenced on ONE connection. Admin + /// frames are served one operation per stream, so each operation runs + /// on a fresh session; on a reused stream the install would write to a + /// session the host already finished. + #[cfg(feature = "sandbox")] + #[tokio::test] + async fn apply_hash_path_sequences_fresh_sessions_on_one_connection() { + let wasm = include_bytes!("../examples/roc-counter/counter.wasm"); + let wasm2 = include_bytes!("../examples/roc-chat/roc-chat.wasm"); + let ep = endpoint().await; + let world = WorldHandle::spawn(WorldCore::new("lobby", WorldLimits::default()).unwrap()); + let blobs: iroh_blobs::api::Store = iroh_blobs::store::mem::MemStore::new().into(); + let service = + WorldService::new(world, Some("admin".to_owned())).with_blob_store(blobs.clone()); + let router = Router::builder(ep.clone()) + .accept(WORLD_ALPN, WorldProtocol::new(service)) + .spawn(); + let addr = EndpointAddr::from_parts( + ep.id(), + ep.bound_sockets().iter().map(|a| { + let ip = if a.ip().is_unspecified() { + std::net::Ipv4Addr::LOCALHOST.into() + } else { + a.ip() + }; + iroh::TransportAddr::Ip(std::net::SocketAddr::new(ip, a.port())) + }), + ); + let client_ep = endpoint().await; + let client = WorldClient::connect(&client_ep, addr.clone()) + .await + .unwrap(); + + let hash = client + .fresh_session() + .await + .unwrap() + .install_wasm("admin", wasm, 7) + .await + .unwrap(); + let hash2 = client + .fresh_session() + .await + .unwrap() + .install_wasm("admin", wasm2, 7) + .await + .unwrap(); + assert_ne!(hash, hash2); + + let stored = client + .fresh_session() + .await + .unwrap() + .download_module_admin("admin", &hash) + .await + .unwrap(); + assert_eq!(stored, wasm.as_slice()); + let reinstalled = client + .fresh_session() + .await + .unwrap() + .install_wasm("admin", &stored, 7) + .await + .unwrap(); + assert_eq!(reinstalled, hash); + + client.close(); + client_ep.close().await; + ep.close().await; + router.shutdown().await.unwrap(); + } + #[cfg(feature = "sandbox")] #[tokio::test] async fn peers_install_then_download_the_active_module_by_hash() { @@ -1527,6 +1649,59 @@ mod tests { ); wrong.close(); + // #807: a second install makes the first module non-active. The + // participant download then refuses it, but an admin can still fetch + // the stored bytes by hash - the path `id world apply` uses to + // install the module a manifest names. + let wasm2 = include_bytes!("../examples/roc-chat/roc-chat.wasm"); + let mut admin2 = WorldClient::connect(&client_ep, addr.clone()) + .await + .unwrap(); + let hash2 = admin2.install_wasm("admin", wasm2, 7).await.unwrap(); + admin2.close(); + assert_ne!(hash2, hash); + + let mut fetch2 = WorldClient::connect(&client_ep, addr.clone()) + .await + .unwrap(); + assert!( + fetch2.download_module(&capability, &hash).await.is_err(), + "the first module is no longer the active one" + ); + fetch2.close(); + + let mut admin_fetch = WorldClient::connect(&client_ep, addr.clone()) + .await + .unwrap(); + let stored = admin_fetch + .download_module_admin("admin", &hash) + .await + .unwrap(); + admin_fetch.close(); + assert_eq!(stored, wasm.as_slice()); + + let mut bad_admin = WorldClient::connect(&client_ep, addr.clone()) + .await + .unwrap(); + assert!( + bad_admin + .download_module_admin("wrong", &hash) + .await + .is_err() + ); + bad_admin.close(); + + let mut missing = WorldClient::connect(&client_ep, addr.clone()) + .await + .unwrap(); + assert!( + missing + .download_module_admin("admin", &"0".repeat(64)) + .await + .is_err() + ); + missing.close(); + // Without a capability, nothing is disclosed. let mut anon = WorldClient::connect(&client_ep, addr).await.unwrap(); assert!(anon.download_module(&"0".repeat(64), &hash).await.is_err()); diff --git a/pkgs/id/src/world_session/mod.rs b/pkgs/id/src/world_session/mod.rs index fdf7b2b0dc..06ab77bf10 100644 --- a/pkgs/id/src/world_session/mod.rs +++ b/pkgs/id/src/world_session/mod.rs @@ -681,6 +681,42 @@ impl WorldService { Ok(bytes.to_vec()) } + /// Read a stored module's bytes by hash, active or not: from the blob + /// store Wasm installs pin into, or from the module directory native + /// installs are saved to. The caller must already have + /// authenticated as an admin. A hash the host never installed is + /// unavailable: the bytes of a module it does not hold cannot be + /// conjured, and the error says so by kind. + pub async fn stored_module_bytes(&self, expected_hash: &str) -> Result, InstallError> { + let hash: iroh_blobs::Hash = expected_hash + .parse() + .map_err(|_| InstallError::InvalidUpload)?; + // Wasm installs are pinned in the blob store; native installs are + // saved only in the module directory (they are never offered for + // peer download), so a stored native module is read from there. + if let Some(blobs) = self.blobs.as_ref() + && let Ok(bytes) = blobs.blobs().get_bytes(hash).await + && bytes.len() <= MAX_WORLD_MODULE_BYTES + && module_hash(&bytes) == expected_hash + { + return Ok(bytes.to_vec()); + } + if let Some(modules) = self.module_dir.clone() { + let requested = expected_hash.to_owned(); + let loaded = tokio::task::spawn_blocking(move || modules.load(&requested)) + .await + .map_err(|_| InstallError::Unavailable)? + .map_err(|_| InstallError::Unavailable)?; + if loaded.len() <= MAX_WORLD_MODULE_BYTES { + return Ok(loaded); + } + } + if self.blobs.is_none() && self.module_dir.is_none() { + return Err(InstallError::Disabled); + } + Err(InstallError::Unavailable) + } + /// Hash of the currently active module, if the world runs one. pub async fn active_module_hash(&self) -> Option { self.module_hash.read().await.clone() @@ -1225,6 +1261,16 @@ async fn run_world_session(service: &WorldService, io: &mut I, fra } } } + ClientFrame::DownloadModuleAdmin { + admin_token, + module_hash, + } => { + if let Err(message) = + download_module_admin_session(service, io, &admin_token, &module_hash).await + { + let _ = send_error(service.frame_meter(), io, message).await; + } + } ClientFrame::WorldState { admin_token, capability, @@ -1612,11 +1658,42 @@ async fn download_module_session( .module_bytes(&active_hash) .await .map_err(|_| "module bytes are unavailable")?; + send_module_bytes(service, io, active_hash, &bytes).await +} + +/// The admin module download (#807): any module the host holds in its blob +/// store, by hash, active or not - so `id world apply` can install the +/// module a manifest names when another module is currently active. +async fn download_module_admin_session( + service: &WorldService, + io: &mut I, + admin_token: &str, + requested_hash: &str, +) -> Result<(), &'static str> { + if admin_token.len() > MAX_ADMIN_TOKEN_BYTES + || service.authorize_admin(Some(admin_token)).is_err() + { + return Err("admin denied"); + } + let bytes = service + .stored_module_bytes(requested_hash) + .await + .map_err(|_| "the host does not hold a module with that hash")?; + send_module_bytes(service, io, requested_hash.to_owned(), &bytes).await +} + +/// Stream one module's bytes as a begin/chunk/end transfer naming `module_hash`. +async fn send_module_bytes( + service: &WorldService, + io: &mut I, + module_hash: String, + bytes: &[u8], +) -> Result<(), &'static str> { if !send_json( service.frame_meter(), io, &ServerFrame::ModuleBegin { - module_hash: active_hash.clone(), + module_hash: module_hash.clone(), total_bytes: bytes.len(), }, ) @@ -1641,9 +1718,7 @@ async fn download_module_session( if !send_json( service.frame_meter(), io, - &ServerFrame::ModuleEnd { - module_hash: active_hash, - }, + &ServerFrame::ModuleEnd { module_hash }, ) .await { @@ -2360,6 +2435,7 @@ async fn handle_client_frame( | ClientFrame::SetFileScope { .. } | ClientFrame::Compile { .. } | ClientFrame::DownloadModule { .. } + | ClientFrame::DownloadModuleAdmin { .. } | ClientFrame::InstallBegin { .. } | ClientFrame::InstallChunk { .. } | ClientFrame::InstallEnd => { diff --git a/pkgs/id/src/world_session/tests.rs b/pkgs/id/src/world_session/tests.rs index 7144ec8c4b..a5f23d1892 100644 --- a/pkgs/id/src/world_session/tests.rs +++ b/pkgs/id/src/world_session/tests.rs @@ -393,6 +393,31 @@ mod tests { ); } + /// #807: a module saved only in the module directory (the native + /// install path never pins blobs) is still retrievable by hash for an + /// admin reconciling a manifest, and an unknown hash is refused. + #[tokio::test] + async fn stored_module_bytes_fall_back_to_the_module_directory() { + let dir = std::env::temp_dir().join(format!( + "id-stored-module-test-{}", + std::process::id() + )); + let modules = crate::world_store::ModuleDir::new(dir.clone()); + let bytes: &[u8] = b"native-module-bytes"; + let hash = modules.save(bytes).unwrap(); + + let world = WorldHandle::spawn(WorldCore::new("lobby", WorldLimits::default()).unwrap()); + let service = WorldService::new(world, Some("admin".to_owned())).with_module_dir(modules); + assert_eq!(service.stored_module_bytes(&hash).await.unwrap(), bytes); + assert!( + service + .stored_module_bytes(&"0".repeat(64)) + .await + .is_err() + ); + std::fs::remove_dir_all(&dir).ok(); + } + #[tokio::test] async fn schedule_and_world_state_frames_round_trip_and_hide_the_seed() { let svc = service(Some("admin")); diff --git a/pkgs/id/src/world_session/types.rs b/pkgs/id/src/world_session/types.rs index a26414be33..b574a7f66b 100644 --- a/pkgs/id/src/world_session/types.rs +++ b/pkgs/id/src/world_session/types.rs @@ -104,6 +104,15 @@ pub(crate) enum ClientFrame { capability: String, module_hash: String, }, + /// Admin: download a stored module by hash, whether or not it is the + /// active module. The participant download above serves only the active + /// module; an admin reconciling a world to a manifest (#807) needs a + /// module the host already holds - installed earlier and still in its + /// blob store - by its hash, to install it under the manifest's seed. + DownloadModuleAdmin { + admin_token: String, + module_hash: String, + }, Invite { admin_token: String, display_name: String,