diff --git a/pkgs/id/contract/shell-contract.v1.json b/pkgs/id/contract/shell-contract.v1.json index ca46620fe3..57a52d2dc7 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": 5, + "revision": 6, "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"], @@ -221,16 +221,21 @@ }, "install_begin": { "class": "admin", - "phases": ["opening"], + "phases": ["opening", "joined"], "opens": "install", "fields": { - "admin_token": "string", + "admin_token": "string?", "total_bytes": { "type": "u64", "min": 1, "max": 16777216 }, "module_hash": "string?", "signature": "object?", "seed": "u64" } }, + "revoke": { + "class": "admin", + "phases": ["joined"], + "fields": { "participant_id": "u64" } + }, "install_chunk": { "class": "control", "phases": ["install"], @@ -405,9 +410,13 @@ "class": "reply", "fields": { "module_hash": "string", "sequence": "u64" } }, + "revoked": { + "class": "reply", + "fields": { "participant_id": "u64", "revoked": "bool" } + }, "error": { "class": "reply", - "fields": { "message": "string" } + "fields": { "message": "string", "code": "string?" } } }, "projection": { diff --git a/pkgs/id/src/commands/world.rs b/pkgs/id/src/commands/world.rs index 5506cb13eb..407bef5770 100644 --- a/pkgs/id/src/commands/world.rs +++ b/pkgs/id/src/commands/world.rs @@ -2381,7 +2381,7 @@ mod tests { .join("\n"); assert_eq!( check_contract(&good).unwrap(), - "3 frames conform to shell contract v1.5" + "3 frames conform to shell contract v1.6" ); let bad = [ r#"{"from": "client", "frame": {"type": "chat", "text": "too early"}}"#, diff --git a/pkgs/id/src/shell_contract.rs b/pkgs/id/src/shell_contract.rs index 6506ef817e..0d5f71d7d8 100644 --- a/pkgs/id/src/shell_contract.rs +++ b/pkgs/id/src/shell_contract.rs @@ -543,6 +543,10 @@ impl fmt::Display for Violation { pub struct Conformance<'c> { contract: &'c ShellContract, phase: Phase, + /// Where the session returns when the current upload ends: a + /// pre-join upload closes the session, a joined builder's upload + /// returns to `Joined` (design #835 phase 3). + install_return: Phase, index: usize, violations: Vec, } @@ -554,6 +558,7 @@ impl<'c> Conformance<'c> { Self { contract, phase: Phase::Opening, + install_return: Phase::Closed, index: 0, violations: Vec::new(), } @@ -580,10 +585,17 @@ impl<'c> Conformance<'c> { .client_frames .get(kind) .and_then(|spec| spec.opens); + if opens == Some(Phase::Install) { + self.install_return = match self.phase { + Phase::Joined => Phase::Joined, + _ => Phase::Closed, + }; + } self.phase = match (self.phase, kind) { (Phase::Opening, _) => opens.unwrap_or(Phase::Closed), (Phase::Query, "join") => Phase::Joined, - (Phase::Install, "install_end") => Phase::Closed, + (Phase::Install, "install_end") => self.install_return, + (Phase::Joined, _) if opens == Some(Phase::Install) => Phase::Install, (phase, _) => phase, }; } @@ -598,11 +610,15 @@ impl<'c> Conformance<'c> { if let Err(message) = self.contract.check_server_frame(frame) { self.violate(Side::Server, message); } - // Before a join, an error ends the session. - if frame.get("type").and_then(Value::as_str) == Some("error") - && matches!(self.phase, Phase::Opening | Phase::Query | Phase::Install) - { - self.phase = Phase::Closed; + // Before a join, an error ends the session; during an upload + // it returns to wherever that upload returns — a refused + // joined upload leaves the session joined. + if frame.get("type").and_then(Value::as_str) == Some("error") { + match self.phase { + Phase::Opening | Phase::Query => self.phase = Phase::Closed, + Phase::Install => self.phase = self.install_return, + Phase::Joined | Phase::Closed => {} + } } self.index += 1; } diff --git a/pkgs/id/src/shell_contract/tests.rs b/pkgs/id/src/shell_contract/tests.rs index 2f26f9af17..522fc7c645 100644 --- a/pkgs/id/src/shell_contract/tests.rs +++ b/pkgs/id/src/shell_contract/tests.rs @@ -50,6 +50,7 @@ fn server_frame_type(frame: &ServerFrame<'_>) -> &'static str { ServerFrame::Compiled { .. } => "compiled", ServerFrame::UploadReady { .. } => "upload_ready", ServerFrame::ModuleInstalled { .. } => "module_installed", + ServerFrame::Revoked { .. } => "revoked", ServerFrame::ProgramChanged { .. } => "program_changed", ServerFrame::EventHistoryBegin { .. } => "event_history_begin", ServerFrame::EventHistoryEvent { .. } => "event_history_event", @@ -81,6 +82,7 @@ const SERVER_FRAME_TYPES: &[&str] = &[ "compiled", "upload_ready", "module_installed", + "revoked", "program_changed", "event_history_begin", "event_history_event", @@ -203,7 +205,18 @@ fn every_server_frame_variant_is_in_the_contract_and_nothing_else_is() { ServerFrame::EventHistoryEvent { event: &history_event, }, - ServerFrame::Error { message: "no" }, + ServerFrame::Error { + message: "no", + code: None, + }, + ServerFrame::Error { + message: "denied", + code: Some("actor_denied"), + }, + ServerFrame::Revoked { + participant_id: 7, + revoked: true, + }, ServerFrame::ModuleInfo { world_id: "w".to_owned(), active_module_hash: None, @@ -438,6 +451,35 @@ fn a_transcript_follows_the_session_phases() { check.client(&json!({"type": "install_end"})); assert!(check.violations().is_empty(), "{:?}", check.violations()); + // A joined upload (design #835 phase 3): install_begin from the + // joined phase enters the upload phase, and install_end returns + // to joined — not closed — so the session continues. + let mut check = Conformance::new(contract); + check.client(&json!({"type": "join", "capability": "c", "after": null})); + check.server(&json!({"type": "snapshot", "snapshot": {}})); + assert_eq!(check.phase(), Phase::Joined); + check.client(&json!({"type": "install_begin", "total_bytes": 2, "seed": 1})); + assert_eq!(check.phase(), Phase::Install); + check.server(&json!({"type": "upload_ready", "chunk_bytes": 6144})); + check.client(&json!({"type": "install_chunk", "offset": 0, "data_hex": "0000"})); + check.client(&json!({"type": "install_end"})); + assert_eq!(check.phase(), Phase::Joined); + check.client(&json!({"type": "chat", "text": "hi"})); + assert!(check.violations().is_empty(), "{:?}", check.violations()); + + // A refused joined upload (an error instead of upload_ready) + // likewise leaves the session joined, not closed. + let mut check = Conformance::new(contract); + check.client(&json!({"type": "join", "capability": "c", "after": null})); + check.server(&json!({"type": "snapshot", "snapshot": {}})); + check.client(&json!({"type": "install_begin", "total_bytes": 2, "seed": 1})); + assert_eq!(check.phase(), Phase::Install); + check.server( + &json!({"type": "error", "message": "module install denied", "code": "actor_denied"}), + ); + assert_eq!(check.phase(), Phase::Joined); + assert!(check.violations().is_empty(), "{:?}", check.violations()); + assert!(check_transcript(contract, "not json").is_err()); assert!(check_transcript(contract, r#"{"from": "peer", "frame": {}}"#).is_err()); } diff --git a/pkgs/id/src/world/actor.rs b/pkgs/id/src/world/actor.rs index f0b7edb713..58df36f036 100644 --- a/pkgs/id/src/world/actor.rs +++ b/pkgs/id/src/world/actor.rs @@ -49,6 +49,7 @@ impl WorldCommand { Self::Revoke { .. } => "Revoke", Self::RevokeAuthorized { .. } => "RevokeAuthorized", Self::ParticipantId { .. } => "ParticipantId", + Self::AuthorizeScope { .. } => "AuthorizeScope", Self::BindAuthorKey { .. } => "BindAuthorKey", Self::Chat { .. } => "Chat", Self::Input { .. } => "Input", @@ -140,6 +141,16 @@ pub(crate) enum WorldCommand { token: JoinCapability, reply: oneshot::Sender>, }, + /// Authorize a live capability for a scope set without performing + /// the operation (design #835 phase 3): session paths check this + /// before receiving upload bytes, while the operation commands + /// (`InstallProgramAuthorized`, `RevokeAuthorized`) still re-check + /// at the effect boundary. Replies with the derived participant ID. + AuthorizeScope { + token: JoinCapability, + required: WorldScopes, + reply: oneshot::Sender>, + }, Chat { token: JoinCapability, text: String, @@ -1725,6 +1736,13 @@ impl WorldActor { WorldCommand::ParticipantId { token, reply } => { let _ = reply.send(self.core.authorize(&token, WorldScopes::JOIN)); } + WorldCommand::AuthorizeScope { + token, + required, + reply, + } => { + let _ = reply.send(self.core.authorize(&token, required)); + } WorldCommand::BindAuthorKey { token, author_key, diff --git a/pkgs/id/src/world/core.rs b/pkgs/id/src/world/core.rs index b7d9dcc6d6..88884b9df3 100644 --- a/pkgs/id/src/world/core.rs +++ b/pkgs/id/src/world/core.rs @@ -1820,10 +1820,9 @@ impl WorldCore { let now = self.clock().now_ms(); let mut current = Some(participant_id); while let Some(record) = current.and_then(|id| self.capabilities.get(&id)) { - ensure!( - record.bounds.expires_at.is_none_or(|expires| now < expires), - "world capability has expired" - ); + if !record.bounds.expires_at.is_none_or(|expires| now < expires) { + return Err(CapabilityDenied::new("world capability has expired").into()); + } current = record.parent; } Ok(()) @@ -2446,19 +2445,20 @@ impl WorldCore { let (participant, _) = token .expose() .split_once('.') - .context("malformed world capability")?; + .ok_or_else(|| CapabilityDenied::new("malformed world capability"))?; let participant_id = participant .parse::() - .context("malformed world capability participant ID")?; + .map_err(|_| CapabilityDenied::new("malformed world capability participant ID"))?; let digest = token_digest(token.expose()); - let record = self - .capabilities - .get(&participant_id) - .context("invalid, revoked, or insufficient world capability")?; - ensure!( - constant_time_eq(&digest, &record.digest), - "invalid, revoked, or insufficient world capability" - ); + let record = self.capabilities.get(&participant_id).ok_or_else(|| { + CapabilityDenied::new("invalid, revoked, or insufficient world capability") + })?; + if !constant_time_eq(&digest, &record.digest) { + return Err(CapabilityDenied::new( + "invalid, revoked, or insufficient world capability", + ) + .into()); + } // The authority check must not seed from `ALL`: that set excludes // the admin bits by design, which would make `BUILDER` / // `MODERATOR` unusable through this path. Seed with every @@ -2466,13 +2466,16 @@ impl WorldCore { // `effective_scopes_seeded` only removes bits, so a required // authority bit survives only when every record in the chain // actually carries it. - ensure!( - !record.revoked - && self - .effective_scopes_seeded(participant_id, WorldScopes::all_recognized()) - .is_some_and(|scopes| scopes.contains(required)), - "invalid, revoked, or insufficient world capability" - ); + if !(!record.revoked + && self + .effective_scopes_seeded(participant_id, WorldScopes::all_recognized()) + .is_some_and(|scopes| scopes.contains(required))) + { + return Err(CapabilityDenied::new( + "invalid, revoked, or insufficient world capability", + ) + .into()); + } self.ensure_not_expired(participant_id)?; Ok(participant_id) } diff --git a/pkgs/id/src/world/handle.rs b/pkgs/id/src/world/handle.rs index cf48bf4038..04415476be 100644 --- a/pkgs/id/src/world/handle.rs +++ b/pkgs/id/src/world/handle.rs @@ -644,6 +644,33 @@ impl WorldHandle { .context("world actor dropped participant lookup response")? } + /// Authorize a live capability for `required` scopes, returning the + /// derived participant ID (design #835 phase 3). The world actor + /// performs the check against the capability's current scope, + /// revocation state, and expiry; the error is the actor's + /// non-oracular "invalid, revoked, or insufficient world + /// capability" for every denial cause. Session paths use this as + /// the early check before receiving upload bytes — the authorized + /// operation commands still re-check at the effect boundary. + pub async fn authorize( + &self, + token: JoinCapability, + required: WorldScopes, + ) -> Result { + let (reply, response) = oneshot::channel(); + self.commands + .send(WorldCommand::AuthorizeScope { + token, + required, + reply, + }) + .await + .map_err(|_| anyhow::anyhow!("world actor is closed"))?; + response + .await + .context("world actor dropped authorization response")? + } + /// Issue a scoped participant capability. pub async fn issue( &self, @@ -1104,13 +1131,17 @@ impl WorldHandle { /// Install a program on the authority of a joined builder's live /// capability (design #835 phase 2). The world actor authorizes the /// capability itself at the mutation boundary and derives the audit - /// actor (`BuilderInstalled { by }`) from it. + /// actor (`BuilderInstalled { by }`) from it. The caller's module + /// trust decision is carried through to the durable install event, + /// exactly as on the admin path (#1069): a verified publisher must + /// stay attributable in the journal. pub async fn install_program_authorized( &self, token: JoinCapability, module_hash: String, seed: u64, provenance: Option, + trust: Option, program: Box, ) -> Result { let (reply, response) = oneshot::channel(); @@ -1120,7 +1151,7 @@ impl WorldHandle { module_hash, seed, provenance, - trust: None, + trust, program, reply, }) diff --git a/pkgs/id/src/world/mod.rs b/pkgs/id/src/world/mod.rs index 00a88cb96c..9a13273d69 100644 --- a/pkgs/id/src/world/mod.rs +++ b/pkgs/id/src/world/mod.rs @@ -1263,6 +1263,42 @@ pub struct TrustDecision { pub publisher: Option, } +/// A capability authorization denial (design #835): the typed root of +/// every error the capability check returns, so callers of the +/// authorized operation commands (`InstallProgramAuthorized`, +/// `RevokeAuthorized`) can classify a denial from the command's own +/// error — told apart from journal, actor, and program failures — +/// without matching message text. The message stays the non-oracular +/// denial text the actor has always returned: one wording for invalid, +/// expired, revoked, and insufficient capabilities alike. +#[derive(Debug)] +pub struct CapabilityDenied { + message: &'static str, +} + +impl CapabilityDenied { + pub(crate) const fn new(message: &'static str) -> Self { + Self { message } + } +} + +impl std::fmt::Display for CapabilityDenied { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(self.message) + } +} + +impl std::error::Error for CapabilityDenied {} + +/// Whether an error returned by a world operation is a capability +/// authorization denial (see [`CapabilityDenied`]). +#[must_use] +pub fn is_capability_denied(error: &anyhow::Error) -> bool { + error + .chain() + .any(|cause| cause.downcast_ref::().is_some()) +} + /// One durable fact about a world, in commit order. /// /// Capability secrets are never journaled, only their SHA-256 digests, so a diff --git a/pkgs/id/src/world_session/mod.rs b/pkgs/id/src/world_session/mod.rs index 87556f5d1a..d8502e2f18 100644 --- a/pkgs/id/src/world_session/mod.rs +++ b/pkgs/id/src/world_session/mod.rs @@ -114,10 +114,12 @@ pub async fn run_session(hub: &WorldHub, io: &mut I) { pub(crate) fn frame_admin_token(frame: &ClientFrame) -> Option<&str> { match frame { ClientFrame::Invite { admin_token, .. } - | ClientFrame::InstallBegin { admin_token, .. } | ClientFrame::Compile { admin_token, .. } | ClientFrame::CreateWorld { admin_token } | ClientFrame::ListWorlds { admin_token } => Some(admin_token), + // A joined builder's install_begin omits the token (design #835 + // phase 3); only a supplied one is an admin credential. + ClientFrame::InstallBegin { admin_token, .. } => admin_token.as_deref(), ClientFrame::EventHistoryAdmin { admin_token } => Some(admin_token), ClientFrame::SetExecutionProfile { admin_token, .. } => Some(admin_token), _ => None, @@ -543,6 +545,13 @@ async fn run_world_session(service: &WorldService, io: &mut I, fra signature, seed, } => { + // The pre-join path is admin-only (design #835 phase 3): + // joined builder sessions are already past this point, so + // an omitted token here names no authority at all. + let Some(admin_token) = admin_token else { + let _ = send_error(service.frame_meter(), io, "module install denied").await; + return; + }; if service.source_only() { if service.authorize_admin(Some(&admin_token)).is_err() { let _ = send_error(service.frame_meter(), io, "module install denied").await; @@ -823,6 +832,7 @@ async fn run_world_session(service: &WorldService, io: &mut I, fra | ClientFrame::DelegateToFriend { .. } | ClientFrame::Input { .. } | ClientFrame::Resize { .. } + | ClientFrame::Revoke { .. } | ClientFrame::Paste { .. } => { let _ = send_error( service.frame_meter(), @@ -1331,6 +1341,193 @@ async fn send_module_bytes( Ok(()) } +/// The wire code carried by error frames that refuse a joined +/// session's role/capability action (design #835 §5): one stable, +/// non-oracular code for invalid, expired, revoked, and insufficient +/// capabilities alike. +const ACTOR_DENIED: &str = "actor_denied"; + +/// Receive one upload's chunks and its terminating `install_end`, +/// exactly as the install paths have always framed them. Shared by +/// the pre-join admin install and the joined builder install so the +/// upload safeguards (offsets, chunk bounds, strict frame parsing) +/// cannot drift apart. +#[cfg(feature = "sandbox")] +async fn receive_module_upload( + io: &mut I, + total_bytes: usize, +) -> Result, &'static str> { + let mut bytes = Vec::with_capacity(total_bytes); + while bytes.len() < total_bytes { + let incoming = tokio::time::timeout(Duration::from_secs(30), io.recv()) + .await + .map_err(|_| "timed out receiving module")?; + let Inbound::Text(text) = incoming else { + return Err("invalid module chunk frame"); + }; + let Ok(ClientFrame::InstallChunk { offset, data_hex }) = + parse_json_without_duplicate_keys(&text) + .and_then(|value| serde_json::from_value::(value)) + else { + return Err("expected module chunk frame"); + }; + if offset != bytes.len() || data_hex.len() > MAX_WORLD_MODULE_CHUNK_BYTES * 2 { + return Err("invalid module chunk offset or size"); + } + let Some(chunk) = decode_hex(&data_hex) else { + return Err("module chunk must be hexadecimal"); + }; + if chunk.is_empty() || chunk.len() > total_bytes.saturating_sub(bytes.len()) { + return Err("invalid module chunk length"); + } + bytes.extend_from_slice(&chunk); + } + + let incoming = tokio::time::timeout(Duration::from_secs(30), io.recv()) + .await + .map_err(|_| "timed out waiting for install completion")?; + if !matches!(incoming, Inbound::Text(ref text) if matches!(parse_json_without_duplicate_keys(text).and_then(|value| serde_json::from_value::(value)), Ok(ClientFrame::InstallEnd))) + { + return Err("expected install_end frame"); + } + Ok(bytes) +} + +/// A joined builder session's module install (design #835 phase 3): +/// the same upload sequence and safeguards as the pre-join admin +/// install, but authorized by the session's live capability — an +/// early `BUILDER` check before any bytes are received, and the +/// actor's own re-check at the effect boundary inside +/// [`WorldService::install_wasm_authorized`]. Role denials carry the +/// `actor_denied` wire code. Returns whether the session continues. +async fn install_module_session_joined( + service: &WorldService, + io: &mut I, + token: &JoinCapability, + total_bytes: usize, + claimed_hash: Option<&str>, + signature: Option<&ModuleSignature>, + seed: u64, +) -> bool { + if service + .world() + .authorize(token.clone(), WorldScopes::BUILDER) + .await + .is_err() + { + return send_error_with_code( + service.frame_meter(), + io, + Some(ACTOR_DENIED), + "module install denied", + ) + .await; + } + if total_bytes == 0 + || total_bytes > MAX_WORLD_MODULE_BYTES + || claimed_hash.is_some_and(|hash| { + hash.len() != 64 || !hash.bytes().all(|byte| byte.is_ascii_hexdigit()) + }) + { + return send_error( + service.frame_meter(), + io, + "invalid module size or content hash", + ) + .await; + } + let upload_permit = match service.try_reserve_module_upload() { + Ok(permit) => permit, + Err(_) => { + return send_error( + service.frame_meter(), + io, + "world is busy installing another module", + ) + .await; + } + }; + #[cfg(not(feature = "sandbox"))] + { + let _ = (token, upload_permit, signature, seed); + return send_error( + service.frame_meter(), + io, + "module installation requires the sandbox feature", + ) + .await; + } + + #[cfg(feature = "sandbox")] + { + if !send_json( + service.frame_meter(), + io, + &ServerFrame::UploadReady { + chunk_bytes: MAX_WORLD_MODULE_CHUNK_BYTES, + }, + ) + .await + { + return false; + } + let bytes = match receive_module_upload(io, total_bytes).await { + Ok(bytes) => bytes, + Err(message) => return send_error(service.frame_meter(), io, message).await, + }; + let actual_hash = module_hash(&bytes); + if claimed_hash.is_some_and(|claimed| actual_hash != claimed.to_ascii_lowercase()) { + return send_error(service.frame_meter(), io, "module content hash mismatch").await; + } + let installed = service + .install_wasm_authorized( + token.clone(), + bytes, + seed, + &actual_hash, + upload_permit, + signature, + ) + .await; + match installed { + Ok((module_hash, sequence)) => send_json( + service.frame_meter(), + io, + &ServerFrame::ModuleInstalled { + module_hash: &module_hash, + sequence, + }, + ) + .await, + Err(InstallError::ActorDenied) => send_error_with_code( + service.frame_meter(), + io, + Some(ACTOR_DENIED), + "module install denied", + ) + .await, + Err(error) => { + let message = match error { + InstallError::Disabled => "module installation is not enabled on this host", + InstallError::Unauthorized | InstallError::ActorDenied => { + "module install denied" + } + InstallError::InvalidUpload => "invalid module upload", + InstallError::RawModuleDisabled => { + "raw module uploads are disabled by source-only policy" + } + InstallError::InvalidModule => { + "Wasm module failed validation or initialization" + } + InstallError::UntrustedModule => "module signature is not trusted", + InstallError::Unavailable => "world could not activate the module", + }; + send_error(service.frame_meter(), io, message).await + } + } + } +} + async fn install_module_session( service: &WorldService, io: &mut I, @@ -1375,39 +1572,7 @@ async fn install_module_session( { return Err("connection closed"); } - let mut bytes = Vec::with_capacity(total_bytes); - while bytes.len() < total_bytes { - let incoming = tokio::time::timeout(Duration::from_secs(30), io.recv()) - .await - .map_err(|_| "timed out receiving module")?; - let Inbound::Text(text) = incoming else { - return Err("invalid module chunk frame"); - }; - let Ok(ClientFrame::InstallChunk { offset, data_hex }) = - parse_json_without_duplicate_keys(&text) - .and_then(|value| serde_json::from_value::(value)) - else { - return Err("expected module chunk frame"); - }; - if offset != bytes.len() || data_hex.len() > MAX_WORLD_MODULE_CHUNK_BYTES * 2 { - return Err("invalid module chunk offset or size"); - } - let Some(chunk) = decode_hex(&data_hex) else { - return Err("module chunk must be hexadecimal"); - }; - if chunk.is_empty() || chunk.len() > total_bytes.saturating_sub(bytes.len()) { - return Err("invalid module chunk length"); - } - bytes.extend_from_slice(&chunk); - } - - let incoming = tokio::time::timeout(Duration::from_secs(30), io.recv()) - .await - .map_err(|_| "timed out waiting for install completion")?; - if !matches!(incoming, Inbound::Text(ref text) if matches!(parse_json_without_duplicate_keys(text).and_then(|value| serde_json::from_value::(value)), Ok(ClientFrame::InstallEnd))) - { - return Err("expected install_end frame"); - } + let bytes = receive_module_upload(io, total_bytes).await?; let actual_hash = module_hash(&bytes); if claimed_hash.is_some_and(|claimed| actual_hash != claimed.to_ascii_lowercase()) { return Err("module content hash mismatch"); @@ -1426,7 +1591,7 @@ async fn install_module_session( .await .map_err(|error| match error { InstallError::Disabled => "module installation is not enabled on this host", - InstallError::Unauthorized => "module install denied", + InstallError::Unauthorized | InstallError::ActorDenied => "module install denied", InstallError::InvalidUpload => "invalid module upload", InstallError::RawModuleDisabled => { "raw module uploads are disabled by source-only policy" @@ -2189,6 +2354,96 @@ async fn handle_client_frame( } } } + ClientFrame::InstallBegin { + admin_token, + total_bytes, + module_hash, + signature, + seed, + } => { + // A joined session installs on its capability's authority + // (design #835 phase 3). An admin token here is mixed + // credentials — the frame must choose one authority — and + // is refused before any scope check, so the refusal cannot + // be read as a statement about either credential. + if admin_token.is_some() { + return send_error( + service.frame_meter(), + io, + "install_begin in a joined session must omit the admin token", + ) + .await; + } + return install_module_session_joined( + service, + io, + token, + total_bytes, + module_hash.as_deref(), + signature.as_ref(), + seed, + ) + .await; + } + ClientFrame::InstallChunk { .. } | ClientFrame::InstallEnd => { + return send_error(service.frame_meter(), io, "no module upload in progress").await; + } + ClientFrame::Revoke { participant_id } => { + // The early scope check classifies a certain denial with + // the stable wire code; `revoke_authorized` re-checks + // inside the actor at the effect boundary and derives the + // audit actor from the capability, never from this frame. + // A denial the command itself returns — the capability + // expired, or a revocation landed, after the early check — + // is classified from the command's own error and carries + // the same code. + if world + .authorize(token.clone(), WorldScopes::MODERATOR) + .await + .is_err() + { + return send_error_with_code( + service.frame_meter(), + io, + Some(ACTOR_DENIED), + "revoke denied", + ) + .await; + } + match world.revoke_authorized(token.clone(), participant_id).await { + Ok(revoked) => { + return send_json( + service.frame_meter(), + io, + &ServerFrame::Revoked { + participant_id, + revoked, + }, + ) + .await; + } + Err(error) if crate::world::is_capability_denied(&error) => { + return send_error_with_code( + service.frame_meter(), + io, + Some(ACTOR_DENIED), + "revoke denied", + ) + .await; + } + Err(error) => { + // The in-memory revocation stands (fail-closed); + // what failed is the audited success, so the reply + // is a failure, never a `Revoked` frame. + return send_error( + service.frame_meter(), + io, + &format!("revoke failed: {error:#}"), + ) + .await; + } + } + } ClientFrame::Join { .. } | ClientFrame::Invite { .. } | ClientFrame::Directory { .. } @@ -2201,10 +2456,7 @@ async fn handle_client_frame( | ClientFrame::Compile { .. } | ClientFrame::DownloadModule { .. } | ClientFrame::DownloadModuleAdmin { .. } - | ClientFrame::EventHistoryAdmin { .. } - | ClientFrame::InstallBegin { .. } - | ClientFrame::InstallChunk { .. } - | ClientFrame::InstallEnd => { + | ClientFrame::EventHistoryAdmin { .. } => { return send_error(service.frame_meter(), io, "already joined").await; } }; @@ -2243,7 +2495,18 @@ async fn send_json(meter: &WorldMetrics, io: &mut I, frame: &impl } async fn send_error(meter: &WorldMetrics, io: &mut I, message: &str) -> bool { - send_json(meter, io, &ServerFrame::Error { message }).await + send_error_with_code(meter, io, None, message).await +} + +/// An error frame carrying a stable denial `code` (design #835 §5). +/// Existing errors pass `None`, so their serialized shape is unchanged. +async fn send_error_with_code( + meter: &WorldMetrics, + io: &mut I, + code: Option<&str>, + message: &str, +) -> bool { + send_json(meter, io, &ServerFrame::Error { message, code }).await } async fn send_delegation( diff --git a/pkgs/id/src/world_session/service.rs b/pkgs/id/src/world_session/service.rs index 397d97df88..a998bd9f34 100644 --- a/pkgs/id/src/world_session/service.rs +++ b/pkgs/id/src/world_session/service.rs @@ -18,7 +18,7 @@ use iroh_blobs::{ use tokio::sync::{Mutex, OwnedSemaphorePermit, RwLock, Semaphore}; use crate::time::unix_ms; -use crate::world::{SessionId, WorldHandle, WorldMetrics, WorldScopes}; +use crate::world::{JoinCapability, SessionId, WorldHandle, WorldMetrics, WorldScopes}; use crate::world_compile::Compiler; #[cfg(feature = "sandbox")] use crate::world_compile::{COMPILE_TIMEOUT, CompileSpec}; @@ -706,6 +706,144 @@ impl WorldService { Ok((module_hash, installed.sequence)) } + /// Install an uploaded Wasm module on the authority of a joined + /// builder's live capability (design #835 phase 3). The upload + /// safeguards are the admin path's — size and hash bounds, the + /// module trust gate, source-only refusal — with two differences: + /// no admin token is involved (the world actor authorizes the + /// capability at the effect boundary and derives the + /// `BuilderInstalled { by }` audit actor from it), and builder + /// installs are **Wasm-only**: a native artifact is refused even + /// when this host enables native execution, so builder authority + /// can never reach the native installer. + #[cfg(feature = "sandbox")] + pub async fn install_wasm_authorized( + &self, + token: JoinCapability, + wasm: Vec, + seed: u64, + claimed_hash: &str, + _permit: OwnedSemaphorePermit, + signature: Option<&ModuleSignature>, + ) -> Result<(String, u64), InstallError> { + let _profile_operation = self.profile_operation.lock().await; + if self.source_only { + return Err(InstallError::RawModuleDisabled); + } + if wasm.is_empty() || wasm.len() > MAX_WORLD_MODULE_BYTES { + return Err(InstallError::InvalidUpload); + } + let hash = Hash::new(&wasm); + let module_hash = hash.to_string(); + if claimed_hash != module_hash { + return Err(InstallError::InvalidUpload); + } + // The same publisher trust gate as an admin upload, and the + // same trust decision recorded for it: a builder install the + // gate admitted on a verified signature must journal that + // decision (basis + publisher) in its install event, exactly + // as the admin path's does (#1069). + verify_module_signature(&self.trusted_module_keys, &wasm, signature)?; + let trust_decision = if self.trusted_module_keys.is_empty() { + crate::world::TrustDecision { + basis: crate::world::TrustBasis::NoTrustList, + publisher: None, + } + } else { + crate::world::TrustDecision { + basis: crate::world::TrustBasis::SignatureVerified, + publisher: signature.map(|sig| sig.public_key.clone()), + } + }; + if crate::world_native::is_native_module(&wasm) { + return Err(InstallError::InvalidModule); + } + let runtime = self + .world + .execution_profile() + .await + .map_err(|_| InstallError::Unavailable)? + .resolve(self.runtime) + .map_err(|_| InstallError::InvalidModule)?; + let limits = runtime.sandbox; + let compile_bytes = wasm.clone(); + let program = tokio::task::spawn_blocking(move || { + crate::sandbox::Sandbox::compile(&compile_bytes, limits)?.instantiate(seed) + }) + .await + .map_err(|_| InstallError::InvalidModule)? + .map_err(|_| InstallError::InvalidModule)?; + let guest: Box = Box::new(program); + + // A durable world must be able to reload this module before + // the journal may reference it. + if let Some(modules) = self.module_dir.clone() { + let bytes = wasm.clone(); + let saved = tokio::task::spawn_blocking(move || modules.save(&bytes)) + .await + .map_err(|_| InstallError::Unavailable)? + .map_err(|_| InstallError::Unavailable)?; + if saved != module_hash { + return Err(InstallError::Unavailable); + } + } + + let blobs = self.blobs.as_ref().ok_or(InstallError::Disabled)?.clone(); + let pin = blobs + .add_bytes_with_opts(AddBytesOptions { + data: wasm.into(), + format: BlobFormat::Raw, + }) + .temp_tag() + .await + .map_err(|_| InstallError::Unavailable)?; + if pin.hash() != hash { + return Err(InstallError::Unavailable); + } + + // The effect boundary: the authorized command re-checks the + // capability inside the actor, and its own answer classifies + // the outcome — a denial the command itself returns (the + // capability expired, or a revocation landed, after the early + // check below) carries the stable `actor_denied` code, told + // apart from an activation failure by the typed denial in the + // command's error. The early check only avoids receiving an + // upload the command would certainly refuse; it never widens + // what the command allows (fail-closed). + self.world + .authorize(token.clone(), WorldScopes::BUILDER) + .await + .map_err(|_| InstallError::ActorDenied)?; + let installed = self + .world + .install_program_authorized( + token, + module_hash.clone(), + seed, + Some(crate::world::ModuleProvenance::Artifact), + Some(trust_decision), + guest, + ) + .await + .map_err(|error| { + if crate::world::is_capability_denied(&error) { + InstallError::ActorDenied + } else { + InstallError::Unavailable + } + })?; + if !matches!( + installed.kind, + crate::world::WorldEventKind::ProgramInstalled { .. } + ) { + return Err(InstallError::Unavailable); + } + *self.module_pin.lock().await = Some(pin); + *self.module_hash.write().await = Some(module_hash.clone()); + Ok((module_hash, installed.sequence)) + } + + /// Read the currently pinned module artifact for peer download. /// The caller must already have authenticated as a world participant. /// diff --git a/pkgs/id/src/world_session/tests.rs b/pkgs/id/src/world_session/tests.rs index c89485a633..186246758e 100644 --- a/pkgs/id/src/world_session/tests.rs +++ b/pkgs/id/src/world_session/tests.rs @@ -2559,4 +2559,495 @@ mod tests { "world event rejected" ); } + + // ---- Design #835 phase 3 (#8036): joined builder/moderator frames ---- + + /// A journal the test can inspect, so session tests can assert the + /// audit records a frame wrote — and, for denials, did not write. + #[derive(Clone, Default)] + struct CapturingJournal( + std::sync::Arc>>, + ); + + impl CapturingJournal { + fn entries(&self) -> Vec { + self.0.lock().unwrap().clone() + } + } + + impl crate::world::WorldJournal for CapturingJournal { + fn append(&mut self, entry: &crate::world::JournalEntry) -> anyhow::Result<()> { + self.0.lock().unwrap().push(entry.clone()); + Ok(()) + } + + fn append_transaction( + &mut self, + entries: &[crate::world::JournalEntry], + ) -> anyhow::Result<()> { + self.0.lock().unwrap().extend_from_slice(entries); + Ok(()) + } + } + + /// A durable world behind a session service with a blob store, so + /// joined installs can pin their module and journal their audit. + fn durable_service() -> (WorldHandle, WorldService, CapturingJournal) { + use iroh_blobs::store::mem::MemStore; + + let journal = CapturingJournal::default(); + let world = WorldHandle::spawn_durable( + WorldCore::new("lobby", WorldLimits::default()).unwrap(), + Box::new(NoProgram), + Some(Box::new(journal.clone())), + ); + let blobs: Store = MemStore::new().into(); + let service = WorldService::new(world.clone(), Some("admin".to_owned())) + .with_blob_store(blobs); + (world, service, journal) + } + + async fn join_as(service: &WorldService, token: &JoinCapability) -> Peer { + let mut peer = Peer::connect(service.clone(), SessionConfig::default()); + peer.say(serde_json::json!({"type": "join", "capability": token.expose()})) + .await; + assert_eq!(peer.next().await.unwrap()["type"], "snapshot"); + peer + } + + /// Read until a frame of `wanted` type arrives (broadcasts and view + /// frames interleave freely in a joined session). + async fn next_of_type(peer: &mut Peer, wanted: &str) -> serde_json::Value { + for _ in 0..32 { + let frame = peer.next().await.unwrap(); + if frame["type"] == wanted { + return frame; + } + } + panic!("no {wanted} frame arrived"); + } + + /// Send an upload's chunks after its `upload_ready`, then + /// `install_end`; returns nothing — the caller reads the outcome. + async fn upload_chunks(peer: &mut Peer, ready: &serde_json::Value, bytes: &[u8]) { + let chunk_bytes = usize::try_from(ready["chunk_bytes"].as_u64().unwrap()).unwrap(); + for (index, chunk) in bytes.chunks(chunk_bytes).enumerate() { + peer.say(serde_json::json!({ + "type": "install_chunk", + "offset": index * chunk_bytes, + "data_hex": encode_hex(chunk), + })) + .await; + } + peer.say(serde_json::json!({"type": "install_end"})).await; + } + + #[cfg(feature = "sandbox")] + #[tokio::test] + async fn joined_builder_installs_and_journals_builder_installed() { + let (world, service, journal) = durable_service(); + let (builder, builder_token) = world + .issue( + "builder".to_owned(), + WorldScopes::from_role("builder").unwrap(), + ) + .await + .unwrap(); + let mut peer = join_as(&service, &builder_token).await; + + let wasm = include_bytes!("../../examples/roc-counter/counter.wasm"); + let hash = module_hash(wasm); + // No `admin_token` field at all: the joined path must not need + // one, and serde must accept its absence. + peer.say(serde_json::json!({ + "type": "install_begin", + "total_bytes": wasm.len(), + "module_hash": hash, + "seed": 12, + })) + .await; + let ready = next_of_type(&mut peer, "upload_ready").await; + upload_chunks(&mut peer, &ready, wasm).await; + let ack = next_of_type(&mut peer, "module_installed").await; + assert_eq!(ack["module_hash"], hash); + + let entries = journal.entries(); + assert!( + entries.iter().any(|entry| matches!( + entry, + crate::world::JournalEntry::BuilderInstalled { by, module_hash, .. } + if *by == builder.id && *module_hash == hash + )), + "install must be journal-attributed to the builder: {entries:?}" + ); + assert!( + entries.iter().any(|entry| matches!( + entry, + crate::world::JournalEntry::Committed { event } + if matches!( + &event.kind, + crate::world::WorldEventKind::ProgramInstalled { trust: Some(decision), .. } + if decision.basis == crate::world::TrustBasis::NoTrustList + && decision.publisher.is_none() + ) + )), + "the install event must record the no-trust-list decision: {entries:?}" + ); + + // The installed program is live for ordinary participants. + let (_, guest) = world.issue("ada".to_owned(), WorldScopes::GUEST).await.unwrap(); + assert!( + world + .view(guest) + .await + .unwrap() + .as_deref() + .is_some_and(|view| view.contains("count=0")), + "the builder-installed program must serve views" + ); + } + + #[cfg(feature = "sandbox")] + #[tokio::test] + async fn joined_builder_install_with_trusted_signer_journals_signature_decision() { + use iroh_blobs::store::mem::MemStore; + + let journal = CapturingJournal::default(); + let world = WorldHandle::spawn_durable( + WorldCore::new("lobby", WorldLimits::default()).unwrap(), + Box::new(NoProgram), + Some(Box::new(journal.clone())), + ); + let signer = SigningKey::from_bytes(&[42; 32]); + let publisher = hex_encode(&signer.verifying_key().to_bytes()); + let service = WorldService::new(world.clone(), Some("admin".to_owned())) + .with_blob_store(MemStore::new().into()) + .with_module_trust_keys(vec![signer.verifying_key().to_bytes()]); + let (builder, builder_token) = world + .issue( + "builder".to_owned(), + WorldScopes::from_role("builder").unwrap(), + ) + .await + .unwrap(); + let mut peer = join_as(&service, &builder_token).await; + + let wasm = include_bytes!("../../examples/roc-counter/counter.wasm"); + let hash = module_hash(wasm); + let mut message = b"developing-today/id-world-module/v1\0".to_vec(); + message.extend_from_slice(blake3::hash(wasm).as_bytes()); + let signature = hex_encode(&signer.sign(&message).to_bytes()); + peer.say(serde_json::json!({ + "type": "install_begin", + "total_bytes": wasm.len(), + "module_hash": hash, + "seed": 12, + "signature": {"public_key": publisher, "signature": signature}, + })) + .await; + let ready = next_of_type(&mut peer, "upload_ready").await; + upload_chunks(&mut peer, &ready, wasm).await; + let ack = next_of_type(&mut peer, "module_installed").await; + assert_eq!(ack["module_hash"], hash); + + let entries = journal.entries(); + assert!( + entries.iter().any(|entry| matches!( + entry, + crate::world::JournalEntry::BuilderInstalled { by, .. } if *by == builder.id + )), + "install must be journal-attributed to the builder: {entries:?}" + ); + assert!( + entries.iter().any(|entry| matches!( + entry, + crate::world::JournalEntry::Committed { event } + if matches!( + &event.kind, + crate::world::WorldEventKind::ProgramInstalled { trust: Some(decision), .. } + if decision.basis == crate::world::TrustBasis::SignatureVerified + && decision.publisher.as_deref() == Some(publisher.as_str()) + ) + )), + "the install event must record the verified publisher: {entries:?}" + ); + } + + #[cfg(feature = "sandbox")] + #[tokio::test] + async fn joined_guest_install_is_actor_denied_and_journals_nothing() { + let (world, service, journal) = durable_service(); + let (_, guest_token) = world + .issue("guest".to_owned(), WorldScopes::GUEST) + .await + .unwrap(); + let mut peer = join_as(&service, &guest_token).await; + + let wasm = include_bytes!("../../examples/roc-counter/counter.wasm"); + peer.say(serde_json::json!({ + "type": "install_begin", + "total_bytes": wasm.len(), + "module_hash": module_hash(wasm), + "seed": 12, + })) + .await; + let denied = next_of_type(&mut peer, "error").await; + assert_eq!(denied["code"], "actor_denied", "{denied}"); + assert_eq!(denied["message"], "module install denied"); + + // A denial is not a disconnect: the session still serves the + // participant's ordinary frames. + peer.say(serde_json::json!({ + "type": "metrics", + "capability": guest_token.expose(), + })) + .await; + assert_eq!(next_of_type(&mut peer, "metrics").await["type"], "metrics"); + + assert!( + !journal.entries().iter().any(|entry| matches!( + entry, + crate::world::JournalEntry::BuilderInstalled { .. } + )), + "a denied install must not journal a BuilderInstalled entry" + ); + } + + #[cfg(feature = "sandbox")] + #[tokio::test] + async fn joined_builder_install_begin_with_admin_token_is_mixed_credentials() { + let (world, service, journal) = durable_service(); + let (_, builder_token) = world + .issue( + "builder".to_owned(), + WorldScopes::from_role("builder").unwrap(), + ) + .await + .unwrap(); + let mut peer = join_as(&service, &builder_token).await; + + let wasm = include_bytes!("../../examples/roc-counter/counter.wasm"); + peer.say(serde_json::json!({ + "type": "install_begin", + "admin_token": "admin", + "total_bytes": wasm.len(), + "module_hash": module_hash(wasm), + "seed": 12, + })) + .await; + let refused = next_of_type(&mut peer, "error").await; + assert_eq!( + refused["message"], + "install_begin in a joined session must omit the admin token" + ); + assert!( + refused["code"].is_null(), + "mixed credentials is not a role denial: {refused}" + ); + assert!( + !journal.entries().iter().any(|entry| matches!( + entry, + crate::world::JournalEntry::BuilderInstalled { .. } + )), + "a mixed-credentials frame must not install anything" + ); + } + + #[cfg(feature = "sandbox")] + #[tokio::test] + async fn joined_builder_revoked_mid_upload_cannot_activate() { + let (world, service, journal) = durable_service(); + let (builder, builder_token) = world + .issue( + "builder".to_owned(), + WorldScopes::from_role("builder").unwrap(), + ) + .await + .unwrap(); + let mut peer = join_as(&service, &builder_token).await; + + let wasm = include_bytes!("../../examples/roc-counter/counter.wasm"); + peer.say(serde_json::json!({ + "type": "install_begin", + "total_bytes": wasm.len(), + "module_hash": module_hash(wasm), + "seed": 12, + })) + .await; + let ready = next_of_type(&mut peer, "upload_ready").await; + + // The revocation lands while the upload is in flight; the + // session is inside the upload, so only the install's effect + // boundary can still refuse — and it must. + assert!(world.revoke(builder.id).await.unwrap()); + upload_chunks(&mut peer, &ready, wasm).await; + let denied = next_of_type(&mut peer, "error").await; + assert_eq!(denied["code"], "actor_denied", "{denied}"); + assert!( + !journal.entries().iter().any(|entry| matches!( + entry, + crate::world::JournalEntry::BuilderInstalled { .. } + )), + "a revoked builder's upload must not activate or journal" + ); + } + + #[cfg(feature = "sandbox")] + #[tokio::test] + async fn joined_builder_native_upload_is_refused() { + let (world, service, journal) = durable_service(); + let (_, builder_token) = world + .issue( + "builder".to_owned(), + WorldScopes::from_role("builder").unwrap(), + ) + .await + .unwrap(); + let mut peer = join_as(&service, &builder_token).await; + + // An ELF image: builder authority is Wasm-only, even on hosts + // where the admin path may install native artifacts. + let mut elf = b"\x7fELF".to_vec(); + elf.extend_from_slice(&[0u8; 60]); + peer.say(serde_json::json!({ + "type": "install_begin", + "total_bytes": elf.len(), + "module_hash": module_hash(&elf), + "seed": 12, + })) + .await; + let ready = next_of_type(&mut peer, "upload_ready").await; + upload_chunks(&mut peer, &ready, &elf).await; + let refused = next_of_type(&mut peer, "error").await; + assert_eq!( + refused["message"], + "Wasm module failed validation or initialization" + ); + assert!( + !journal.entries().iter().any(|entry| matches!( + entry, + crate::world::JournalEntry::BuilderInstalled { .. } + )), + "a native upload must not install or journal" + ); + } + + #[tokio::test] + async fn prejoin_install_begin_without_admin_token_is_denied() { + let (_world, service, _journal) = durable_service(); + let mut peer = Peer::connect(service, SessionConfig::default()); + peer.say(serde_json::json!({ + "type": "install_begin", + "total_bytes": 4, + "module_hash": null, + "seed": 12, + })) + .await; + let denied = peer.next().await.unwrap(); + assert_eq!(denied["type"], "error"); + assert_eq!(denied["message"], "module install denied"); + assert!( + peer.next().await.is_none(), + "the pre-join path ends the session after the refusal" + ); + } + + #[tokio::test] + async fn joined_moderator_revoke_disconnects_and_journals() { + let (world, service, journal) = durable_service(); + let (moderator, moderator_token) = world + .issue( + "mod".to_owned(), + WorldScopes::from_role("moderator").unwrap(), + ) + .await + .unwrap(); + let (victim, victim_token) = world + .issue("victim".to_owned(), WorldScopes::GUEST) + .await + .unwrap(); + let mut mod_peer = join_as(&service, &moderator_token).await; + let mut victim_peer = join_as(&service, &victim_token).await; + + mod_peer + .say(serde_json::json!({"type": "revoke", "participant_id": victim.id})) + .await; + let ack = next_of_type(&mut mod_peer, "revoked").await; + assert_eq!(ack["participant_id"], victim.id); + assert_eq!(ack["revoked"], true); + + // The victim's session is closed by the revocation. + let closed = next_of_type(&mut victim_peer, "error").await; + assert_eq!(closed["message"], "world capability revoked"); + + let entries = journal.entries(); + assert!( + entries.iter().any(|entry| matches!( + entry, + crate::world::JournalEntry::Revoked { participant_id, by: Some(by) } + if *participant_id == victim.id && *by == moderator.id + )), + "revoke must be journal-attributed to the moderator: {entries:?}" + ); + + // Revoking an inactive target is a no-op reply, not an error, + // and writes no second journal record. + mod_peer + .say(serde_json::json!({"type": "revoke", "participant_id": victim.id})) + .await; + let noop = next_of_type(&mut mod_peer, "revoked").await; + assert_eq!(noop["revoked"], false); + assert_eq!( + journal + .entries() + .iter() + .filter(|entry| matches!( + entry, + crate::world::JournalEntry::Revoked { .. } + )) + .count(), + 1, + "a no-op revoke must not journal" + ); + } + + #[tokio::test] + async fn joined_guest_revoke_is_actor_denied() { + let (world, service, journal) = durable_service(); + let (moderator, moderator_token) = world + .issue( + "mod".to_owned(), + WorldScopes::from_role("moderator").unwrap(), + ) + .await + .unwrap(); + let (_, guest_token) = world + .issue("guest".to_owned(), WorldScopes::GUEST) + .await + .unwrap(); + let mut mod_peer = join_as(&service, &moderator_token).await; + let mut guest_peer = join_as(&service, &guest_token).await; + + guest_peer + .say(serde_json::json!({"type": "revoke", "participant_id": moderator.id})) + .await; + let denied = next_of_type(&mut guest_peer, "error").await; + assert_eq!(denied["code"], "actor_denied", "{denied}"); + + // The target is untouched: the moderator session still serves. + mod_peer + .say(serde_json::json!({ + "type": "metrics", + "capability": moderator_token.expose(), + })) + .await; + assert_eq!(next_of_type(&mut mod_peer, "metrics").await["type"], "metrics"); + assert!( + !journal.entries().iter().any(|entry| matches!( + entry, + crate::world::JournalEntry::Revoked { .. } + )), + "a denied revoke must not journal" + ); + } } diff --git a/pkgs/id/src/world_session/types.rs b/pkgs/id/src/world_session/types.rs index bc3a61a487..64336ea9bb 100644 --- a/pkgs/id/src/world_session/types.rs +++ b/pkgs/id/src/world_session/types.rs @@ -273,7 +273,12 @@ pub(crate) enum ClientFrame { text: String, }, InstallBegin { - admin_token: String, + /// The admin secret, for the pre-join admin path. Joined builder + /// sessions (design #835 phase 3) omit it and are authorized by + /// their live capability instead; a joined frame that carries + /// one is refused as mixed credentials. + #[serde(default)] + admin_token: Option, total_bytes: usize, /// Expected BLAKE3 hash. Optional for browser uploads, whose `WebCrypto` /// API does not provide BLAKE3; the host still computes and returns it. @@ -288,6 +293,13 @@ pub(crate) enum ClientFrame { data_hex: String, }, InstallEnd, + /// Joined moderator: revoke an active participant (design #835 + /// phase 3). The frame names only the target — the audit actor is + /// derived from this session's live capability by the world actor, + /// never from the frame. + Revoke { + participant_id: u64, + }, } /// Signer metadata supplied with an uploaded module. Public keys and @@ -431,12 +443,24 @@ pub(crate) enum ServerFrame<'a> { module_hash: &'a str, sequence: u64, }, + /// A joined moderator's revoke was carried out (`revoked: true`) + /// or named an inactive/unknown target (`revoked: false`, a no-op + /// that writes no journal record). + Revoked { + participant_id: u64, + revoked: bool, + }, ProgramChanged { module_hash: &'a str, sequence: u64, }, Error { message: &'a str, + /// Stable denial code for joined role/capability refusals + /// (`actor_denied`, design #835 §5). Omitted for every existing + /// error, so their serialized shape is unchanged. + #[serde(skip_serializing_if = "Option::is_none")] + code: Option<&'a str>, }, } @@ -515,6 +539,11 @@ pub enum InstallError { RawModuleDisabled, /// Wasmtime rejected or could not instantiate the module. InvalidModule, + /// The joined session's live capability does not authorize this + /// install (design #835 phase 3): invalid, expired, revoked, or + /// missing the `BUILDER` scope. Non-oracular by design — the wire + /// code is `actor_denied` for every one of those causes. + ActorDenied, /// The server has a module trust list and the artifact is unsigned, /// signed by an untrusted key, or has an invalid signature. UntrustedModule, diff --git a/pkgs/id/tests/world_roles.rs b/pkgs/id/tests/world_roles.rs index b03dfc4391..5741a5c256 100644 --- a/pkgs/id/tests/world_roles.rs +++ b/pkgs/id/tests/world_roles.rs @@ -8,8 +8,9 @@ use std::sync::{Arc, Mutex}; use id::world::{ - CapabilityBounds, JoinCapability, JournalEntry, WorldCore, WorldHandle, WorldJournal, - WorldLimits, WorldProgram, WorldScopes, + CapabilityBounds, JoinCapability, JournalEntry, TrustBasis, TrustDecision, WorldCore, + WorldEventKind, WorldHandle, WorldJournal, WorldLimits, WorldProgram, WorldScopes, + is_capability_denied, }; /// A capturing journal for asserting what a world records. @@ -249,18 +250,20 @@ async fn a_builder_capability_installs_and_a_revoked_builder_is_denied() { ); // A plain guest capability carries no BUILDER authority. + let guest_error = handle + .install_program_authorized( + guest_token, + "guest-hash".to_owned(), + 1, + None, + None, + Box::::default(), + ) + .await + .expect_err("guest capability must be denied the authorized install"); assert!( - handle - .install_program_authorized( - guest_token, - "guest-hash".to_owned(), - 1, - None, - Box::::default(), - ) - .await - .is_err(), - "guest capability must be denied the authorized install" + is_capability_denied(&guest_error), + "the denial must be classifiable from the command's own error: {guest_error:#}" ); assert!( !journal @@ -271,13 +274,20 @@ async fn a_builder_capability_installs_and_a_revoked_builder_is_denied() { ); // The builder's live capability installs, attributed to the builder ID - // the actor derived from the capability. + // the actor derived from the capability. The caller's trust decision + // is carried through to the durable install event, as on the admin + // path: a verified publisher stays attributable in the journal. + let trust = TrustDecision { + basis: TrustBasis::SignatureVerified, + publisher: Some("publisher-key".to_owned()), + }; handle .install_program_authorized( builder_token, "builder-hash".to_owned(), 7, None, + Some(trust.clone()), Box::::default(), ) .await @@ -291,6 +301,18 @@ async fn a_builder_capability_installs_and_a_revoked_builder_is_denied() { )), "expected a BuilderInstalled audit record naming the derived builder: {entries:?}" ); + assert!( + entries.iter().any(|entry| matches!( + entry, + JournalEntry::Committed { event } + if matches!( + &event.kind, + WorldEventKind::ProgramInstalled { trust: recorded, .. } + if recorded.as_ref() == Some(&trust) + ) + )), + "the authorized install must journal the caller's trust decision: {entries:?}" + ); handle.shutdown().await.unwrap(); } @@ -319,12 +341,13 @@ async fn a_revoked_moderator_capability_is_denied() { // authorizing at the actor boundary (the check is at mutation time, // not at some earlier session check). assert!(handle.revoke(moderator.id).await.unwrap()); + let revoke_error = handle + .revoke_authorized(moderator_token, victim.id) + .await + .expect_err("a revoked moderator capability must be denied"); assert!( - handle - .revoke_authorized(moderator_token, victim.id) - .await - .is_err(), - "a revoked moderator capability must be denied" + is_capability_denied(&revoke_error), + "the denial must be classifiable from the command's own error: {revoke_error:#}" ); handle.shutdown().await.unwrap();