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
17 changes: 13 additions & 4 deletions pkgs/id/contract/shell-contract.v1.json
Original file line number Diff line number Diff line change
@@ -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"],
Expand Down Expand Up @@ -221,16 +221,21 @@
},
"install_begin": {
"class": "admin",
"phases": ["opening"],
"phases": ["opening", "joined"],
"opens": "install",
Comment on lines +224 to 225

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Track joined uploads in the conformance state machine

For a valid joined builder upload, Conformance::client in src/shell_contract.rs remains in Phase::Joined after install_begin: it only applies a frame's opens transition in Phase::Opening. Consequently, the subsequent install_chunk and install_end frames are rejected because their contract phases are exclusively install, and check_contract rejects transcripts produced by the newly supported flow. Update the conformance state machine to enter the upload phase from a joined session and return to joined, rather than closed, when that upload ends.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in cdd39d5 (head now 6f28758, which also merges current main).

Conformance now records the phase an upload returns to when the upload opens: install_begin from Joined enters Install with return phase Joined; install_end returns there instead of Closed, and a refusal error during the upload returns there too (a refused joined upload does not end the session). Only an upload opens a phase from Joined — the opens values on joined query/admin frames stay non-transitional, as the existing joined-session conformance tests require.

Coverage: new shell_contract assertions run the joined upload sequence (join → install_begin → upload_ready → install_chunk → install_end → chat) and the refused variant (error instead of upload_ready), both conforming and ending in Joined. cargo test -p id --lib: 2648 passed; the only failure is the pre-existing frames::tests::byte_refusal... breakage tracked in #8354, which fails identically on pristine main.

"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"],
Expand Down Expand Up @@ -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": {
Expand Down
2 changes: 1 addition & 1 deletion pkgs/id/src/commands/world.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"}}"#,
Expand Down
28 changes: 22 additions & 6 deletions pkgs/id/src/shell_contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Violation>,
}
Expand All @@ -554,6 +558,7 @@ impl<'c> Conformance<'c> {
Self {
contract,
phase: Phase::Opening,
install_return: Phase::Closed,
index: 0,
violations: Vec::new(),
}
Expand All @@ -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,
};
}
Expand All @@ -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;
}
Expand Down
44 changes: 43 additions & 1 deletion pkgs/id/src/shell_contract/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -81,6 +82,7 @@ const SERVER_FRAME_TYPES: &[&str] = &[
"compiled",
"upload_ready",
"module_installed",
"revoked",
"program_changed",
"event_history_begin",
"event_history_event",
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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());
}
18 changes: 18 additions & 0 deletions pkgs/id/src/world/actor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -140,6 +141,16 @@ pub(crate) enum WorldCommand {
token: JoinCapability,
reply: oneshot::Sender<Result<u64>>,
},
/// 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<Result<u64>>,
},
Chat {
token: JoinCapability,
text: String,
Expand Down Expand Up @@ -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,
Expand Down
45 changes: 24 additions & 21 deletions pkgs/id/src/world/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(())
Expand Down Expand Up @@ -2446,33 +2445,37 @@ 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::<u64>()
.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
// recognized bit instead — the ancestor-chain intersection in
// `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)
}
Expand Down
35 changes: 33 additions & 2 deletions pkgs/id/src/world/handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u64> {
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,
Expand Down Expand Up @@ -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<ModuleProvenance>,
trust: Option<TrustDecision>,
program: Box<dyn WorldProgram>,
) -> Result<WorldEvent> {
let (reply, response) = oneshot::channel();
Expand All @@ -1120,7 +1151,7 @@ impl WorldHandle {
module_hash,
seed,
provenance,
trust: None,
trust,
program,
reply,
})
Expand Down
Loading
Loading