diff --git a/.opencode/plans/2026-10-20_phase-11-status.md b/.opencode/plans/2026-10-20_phase-11-status.md index d448032f1e..111e7ecb1f 100644 --- a/.opencode/plans/2026-10-20_phase-11-status.md +++ b/.opencode/plans/2026-10-20_phase-11-status.md @@ -12,15 +12,15 @@ This document audits the completion status of all eighteen Phase 11 tasks (F11.1 | **F11.2** | Firefox E2E isolation | **In Progress** | [Issue #229](https://github.com/developing-today/code/issues/229), [Workflow](https://github.com/developing-today/code/blob/main/.github/workflows/id-e2e-nightly.yml) | Split out into nightly workflow; per-spec ephemeral server isolation tracked in #229. | | **F11.3** | Explain LogSync flakes | **In Progress** | [PR #224](https://github.com/developing-today/code/pull/224), [PR #254](https://github.com/developing-today/code/pull/254), [PR #255](https://github.com/developing-today/code/pull/255) | Shared deadline aligned to 60s (#224); interrupted session test fixed (#254); ingest batching coalesced in open PR #255. Issue #241 open. | | **F11.4** | A fast lane | **Done** | [PR #224](https://github.com/developing-today/code/pull/224), [Workflow](https://github.com/developing-today/code/blob/main/.github/workflows/id-check.yml) | Fast checks (fmt, clippy, unit tests) gate PRs with `--keep-going`; E2E split to nightly. | -| **F11.5** | Injected time | **Planned** | Tracked in roadmap | Introduce injectable `Clock` for actor and scheduler to eliminate sleeps in tests. | +| **F11.5** | Injected time | **Done** | [PR #808](https://github.com/developing-today/code/pull/808) | `Clock` trait + `SystemClock`/`ManualClock`; schedule/tick/expiry decisions read the injected clock; 11 sleeps removed. | | **F11.6** | Per-call fuel metrics & budgets | **Done** | [PR #247](https://github.com/developing-today/code/pull/247) | Added `id world measure` and baseline+25% `FUEL_BUDGETS` test guards. | | **F11.7** | Host metrics & tracing | **Planned** | Tracked in roadmap | Actor queue depth, command latency, and Prometheus metrics endpoint. | | **F11.8** | Benchmarks | **Planned** | Tracked in roadmap | Replay, append/fsync, and fan-out benchmarks with committed baselines. | | **F11.9** | Bytes per frame | **Planned** | Tracked in roadmap | Measure full-screen frame sizes at 80x24 and 200x60 across examples. | -| **F11.10** | Split large modules | **Planned** | Tracked in roadmap | Split `world.rs` (6,120 lines), `world_session.rs` (4,017 lines), and `cli.rs` (3,958 lines). Unblocked now that platform stack has landed. | -| **F11.11** | One client projection | **Done** | [PR #250](https://github.com/developing-today/code/pull/250), [PR #256](https://github.com/developing-today/code/pull/256) | Seed redacted in snapshot/history (#250); single `project_event_for` projection with `history` scope (#256). Host events (#242) open. | +| **F11.10** | Split large modules | **Done** | [PR #808](https://github.com/developing-today/code/pull/808) | `world.rs` → `world/{mod,types,core,actor,handle,util,tests}.rs`; `world_session.rs` → `world_session/{mod,types,tests}.rs`. No file over 2,500 production lines. | +| **F11.11** | One client projection | **Done** | [PR #250](https://github.com/developing-today/code/pull/250), [PR #256](https://github.com/developing-today/code/pull/256), [PR #808](https://github.com/developing-today/code/pull/808) | Seed redacted in snapshot/history (#250); single `project_event_for` projection with `history` scope (#256); structural guard pinning the two session serialization sites (#543, PR #808). Host events (#242) open. | | **F11.12** | Journal format management | **Planned** | [Issue #227](https://github.com/developing-today/code/issues/227) | Pre-fix fail-loud rollback check landed in #244. Version header and `check`/`backup` CLI planned. | -| **F11.13** | Error taxonomy | **Planned** | Tracked in roadmap | Stable typed wire error codes for capability errors. | +| **F11.13** | Error taxonomy | **Done** | [PR #808](https://github.com/developing-today/code/pull/808) | `CapError` now carries a stable `CapErrorCode` plus an advisory reason on the wire; `schedule.at` returns the `check_schedule` reason. Codes documented in `world_caps`. | | **F11.14** | Cheaper `Screen` | **Done** | [PR #248](https://github.com/developing-today/code/pull/248) | `Screen.render_rows_json` reduces territory full-house (8 seats) view fuel from 7.1M to 1.6M (16% of 10M budget). | | **F11.15** | Smaller modules | **Planned** | Tracked in roadmap | `wasm-opt -Os` and strip integration in example `build.sh` scripts. | | **F11.16** | Replay self-check | **In Progress** | [PR #239](https://github.com/developing-today/code/pull/239) | `id world record` and `replay` fixtures with record-match verdicts landed; determinism check planned. | diff --git a/.opencode/plans/phase-11-foundations.md b/.opencode/plans/phase-11-foundations.md index 85db305d24..b8e14c41d4 100644 --- a/.opencode/plans/phase-11-foundations.md +++ b/.opencode/plans/phase-11-foundations.md @@ -76,6 +76,7 @@ F11.10 should land before F11.12, because that task touches the code the split m 1. Relay kit (#238): settled on `main` by #249 with a vendored copy and a drift test, not a move. The move into `pkgs/id/deploy/relay/` was approved but is not needed now. 2. Seeds and chat (F11.11): seeds secret, join-only participants do not see chat, an explicit `history` scope opts in. Approved. 3. Firefox E2E (#229, F11.2): not yet decided. It remains the last red check once the sync tests are fixed. +4. SSH input modes: raw keystrokes by default, `cmd:` line mode as the explicit login-time entry, other variations later. Username grammar is `world-name` / `explore:` / `cmd:`. See the [decision record](../../doc/2026-10-24T20-18-37Z_decision_ssh_input_modes/2026-10-24T20-18-37Z_decision_ssh_input_modes.md) and the SSH command-grammar task (#546). ## Out of scope diff --git a/.opencode/plans/phase-11-ssh-grammar.md b/.opencode/plans/phase-11-ssh-grammar.md new file mode 100644 index 0000000000..18ba207198 --- /dev/null +++ b/.opencode/plans/phase-11-ssh-grammar.md @@ -0,0 +1,39 @@ +# SSH command grammar, the `id world join` pump, and `--command-mode` + +Short plan for issue #546: one line grammar for the three surfaces that already +each know a different subset — SSH command mode, the `id world join` stdin +pump, and the CLI one-off verbs. + +## Goal + +The same sentence — `chat`, `records`, `stats`, `logs`, `caps`, `quit` — works +as an SSH command (`/chat` … or a plain line), a piped script line, and a CLI +one-off, so the three surfaces stop drifting. + +## Approach + +1. **One shared parser.** A new `world_line` module parses one line into a + `WorldLine` action with no surface knowledge. It understands the `/`-prefixed + commands (help, quit, records, documents, document, input, stats, logs, + caps) and treats any other non-empty line as chat. + +2. **SSH command mode uses the parser.** `world_ssh::world_command` becomes a + thin wrapper over `world_line::parse`, gaining `/stats`, `/logs` and `/caps` + on top of the existing `/help`, `/quit`, `/records`, `/documents`, + `/document` and `/input`. + +3. **The join pump uses the parser behind `--command-mode`.** `id world join` + gains a `--command-mode` flag. With it set, each stdin line is parsed by the + same grammar and mapped to the session frame it needs (chat, input, records, + stats, caps, logs, quit). Without the flag, today's behaviour is unchanged + (`/quit`, `/input`, everything else chat). + +4. **Tests.** One test table asserts the same line yields the same action on + SSH, the pump and the CLI. + +## Not in scope + +- New capability providers; `/stats`, `/logs` and `/caps` reuse the world's + existing info, event-tail and caps-report paths. +- A structured (non-line) command framing; that is a later input-mode variant + per the [SSH input-modes decision](../../../doc/2026-10-24T20-18-37Z_decision_ssh_input_modes/2026-10-24T20-18-37Z_decision_ssh_input_modes.md). \ No newline at end of file diff --git a/doc/2026-10-24T20-18-37Z_decision_ssh_input_modes/2026-10-24T20-18-37Z_decision_ssh_input_modes.md b/doc/2026-10-24T20-18-37Z_decision_ssh_input_modes/2026-10-24T20-18-37Z_decision_ssh_input_modes.md new file mode 100644 index 0000000000..16bb7d6afa --- /dev/null +++ b/doc/2026-10-24T20-18-37Z_decision_ssh_input_modes/2026-10-24T20-18-37Z_decision_ssh_input_modes.md @@ -0,0 +1,55 @@ +# SSH input modes: raw by default, `cmd:` line mode, and the username grammar + +Decision record for the SSH presentation of a hosted world. Fixes the gap +flagged in the platform world-state report (RPT §8 "Input modes — not in +either plan"): the input-mode decision and the username grammar existed only +in uncommitted reports. + +## Decision + +1. **Raw keystrokes are the default.** When an SSH user logs in with a plain + world name (or an empty name for the default world), the session runs in + _raw_ mode: every keystroke becomes an `input` frame and each `view` frame + repaints the terminal, so an ordinary `ssh` client can play any world that + presents a view. The alternate screen buffer is used in raw mode only. + +2. **`cmd:` line mode is the explicit login-time entry.** Prefixing the SSH + username with `cmd:` enters _command_ (line) mode, where each line is parsed + as a command instead of forwarded as an input keystroke. The grammar mirrors + the `id world` subcommands: chat, records, stats, logs, caps, and quit. See + the grammar task (below) and the `world_ssh` module. + +3. **Other variations come later.** Additional input modes (scripted pipes, + structured command framing, and any further username prefixes) are future + work and are not part of this decision. They will reuse the same line + grammar and the same username-prefix mechanism. + +## Username grammar + +The SSH username selects the world and the mode, in one string: + +| Username | Meaning | +| --------------- | --------------------------------------------------------- | +| `world-name` | Join `world-name` in raw mode (default world when empty). | +| `explore:world` | Read-only explore session for `world` (public-key login). | +| `cmd:world` | Join `world` in command (line) mode. | + +The SSH password is the join capability. `explore:` is the only prefix that +supports public-key login; `cmd:` and the plain name use password auth. + +## Related reconciliation decisions (#548) + +- **Records drain is bounded in total.** `/records` pages are each capped by + `MAX_RECORDS_TERMINAL_BYTES`, and the whole drain across pages is capped by + `MAX_RECORDS_TOTAL_BYTES` in the SSH presentation, so a many-record world + stops instead of streaming pages without bound. +- **Documents read the server blob store for now.** Document `/documents` and + `/document` read the server's local blob store (tags), not a per-world store. + A per-world document store is future work; the server store is the source of + truth the tags are written against today. + +## References + +- [Phase 11 plan](../../.opencode/plans/phase-11-foundations.md) +- [Phase 12 plan](../../.opencode/plans/phase-12-platform-flexibility.md) +- [SSH command grammar issue](https://github.com/developing-today/code/issues/546) diff --git a/pkgs/id/src/cli.rs b/pkgs/id/src/cli.rs index c0df90ca88..d1959cc328 100644 --- a/pkgs/id/src/cli.rs +++ b/pkgs/id/src/cli.rs @@ -1521,6 +1521,10 @@ pub enum WorldCommand { /// Replay events after this sequence instead of a full snapshot. #[arg(long)] after: Option, + /// Parse stdin as commands (`/chat`, `/records`, `/stats`, `/caps`, + /// `/quit`, ...) instead of sending every line as chat. + #[arg(long)] + command_mode: bool, /// World on the host to use (default: the host's default world). #[arg(long, env = "ID_WORLD")] world: Option, diff --git a/pkgs/id/src/commands/world.rs b/pkgs/id/src/commands/world.rs index 0dc1cbfd92..3c440e9271 100644 --- a/pkgs/id/src/commands/world.rs +++ b/pkgs/id/src/commands/world.rs @@ -564,6 +564,7 @@ pub async fn cmd_world(command: WorldCommand) -> Result<()> { node, capability, after, + command_mode, world, addrs, no_relay, @@ -576,7 +577,7 @@ pub async fn cmd_world(command: WorldCommand) -> Result<()> { "after": after, })) .await?; - let result = pump(client).await; + let result = pump(client, command_mode).await; endpoint.close().await; result } @@ -986,7 +987,7 @@ impl Replica { } /// Print server frames as JSON lines while sending stdin lines as chat. -async fn pump(client: WorldClient) -> Result<()> { +async fn pump(client: WorldClient, command_mode: bool) -> Result<()> { let (conn, mut send, mut recv) = client.into_parts(); let mut reader = tokio::spawn(async move { while let Some(body) = read_frame(&mut recv).await? { @@ -1002,11 +1003,15 @@ async fn pump(client: WorldClient) -> Result<()> { Some(line) => { let line = line.trim(); if line.is_empty() { continue; } - if line == "/quit" { break Ok(()); } - let frame = match line.strip_prefix("/input ") { - Some(hex) => serde_json::json!({"type": "input", "data_hex": hex.trim()}), - None => serde_json::json!({"type": "chat", "text": line}), + let frame = if command_mode { + pump_command_frame(line)? + } else { + match line.strip_prefix("/input ") { + Some(hex) => serde_json::json!({"type": "input", "data_hex": hex.trim()}), + None => serde_json::json!({"type": "chat", "text": line}), + } }; + if frame.is_null() { break Ok(()); } if let Err(e) = write_frame(&mut send, frame.to_string().as_bytes()).await { break Err(e); } @@ -1024,10 +1029,67 @@ async fn pump(client: WorldClient) -> Result<()> { result } +/// Map one parsed [`crate::world_line::WorldLine`] to the session frame it +/// needs in the `id world join --command-mode` pump. `null` ends the pump. +fn pump_command_frame(line: &str) -> Result { + use crate::world_line::{WorldLine, parse_line}; + let Some(action) = parse_line(line) else { + return Ok(serde_json::Value::Null); + }; + Ok(match action { + WorldLine::Chat(text) => serde_json::json!({"type": "chat", "text": text}), + WorldLine::Input(hex) => serde_json::json!({"type": "input", "data_hex": hex}), + WorldLine::Records { prefix } => { + serde_json::json!({"type": "records", "prefix": prefix, "after": null}) + } + WorldLine::Documents { prefix } => { + serde_json::json!({"type": "documents", "prefix": prefix}) + } + WorldLine::Document(name) => serde_json::json!({"type": "document", "name": name}), + WorldLine::Stats => serde_json::json!({"type": "info"}), + WorldLine::Caps => serde_json::json!({"type": "caps"}), + WorldLine::Logs { .. } => serde_json::json!({"type": "logs"}), + WorldLine::Help => serde_json::json!({"type": "help"}), + WorldLine::Quit => return Ok(serde_json::Value::Null), + WorldLine::Message(message) => { + anyhow::bail!("{message}") + } + }) +} + #[cfg(test)] #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] mod tests { - use super::scaffold_world; + use super::{pump_command_frame, scaffold_world}; + + /// The shared line grammar maps the same line to the same action on the + /// join pump as it does on the SSH command mode (both call + /// [`crate::world_line::parse_line`]); this asserts the pump's mapping. + #[test] + fn the_pump_command_mode_maps_the_shared_grammar() { + assert_eq!( + pump_command_frame("/stats").unwrap(), + serde_json::json!({"type": "info"}) + ); + assert_eq!( + pump_command_frame("/caps").unwrap(), + serde_json::json!({"type": "caps"}) + ); + assert_eq!( + pump_command_frame("/records x").unwrap(), + serde_json::json!({"type": "records", "prefix": "x", "after": null}) + ); + assert_eq!( + pump_command_frame("/input 00aF").unwrap(), + serde_json::json!({"type": "input", "data_hex": "00af"}) + ); + assert_eq!( + pump_command_frame("hello").unwrap(), + serde_json::json!({"type": "chat", "text": "hello"}) + ); + assert!(pump_command_frame("/quit").unwrap().is_null()); + assert!(pump_command_frame("/nope").is_err()); + } #[test] fn scaffolding_writes_a_buildable_app_skeleton() { diff --git a/pkgs/id/src/lib.rs b/pkgs/id/src/lib.rs index a5e0c70c13..e821e05d35 100644 --- a/pkgs/id/src/lib.rs +++ b/pkgs/id/src/lib.rs @@ -229,6 +229,8 @@ pub mod world_hub; #[cfg(feature = "world")] pub mod world_limits; #[cfg(feature = "world")] +pub(crate) mod world_line; +#[cfg(feature = "world")] pub mod world_native; #[cfg(feature = "world")] pub mod world_net; diff --git a/pkgs/id/src/sandbox.rs b/pkgs/id/src/sandbox.rs index 54cb18c0b3..ea2a301e85 100644 --- a/pkgs/id/src/sandbox.rs +++ b/pkgs/id/src/sandbox.rs @@ -511,9 +511,8 @@ impl WorldInstance { ); let result = self.view_inner(); self.settle(GuestCall::View); - if result.is_err() { - self.poisoned = true; - } + // A trapped view does not poison the instance: rendering never changes + // the model, so the next event retries against intact state (F11.17). result } @@ -547,9 +546,7 @@ impl WorldInstance { }; let result = self.layout_inner(&layout, width, height); self.settle(GuestCall::Layout); - if result.is_err() { - self.poisoned = true; - } + // As with `view`, a trapped layout does not poison the instance. result } @@ -1659,7 +1656,16 @@ mod tests { .to_string() .contains("fuel exhausted") ); - assert!(world.view().unwrap_err().to_string().contains("poisoned")); + // A trapped view does not poison the instance (F11.17): the retry runs + // the same view and exhausts fuel again, rather than being refused up + // front as poisoned. + assert!( + world + .view() + .unwrap_err() + .to_string() + .contains("fuel exhausted") + ); } #[test] @@ -1747,9 +1753,10 @@ mod tests { .unwrap(); world.view().unwrap_err(); assert_eq!(world.last_fuel(GuestCall::View), 1_000); - // A poisoned world refuses the call before the guest runs. + // A trapped view no longer poisons the instance (F11.17): the retry + // runs the guest again, so the call is counted a second time. world.view().unwrap_err(); - assert_eq!(world.metrics().get(GuestCall::View).calls, 1); + assert_eq!(world.metrics().get(GuestCall::View).calls, 2); } #[test] diff --git a/pkgs/id/src/world.rs b/pkgs/id/src/world.rs deleted file mode 100644 index 60ccc7b0c5..0000000000 --- a/pkgs/id/src/world.rs +++ /dev/null @@ -1,7596 +0,0 @@ -//! Transport-independent, authoritative in-memory world core. -//! -//! A transport should place one `WorldActor` behind its world ID and pass -//! messages to it serially. This module does not open sockets or persist world -//! state. Capability tokens are returned only at issuance and retained only as -//! SHA-256 digests for revocation and membership checks. -//! -//! ## What a grant carries, and what stays local -//! -//! A participant capability is a bearer secret. Its digest, scopes, expiry, -//! parent and subject are the grant, and the journal records them. Nothing -//! about a participant grant is signed here; the signed records are the -//! directory's artifacts (friendships and their removals). A grant carries no -//! use count. A delegation narrows scopes and may set an expiry, nothing else. -//! The host alone enforces a use limit, and only on a capability it issued (an -//! invite or an account grant), by counting actions in its own journal. Those -//! counts are local to the hosting node and need not converge across partitions. - -use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque}; -use std::sync::Arc; - -use crate::world_caps::{CapError, CapsReport, Decision, Request, Subscription}; -use anyhow::{Context, Result, bail, ensure}; -use rand::RngExt as _; -use serde::{Deserialize, Serialize}; -use sha2::{Digest, Sha256}; -use subtle::ConstantTimeEq as _; -use tokio::sync::{broadcast, mpsc, oneshot, watch}; - -/// Re-exported so `crate::world::Isolation` keeps working: the type now lives -/// in [`crate::groups::worlds`] so the crate builds without this feature. -pub use crate::groups::worlds::Isolation; - -/// Re-exported so `crate::world::unix_ms` keeps working: the function now -/// lives in [`crate::time`] so the crate builds without this feature. -pub(crate) use crate::time::unix_ms; - -/// A chat participant may send at most this many lines during the rolling window. -const CHAT_RATE_BURST: u8 = 50; -const CHAT_RATE_WINDOW: std::time::Duration = std::time::Duration::from_secs(10); - -/// Bounded limits for one world. -#[derive(Clone, Debug)] -pub struct WorldLimits { - /// Maximum number of active capabilities in this world. - pub participants: usize, - /// Maximum UTF-8 chat message length in bytes. - pub chat_bytes: usize, - /// Maximum opaque game input size in bytes. - pub input_bytes: usize, - /// Number of recent events kept for reconnect catch-up. - pub retained_events: usize, - /// Maximum presentation text returned by a world program, in bytes. - pub presentation_bytes: usize, - /// Largest snapshot frame, in bytes. A snapshot carries only the most - /// recent events that fit; a client rebases its cursor on the snapshot, - /// it does not need every retained event. - pub snapshot_bytes: usize, - /// Trim the journal behind a program snapshot once this many events were - /// committed since the last one. `0` disables checkpointing. - pub checkpoint_every: u64, - /// Slowest tick a program may subscribe to, in milliseconds. - pub min_tick_ms: u64, - /// Whether a world's policy grants a capability on its first use. - pub grant_on_use: bool, - /// Capabilities the server allows any world to use. Runtime configuration, - /// not journaled; a world's own ceiling and grants only narrow it. - pub server_caps: BTreeSet, -} - -impl Default for WorldLimits { - fn default() -> Self { - Self { - participants: 256, - chat_bytes: 2048, - input_bytes: 16 * 1024, - retained_events: 1024, - presentation_bytes: 8192, - snapshot_bytes: 512 * 1024, - checkpoint_every: 1000, - min_tick_ms: 1000, - grant_on_use: false, - server_caps: crate::world_caps::catalog_names(), - } - } -} - -/// Permission scopes granted by a world capability. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct WorldScopes(u8); - -impl WorldScopes { - /// Join the world and receive snapshots/events. - pub const JOIN: Self = Self(0b001); - /// Send chat messages. - pub const CHAT: Self = Self(0b010); - /// Submit game input events. - pub const INPUT: Self = Self(0b100); - /// Mint capabilities with a subset of this set. - pub const DELEGATE: Self = Self(0b1000); - /// Read chat lines without being able to send them. `CHAT` also reads. - pub const HISTORY: Self = Self(0b1_0000); - /// Default guest permissions. - pub const GUEST: Self = Self(Self::JOIN.0 | Self::CHAT.0 | Self::INPUT.0); - /// Every scope. - pub const ALL: Self = Self(Self::GUEST.0 | Self::DELEGATE.0 | Self::HISTORY.0); - - /// Role presets used by `id world invite --role`. `spectator` joins and - /// sees the world but not the chat; `observer` also reads chat without - /// sending it; `player` submits input; `guest` (the default) also chats; - /// `delegator` additionally mints narrower capabilities for others. - /// - /// The names are stable; the mapping to scopes is part of the protocol. - #[must_use] - pub fn from_role(name: &str) -> Option { - match name { - "spectator" => Some(Self::JOIN), - "observer" => Some(Self(Self::JOIN.0 | Self::HISTORY.0)), - "player" => Some(Self(Self::JOIN.0 | Self::INPUT.0)), - "guest" => Some(Self::GUEST), - "delegator" => Some(Self(Self::GUEST.0 | Self::DELEGATE.0)), - _ => None, - } - } - - /// The names accepted by [`Self::from_role`]. - pub const ROLES: &'static [&'static str] = - &["spectator", "observer", "player", "guest", "delegator"]; - - /// Raw scope bits, as journaled. - #[must_use] - pub const fn bits(self) -> u8 { - self.0 - } - - /// Scopes from raw bits; `None` if any bit names no scope. - #[must_use] - pub const fn from_bits(bits: u8) -> Option { - if bits & !Self::ALL.0 == 0 { - Some(Self(bits)) - } else { - None - } - } - - /// Every scope either set includes. - #[must_use] - pub const fn union(self, other: Self) -> Self { - Self(self.0 | other.0) - } - - /// Only the scopes both sets include. - #[must_use] - pub const fn intersect(self, other: Self) -> Self { - Self(self.0 & other.0) - } - - /// Whether this scope set includes `required`. - #[must_use] - pub const fn contains(self, required: Self) -> bool { - self.0 & required.0 == required.0 - } - - /// This set with the scopes it includes by implication: `CHAT` reads, so - /// it carries `HISTORY`. Apply it wherever sets are compared as sets. - #[must_use] - pub const fn implied(self) -> Self { - if self.contains(Self::CHAT) { - Self(self.0 | Self::HISTORY.0) - } else { - self - } - } - - /// Whether a participant with this set may see chat lines. - #[must_use] - pub const fn reads_chat(self) -> bool { - self.0 & (Self::CHAT.0 | Self::HISTORY.0) != 0 - } - - /// The scopes a delegate of this set may hold: a subset that keeps `JOIN`. - /// `None` unless this set includes `DELEGATE` and `requested` is a subset. - /// A set with `CHAT` may delegate `HISTORY`, which `CHAT` includes. - #[must_use] - pub const fn attenuate(self, requested: Self) -> Option { - if self.contains(Self::DELEGATE) - && requested.contains(Self::JOIN) - && self.implied().contains(requested) - { - Some(requested) - } else { - None - } - } - - /// Whether a participant with this set may cause the effect `cap`. Every - /// connected participant may read; `chat.say` also needs `CHAT`. - #[must_use] - pub fn allows_effect(self, cap: &str) -> bool { - match cap { - "chat.say" => self.contains(Self::CHAT), - // Reading chat needs only the right to read it (`CHAT` or - // `HISTORY`), the same rule the event stream applies. - "chat.history" => self.reads_chat(), - _ => self.contains(Self::JOIN), - } - } - - /// Scopes named on the wire (`join`, `chat`, `history`, `input`, - /// `delegate`), or `None` if a name is unknown. - #[must_use] - pub fn from_names<'a>(names: impl IntoIterator) -> Option { - names.into_iter().try_fold(Self(0), |scopes, name| { - let bit = match name { - "join" => Self::JOIN, - "chat" => Self::CHAT, - "history" => Self::HISTORY, - "input" => Self::INPUT, - "delegate" => Self::DELEGATE, - _ => return None, - }; - Some(Self(scopes.0 | bit.0)) - }) - } -} - -/// Bearer secret that grants access to one world. Never serialize it into a snapshot. -#[derive(Clone, PartialEq, Eq)] -pub struct JoinCapability(String); - -impl std::fmt::Debug for JoinCapability { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str("JoinCapability([REDACTED])") - } -} - -impl JoinCapability { - /// Construct from an untrusted wire token; it is authorized only by its - /// owning [`WorldCore`] or [`WorldHandle`]. - #[must_use] - pub const fn from_wire(token: String) -> Self { - Self(token) - } - - /// Expose the token for a deliberate invitation/transport response. - #[must_use] - pub fn expose(&self) -> &str { - &self.0 - } -} - -/// Public participant summary; it contains no capability material. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct Participant { - /// Opaque server-assigned participant identifier. - pub id: u64, - /// Caller-provided display name, sanitized and bounded at issue time. - pub display_name: String, -} - -/// Versioned event committed by the world authority. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct WorldEvent { - /// Monotonic event sequence, starting at one. - pub sequence: u64, - /// Server-assigned participant that caused the event. - pub participant_id: u64, - /// Event payload. - pub kind: WorldEventKind, -} - -/// Participant-originated event data. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(tag = "kind", content = "data", rename_all = "snake_case")] -pub enum WorldEventKind { - /// Plain text message, UTF-8 and control-character sanitized. - Chat(String), - /// Opaque input for a future game/world module. - Input(Vec), - /// An event the host originated for the program: capability results, - /// ticks, presence. Delivered with `participant_id` 0; never sequenced, - /// never broadcast to sessions. - System { - /// The event's JSON. - event: String, - }, - /// A world admin installed a new program. `participant_id` is zero for - /// this host-authored event. - ProgramInstalled { - /// Iroh BLAKE3 hash of the newly active module artifact. - module_hash: String, - /// Seed passed to the program's `init`; with the module and the - /// inputs after this event it reproduces the program state exactly. - /// Journal/admin only: join projections redact it to zero (#240). - #[serde(default)] - seed: u64, - /// Server-observed origin metadata. Absent on older journal entries. - #[serde(default, skip_serializing_if = "Option::is_none")] - provenance: Option, - }, -} - -/// How the active module artifact entered the world. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(tag = "origin", content = "build", rename_all = "snake_case")] -pub enum ModuleProvenance { - /// A raw module artifact was installed; no compiler identity is asserted. - Artifact, - /// The server observed a successful source build. These hashes identify - /// inputs; they are not a signature or a trust attestation. - SourceBuild(SourceBuildProvenance), -} - -/// Bounded, deterministic metadata observed for one source compilation. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct SourceBuildProvenance { - /// Provenance record schema, independent of the world journal version. - pub schema_version: u8, - /// Domain-separated BLAKE3 digest of the compiler executable bytes. - pub compiler_blake3: String, - /// BLAKE3 digest of the platform tree, including relative paths. - pub platform_blake3: String, - /// BLAKE3 digest of the submitted source filenames and contents. - pub source_blake3: String, - /// Compiler target (`wasm32` or `x64musl`). - pub target: String, - /// Stable compiler arguments, excluding the temporary output path. - pub arguments: Vec, -} - -/// Which paths a world's files may name. -/// -/// No world file capability exists yet; this is the policy one must check. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum FileScope { - /// Only the world's own sandbox root. - #[default] - Confined, - /// Any path. - Unrestricted, -} - -/// Whether a file access reads or writes. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum FileMode { - /// Reading a file. - Read, - /// Creating, changing or deleting a file. - Write, -} - -/// A world's sharing and file settings, read in one step. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] -pub struct WorldPolicy { - /// Whether other worlds may read this one. - pub isolation: Isolation, - /// Whether other unisolated worlds may write here. - pub cross_world_write: bool, - /// Whether an admin forced `cross_world_write` on, so a moderator cannot turn it off. - pub cross_world_forced: bool, - /// Which paths the world's files may name. - pub file_scope: FileScope, - /// Whether the admin let an isolated world write files. - pub file_write_override: bool, -} - -impl WorldPolicy { - /// Whether a file access is allowed. Isolated worlds only read unless the - /// admin override is set; the scope then decides which paths. - #[must_use] - pub const fn file_allowed(self, mode: FileMode, inside_root: bool) -> bool { - let in_scope = match self.file_scope { - FileScope::Confined => inside_root, - FileScope::Unrestricted => true, - }; - let writable = match mode { - FileMode::Read => true, - FileMode::Write => { - matches!(self.isolation, Isolation::Unisolated) || self.file_write_override - } - }; - in_scope && writable - } -} - -/// Who asks for a change only an admin or a moderator may make. -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum Authority { - /// The process admin token, already checked by the transport. - Admin, - /// A signed request made with this public key, as lower-case hex. - Signed(String), -} - -/// One durable fact about a world, in commit order. -/// -/// Capability secrets are never journaled, only their SHA-256 digests, so a -/// leaked journal cannot be used to join. Replaying a journal rebuilds the -/// participants, the event sequence, and (with the module bytes) the program. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(tag = "entry", rename_all = "snake_case")] -pub enum JournalEntry { - /// First entry of every journal. - Created { - /// World this journal belongs to. - world_id: String, - /// Journal format version. - version: u32, - }, - /// A capability was issued. - Issued { - /// The new participant. - participant: Participant, - /// Hex SHA-256 of the bearer capability. - digest: String, - /// Granted scopes (bit set). - scopes: u8, - /// The capability this one was delegated from, if any. - #[serde(default, skip_serializing_if = "Option::is_none")] - parent: Option, - /// Unix milliseconds at which the capability stops working. - #[serde(default, skip_serializing_if = "Option::is_none")] - expires_at: Option, - /// Committed chat and input actions the capability may take. Host-local: - /// only a capability the host issued has one, never a delegation. - #[serde(default, skip_serializing_if = "Option::is_none")] - uses: Option, - /// Actions already taken, written at checkpoint so counts survive compaction. - /// Host-local, like `uses`. - #[serde(default)] - used: u32, - /// Account the capability acts for; its ceiling and friendships bound it. - #[serde(default, skip_serializing_if = "Option::is_none")] - subject: Option, - }, - /// A capability was revoked, with every capability delegated from it. - /// Replay revokes the same tree. - Revoked { - /// Participant whose capability was revoked. - participant_id: u64, - }, - /// A sequenced event was committed. - Committed { - /// The event. - event: WorldEvent, - }, - /// A host event delivered to the program (capability result, tick, - /// presence). Delivered with sequence 0; the program saw it, so replay - /// must too. - System { - /// The event as it was delivered. - event: WorldEvent, - }, - /// The world's granted capability set, written whole on every change. - CapsGranted { - /// Capability names. - granted: Vec, - }, - /// The world's capability ceiling, written whole on every change. Absent - /// means the whole catalog. Checkpoints carry it in `caps_ceiling`. - CapsCeiling { - /// Capability names the world allows. - ceiling: Vec, - }, - /// The world's requested execution profile. Limits are resolved against - /// the current server hard ceilings when a program instance is created. - ExecutionProfile { - /// Per-world resource requests; omitted fields inherit server limits. - profile: crate::world_limits::WorldExecutionProfile, - }, - /// The world's isolation, written whole on every change. Absent means - /// [`Isolation::Isolated`]. - Isolation { - /// The new isolation. - isolation: Isolation, - }, - /// Whether other unisolated worlds may write here, set by a moderator or - /// the admin. `enabled: false` also clears a force. Absent means off. - CrossWorldWrite { - /// The new setting. - enabled: bool, - }, - /// The admin forced cross-world writes on. Absent means not forced. - CrossWorldWriteForced, - /// The world's file scope, written whole on every change. Absent means confined. - FileScope { - /// The new scope. - scope: FileScope, - }, - /// Whether the admin let an isolated world write files. Absent means off. - FileWriteOverride { - /// The new setting. - enabled: bool, - }, - /// A `schedule.at` request was accepted: `id` fires once, at `at_ms` (unix - /// milliseconds). Written before the request's result is delivered. - ScheduleSet { - /// The schedule's id, unique among pending schedules. - id: String, - /// When it fires, in unix milliseconds. - at_ms: u64, - }, - /// A pending schedule was cancelled before it fired. - ScheduleCancelled { - /// The cancelled schedule's id. - id: String, - }, - /// A pending schedule fired. It follows the fire's `System` entry, which - /// the program accepted first, so the schedule is consumed only once its - /// delivery is durable. - ScheduleFired { - /// The fired schedule's id. - id: String, - }, - /// The world as of `sequence`, standing in for every event up to it. Only - /// ever written by compaction, directly after the participant entries. - Checkpoint { - /// Sequence of the last event the checkpoint covers. - sequence: u64, - /// Active program. - module_hash: String, - /// Seed the program was initialized with. - seed: u64, - /// Provenance of the active module, if it was recorded. - #[serde(default, skip_serializing_if = "Option::is_none")] - provenance: Option, - /// Requested resource profile. Absent in older checkpoints. - #[serde(default, skip_serializing_if = "Option::is_none")] - execution_profile: Option, - /// The world's capability ceiling. Absent in older checkpoints, and - /// when it is the whole catalog. - #[serde(default, skip_serializing_if = "Option::is_none")] - caps_ceiling: Option>, - /// Pending schedules as `(id, at_ms)`. Absent when none are pending, - /// and it must match the `ScheduleSet` entries before it. - #[serde(default, skip_serializing_if = "Option::is_none")] - schedules: Option>, - /// The program's own serialization of its state. - snapshot: String, - /// Recent events kept for reconnect catch-up. - events: Vec, - }, -} - -/// Current [`JournalEntry::Created`] version. -pub const JOURNAL_VERSION: u32 = 1; - -/// Durable, append-only record of a world's history. -/// -/// The actor calls `append` before acknowledging or broadcasting a mutation. -/// If `append` fails, the world turns read-only: acknowledged history must -/// never get ahead of durable history. -pub trait WorldJournal: Send + 'static { - /// Durably append one entry. - /// - /// # Errors - /// - /// Any I/O failure; the actor then refuses further mutations. - fn append(&mut self, entry: &JournalEntry) -> Result<()>; - - /// Atomically replace the whole journal with `entries` (a header, the - /// participants and a [`JournalEntry::Checkpoint`]). Either the old or - /// the new journal survives a crash, never a mixture. - /// - /// # Errors - /// - /// Journals that cannot compact (the default), or any I/O failure. After - /// an error the journal must still be a complete record of the world. - fn compact(&mut self, _entries: &[JournalEntry]) -> Result<()> { - bail!("this journal cannot be compacted") - } -} - -/// The program a journal says was running, and where to resume it from. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct RestoredProgram { - /// Content hash of the module. - pub module_hash: String, - /// Seed it was initialized with. - pub seed: u64, - /// State to restore before replaying, if the journal was compacted behind - /// a checkpoint; otherwise the program starts from `init(seed)`. - pub snapshot: Option, - /// Server-observed module origin, if this journal version recorded it. - pub provenance: Option, -} - -/// A world rebuilt from its journal, before its program is re-instantiated. -#[derive(Debug)] -pub struct RestoredWorld { - /// Participants, sequence and retained events as of the last entry. - pub core: WorldCore, - /// The last installed program, if any. - pub program: Option, - /// Inputs committed after the install or checkpoint, in order, to replay - /// through it. - pub replay: Vec, -} - -/// The profile requested by the world admin and when it takes effect. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct ExecutionProfileUpdate { - /// Requested profile; this is not necessarily the active instance's limits. - pub requested: crate::world_limits::WorldExecutionProfile, - /// True when a program is currently running with its previously resolved limits. - pub applies_on_next_program_install_or_process_restart: bool, -} - -/// Structured records a program publishes: key to JSON value, key-ordered. -pub type Records = BTreeMap; - -fn presence_event(participant: u64, name: &str, joined: bool) -> String { - serde_json::json!({ - "cap": "players", - "event": if joined { "joined" } else { "left" }, - "participant": {"id": participant, "name": name}, - }) - .to_string() -} - -fn presence_change(text: &str) -> Option<(u64, bool)> { - let value: serde_json::Value = serde_json::from_str(text).ok()?; - if value.get("cap")?.as_str()? != "players" { - return None; - } - let joined = match value.get("event")?.as_str()? { - "joined" => true, - "left" => false, - _ => return None, - }; - Some((value.get("participant")?.get("id")?.as_u64()?, joined)) -} - -/// The host event a program receives when schedule `id` fires. `late` is set -/// only for a schedule the journal left overdue when the world reopened. -fn schedule_fired_event(id: &str, late: bool) -> String { - let mut event = serde_json::json!({"cap": "schedule", "event": "fired", "id": id}); - if late { - event["late"] = serde_json::Value::Bool(true); - } - event.to_string() -} - -/// When the earliest pending schedule is due, as a monotonic deadline. Nothing -/// waits while the program cannot take a fire (`deliverable` is false): a due -/// schedule that cannot be delivered would otherwise wake the loop without end. -fn next_schedule_wake( - schedules: &BTreeMap, - now_ms: u64, - deliverable: bool, -) -> Option { - if !deliverable { - return None; - } - let earliest = schedules.values().min().copied()?; - let wait = std::time::Duration::from_millis(earliest.saturating_sub(now_ms)); - Some(std::time::Instant::now() + wait) -} - -/// The newest `count` chat lines in `events`, oldest first, each carrying its -/// sequence, participant id, and text. The retained-events buffer is itself -/// bounded by the world's limits, so a request can never see unbounded history. -fn chat_history(events: &VecDeque, count: usize) -> Vec { - let mut lines: Vec = Vec::new(); - for event in events.iter().rev() { - if lines.len() >= count { - break; - } - if let WorldEventKind::Chat(text) = &event.kind { - lines.push(serde_json::json!({ - "sequence": event.sequence, - "participant": event.participant_id, - "text": text, - })); - } - } - lines.reverse(); - lines -} - -/// Most records one world may publish. -pub const MAX_RECORDS: usize = 4096; -/// Longest record key, in bytes. -pub const MAX_RECORD_KEY_BYTES: usize = 256; -/// Largest single record value (serialized JSON), in bytes. -pub const MAX_RECORD_VALUE_BYTES: usize = 8 * 1024; - -/// Parse and bound a program's records output. Keys must be non-empty, -/// at most [`MAX_RECORD_KEY_BYTES`], and free of control characters (the -/// storage layer uses `\0` as a key terminator). -/// -/// # Errors -/// -/// Anything that is not a bounded JSON object of valid keys. -pub fn parse_records(text: &str) -> Result { - let records: Records = - serde_json::from_str(text).context("world records must be a JSON object")?; - ensure!( - records.len() <= MAX_RECORDS, - "world publishes {} records; the limit is {MAX_RECORDS}", - records.len() - ); - for (key, value) in &records { - ensure!( - !key.is_empty() && key.len() <= MAX_RECORD_KEY_BYTES, - "record key must be 1..={MAX_RECORD_KEY_BYTES} bytes" - ); - ensure!( - !key.chars().any(char::is_control), - "record key {key:?} contains a control character" - ); - let size = serde_json::to_vec(value).map_or(usize::MAX, |v| v.len()); - ensure!( - size <= MAX_RECORD_VALUE_BYTES, - "record {key:?} is {size} bytes; the limit is {MAX_RECORD_VALUE_BYTES}" - ); - } - Ok(records) -} - -/// Records of `program`, validated; `Ok(None)` when it keeps none. -fn program_records(program: &mut dyn WorldProgram) -> Result> { - program - .records()? - .map(|text| parse_records(&text)) - .transpose() -} - -/// Behavior supplied by the running world program. -/// -/// Implementations execute inside the actor's serial command loop. They must -/// not perform network or filesystem I/O. An error from `update` rejects the -/// candidate input before it is committed to the event log. The Wasmtime -/// implementation poisons its guest instance on traps. -pub trait WorldProgram: Send + 'static { - /// Apply an opaque participant input. Chat is managed by the host and is - /// not passed to the game program. - fn update(&mut self, _event: &WorldEvent) -> Result<()> { - Ok(()) - } - - /// Return this participant's presentation, or `None` for a chat-only - /// world. The presentation must be UTF-8 and fit `presentation_bytes`. - fn view(&mut self, _viewer: &Participant) -> Result> { - Ok(None) - } - - /// Return this participant's presentation laid out for a `width` by - /// `height` viewport. Defaults to [`Self::view`]; a program that can reflow - /// overrides it. Rendering must not change state. - fn layout( - &mut self, - viewer: &Participant, - _width: u16, - _height: u16, - ) -> Result> { - self.view(viewer) - } - - /// Structured records projected from the program state: a JSON object - /// mapping record keys to JSON values, or `None` if the program keeps no - /// records. Must be a pure function of state (it is recomputed on replay). - fn records(&mut self) -> Result> { - Ok(None) - } - - /// The program's state as text that [`crate::world_store`] can restore it - /// from, or `None` if it cannot snapshot (its journal then keeps growing). - /// An implementation must only return a snapshot it has verified restores - /// faithfully: the journal is trimmed behind it. - fn snapshot(&mut self) -> Result> { - Ok(None) - } - - /// What the program wants from the server right now (see - /// [`crate::world_caps`]), or `None` if it makes no use of capabilities. - /// Must be a pure function of state: the host re-reads it after every - /// change and after a restart. - fn wants(&mut self) -> Result> { - Ok(None) - } -} - -#[derive(Debug, Default)] -struct EmptyWorldProgram; - -impl WorldProgram for EmptyWorldProgram {} - -/// Snapshot returned on join or reconnect. -#[derive(Clone, Debug, PartialEq, Eq, Serialize)] -pub struct WorldSnapshot { - /// Stable world identifier. - pub world_id: String, - /// Content hash of the active program, if this world executes one. - pub active_module_hash: Option, - /// Provenance for the active module, when recorded. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub active_module_provenance: Option, - /// Latest committed sequence at snapshot time. - pub current_sequence: u64, - /// Earliest event sequence present in this snapshot, or the current - /// sequence + 1 when it carries no events. - pub oldest_retained_sequence: u64, - /// Recent events, bounded by [`WorldLimits::retained_events`] and - /// [`WorldLimits::snapshot_bytes`] (the newest that fit). - pub events: Vec, - /// Public participant list. - pub participants: Vec, -} - -/// The one projection of an event onto a viewer holding `scopes`. -/// -/// Every path that hands an event to a participant — the snapshot, catch-up -/// pages and the live stream — goes through it. -/// -/// - A chat line is `None` unless `scopes` may read chat (`CHAT` or -/// `HISTORY`): a join-only participant sees the world, not the talk. -/// - A `ProgramInstalled` event keeps its module hash — joiners need it to -/// fetch the module — but its install seed is zeroed (#240), because a -/// program whose hidden state derives from `init(seed)` must not leak that -/// state to every participant. -/// - Anything else is returned as is. -/// -/// The journal, the core's retained events and the admin paths keep the real -/// events; replay that needs the seed uses the seed the admin installed with, -/// through the journal/admin path. -#[must_use] -pub fn project_event_for(scopes: WorldScopes, event: &WorldEvent) -> Option { - match &event.kind { - WorldEventKind::Chat(_) if !scopes.reads_chat() => None, - WorldEventKind::ProgramInstalled { .. } => { - // Mutate in place so every other field, including the observed - // build provenance, is kept as it is. - let mut shown = event.clone(); - if let WorldEventKind::ProgramInstalled { seed, .. } = &mut shown.kind { - *seed = 0; - } - Some(shown) - } - _ => Some(event.clone()), - } -} - -/// Limits on what a capability may do before it stops working. -/// -/// Only the host sets `uses`, on a capability it issues. A delegation may set -/// `expires_at` and never `uses` (see [`WorldCore::attenuate`]). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub struct CapabilityBounds { - /// Unix milliseconds at which the capability stops working. - pub expires_at: Option, - /// Committed chat and input actions the capability may take. Enforced by - /// the host alone, from its own journal. - pub uses: Option, -} - -#[derive(Clone, Debug)] -struct CapabilityRecord { - digest: [u8; 32], - participant: Participant, - scopes: WorldScopes, - parent: Option, - revoked: bool, - bounds: CapabilityBounds, - used: u32, - subject: Option, -} - -/// Mutable world state. Keep it behind one actor/mutex so event sequencing is serialized. -#[derive(Debug)] -pub struct WorldCore { - world_id: String, - limits: WorldLimits, - execution_profile: crate::world_limits::WorldExecutionProfile, - next_participant_id: u64, - sequence: u64, - active_module_hash: Option, - active_module_provenance: Option, - active_seed: u64, - /// What this world's program may ask the server for. - pub(crate) ledger: crate::world_caps::CapLedger, - /// This world's own capability ceiling. The ledger allows the intersection - /// of this and the server's `limits.server_caps`. - caps_ceiling: BTreeSet, - /// Pending `schedule.at` fires: id to due time, in unix milliseconds. - schedules: BTreeMap, - isolation: Isolation, - cross_world_write: bool, - cross_world_forced: bool, - file_scope: FileScope, - file_write_override: bool, - /// Events committed since the journal last started from a checkpoint. - since_checkpoint: u64, - capabilities: HashMap, - /// Recent chat timestamps, pruned to the active rolling window on each send. - chat_rates: HashMap>, - events: VecDeque, - directory: crate::directory::Directory, - petnames: crate::petname::Petnames, -} - -impl WorldCore { - /// Create an empty in-memory world. - pub fn new(world_id: impl Into, limits: WorldLimits) -> Result { - let world_id = world_id.into(); - ensure!(!world_id.trim().is_empty(), "world ID must not be empty"); - ensure!( - limits.participants > 0, - "world participant limit must be nonzero" - ); - ensure!(limits.chat_bytes > 0, "world chat limit must be nonzero"); - ensure!(limits.input_bytes > 0, "world input limit must be nonzero"); - ensure!( - limits.retained_events > 0, - "world event retention must be nonzero" - ); - ensure!( - limits.presentation_bytes > 0, - "world presentation limit must be nonzero" - ); - ensure!( - limits.snapshot_bytes > 0, - "world snapshot limit must be nonzero" - ); - let server_caps: Vec = limits.server_caps.iter().cloned().collect(); - crate::world_caps::validate_ceiling_names(&server_caps) - .context("server capability ceiling")?; - let grant_on_use = limits.grant_on_use; - let mut core = Self { - world_id, - limits, - execution_profile: crate::world_limits::WorldExecutionProfile::default(), - next_participant_id: 1, - sequence: 0, - active_module_hash: None, - active_module_provenance: None, - active_seed: 0, - ledger: crate::world_caps::CapLedger::new(BTreeSet::new(), grant_on_use), - caps_ceiling: crate::world_caps::catalog_names(), - schedules: BTreeMap::new(), - isolation: Isolation::default(), - cross_world_write: false, - cross_world_forced: false, - file_scope: FileScope::default(), - file_write_override: false, - since_checkpoint: 0, - capabilities: HashMap::new(), - chat_rates: HashMap::new(), - events: VecDeque::new(), - directory: crate::directory::Directory::new(), - petnames: crate::petname::Petnames::new(), - }; - core.sync_ledger_ceiling(); - Ok(core) - } - - /// Recompute what the ledger may allow: the server's limit intersected with - /// this world's ceiling. Call whenever either one changes. - fn sync_ledger_ceiling(&mut self) { - let allowed = self - .limits - .server_caps - .intersection(&self.caps_ceiling) - .cloned() - .collect(); - self.ledger.set_allowed(allowed); - } - - /// Rebuild a world from its journal. - /// - /// # Errors - /// - /// Fails if the journal belongs to another world, uses an unknown - /// version, or is internally inconsistent (out-of-order sequences, - /// unknown participants, malformed digests). A bad journal is refused, - /// never partially applied. - pub fn restore( - world_id: impl Into, - limits: WorldLimits, - entries: impl IntoIterator, - ) -> Result { - let mut core = Self::new(world_id, limits)?; - let mut program = None; - let mut replay = Vec::new(); - let mut present: BTreeMap = BTreeMap::new(); - let mut entries = entries.into_iter(); - match entries.next() { - Some(JournalEntry::Created { world_id, version }) => { - ensure!( - world_id == core.world_id, - "journal belongs to world {world_id:?}, not {:?}", - core.world_id - ); - ensure!( - version == JOURNAL_VERSION, - "unsupported world journal version {version}" - ); - } - Some(_) => anyhow::bail!("world journal does not start with a header"), - None => { - return Ok(RestoredWorld { - core, - program, - replay, - }); - } - } - for entry in entries { - match entry { - JournalEntry::Created { .. } => anyhow::bail!("duplicate world journal header"), - JournalEntry::Issued { - participant, - digest, - scopes, - parent, - expires_at, - uses, - used, - subject, - } => { - let digest = hex_decode_32(&digest).context("malformed capability digest")?; - ensure!( - !core.capabilities.contains_key(&participant.id), - "participant {} issued twice", - participant.id - ); - ensure!( - parent.is_none_or(|parent| core.capabilities.contains_key(&parent)), - "participant {} delegated from an unknown capability", - participant.id - ); - ensure!( - uses.is_none_or(|uses| uses >= 1), - "participant {} has an empty use limit", - participant.id - ); - if let Some(parent) = parent.and_then(|id| core.capabilities.get(&id)) { - ensure!( - expires_at.is_none_or(|expires| parent - .bounds - .expires_at - .is_none_or(|limit| expires <= limit)), - "participant {} outlives the capability it was delegated from", - participant.id - ); - } - core.next_participant_id = core.next_participant_id.max( - participant - .id - .checked_add(1) - .context("participant ID exhausted")?, - ); - core.capabilities.insert( - participant.id, - CapabilityRecord { - digest, - participant, - scopes: WorldScopes(scopes), - parent, - revoked: false, - bounds: CapabilityBounds { expires_at, uses }, - used, - subject, - }, - ); - } - JournalEntry::Revoked { participant_id } => { - ensure!( - !core.revoke_tree(participant_id).is_empty(), - "journal revokes unknown or revoked participant {participant_id}" - ); - } - JournalEntry::CapsGranted { granted } => { - for name in &granted { - ensure!( - name == "*" || crate::world_caps::is_known(name), - "journal grants unknown capability {name:?}" - ); - } - core.ledger.set_granted(granted.iter().cloned().collect()); - } - JournalEntry::CapsCeiling { ceiling } => { - crate::world_caps::validate_ceiling_names(&ceiling) - .context("invalid capability ceiling in journal")?; - core.caps_ceiling = ceiling.into_iter().collect(); - } - JournalEntry::ExecutionProfile { profile } => { - profile - .resolve(crate::world_limits::RuntimeLimits::default()) - .context("invalid world execution profile in journal")?; - core.execution_profile = profile; - } - JournalEntry::Isolation { isolation } => core.isolation = isolation, - JournalEntry::CrossWorldWrite { enabled } => { - core.cross_world_write = enabled; - if !enabled { - core.cross_world_forced = false; - } - } - JournalEntry::CrossWorldWriteForced => { - core.cross_world_write = true; - core.cross_world_forced = true; - } - JournalEntry::FileScope { scope } => core.file_scope = scope, - JournalEntry::FileWriteOverride { enabled } => core.file_write_override = enabled, - JournalEntry::ScheduleSet { id, at_ms } => { - crate::world_caps::validate_schedule_id(&id) - .context("invalid schedule id in journal")?; - ensure!( - !core.schedules.contains_key(&id), - "journal schedules {id:?} twice" - ); - ensure!( - core.schedules.len() < crate::world_caps::MAX_PENDING_SCHEDULES, - "journal holds more than {} pending schedules", - crate::world_caps::MAX_PENDING_SCHEDULES - ); - // No clock here: the due time is what the request set, and - // a restore never judges it against now. - core.schedules.insert(id, at_ms); - } - JournalEntry::ScheduleCancelled { id } => { - ensure!( - core.schedules.remove(&id).is_some(), - "journal cancels schedule {id:?}, which is not pending" - ); - } - JournalEntry::ScheduleFired { id } => { - ensure!( - core.schedules.remove(&id).is_some(), - "journal fires schedule {id:?}, which is not pending" - ); - } - JournalEntry::System { event } => { - ensure!( - event.sequence == 0 && event.participant_id == 0, - "journal system event claims a sequence" - ); - let change = match &event.kind { - WorldEventKind::System { event: text } => presence_change(text), - _ => None, - }; - if let Some((participant, joined)) = change { - let count = present.entry(participant).or_insert(0); - if joined { - *count += 1; - } else { - *count = count.saturating_sub(1); - } - if *count == 0 { - present.remove(&participant); - } - } - replay.push(event.clone()); - core.since_checkpoint = core.since_checkpoint.saturating_add(1); - } - JournalEntry::Committed { event } => { - ensure!( - event.sequence == core.sequence.saturating_add(1), - "journal sequence jumps from {} to {}", - core.sequence, - event.sequence - ); - match &event.kind { - WorldEventKind::ProgramInstalled { - module_hash, - seed, - provenance, - } => { - core.active_module_hash = Some(module_hash.clone()); - core.active_module_provenance = provenance.clone(); - core.active_seed = *seed; - program = Some(RestoredProgram { - module_hash: module_hash.clone(), - seed: *seed, - snapshot: None, - provenance: provenance.clone(), - }); - replay.clear(); - } - WorldEventKind::Input(_) => replay.push(event.clone()), - // System events belong to the journal's tail; a - // checkpoint behind them already contains their effect. - WorldEventKind::System { .. } | WorldEventKind::Chat(_) => {} - } - core.commit_prepared(event)?; - } - JournalEntry::Checkpoint { - sequence, - module_hash, - seed, - provenance, - execution_profile, - caps_ceiling, - schedules, - snapshot, - events, - } => { - ensure!( - core.sequence == 0 && program.is_none(), - "journal checkpoint does not come first" - ); - ensure!( - events.last().is_none_or(|last| last.sequence == sequence) - && events - .windows(2) - .all(|pair| pair[1].sequence == pair[0].sequence + 1), - "journal checkpoint events are out of order" - ); - core.sequence = sequence; - core.events = events.into(); - while core.events.len() > core.limits.retained_events { - core.events.pop_front(); - } - core.active_module_hash = Some(module_hash.clone()); - core.active_module_provenance = provenance.clone(); - core.active_seed = seed; - let execution_profile = execution_profile.unwrap_or_default(); - execution_profile - .resolve(crate::world_limits::RuntimeLimits::default()) - .context("invalid world execution profile in checkpoint")?; - core.execution_profile = execution_profile; - // Absent means the whole catalog: older checkpoints and - // default ceilings omit the field. - core.caps_ceiling = match caps_ceiling { - Some(ceiling) => { - crate::world_caps::validate_ceiling_names(&ceiling) - .context("invalid capability ceiling in checkpoint")?; - ceiling.into_iter().collect() - } - None => crate::world_caps::catalog_names(), - }; - // The writer emits one `ScheduleSet` per pending schedule - // before the checkpoint, so the two must agree exactly. - let listed = schedules.unwrap_or_default(); - let declared: BTreeMap = listed.iter().cloned().collect(); - ensure!( - declared.len() == listed.len() && declared == core.schedules, - "journal checkpoint's pending schedules disagree with its schedule entries" - ); - program = Some(RestoredProgram { - module_hash, - seed, - snapshot: Some(snapshot), - provenance, - }); - } - } - } - // Sessions end with the process, and a crash skips their leave, so - // anyone the journal still shows present is gone by now. - for participant in present.into_keys() { - let name = core - .participant(participant) - .map_or_else(|| participant.to_string(), |p| p.display_name); - replay.push(WorldEvent { - sequence: 0, - participant_id: 0, - kind: WorldEventKind::System { - event: presence_event(participant, &name, false), - }, - }); - } - core.sync_ledger_ceiling(); - Ok(RestoredWorld { - core, - program, - replay, - }) - } - - /// Whether enough events piled up behind the last checkpoint to trim. - const fn checkpoint_due(&self) -> bool { - self.limits.checkpoint_every > 0 - && self.active_module_hash.is_some() - && self.since_checkpoint >= self.limits.checkpoint_every - } - - /// The journal that replaces the current one behind `snapshot`: a header, - /// every participant (and revocation), then the checkpoint itself. - fn checkpoint_entries(&self, snapshot: String) -> Result> { - let module_hash = self - .active_module_hash - .clone() - .context("no active program to checkpoint")?; - let mut ids: Vec = self.capabilities.keys().copied().collect(); - ids.sort_unstable(); - let mut entries = vec![JournalEntry::Created { - world_id: self.world_id.clone(), - version: JOURNAL_VERSION, - }]; - for id in ids { - entries.extend(self.issued_entry(id)); - if self - .capabilities - .get(&id) - .is_some_and(|record| record.revoked) - { - entries.push(JournalEntry::Revoked { participant_id: id }); - } - } - let granted: Vec = self.ledger.granted().iter().cloned().collect(); - if !granted.is_empty() { - entries.push(JournalEntry::CapsGranted { granted }); - } - // The ceiling rides on the checkpoint, so compaction keeps it; the - // default is omitted and reads back as the whole catalog. - let caps_ceiling: Option> = (self.caps_ceiling - != crate::world_caps::catalog_names()) - .then(|| self.caps_ceiling.iter().cloned().collect()); - if let Some(ceiling) = &caps_ceiling { - // An older binary cannot read a `CapsCeiling` entry and refuses the - // journal. Without it, the older binary would ignore the checkpoint - // field and restore the whole catalog, widening authority silently. - entries.push(JournalEntry::CapsCeiling { - ceiling: ceiling.clone(), - }); - } - if self.isolation != Isolation::default() { - entries.push(JournalEntry::Isolation { - isolation: self.isolation, - }); - } - if self.cross_world_forced { - entries.push(JournalEntry::CrossWorldWriteForced); - } else if self.cross_world_write { - entries.push(JournalEntry::CrossWorldWrite { enabled: true }); - } - if self.file_scope != FileScope::default() { - entries.push(JournalEntry::FileScope { - scope: self.file_scope, - }); - } - if self.file_write_override { - entries.push(JournalEntry::FileWriteOverride { enabled: true }); - } - if self.execution_profile != crate::world_limits::WorldExecutionProfile::default() { - entries.push(JournalEntry::ExecutionProfile { - profile: self.execution_profile, - }); - } - // One entry per pending schedule, before the checkpoint, mirroring the - // ceiling: an older binary cannot read `ScheduleSet` and refuses the - // journal, instead of restoring without the schedules. - for (id, at_ms) in &self.schedules { - entries.push(JournalEntry::ScheduleSet { - id: id.clone(), - at_ms: *at_ms, - }); - } - let schedules: Option> = (!self.schedules.is_empty()).then(|| { - self.schedules - .iter() - .map(|(id, at_ms)| (id.clone(), *at_ms)) - .collect() - }); - entries.push(JournalEntry::Checkpoint { - sequence: self.sequence, - module_hash, - seed: self.active_seed, - provenance: self.active_module_provenance.clone(), - execution_profile: Some(self.execution_profile), - caps_ceiling, - schedules, - snapshot, - events: self.events.iter().cloned().collect(), - }); - Ok(entries) - } - - /// The world's active (non-revoked) participants. - #[must_use] - pub(crate) fn participants(&self) -> Vec { - self.capabilities - .values() - .filter(|record| !record.revoked) - .map(|record| record.participant.clone()) - .collect() - } - - /// One participant, whether revoked or not. - #[must_use] - pub(crate) fn participant(&self, id: u64) -> Option { - self.capabilities - .get(&id) - .map(|record| record.participant.clone()) - } - - /// Commit a host-authored chat line as participant 0. - /// - /// # Errors - /// - /// Fails when the text is empty, oversized, or entirely sanitized away. - pub(crate) fn system_chat(&mut self, text: &str) -> Result { - ensure!( - text.len() <= self.limits.chat_bytes, - "chat message exceeds {} bytes", - self.limits.chat_bytes - ); - let text = sanitize_chat(text); - ensure!(!text.is_empty(), "chat message must not be empty"); - self.commit(0, WorldEventKind::Chat(text)) - } - - /// Whether a `schedule.at` for `id` may be pended, given the host clock - /// `now_ms`. The error says why; the program sees only `bad_args`. - /// - /// # Errors - /// - /// A malformed id, a duplicate pending id, a full schedule, or a time past - /// the horizon. - fn check_schedule(&self, id: &str, at_ms: u64, now_ms: u64) -> Result<()> { - crate::world_caps::validate_schedule_id(id)?; - ensure!( - !self.schedules.contains_key(id), - "schedule {id:?} is already pending; cancel it before scheduling it again" - ); - ensure!( - self.schedules.len() < crate::world_caps::MAX_PENDING_SCHEDULES, - "world already has {} pending schedules", - crate::world_caps::MAX_PENDING_SCHEDULES - ); - let horizon = now_ms.saturating_add(crate::world_caps::MAX_SCHEDULE_HORIZON_MS); - ensure!( - at_ms <= horizon, - "schedule {id:?} is more than {} days past the host clock", - crate::world_caps::MAX_SCHEDULE_HORIZON_DAYS - ); - Ok(()) - } - - /// Journal entry for an already-issued capability. - fn issued_entry(&self, participant_id: u64) -> Option { - self.capabilities - .get(&participant_id) - .map(|record| JournalEntry::Issued { - participant: record.participant.clone(), - digest: hex_encode(&record.digest), - scopes: record.scopes.0, - parent: record.parent, - expires_at: record.bounds.expires_at, - uses: record.bounds.uses, - used: record.used, - subject: record.subject.clone(), - }) - } - - /// Latest committed event sequence. - #[must_use] - pub const fn current_sequence(&self) -> u64 { - self.sequence - } - - /// The world's identifier. - #[must_use] - pub fn world_id(&self) -> &str { - &self.world_id - } - - /// The per-world resource requests, independent of current server ceilings. - #[must_use] - pub const fn execution_profile(&self) -> crate::world_limits::WorldExecutionProfile { - self.execution_profile - } - - /// Issue a capability for a participant. Only `JOIN`-scoped capabilities - /// count toward active participant capacity. - pub fn issue_capability( - &mut self, - display_name: &str, - scopes: WorldScopes, - bounds: CapabilityBounds, - ) -> Result<(Participant, JoinCapability)> { - self.mint(display_name, scopes, None, None, bounds) - } - - /// Issue a capability that acts for the account `credential` belongs to. - /// Its scopes may not exceed that account's ceiling. - pub fn issue_for_account( - &mut self, - credential: &str, - scopes: WorldScopes, - bounds: CapabilityBounds, - display_name: &str, - ) -> Result<(Participant, JoinCapability)> { - let account = self - .directory - .account_for(credential) - .context("invalid account credential")?; - ensure!( - self.directory.ceiling(&account).implied().contains(scopes), - "this account may not hold those scopes" - ); - self.mint(display_name, scopes, None, Some(account), bounds) - } - - /// Delegate a capability: a new participant whose scopes are a subset of - /// the delegating capability's, and which is revoked with it. Its expiry - /// may not be later than the delegator's. It carries no use count: each - /// action it takes counts against the host-issued limit above it, if any. - pub fn attenuate( - &mut self, - token: &JoinCapability, - scopes: WorldScopes, - bounds: CapabilityBounds, - display_name: &str, - ) -> Result<(Participant, JoinCapability)> { - self.delegate(token, scopes, bounds, display_name, None) - } - - /// Delegate to a friend of the account this capability acts for. The - /// friend's ceiling must already hold the scopes, and the friendship must - /// still hold each time the capability is used. - pub fn delegate_to_friend( - &mut self, - token: &JoinCapability, - friend: &str, - scopes: WorldScopes, - bounds: CapabilityBounds, - display_name: &str, - ) -> Result<(Participant, JoinCapability)> { - let parent = self.authorize(token, WorldScopes::JOIN)?; - let owner = self - .capabilities - .get(&parent) - .and_then(|record| record.subject.clone()) - .context("only an account's capability can delegate to a friend")?; - ensure!( - self.directory.are_friends(&owner, friend), - "you can only delegate to a friend" - ); - ensure!( - self.directory.ceiling(friend).implied().contains(scopes), - "that friend may not hold those scopes" - ); - self.delegate(token, scopes, bounds, display_name, Some(friend.to_owned())) - } - - fn delegate( - &mut self, - token: &JoinCapability, - scopes: WorldScopes, - bounds: CapabilityBounds, - display_name: &str, - subject: Option, - ) -> Result<(Participant, JoinCapability)> { - let parent = self.authorize(token, WorldScopes::JOIN)?; - let parent_scopes = self - .effective_scopes(parent) - .context("world participant is unavailable")?; - let parent_record = self - .capabilities - .get(&parent) - .context("world participant is unavailable")?; - let scopes = parent_scopes - .attenuate(scopes) - .context("this capability may not delegate those scopes")?; - if let Some(expires_at) = bounds.expires_at { - ensure!( - expires_at > unix_ms(), - "delegated expiry must be in the future" - ); - ensure!( - parent_record - .bounds - .expires_at - .is_none_or(|limit| expires_at <= limit), - "this capability may not delegate a later expiry" - ); - } - ensure!( - bounds.uses.is_none(), - "a delegated capability carries no use count; the host's limit still applies" - ); - self.mint(display_name, scopes, Some(parent), subject, bounds) - } - - /// What a capability may do right now: its own scopes, held to the ceiling - /// of each account in its chain. A delegation to a friend stops once the - /// friendship ends. - fn effective_scopes(&self, participant_id: u64) -> Option { - self.capabilities.get(&participant_id)?; - let mut scopes = WorldScopes::ALL; - let mut current = Some(participant_id); - while let Some(record) = current.and_then(|id| self.capabilities.get(&id)) { - scopes = scopes.intersect(record.scopes.implied()); - if let Some(subject) = &record.subject { - scopes = scopes.intersect(self.directory.ceiling(subject).implied()); - } - let parent = record.parent.and_then(|id| self.capabilities.get(&id)); - if let Some(subject) = &record.subject - && let Some(parent_subject) = parent.and_then(|p| p.subject.as_ref()) - && subject != parent_subject - && !self.directory.are_friends(parent_subject, subject) - { - return Some(WorldScopes(0)); - } - current = record.parent; - } - Some(scopes) - } - - /// Fewest actions the capability or any ancestor may still take, or `None` - /// if no capability in the chain is limited. - fn uses_left(&self, participant_id: u64) -> Option { - let mut left = None; - let mut current = Some(participant_id); - while let Some(record) = current.and_then(|id| self.capabilities.get(&id)) { - if let Some(limit) = record.bounds.uses { - let remaining = limit.saturating_sub(record.used); - left = Some(left.map_or(remaining, |so_far: u32| so_far.min(remaining))); - } - current = record.parent; - } - left - } - - fn ensure_not_expired(&self, participant_id: u64) -> Result<()> { - let now = unix_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" - ); - current = record.parent; - } - Ok(()) - } - - fn ensure_uses_left(&self, participant_id: u64) -> Result<()> { - ensure!( - self.uses_left(participant_id).is_none_or(|left| left > 0), - "world capability has no uses left" - ); - Ok(()) - } - - /// Count one committed action against the participant and each ancestor. - fn spend(&mut self, participant_id: u64) { - let mut current = Some(participant_id); - while let Some(record) = current.and_then(|id| self.capabilities.get_mut(&id)) { - record.used = record.used.saturating_add(1); - current = record.parent; - } - } - - fn mint( - &mut self, - display_name: &str, - scopes: WorldScopes, - parent: Option, - subject: Option, - bounds: CapabilityBounds, - ) -> Result<(Participant, JoinCapability)> { - let active = self - .capabilities - .values() - .filter(|record| !record.revoked) - .count(); - ensure!( - active < self.limits.participants, - "world participant limit reached" - ); - ensure!( - scopes.contains(WorldScopes::JOIN), - "world capability must include join scope" - ); - let display_name = sanitize_display_name(display_name); - ensure!( - !display_name.is_empty(), - "participant display name must not be empty" - ); - let id = self.next_participant_id; - self.next_participant_id = self - .next_participant_id - .checked_add(1) - .context("participant ID exhausted")?; - let mut secret = [0_u8; 32]; - rand::rng().fill(&mut secret); - let token = format!("{id}.{}", hex_encode(&secret)); - let digest = token_digest(&token); - let participant = Participant { id, display_name }; - self.capabilities.insert( - id, - CapabilityRecord { - digest, - participant: participant.clone(), - scopes, - parent, - revoked: false, - bounds, - used: 0, - subject, - }, - ); - Ok((participant, JoinCapability(token))) - } - - /// Revoke a capability and every capability delegated from it. Returns - /// the participants newly revoked; empty if none was active. - pub fn revoke_tree(&mut self, participant_id: u64) -> Vec { - let mut revoked = Vec::new(); - let mut pending = vec![participant_id]; - while let Some(id) = pending.pop() { - let Some(record) = self.capabilities.get_mut(&id) else { - continue; - }; - if record.revoked { - continue; - } - record.revoked = true; - revoked.push(id); - pending.extend( - self.capabilities - .values() - .filter(|child| child.parent == Some(id)) - .map(|child| child.participant.id), - ); - } - revoked - } - - /// The world's isolation. - #[must_use] - pub const fn isolation(&self) -> Isolation { - self.isolation - } - - /// The world's sharing and file settings. - #[must_use] - pub const fn policy(&self) -> WorldPolicy { - WorldPolicy { - isolation: self.isolation, - cross_world_write: self.cross_world_write, - cross_world_forced: self.cross_world_forced, - file_scope: self.file_scope, - file_write_override: self.file_write_override, - } - } - - /// The directory of accounts, groups and friends this world is held to. - #[must_use] - pub const fn directory(&self) -> &crate::directory::Directory { - &self.directory - } - - /// The directory of accounts, groups and friends this world is held to. - pub const fn directory_mut(&mut self) -> &mut crate::directory::Directory { - &mut self.directory - } - - /// The directory and the private petnames, borrowed together. - pub const fn directory_and_petnames_mut( - &mut self, - ) -> ( - &mut crate::directory::Directory, - &mut crate::petname::Petnames, - ) { - (&mut self.directory, &mut self.petnames) - } - - /// Replace the petname store, as the world's data directory is opened. - pub fn set_petnames(&mut self, petnames: crate::petname::Petnames) { - self.petnames = petnames; - } - - /// Commit a chat message after validating capability and bounds. - pub fn chat(&mut self, token: &JoinCapability, text: &str) -> Result { - let participant_id = self.authorize(token, WorldScopes::CHAT)?; - self.ensure_uses_left(participant_id)?; - ensure!( - text.len() <= self.limits.chat_bytes, - "chat message exceeds {} bytes", - self.limits.chat_bytes - ); - let text = sanitize_chat(text); - ensure!(!text.is_empty(), "chat message must not be empty"); - let now = std::time::Instant::now(); - self.chat_rates.retain(|_, sent| { - while sent - .front() - .is_some_and(|at| now.duration_since(*at) >= CHAT_RATE_WINDOW) - { - sent.pop_front(); - } - !sent.is_empty() - }); - let current = self.chat_rates.get(&participant_id); - ensure!( - current.is_none_or(|sent| sent.len() < usize::from(CHAT_RATE_BURST)), - "chat rate exceeded; try again later" - ); - let event = self.commit(participant_id, WorldEventKind::Chat(text))?; - self.chat_rates - .entry(participant_id) - .or_default() - .push_back(now); - Ok(event) - } - - /// Commit an opaque game input after validating capability and bounds. - pub fn input(&mut self, token: &JoinCapability, input: &[u8]) -> Result { - let event = self.prepare_input(token, input)?; - self.commit_prepared(event) - } - - fn prepare_input(&self, token: &JoinCapability, input: &[u8]) -> Result { - let participant_id = self.authorize(token, WorldScopes::INPUT)?; - self.ensure_uses_left(participant_id)?; - ensure!( - input.len() <= self.limits.input_bytes, - "world input exceeds {} bytes", - self.limits.input_bytes - ); - ensure!(!input.is_empty(), "world input must not be empty"); - let sequence = self - .sequence - .checked_add(1) - .context("world event sequence exhausted")?; - Ok(WorldEvent { - sequence, - participant_id, - kind: WorldEventKind::Input(input.to_vec()), - }) - } - - fn commit_prepared(&mut self, event: WorldEvent) -> Result { - ensure!( - event.sequence == self.sequence.saturating_add(1), - "prepared world event is stale" - ); - self.sequence = event.sequence; - self.spend(event.participant_id); - self.since_checkpoint = self.since_checkpoint.saturating_add(1); - self.events.push_back(event.clone()); - while self.events.len() > self.limits.retained_events { - self.events.pop_front(); - } - Ok(event) - } - - /// Return the current bounded snapshot after validating join scope. Its - /// events are the viewer's projection: no chat without `chat` or - /// `history`, and no install seeds (#240). - pub fn snapshot(&self, token: &JoinCapability) -> Result { - let participant_id = self.authorize(token, WorldScopes::JOIN)?; - Ok(self.snapshot_unchecked(self.viewer_scopes(participant_id))) - } - - /// What the viewer holding `token` may see of `event`, as it is delivered - /// live. `Err` if the capability no longer joins (revoked, expired, or its - /// chain was cut), so a session can end; `Ok(None)` if the event is not - /// for this viewer. - pub fn project_for( - &self, - token: &JoinCapability, - event: &WorldEvent, - ) -> Result> { - let participant_id = self.authorize(token, WorldScopes::JOIN)?; - Ok(project_event_for(self.viewer_scopes(participant_id), event)) - } - - fn viewer_scopes(&self, participant_id: u64) -> WorldScopes { - self.effective_scopes(participant_id) - .unwrap_or(WorldScopes(0)) - } - - fn viewer(&self, token: &JoinCapability) -> Result { - let id = self.authorize(token, WorldScopes::JOIN)?; - self.capabilities - .get(&id) - .map(|record| record.participant.clone()) - .context("world participant is unavailable") - } - - /// Return retained events newer than `after_sequence`, plus the current - /// cursor. If the cursor fell behind retention, the caller must resnapshot. - /// The events are the viewer's projection (see [`project_event_for`]), so - /// their sequences may skip withheld lines: a caller advances to - /// `current_sequence`, not to the last sequence it was given plus one. - /// Retention and `needs_snapshot` do not depend on the viewer. - pub fn events_after(&self, token: &JoinCapability, after_sequence: u64) -> Result { - let participant_id = self.authorize(token, WorldScopes::JOIN)?; - let scopes = self.viewer_scopes(participant_id); - let oldest = self.oldest_sequence(); - let needs_snapshot = after_sequence.saturating_add(1) < oldest; - let events = if needs_snapshot { - Vec::new() - } else { - self.events - .iter() - .filter(|event| event.sequence > after_sequence) - .filter_map(|event| project_event_for(scopes, event)) - .collect() - }; - Ok(EventPage { - current_sequence: self.sequence, - oldest_retained_sequence: oldest, - needs_snapshot, - events, - }) - } - - fn authorize(&self, token: &JoinCapability, required: WorldScopes) -> Result { - let (participant, _) = token - .expose() - .split_once('.') - .context("malformed world capability")?; - let participant_id = participant - .parse::() - .context("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" - ); - ensure!( - !record.revoked - && self - .effective_scopes(participant_id) - .is_some_and(|scopes| scopes.contains(required)), - "invalid, revoked, or insufficient world capability" - ); - self.ensure_not_expired(participant_id)?; - Ok(participant_id) - } - - fn commit(&mut self, participant_id: u64, kind: WorldEventKind) -> Result { - self.sequence = self - .sequence - .checked_add(1) - .context("world event sequence exhausted")?; - let event = WorldEvent { - sequence: self.sequence, - participant_id, - kind, - }; - self.spend(participant_id); - self.since_checkpoint = self.since_checkpoint.saturating_add(1); - self.events.push_back(event.clone()); - while self.events.len() > self.limits.retained_events { - self.events.pop_front(); - } - Ok(event) - } - - fn oldest_sequence(&self) -> u64 { - self.events - .front() - .map_or_else(|| self.sequence.saturating_add(1), |event| event.sequence) - } - - fn snapshot_unchecked(&self, viewer: WorldScopes) -> WorldSnapshot { - let participants = self - .capabilities - .values() - .filter(|record| !record.revoked && record.scopes.contains(WorldScopes::JOIN)) - .map(|record| record.participant.clone()) - .collect(); - // Take the most recent events that fit the snapshot budget, newest - // first. A snapshot is a baseline, not a complete replay: clients - // adopt its sequence as their cursor. Events the viewer may not see - // are dropped before the budget is spent, so it counts only what the - // snapshot carries. - let mut budget = self.limits.snapshot_bytes; - let mut events: VecDeque = VecDeque::new(); - for event in self - .events - .iter() - .rev() - .filter_map(|event| project_event_for(viewer, event)) - { - let size = serde_json::to_vec(&event).map_or(budget, |encoded| encoded.len()); - if size > budget { - break; - } - budget -= size; - events.push_front(event); - } - let oldest_retained_sequence = events - .front() - .map_or_else(|| self.sequence.saturating_add(1), |event| event.sequence); - WorldSnapshot { - world_id: self.world_id.clone(), - active_module_hash: self.active_module_hash.clone(), - active_module_provenance: self.active_module_provenance.clone(), - current_sequence: self.sequence, - oldest_retained_sequence, - events: events.into_iter().collect(), - participants, - } - } -} - -/// Cloneable, serialized access to a world core. Every request passes through -/// one actor task, which defines the authoritative event order. -#[derive(Clone, Debug)] -pub struct WorldHandle { - commands: mpsc::Sender, - events: broadcast::Sender, - revocations: broadcast::Sender, - records: watch::Receiver<(u64, Arc)>, - view_changed: watch::Receiver, -} - -enum WorldCommand { - Issue { - name: String, - scopes: WorldScopes, - bounds: CapabilityBounds, - reply: oneshot::Sender>, - }, - Attenuate { - token: JoinCapability, - name: String, - scopes: WorldScopes, - bounds: CapabilityBounds, - reply: oneshot::Sender>, - }, - DelegateToFriend { - token: JoinCapability, - friend: String, - name: String, - scopes: WorldScopes, - bounds: CapabilityBounds, - reply: oneshot::Sender>, - }, - Directory { - caller: crate::directory_auth::Caller, - action: crate::directory_view::DirectoryAction, - /// Whether this server has an outbox to queue what the action sends. - outbox: bool, - reply: oneshot::Sender>, - }, - ApplyDirectory { - entry: crate::directory::DirectoryEntry, - reply: oneshot::Sender>, - }, - Revoke { - participant_id: u64, - reply: oneshot::Sender, - }, - ParticipantId { - token: JoinCapability, - reply: oneshot::Sender>, - }, - Chat { - token: JoinCapability, - text: String, - reply: oneshot::Sender>, - }, - Input { - token: JoinCapability, - input: Vec, - reply: oneshot::Sender>, - }, - Snapshot { - token: JoinCapability, - reply: oneshot::Sender>, - }, - EventsAfter { - token: JoinCapability, - sequence: u64, - reply: oneshot::Sender>, - }, - ProjectEvent { - token: JoinCapability, - event: WorldEvent, - reply: oneshot::Sender>>, - }, - View { - token: JoinCapability, - reply: oneshot::Sender>>, - }, - ViewAt { - token: JoinCapability, - width: u16, - height: u16, - reply: oneshot::Sender>>, - }, - InstallProgram { - module_hash: String, - seed: u64, - provenance: Option, - program: Box, - reply: oneshot::Sender>, - }, - /// A session opened or closed for this participant. - Presence { - participant: u64, - joined: bool, - }, - /// Admin: change the granted capability set. - UpdateCaps { - grant: Vec, - revoke: Vec, - reply: oneshot::Sender>, - }, - /// Admin: replace the world's capability ceiling. It applies immediately. - SetCapsCeiling { - ceiling: Vec, - reply: oneshot::Sender>, - }, - /// Admin: durably replace this world's requested runtime profile. - SetExecutionProfile { - profile: crate::world_limits::WorldExecutionProfile, - reply: oneshot::Sender>, - }, - /// Read this world's requested runtime profile. - ExecutionProfileInfo { - reply: oneshot::Sender, - }, - /// Admin: read the capability report. - CapsInfo { - reply: oneshot::Sender>, - }, - /// Admin or moderator: change the world's isolation. - SetIsolation { - authority: Authority, - isolation: Isolation, - reply: oneshot::Sender>, - }, - IsolationInfo { - reply: oneshot::Sender, - }, - /// Moderator or admin: let other unisolated worlds write here. - SetCrossWorldWrite { - authority: Authority, - enabled: bool, - reply: oneshot::Sender>, - }, - /// Admin: force cross-world writes on. - ForceCrossWorldWrite { - authority: Authority, - reply: oneshot::Sender>, - }, - /// Moderator or admin: set the file scope; the admin alone sets the override. - SetFileScope { - authority: Authority, - scope: FileScope, - write_override: Option, - reply: oneshot::Sender>, - }, - PolicyInfo { - reply: oneshot::Sender, - }, - Shutdown { - reply: oneshot::Sender<()>, - }, -} - -/// Trim `journal` behind a verified snapshot of `program`. `Ok(false)` means -/// the program cannot snapshot. -fn compact_journal( - core: &mut WorldCore, - program: &mut dyn WorldProgram, - journal: &mut dyn WorldJournal, -) -> Result { - let Some(snapshot) = program.snapshot()? else { - return Ok(false); - }; - let entries = core.checkpoint_entries(snapshot)?; - journal.compact(&entries)?; - core.since_checkpoint = 0; - tracing::info!( - "world {}: journal trimmed at sequence {}", - core.world_id, - core.sequence - ); - Ok(true) -} - -/// The world's single authority: owns the core, the program instance and the -/// journal, and runs commands plus the program's capability needs serially. -struct WorldActor { - core: WorldCore, - /// Sessions and pending email codes. In memory only: a restart ends them. - auth: crate::directory_auth::DirectoryAuth, - program: Box, - journal: Option>, - storage_failed: bool, - program_healthy: bool, - compaction_off: bool, - event_sender: broadcast::Sender, - revocation_sender: broadcast::Sender, - records_sender: watch::Sender<(u64, Arc)>, - view_changed: watch::Sender, - /// Live sessions per participant: presence is refcounted. - presence: HashMap, - /// Subscriptions the program asked for (granted or refused-and-remembered). - active_subs: BTreeSet, - /// Request ids already executed, so `wants` states intent, not polling. - handled_requests: BTreeSet, - /// Subscription specs already reported as refused. - denied_subs: BTreeSet, - /// Armed tick intervals to their next fire time. - ticks: BTreeMap, - /// Restored schedules already overdue when the world opened. Their first - /// fire is marked `late`; a cancel or fire removes the id. - overdue_at_open: BTreeSet, - /// The participant whose input is being processed. Requests the program - /// makes in response are checked against that participant's scopes. - acting: Option, -} - -impl WorldActor { - async fn run(mut self, mut receiver: mpsc::Receiver) { - self.after_change().await; - loop { - // Ticks and schedules sleep until their earliest deadline; with - // neither armed this branch never wakes. - let deadline = self.next_deadline(); - let command = tokio::select! { - command = receiver.recv() => match command { - Some(command) => command, - None => break, - }, - () = Self::sleep_until(deadline) => { - self.fire_ticks().await; - self.fire_schedules().await; - self.after_change().await; - continue; - } - }; - if matches!(command, WorldCommand::Shutdown { .. }) { - if let WorldCommand::Shutdown { reply } = command { - let _ = reply.send(()); - } - break; - } - self.handle(command).await; - self.after_change().await; - self.acting = None; - } - } - - async fn sleep_until(deadline: Option) { - match deadline { - Some(deadline) => { - tokio::time::sleep_until(tokio::time::Instant::from_std(deadline)).await; - } - None => std::future::pending().await, - } - } - - /// The earliest moment the loop must wake: the soonest armed tick or - /// pending schedule. Schedules wait only while the program can take them. - fn next_deadline(&self) -> Option { - let deliverable = self.program_healthy && !self.storage_failed; - self.ticks - .values() - .min() - .copied() - .into_iter() - .chain(next_schedule_wake( - &self.core.schedules, - unix_ms(), - deliverable, - )) - .min() - } - - fn check_storage(&self) -> Result<()> { - ensure!( - !self.storage_failed, - "world storage failed; the world is read-only" - ); - Ok(()) - } - - fn record_issued( - &mut self, - issued: (Participant, JoinCapability), - ) -> Result<(Participant, JoinCapability)> { - let entry = self - .core - .issued_entry(issued.0.id) - .context("issued capability vanished")?; - self.persist(entry)?; - Ok(issued) - } - - /// Durably record `entry`, or turn the world read-only. - fn persist(&mut self, entry: JournalEntry) -> Result<()> { - ensure!( - !self.storage_failed, - "world storage failed; the world is read-only" - ); - if let Some(journal) = self.journal.as_mut() - && let Err(error) = journal.append(&entry) - { - self.storage_failed = true; - tracing::error!("world journal append failed: {error:#}"); - return Err(error.context("world storage failed; the world is read-only")); - } - Ok(()) - } - - /// Publish freshly recomputed records. Participant events push their own - /// view frame right after the event; host events signal the views watch. - fn republished(&mut self, records: Records, sequence: u64) { - publish_records(&self.records_sender, sequence, records); - } - - /// Deliver a host-originated event to the program: journal it first is - /// impossible (the program must accept it for the journal to be true), so - /// the order is update, then journal, exactly like participant input. - /// Returns whether the program accepted the event and it was journaled. - async fn deliver(&mut self, text: String) -> bool { - if !self.program_healthy || self.storage_failed { - return false; - } - if text.len() > crate::world_caps::MAX_EVENT_BYTES { - tracing::error!("world event exceeds the delivery bound; dropped"); - return false; - } - let event = WorldEvent { - sequence: 0, - participant_id: 0, - kind: WorldEventKind::System { event: text }, - }; - if let Err(error) = self.program.update(&event) { - self.program_healthy = false; - tracing::error!("world program rejected a host event: {error:#}"); - return false; - } - match program_records(self.program.as_mut()) { - Ok(records) => { - let records = records.unwrap_or_default(); - publish_records(&self.records_sender, self.core.sequence, records); - } - Err(error) => { - self.program_healthy = false; - tracing::error!("world program records failed: {error:#}"); - return false; - } - } - let journaled = self.persist(JournalEntry::System { event }).is_ok(); - if journaled { - self.core.since_checkpoint = self.core.since_checkpoint.saturating_add(1); - } - let _ = self.view_changed.send(self.core.sequence); - journaled - } - - /// Recompute the program's `wants` and serve the delta: new subscriptions - /// (armed or refused), new requests (executed, result delivered). Passes - /// repeat while the program reacts to delivered results, so a chain of - /// asks settles inside one change. - async fn after_change(&mut self) { - for _ in 0..64 { - if !self.program_healthy || self.storage_failed { - break; - } - let Some(text) = (match self.program.wants() { - Ok(wants) => wants, - Err(error) => { - self.program_healthy = false; - tracing::error!("world program wants failed: {error:#}"); - break; - } - }) else { - break; - }; - let wants = match crate::world_caps::parse_wants(&text) { - Ok(wants) => wants, - Err(error) => { - self.program_healthy = false; - tracing::error!("world program wants invalid: {error:#}"); - break; - } - }; - self.apply_subscriptions(&wants).await; - let mut fresh = Vec::new(); - for request in &wants.requests { - if self.handled_requests.insert(request.id.clone()) { - fresh.push(request.clone()); - } - } - if fresh.is_empty() { - break; - } - // A program inventing endless request ids cannot grow this set - // without bound; old ids may then re-execute, which is the - // documented at-least-once behavior. - if self.handled_requests.len() > 4096 { - let current: BTreeSet = wants - .requests - .iter() - .map(|request| request.id.clone()) - .collect(); - self.handled_requests.retain(|id| current.contains(id)); - } - for request in fresh { - let outcome = self.execute(&request); - self.deliver(crate::world_caps::result_event(&request.id, outcome)) - .await; - } - } - self.compact_if_due().await; - } - - /// Subscribe new subscriptions, drop removed ones, refuse ungranted ones - /// (once per spec), and keep ticks armed only while someone is present. - async fn apply_subscriptions(&mut self, wants: &crate::world_caps::Wants) { - for sub in &wants.subscribe { - if !self.active_subs.insert(sub.clone()) { - continue; - } - match self.core.ledger.decide(sub.cap()) { - Decision::Allow => self.arm(sub), - Decision::AllowAndGrant => { - let granted: Vec = self.core.ledger.granted().iter().cloned().collect(); - let _ = self.persist(JournalEntry::CapsGranted { granted }); - self.arm(sub); - } - Decision::Deny(error) => { - let spec = sub.spec(); - if self.denied_subs.insert(spec.clone()) { - self.deliver(crate::world_caps::subscription_refused_event(&spec, error)) - .await; - } - } - } - } - let current = wants.subscribe.clone(); - self.active_subs.retain(|sub| current.contains(sub)); - self.denied_subs - .retain(|spec| current.iter().any(|sub| &sub.spec() == spec)); - if self.presence.values().all(|count| *count == 0) { - self.ticks.clear(); - } - } - - /// Arm a granted subscription's timer, if any and if anyone is present. - fn arm(&mut self, sub: &Subscription) { - if let Subscription::Tick(ms) = sub - && !self.presence.is_empty() - && !self.ticks.contains_key(ms) - { - self.ticks.insert( - *ms, - std::time::Instant::now() + std::time::Duration::from_millis(*ms), - ); - } - } - - /// Deliver one tick event per due interval and re-arm. - async fn fire_ticks(&mut self) { - let now = std::time::Instant::now(); - let due: Vec = self - .ticks - .iter() - .filter(|(_, next)| **next <= now) - .map(|(ms, _)| *ms) - .collect(); - for ms in due { - self.ticks - .insert(ms, now + std::time::Duration::from_millis(ms)); - let event = serde_json::json!({ - "cap": "time.tick", - "interval": ms, - "now": unix_ms(), - }); - self.deliver(event.to_string()).await; - } - } - - /// Fire the schedules that are due, earliest first, at most - /// [`crate::world_caps::MAX_SCHEDULE_FIRES_PER_WAKEUP`] per wakeup. Each - /// fire is delivered as a tick is, and its schedule is consumed only after - /// that delivery is journaled. A refused fire, or one that could not be - /// journaled, leaves its schedule pending, so the next run delivers it. - async fn fire_schedules(&mut self) { - let now = unix_ms(); - let mut due: Vec<(u64, String)> = self - .core - .schedules - .iter() - .filter(|(_, at_ms)| **at_ms <= now) - .map(|(id, at_ms)| (*at_ms, id.clone())) - .collect(); - due.sort_unstable(); - due.truncate(crate::world_caps::MAX_SCHEDULE_FIRES_PER_WAKEUP); - for (_, id) in due { - let late = self.overdue_at_open.contains(&id); - if !self.deliver(schedule_fired_event(&id, late)).await { - break; - } - if self - .persist(JournalEntry::ScheduleFired { id: id.clone() }) - .is_err() - { - break; - } - self.core.schedules.remove(&id); - self.overdue_at_open.remove(&id); - } - } - - /// Execute one capability request. Anything the world has not granted is - /// an error the program sees. - fn execute(&mut self, request: &Request) -> Result { - let actor_permits = match self.acting { - None => true, - Some(participant) => self - .core - .effective_scopes(participant) - .is_some_and(|scopes| scopes.allows_effect(&request.cap)), - }; - match self.core.ledger.decide_for(&request.cap, actor_permits) { - Decision::Allow => {} - Decision::AllowAndGrant => { - let granted: Vec = self.core.ledger.granted().iter().cloned().collect(); - let _ = self.persist(JournalEntry::CapsGranted { granted }); - } - Decision::Deny(error) => return Err(error), - } - match request.cap.as_str() { - "time.now" => Ok(serde_json::json!({"now": unix_ms()})), - "random.u64" => Ok(serde_json::json!({"value": rand::rng().random::()})), - "players.list" => Ok(serde_json::json!({"players": self.players_list()})), - "world.info" => Ok(serde_json::json!({ - "world": self.core.world_id, - "sequence": self.core.sequence, - })), - "chat.say" => self.execute_chat(&request.args), - "chat.history" => Ok(serde_json::json!({ - "lines": chat_history( - &self.core.events, - request - .args - .get("count") - .and_then(serde_json::Value::as_u64) - .unwrap_or(16) - .min(crate::world_caps::MAX_CHAT_HISTORY_LINES as u64) as usize, - ), - })), - "records.read" => self.execute_records_read(&request.args), - "schedule.at" => self.execute_schedule_at(&request.args), - "schedule.cancel" => self.execute_schedule_cancel(&request.args), - _ => Err(CapError::Unknown), - } - } - - fn players_list(&self) -> Vec { - self.core - .participants() - .into_iter() - .map(|participant| { - serde_json::json!({ - "id": participant.id, - "name": participant.display_name, - "present": self.presence.get(&participant.id).is_some_and(|c| *c > 0), - }) - }) - .collect() - } - - /// `records.read`: a byte-bounded, prefix-scoped page of the world's - /// published records, key-ordered with the same exclusive `after` cursor - /// the session protocol uses. Follow `next_after` while it is non-empty. - fn execute_records_read( - &self, - args: &serde_json::Value, - ) -> Result { - let records = self.records_sender.borrow().1.clone(); - let prefix = args.get("prefix").and_then(serde_json::Value::as_str); - let after = args.get("after").and_then(serde_json::Value::as_str); - let mut page: Vec = Vec::new(); - let mut used = 0usize; - let mut last_included: Option = None; - let mut more = false; - for (key, value) in records.iter() { - if let Some(prefix) = prefix - && !key.starts_with(prefix) - { - continue; - } - if let Some(after) = after - && key.as_str() <= after - { - continue; - } - let size = key.len() + serde_json::to_vec(value).map_or(0, |v| v.len()) + 8; - if used + size > crate::world_session::MAX_RECORDS_PAGE_BYTES { - if page.is_empty() { - return Err(CapError::BadArgs); - } - more = true; - break; - } - used += size; - last_included = Some(key.clone()); - page.push(serde_json::json!({"key": key, "value": value})); - } - Ok(serde_json::json!({ - "records": page, - "next_after": more.then_some(last_included).flatten(), - })) - } - - /// `chat.say` commits a host chat line; its result is the new sequence. - fn execute_chat(&mut self, args: &serde_json::Value) -> Result { - let Some(text) = args.get("text").and_then(serde_json::Value::as_str) else { - return Err(CapError::BadArgs); - }; - match self.core.system_chat(text) { - Ok(event) => { - if self - .persist(JournalEntry::Committed { - event: event.clone(), - }) - .is_err() - { - return Err(CapError::Failed); - } - let _ = self.event_sender.send(event.clone()); - Ok(serde_json::json!({"sequence": event.sequence})) - } - Err(_) => Err(CapError::BadArgs), - } - } - - /// `schedule.at`: pend one fire of `id` at `at` (unix ms). The schedule is - /// journaled before the result is delivered. A refused request changes - /// nothing but the usage count. - fn execute_schedule_at( - &mut self, - args: &serde_json::Value, - ) -> Result { - let id = args - .get("id") - .and_then(serde_json::Value::as_str) - .ok_or(CapError::BadArgs)?; - let at_ms = args - .get("at") - .and_then(serde_json::Value::as_u64) - .ok_or(CapError::BadArgs)?; - if let Err(error) = self.core.check_schedule(id, at_ms, unix_ms()) { - tracing::debug!("world {}: schedule refused: {error:#}", self.core.world_id); - return Err(CapError::BadArgs); - } - if self - .persist(JournalEntry::ScheduleSet { - id: id.to_owned(), - at_ms, - }) - .is_err() - { - return Err(CapError::Failed); - } - self.core.schedules.insert(id.to_owned(), at_ms); - Ok(serde_json::json!({"id": id, "fires_at": at_ms})) - } - - /// `schedule.cancel`: drop a pending schedule before it fires. `cancelled` - /// is false when nothing by that id is pending. - fn execute_schedule_cancel( - &mut self, - args: &serde_json::Value, - ) -> Result { - let id = args - .get("id") - .and_then(serde_json::Value::as_str) - .ok_or(CapError::BadArgs)?; - if crate::world_caps::validate_schedule_id(id).is_err() { - return Err(CapError::BadArgs); - } - if !self.core.schedules.contains_key(id) { - return Ok(serde_json::json!({"cancelled": false})); - } - if self - .persist(JournalEntry::ScheduleCancelled { id: id.to_owned() }) - .is_err() - { - return Err(CapError::Failed); - } - self.core.schedules.remove(id); - self.overdue_at_open.remove(id); - Ok(serde_json::json!({"cancelled": true})) - } - - /// A participant opened or closed a session: presence transitions deliver - /// `players` events and arm or disarm ticks. - async fn handle_presence(&mut self, participant: u64, joined: bool) { - let was_present = self - .presence - .get(&participant) - .is_some_and(|count| *count > 0); - let count = self.presence.entry(participant).or_default(); - if joined { - *count += 1; - } else if *count > 0 { - *count -= 1; - } - let now_present = *count > 0; - if *count == 0 { - self.presence.remove(&participant); - } - if now_present && !was_present && self.ticks.is_empty() { - let intervals: Vec = self - .active_subs - .iter() - .filter_map(|sub| match sub { - Subscription::Tick(ms) if self.core.ledger.is_granted(sub.cap()) => Some(*ms), - _ => None, - }) - .collect(); - for ms in intervals { - self.ticks.entry(ms).or_insert_with(|| { - std::time::Instant::now() + std::time::Duration::from_millis(ms) - }); - } - } - if self.presence.is_empty() { - self.ticks.clear(); - } - if now_present != was_present - && self.active_subs.contains(&Subscription::Players) - && self.core.ledger.is_granted("players") - { - let name = self - .core - .participant(participant) - .map_or_else(|| participant.to_string(), |p| p.display_name); - self.deliver(presence_event(participant, &name, now_present)) - .await; - } - } - - fn require_moderation(&self, authority: &Authority, what: &str) -> Result<()> { - let directory = self.core.directory(); - let allowed = match authority { - Authority::Admin => true, - Authority::Signed(key) => directory - .account_for_key(key) - .is_some_and(|account| directory.is_moderator(&account)), - }; - if allowed { - Ok(()) - } else { - Err(crate::directory::Refusal::Forbidden(format!( - "only an admin or a moderator {what}" - )) - .into()) - } - } - - fn set_isolation(&mut self, authority: &Authority, isolation: Isolation) -> Result { - self.require_moderation(authority, "changes isolation")?; - self.persist(JournalEntry::Isolation { isolation })?; - self.core.isolation = isolation; - Ok(isolation) - } - - fn set_cross_world_write( - &mut self, - authority: &Authority, - enabled: bool, - ) -> Result { - self.require_moderation(authority, "changes cross-world writes")?; - if !enabled && self.core.cross_world_forced && *authority != Authority::Admin { - return Err(crate::directory::Refusal::Forbidden( - "the admin forced cross-world writes on; only the admin can turn them off" - .to_owned(), - ) - .into()); - } - self.persist(JournalEntry::CrossWorldWrite { enabled })?; - self.core.cross_world_write = enabled; - if !enabled { - self.core.cross_world_forced = false; - } - Ok(self.core.policy()) - } - - fn force_cross_world_write(&mut self, authority: &Authority) -> Result { - if *authority != Authority::Admin { - return Err(crate::directory::Refusal::Forbidden( - "only the admin forces cross-world writes".to_owned(), - ) - .into()); - } - if self.core.isolation == Isolation::Isolated { - return Err(crate::directory::Refusal::Forbidden( - "an isolated world cannot be forced to accept cross-world writes; unisolate it first" - .to_owned(), - ) - .into()); - } - self.persist(JournalEntry::CrossWorldWriteForced)?; - self.core.cross_world_write = true; - self.core.cross_world_forced = true; - Ok(self.core.policy()) - } - - fn set_file_scope( - &mut self, - authority: &Authority, - scope: FileScope, - write_override: Option, - ) -> Result { - self.require_moderation(authority, "changes the file scope")?; - if write_override.is_some() && *authority != Authority::Admin { - return Err(crate::directory::Refusal::Forbidden( - "only the admin sets the file write override".to_owned(), - ) - .into()); - } - self.persist(JournalEntry::FileScope { scope })?; - self.core.file_scope = scope; - if let Some(enabled) = write_override { - self.persist(JournalEntry::FileWriteOverride { enabled })?; - self.core.file_write_override = enabled; - } - Ok(self.core.policy()) - } - - /// Replace the world's capability ceiling. It takes effect now: uses and - /// subscriptions the ceiling excludes are refused from here on. Grants are - /// kept, so lifting the ceiling again restores them. - fn set_caps_ceiling(&mut self, ceiling: Vec) -> Result { - crate::world_caps::validate_ceiling_names(&ceiling)?; - let ceiling: BTreeSet = ceiling.into_iter().collect(); - self.persist(JournalEntry::CapsCeiling { - ceiling: ceiling.iter().cloned().collect(), - })?; - self.core.caps_ceiling = ceiling; - self.core.sync_ledger_ceiling(); - self.reconcile_subscriptions(); - self.caps_report() - } - - /// Re-check subscriptions after an authority change. An armed one that is - /// no longer granted is dropped and its tick disarmed. Every refused one is - /// dropped too, so the next pass decides it again: a refusal that still - /// holds is announced again, and one the change now grants is armed. - fn reconcile_subscriptions(&mut self) { - let ledger = &self.core.ledger; - let refused = &self.denied_subs; - self.active_subs - .retain(|sub| !refused.contains(&sub.spec()) && ledger.is_granted(sub.cap())); - self.denied_subs.clear(); - let active = &self.active_subs; - self.ticks - .retain(|ms, _| active.contains(&Subscription::Tick(*ms))); - } - - /// The capability report an admin sees. - fn caps_report(&mut self) -> Result { - let requested = match self.program.wants() { - Ok(Some(text)) => crate::world_caps::parse_wants(&text) - .map(|wants| wants.caps().into_iter().collect::>()) - .unwrap_or_default(), - Ok(None) => Vec::new(), - Err(_) => Vec::new(), - }; - let granted: Vec = self.core.ledger.granted().iter().cloned().collect(); - let effective: Vec = self.core.ledger.effective().into_iter().collect(); - let missing: Vec = requested - .iter() - .filter(|cap| !effective.contains(cap)) - .cloned() - .collect(); - Ok(CapsReport { - granted, - requested, - missing, - usage: self.core.ledger.usage().clone(), - policy: if self.core.ledger.grant_on_use() { - "grant-on-use" - } else { - "deny" - } - .to_owned(), - catalog: crate::world_caps::CATALOG - .iter() - .map(|name| (*name).to_owned()) - .collect(), - ceiling: self.core.caps_ceiling.iter().cloned().collect(), - effective, - }) - } - - async fn handle(&mut self, command: WorldCommand) { - match command { - WorldCommand::Issue { - name, - scopes, - bounds, - reply, - } => { - let result = self.check_storage().and_then(|()| { - let issued = self.core.issue_capability(&name, scopes, bounds)?; - self.record_issued(issued) - }); - let _ = reply.send(result); - } - WorldCommand::Attenuate { - token, - name, - scopes, - bounds, - reply, - } => { - let result = self.check_storage().and_then(|()| { - let issued = self.core.attenuate(&token, scopes, bounds, &name)?; - self.record_issued(issued) - }); - let _ = reply.send(result); - } - WorldCommand::DelegateToFriend { - token, - friend, - name, - scopes, - bounds, - reply, - } => { - let result = self.check_storage().and_then(|()| { - let issued = self - .core - .delegate_to_friend(&token, &friend, scopes, bounds, &name)?; - self.record_issued(issued) - }); - let _ = reply.send(result); - } - WorldCommand::Directory { - caller, - action, - outbox, - reply, - } => { - let world = self.core.world_id().to_owned(); - let now = unix_ms(); - let (directory, petnames) = self.core.directory_and_petnames_mut(); - // Refused before the directory changes, so a refused change leaves nothing half-applied. - let result = if !outbox - && action.queues_for_other_servers(directory, &mut self.auth, &caller, now) - { - Err(crate::directory::Refusal::Forbidden( - "this server cannot send to other servers".to_owned(), - ) - .into()) - } else { - crate::directory_view::run( - directory, - petnames, - &mut self.auth, - &caller, - &world, - now, - action, - ) - }; - let _ = reply.send(result); - } - WorldCommand::ApplyDirectory { entry, reply } => { - let _ = reply.send(self.core.directory_mut().apply(&entry)); - } - WorldCommand::Revoke { - participant_id, - reply, - } => { - // Revocation takes effect in memory even if storage failed: - // denying access is always the safe side. - let revoked = self.core.revoke_tree(participant_id); - let was_active = !revoked.is_empty(); - if was_active { - let _ = self.persist(JournalEntry::Revoked { participant_id }); - for id in revoked { - let _ = self.revocation_sender.send(id); - } - } - let _ = reply.send(was_active); - } - WorldCommand::ParticipantId { token, reply } => { - let _ = reply.send(self.core.authorize(&token, WorldScopes::JOIN)); - } - WorldCommand::Presence { - participant, - joined, - } => { - self.handle_presence(participant, joined).await; - } - WorldCommand::Chat { token, text, reply } => { - let result = if self.storage_failed { - Err(anyhow::anyhow!( - "world storage failed; the world is read-only" - )) - } else { - self.core.chat(&token, &text).and_then(|event| { - self.persist(JournalEntry::Committed { - event: event.clone(), - })?; - Ok(event) - }) - }; - if let Ok(event) = &result { - let _ = self.event_sender.send(event.clone()); - } - let _ = reply.send(result); - } - WorldCommand::Input { - token, - input, - reply, - } => { - let result = match self.core.prepare_input(&token, &input) { - Ok(_) if self.storage_failed => Err(anyhow::anyhow!( - "world storage failed; the world is read-only" - )), - Ok(candidate) if self.program_healthy => { - self.acting = Some(candidate.participant_id); - match self - .program - .update(&candidate) - .and_then(|()| program_records(self.program.as_mut())) - { - Ok(records) => self - .persist(JournalEntry::Committed { - event: candidate.clone(), - }) - .and_then(|()| self.core.commit_prepared(candidate)) - .inspect(|event| { - let records = records.unwrap_or_default(); - self.republished(records, event.sequence); - }), - Err(error) => { - self.program_healthy = false; - Err(error.context("world program rejected input")) - } - } - } - Ok(_) => Err(anyhow::anyhow!( - "world program is unavailable after a previous failure" - )), - Err(error) => Err(error), - }; - if let Ok(event) = &result { - let _ = self.event_sender.send(event.clone()); - } - let _ = reply.send(result); - } - WorldCommand::Snapshot { token, reply } => { - let _ = reply.send(self.core.snapshot(&token)); - } - WorldCommand::EventsAfter { - token, - sequence, - reply, - } => { - let _ = reply.send(self.core.events_after(&token, sequence)); - } - WorldCommand::ProjectEvent { - token, - event, - reply, - } => { - let _ = reply.send(self.core.project_for(&token, &event)); - } - WorldCommand::View { token, reply } => { - let result = match self.core.viewer(&token) { - Ok(viewer) if self.program_healthy => match self.program.view(&viewer) { - Ok(view) => { - if let Some(text) = &view { - if text.len() > self.core.limits.presentation_bytes { - self.program_healthy = false; - Err(anyhow::anyhow!( - "world presentation exceeds {} bytes", - self.core.limits.presentation_bytes - )) - } else { - Ok(view) - } - } else { - Ok(None) - } - } - Err(error) => { - self.program_healthy = false; - Err(error.context("world program view failed")) - } - }, - Ok(_) => Err(anyhow::anyhow!( - "world program is unavailable after a previous failure" - )), - Err(error) => Err(error), - }; - let _ = reply.send(result); - } - WorldCommand::ViewAt { - token, - width, - height, - reply, - } => { - let result = match self.core.viewer(&token) { - Ok(viewer) if self.program_healthy => { - match self.program.layout(&viewer, width, height) { - Ok(view) => { - if let Some(text) = &view { - if text.len() > self.core.limits.presentation_bytes { - self.program_healthy = false; - Err(anyhow::anyhow!( - "world presentation exceeds {} bytes", - self.core.limits.presentation_bytes - )) - } else { - Ok(view) - } - } else { - Ok(None) - } - } - Err(error) => { - self.program_healthy = false; - Err(error.context("world program layout failed")) - } - } - } - Ok(_) => Err(anyhow::anyhow!( - "world program is unavailable after a previous failure" - )), - Err(error) => Err(error), - }; - let _ = reply.send(result); - } - WorldCommand::InstallProgram { - module_hash, - seed, - provenance, - program: mut replacement, - reply, - } => { - // A program whose initial records are invalid is refused - // before anything is journaled. - let new_records = match program_records(replacement.as_mut()) { - Ok(records) => records.unwrap_or_default(), - Err(error) => { - let _ = reply.send(Err(error.context("new world program records failed"))); - return; - } - }; - // Actor serialization makes activation and its event atomic - // with respect to other world commands. - let candidate = WorldEvent { - sequence: self.core.sequence.saturating_add(1), - participant_id: 0, - kind: WorldEventKind::ProgramInstalled { - module_hash, - seed, - provenance: provenance.clone(), - }, - }; - let result = self - .persist(JournalEntry::Committed { - event: candidate.clone(), - }) - .and_then(|()| self.core.commit_prepared(candidate)); - let result = match result { - Ok(event) => { - if let WorldEventKind::ProgramInstalled { module_hash, .. } = &event.kind { - self.core.active_module_hash = Some(module_hash.clone()); - } - self.core.active_module_provenance = provenance; - self.core.active_seed = seed; - self.program = replacement; - self.program_healthy = true; - self.compaction_off = false; - // A new program starts with a clean slate. - self.handled_requests.clear(); - self.denied_subs.clear(); - self.active_subs.clear(); - self.ticks.clear(); - self.republished(new_records, event.sequence); - let _ = self.event_sender.send(event.clone()); - Ok(event) - } - Err(error) => Err(error), - }; - let _ = reply.send(result); - } - WorldCommand::UpdateCaps { - grant, - revoke, - reply, - } => { - let result = (|| -> Result { - crate::world_caps::validate_grant_names(&grant)?; - crate::world_caps::validate_grant_names(&revoke)?; - let mut granted: BTreeSet = - self.core.ledger.granted().iter().cloned().collect(); - for name in revoke { - granted.remove(&name); - } - granted.extend(grant); - self.persist(JournalEntry::CapsGranted { - granted: granted.iter().cloned().collect(), - })?; - self.core.ledger.set_granted(granted); - self.reconcile_subscriptions(); - self.caps_report() - })(); - let _ = reply.send(result); - } - WorldCommand::SetCapsCeiling { ceiling, reply } => { - let result = self.set_caps_ceiling(ceiling); - let _ = reply.send(result); - } - WorldCommand::SetExecutionProfile { profile, reply } => { - let result = self - .persist(JournalEntry::ExecutionProfile { profile }) - .map(|()| { - self.core.execution_profile = profile; - ExecutionProfileUpdate { - requested: profile, - applies_on_next_program_install_or_process_restart: true, - } - }); - let _ = reply.send(result); - } - WorldCommand::ExecutionProfileInfo { reply } => { - let _ = reply.send(self.core.execution_profile); - } - WorldCommand::SetIsolation { - authority, - isolation, - reply, - } => { - let result = self.set_isolation(&authority, isolation); - let _ = reply.send(result); - } - WorldCommand::IsolationInfo { reply } => { - let _ = reply.send(self.core.isolation()); - } - WorldCommand::SetCrossWorldWrite { - authority, - enabled, - reply, - } => { - let result = self.set_cross_world_write(&authority, enabled); - let _ = reply.send(result); - } - WorldCommand::ForceCrossWorldWrite { authority, reply } => { - let result = self.force_cross_world_write(&authority); - let _ = reply.send(result); - } - WorldCommand::SetFileScope { - authority, - scope, - write_override, - reply, - } => { - let result = self.set_file_scope(&authority, scope, write_override); - let _ = reply.send(result); - } - WorldCommand::PolicyInfo { reply } => { - let _ = reply.send(self.core.policy()); - } - WorldCommand::CapsInfo { reply } => { - let _ = reply.send(self.caps_report()); - } - WorldCommand::Shutdown { .. } => unreachable!("handled by run"), - } - } - - /// Trim the journal behind a verified snapshot, at most once per run of - /// commits and never while the program cannot snapshot. - async fn compact_if_due(&mut self) { - if self.compaction_off - || self.storage_failed - || !self.program_healthy - || !self.core.checkpoint_due() - { - return; - } - let Some(journal) = self.journal.as_mut() else { - return; - }; - match compact_journal(&mut self.core, self.program.as_mut(), journal.as_mut()) { - Ok(true) => {} - Ok(false) => self.compaction_off = true, - Err(error) => { - // The journal is still complete; just do not retry until - // something changes. - tracing::warn!("world checkpoint skipped: {error:#}"); - self.compaction_off = true; - } - } - } -} - -impl WorldHandle { - /// Spawn a world actor on the current Tokio runtime. - pub fn spawn(core: WorldCore) -> Self { - Self::spawn_with_program(core, Box::::default()) - } - - /// Spawn a world actor with an executable program. Only the actor owns - /// the program instance, so calls are serialized with world mutations. - pub fn spawn_with_program(core: WorldCore, program: Box) -> Self { - Self::spawn_durable(core, program, None) - } - - /// Spawn a world actor that journals every mutation before acknowledging - /// it. `program` must already reflect the journal (see - /// [`WorldCore::restore`]); the actor only appends. - pub fn spawn_durable( - core: WorldCore, - mut program: Box, - journal: Option>, - ) -> Self { - let (commands, receiver) = mpsc::channel(256); - let (events, _) = broadcast::channel(256); - let (revocations, _) = broadcast::channel(256); - let (view_changed_sender, view_changed) = watch::channel(core.sequence); - // Records are recomputed from the (restored) program, so they are a - // pure function of the journal and need no storage of their own here. - let mut program_healthy = true; - let initial = match program_records(program.as_mut()) { - Ok(records) => records.unwrap_or_default(), - Err(error) => { - tracing::error!("world program records failed: {error:#}"); - program_healthy = false; - Records::new() - } - }; - let (records_sender, records) = watch::channel((core.sequence, Arc::new(initial))); - // Schedules the journal left pending that are already due fire late. - let now = unix_ms(); - let overdue_at_open: BTreeSet = core - .schedules - .iter() - .filter(|(_, at_ms)| **at_ms <= now) - .map(|(id, _)| id.clone()) - .collect(); - let actor = WorldActor { - core, - program, - journal, - storage_failed: false, - program_healthy, - compaction_off: false, - event_sender: events.clone(), - revocation_sender: revocations.clone(), - records_sender, - view_changed: view_changed_sender, - presence: HashMap::new(), - active_subs: BTreeSet::new(), - handled_requests: BTreeSet::new(), - denied_subs: BTreeSet::new(), - ticks: BTreeMap::new(), - overdue_at_open, - acting: None, - auth: crate::directory_auth::DirectoryAuth::default(), - }; - tokio::spawn(actor.run(receiver)); - Self { - commands, - events, - revocations, - records, - view_changed, - } - } - /// The latest `(sequence, records)` published by the world program. - /// Callers must authorize the reader first (see [`Self::participant_id`]). - #[must_use] - pub fn records(&self) -> (u64, Arc) { - let current = self.records.borrow(); - (current.0, Arc::clone(¤t.1)) - } - - /// Watch record changes (coalesced: a slow reader sees the latest set). - #[must_use] - pub fn watch_records(&self) -> watch::Receiver<(u64, Arc)> { - self.records.clone() - } - - /// Subscribe to newly committed world events, as the host committed them: - /// unprojected, with chat and the real install seed. Whatever forwards - /// these to a participant must first pass each through - /// [`WorldHandle::project_event`]. - #[must_use] - pub fn subscribe(&self) -> broadcast::Receiver { - self.events.subscribe() - } - - /// Subscribe to capability revocations. - #[must_use] - pub fn subscribe_revocations(&self) -> broadcast::Receiver { - self.revocations.subscribe() - } - - /// Watch for state changes a rendered view may want to reflect. The value - /// is the world sequence at the change (unchanged for host events). - #[must_use] - pub fn watch_views(&self) -> watch::Receiver { - self.view_changed.clone() - } - - /// Tell the world a participant opened (`true`) or closed (`false`) a - /// session. Drives presence and, while anyone is present, subscribed - /// ticks. - pub async fn presence(&self, participant: u64, joined: bool) { - let _ = self - .commands - .send(WorldCommand::Presence { - participant, - joined, - }) - .await; - } - - /// Grant and revoke capabilities for this world, and return the report. - /// - /// # Errors - /// - /// Fails on unknown capability names or world storage failure. - pub async fn update_caps(&self, grant: Vec, revoke: Vec) -> Result { - let (reply, response) = oneshot::channel(); - self.commands - .send(WorldCommand::UpdateCaps { - grant, - revoke, - reply, - }) - .await - .map_err(|_| anyhow::anyhow!("world actor is closed"))?; - response - .await - .context("world actor dropped caps response")? - } - - /// Replace this world's capability ceiling. It applies immediately to new - /// uses and active subscriptions; it does not rewrite the grants. - /// - /// # Errors - /// - /// Fails on `*`, on unknown names, or on world storage failure. - pub async fn set_caps_ceiling(&self, ceiling: Vec) -> Result { - let (reply, response) = oneshot::channel(); - self.commands - .send(WorldCommand::SetCapsCeiling { ceiling, reply }) - .await - .ok() - .context("world actor is closed")?; - response - .await - .context("world actor dropped caps ceiling response")? - } - - /// Persist this world's requested resource profile. The current program - /// instance is deliberately left untouched. - pub async fn set_execution_profile( - &self, - profile: crate::world_limits::WorldExecutionProfile, - ) -> Result { - let (reply, response) = oneshot::channel(); - self.commands - .send(WorldCommand::SetExecutionProfile { profile, reply }) - .await - .map_err(|_| anyhow::anyhow!("world actor is closed"))?; - response - .await - .context("world actor dropped execution profile response")? - } - - /// Read this world's currently requested resource profile. - pub async fn execution_profile(&self) -> Result { - let (reply, response) = oneshot::channel(); - self.commands - .send(WorldCommand::ExecutionProfileInfo { reply }) - .await - .map_err(|_| anyhow::anyhow!("world actor is closed"))?; - response - .await - .context("world actor dropped execution profile") - } - - /// Change the world's isolation. - /// - /// # Errors - /// - /// Fails with a forbidden refusal unless the authority is an admin or a - /// moderator, or on world storage failure. - pub async fn set_isolation( - &self, - authority: Authority, - isolation: Isolation, - ) -> Result { - let (reply, response) = oneshot::channel(); - self.commands - .send(WorldCommand::SetIsolation { - authority, - isolation, - reply, - }) - .await - .map_err(|_| anyhow::anyhow!("world actor is closed"))?; - response - .await - .context("world actor dropped isolation response")? - } - - /// The world's isolation. - /// - /// # Errors - /// - /// Fails if the world actor is closed. - pub async fn isolation(&self) -> Result { - let (reply, response) = oneshot::channel(); - self.commands - .send(WorldCommand::IsolationInfo { reply }) - .await - .map_err(|_| anyhow::anyhow!("world actor is closed"))?; - response - .await - .context("world actor dropped isolation response") - } - - /// Let other unisolated worlds write here, or stop them. - /// - /// # Errors - /// - /// Fails with a forbidden refusal unless the authority is an admin or a - /// moderator, or if a moderator turns off a forced setting, or on storage failure. - pub async fn set_cross_world_write( - &self, - authority: Authority, - enabled: bool, - ) -> Result { - let (reply, response) = oneshot::channel(); - self.commands - .send(WorldCommand::SetCrossWorldWrite { - authority, - enabled, - reply, - }) - .await - .map_err(|_| anyhow::anyhow!("world actor is closed"))?; - response - .await - .context("world actor dropped cross-world write response")? - } - - /// Force cross-world writes on for an unisolated world. - /// - /// # Errors - /// - /// Fails with a forbidden refusal unless the authority is the admin, or if - /// the world is isolated, or on storage failure. - pub async fn force_cross_world_write(&self, authority: Authority) -> Result { - let (reply, response) = oneshot::channel(); - self.commands - .send(WorldCommand::ForceCrossWorldWrite { authority, reply }) - .await - .map_err(|_| anyhow::anyhow!("world actor is closed"))?; - response - .await - .context("world actor dropped force response")? - } - - /// Set the file scope, and with `write_override` the admin override. - /// - /// # Errors - /// - /// Fails with a forbidden refusal unless the authority is an admin or a - /// moderator, or if a moderator sets the override, or on storage failure. - pub async fn set_file_scope( - &self, - authority: Authority, - scope: FileScope, - write_override: Option, - ) -> Result { - let (reply, response) = oneshot::channel(); - self.commands - .send(WorldCommand::SetFileScope { - authority, - scope, - write_override, - reply, - }) - .await - .map_err(|_| anyhow::anyhow!("world actor is closed"))?; - response - .await - .context("world actor dropped file scope response")? - } - - /// The world's sharing and file settings. - /// - /// # Errors - /// - /// Fails if the world actor is closed. - pub async fn policy(&self) -> Result { - let (reply, response) = oneshot::channel(); - self.commands - .send(WorldCommand::PolicyInfo { reply }) - .await - .map_err(|_| anyhow::anyhow!("world actor is closed"))?; - response - .await - .context("world actor dropped policy response") - } - - /// The world's capability report: grants, what the program wants, and use. - /// - /// # Errors - /// - /// Fails if the world actor is closed. - pub async fn caps_report(&self) -> Result { - let (reply, response) = oneshot::channel(); - self.commands - .send(WorldCommand::CapsInfo { reply }) - .await - .map_err(|_| anyhow::anyhow!("world actor is closed"))?; - response - .await - .context("world actor dropped caps response")? - } - - /// Resolve the participant authorized by a join capability. - pub async fn participant_id(&self, token: JoinCapability) -> Result { - let (reply, response) = oneshot::channel(); - self.commands - .send(WorldCommand::ParticipantId { token, reply }) - .await - .map_err(|_| anyhow::anyhow!("world actor is closed"))?; - response - .await - .context("world actor dropped participant lookup response")? - } - - /// Issue a scoped participant capability. - pub async fn issue( - &self, - name: impl Into, - scopes: WorldScopes, - ) -> Result<(Participant, JoinCapability)> { - self.issue_bounded(name, scopes, CapabilityBounds::default()) - .await - } - - /// Issue a scoped participant capability that stops working at its bounds. - pub async fn issue_bounded( - &self, - name: impl Into, - scopes: WorldScopes, - bounds: CapabilityBounds, - ) -> Result<(Participant, JoinCapability)> { - let (reply, response) = oneshot::channel(); - self.commands - .send(WorldCommand::Issue { - name: name.into(), - scopes, - bounds, - reply, - }) - .await - .map_err(|_| anyhow::anyhow!("world actor is closed"))?; - response - .await - .context("world actor dropped capability response")? - } - - /// Delegate a narrower capability from `token`, which must hold `JOIN`. - pub async fn attenuate( - &self, - token: JoinCapability, - scopes: WorldScopes, - bounds: CapabilityBounds, - name: impl Into, - ) -> Result<(Participant, JoinCapability)> { - let (reply, response) = oneshot::channel(); - self.commands - .send(WorldCommand::Attenuate { - token, - name: name.into(), - scopes, - bounds, - reply, - }) - .await - .map_err(|_| anyhow::anyhow!("world actor is closed"))?; - response - .await - .context("world actor dropped delegation response")? - } - - /// Delegate a narrower capability to a friend of the account `token` - /// acts for. The friendship must still hold when the capability is used. - pub async fn delegate_to_friend( - &self, - token: JoinCapability, - friend: impl Into, - scopes: WorldScopes, - bounds: CapabilityBounds, - name: impl Into, - ) -> Result<(Participant, JoinCapability)> { - let (reply, response) = oneshot::channel(); - self.commands - .send(WorldCommand::DelegateToFriend { - token, - friend: friend.into(), - name: name.into(), - scopes, - bounds, - reply, - }) - .await - .map_err(|_| anyhow::anyhow!("world actor is closed"))?; - response - .await - .context("world actor dropped friend delegation response")? - } - - /// Read or change the directory as the caller. The caller's proof must - /// already be checked by the transport. `outbox` says whether this server - /// can queue what the change sends to other servers. - pub async fn directory( - &self, - caller: crate::directory_auth::Caller, - action: crate::directory_view::DirectoryAction, - outbox: bool, - ) -> Result { - let (reply, response) = oneshot::channel(); - self.commands - .send(WorldCommand::Directory { - caller, - action, - outbox, - reply, - }) - .await - .map_err(|_| anyhow::anyhow!("world actor is closed"))?; - response - .await - .context("world actor dropped directory response")? - } - - /// Apply a change prepared by a remote friend action, once its envelope is queued. - pub async fn apply_directory_entry( - &self, - entry: crate::directory::DirectoryEntry, - ) -> Result<()> { - let (reply, response) = oneshot::channel(); - self.commands - .send(WorldCommand::ApplyDirectory { entry, reply }) - .await - .map_err(|_| anyhow::anyhow!("world actor is closed"))?; - response - .await - .context("world actor dropped directory apply response")? - } - - /// Revoke an active capability and everything delegated from it. - pub async fn revoke(&self, participant_id: u64) -> Result { - let (reply, response) = oneshot::channel(); - self.commands - .send(WorldCommand::Revoke { - participant_id, - reply, - }) - .await - .map_err(|_| anyhow::anyhow!("world actor is closed"))?; - response - .await - .context("world actor dropped revocation response") - } - - /// Submit a bounded chat message. - pub async fn chat(&self, token: JoinCapability, text: impl Into) -> Result { - let (reply, response) = oneshot::channel(); - self.commands - .send(WorldCommand::Chat { - token, - text: text.into(), - reply, - }) - .await - .map_err(|_| anyhow::anyhow!("world actor is closed"))?; - response - .await - .context("world actor dropped chat response")? - } - - /// Submit bounded opaque game input. - pub async fn input(&self, token: JoinCapability, input: Vec) -> Result { - let (reply, response) = oneshot::channel(); - self.commands - .send(WorldCommand::Input { - token, - input, - reply, - }) - .await - .map_err(|_| anyhow::anyhow!("world actor is closed"))?; - response - .await - .context("world actor dropped input response")? - } - - /// Read a world snapshot. - pub async fn snapshot(&self, token: JoinCapability) -> Result { - let (reply, response) = oneshot::channel(); - self.commands - .send(WorldCommand::Snapshot { token, reply }) - .await - .map_err(|_| anyhow::anyhow!("world actor is closed"))?; - response - .await - .context("world actor dropped snapshot response")? - } - - /// What the holder of `token` may see of a live `event` (from - /// [`WorldHandle::subscribe`]): `Ok(None)` if the event is not for this - /// viewer, `Err` if the capability no longer joins. Judged by the - /// viewer's scopes at this moment. - pub async fn project_event( - &self, - token: JoinCapability, - event: WorldEvent, - ) -> Result> { - let (reply, response) = oneshot::channel(); - self.commands - .send(WorldCommand::ProjectEvent { - token, - event, - reply, - }) - .await - .map_err(|_| anyhow::anyhow!("world actor is closed"))?; - response - .await - .context("world actor dropped projection response")? - } - - /// Catch up from an event cursor, or learn that a new snapshot is needed. - pub async fn events_after(&self, token: JoinCapability, sequence: u64) -> Result { - let (reply, response) = oneshot::channel(); - self.commands - .send(WorldCommand::EventsAfter { - token, - sequence, - reply, - }) - .await - .map_err(|_| anyhow::anyhow!("world actor is closed"))?; - response - .await - .context("world actor dropped event response")? - } - - /// Render the current world for an authorized participant. A chat-only - /// world returns `None`. - pub async fn view(&self, token: JoinCapability) -> Result> { - let (reply, response) = oneshot::channel(); - self.commands - .send(WorldCommand::View { token, reply }) - .await - .map_err(|_| anyhow::anyhow!("world actor is closed"))?; - response - .await - .context("world actor dropped view response")? - } - - /// Render for one viewer at a viewport. Programs that cannot reflow fall - /// back to their fixed view, and rendering never advances the sequence. - pub async fn view_at( - &self, - token: JoinCapability, - width: u16, - height: u16, - ) -> Result> { - let (reply, response) = oneshot::channel(); - self.commands - .send(WorldCommand::ViewAt { - token, - width, - height, - reply, - }) - .await - .map_err(|_| anyhow::anyhow!("world actor is closed"))?; - response - .await - .context("world actor dropped layout response")? - } - - /// Atomically replace the active program and sequence a host-authored - /// module-installed event. The new program is used after this command. - pub async fn install_program( - &self, - module_hash: String, - seed: u64, - program: Box, - ) -> Result { - self.install_program_with_provenance(module_hash, seed, None, program) - .await - } - - /// As [`Self::install_program`], preserving server-observed origin metadata. - pub async fn install_program_with_provenance( - &self, - module_hash: String, - seed: u64, - provenance: Option, - program: Box, - ) -> Result { - let (reply, response) = oneshot::channel(); - self.commands - .send(WorldCommand::InstallProgram { - module_hash, - seed, - provenance, - program, - reply, - }) - .await - .map_err(|_| anyhow::anyhow!("world actor is closed"))?; - response - .await - .context("world actor dropped install response")? - } - - /// Stop the actor after processing all commands queued before shutdown. - pub async fn shutdown(&self) -> Result<()> { - let (reply, response) = oneshot::channel(); - self.commands - .send(WorldCommand::Shutdown { reply }) - .await - .map_err(|_| anyhow::anyhow!("world actor is closed"))?; - response - .await - .context("world actor dropped shutdown response") - } -} - -/// Incremental event page for an authorized participant. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct EventPage { - /// Latest committed sequence at response time. - pub current_sequence: u64, - /// Earliest retained sequence. - pub oldest_retained_sequence: u64, - /// The event cursor fell behind retention and a full snapshot is required. - pub needs_snapshot: bool, - /// Events newer than the requested cursor, if it is still retained. - pub events: Vec, -} - -fn token_digest(token: &str) -> [u8; 32] { - Sha256::digest(token.as_bytes()).into() -} - -fn constant_time_eq(left: &[u8; 32], right: &[u8; 32]) -> bool { - bool::from(left.ct_eq(right)) -} - -pub(crate) fn hex_encode(bytes: &[u8]) -> String { - const HEX: &[u8; 16] = b"0123456789abcdef"; - let mut encoded = String::with_capacity(bytes.len() * 2); - for byte in bytes { - encoded.push(char::from(HEX[usize::from(byte >> 4)])); - encoded.push(char::from(HEX[usize::from(byte & 0x0f)])); - } - encoded -} - -fn publish_records(sender: &watch::Sender<(u64, Arc)>, sequence: u64, records: Records) { - sender.send_if_modified(|current| { - if *current.1 == records { - false - } else { - *current = (sequence, Arc::new(records)); - true - } - }); -} - -fn hex_decode_32(encoded: &str) -> Option<[u8; 32]> { - let bytes = encoded.as_bytes(); - if bytes.len() != 64 { - return None; - } - let mut out = [0_u8; 32]; - for (slot, pair) in out.iter_mut().zip(bytes.chunks_exact(2)) { - let nibble = |b: u8| char::from(b).to_digit(16); - *slot = u8::try_from(nibble(pair[0])? << 4 | nibble(pair[1])?).ok()?; - } - Some(out) -} - -fn sanitize_display_name(name: &str) -> String { - name.chars() - .filter(|ch| !ch.is_control()) - .take(48) - .collect::() - .trim() - .to_owned() -} - -fn sanitize_chat(text: &str) -> String { - text.chars() - .filter(|ch| !ch.is_control() || *ch == '\n' || *ch == '\t') - .collect::() - .trim() - .to_owned() -} - -#[cfg(test)] -#[allow(clippy::unwrap_used, clippy::expect_used)] -mod tests { - use super::*; - - fn world(retained_events: usize) -> WorldCore { - WorldCore::new( - "test-world", - WorldLimits { - retained_events, - ..WorldLimits::default() - }, - ) - .unwrap() - } - - fn join(core: &mut WorldCore, name: &str) -> (Participant, JoinCapability) { - core.issue_capability(name, WorldScopes::GUEST, CapabilityBounds::default()) - .unwrap() - } - - fn sample_source_provenance() -> ModuleProvenance { - ModuleProvenance::SourceBuild(SourceBuildProvenance { - schema_version: 1, - compiler_blake3: "compiler".to_owned(), - platform_blake3: "platform".to_owned(), - source_blake3: "source".to_owned(), - target: "wasm32".to_owned(), - arguments: vec!["build".to_owned(), "main.roc".to_owned()], - }) - } - - #[test] - fn provenance_is_optional_and_old_install_events_keep_their_wire_shape() { - let old = serde_json::json!({ - "sequence": 1, - "participant_id": 0, - "kind": { "kind": "program_installed", "data": { "module_hash": "h", "seed": 3 } } - }); - let parsed: WorldEvent = serde_json::from_value(old.clone()).unwrap(); - assert!(matches!( - parsed.kind, - WorldEventKind::ProgramInstalled { - provenance: None, - .. - } - )); - assert_eq!(serde_json::to_value(parsed).unwrap(), old); - - let event = WorldEvent { - sequence: 1, - participant_id: 0, - kind: WorldEventKind::ProgramInstalled { - module_hash: "h".to_owned(), - seed: 3, - provenance: Some(sample_source_provenance()), - }, - }; - let encoded = serde_json::to_value(&event).unwrap(); - assert_eq!( - serde_json::from_value::(encoded).unwrap(), - event - ); - } - - #[test] - fn checkpoint_defaults_missing_provenance_and_round_trips_recorded_provenance() { - let old = serde_json::json!({ - "entry": "checkpoint", - "sequence": 0, - "module_hash": "h", - "seed": 1, - "snapshot": "s", - "events": [] - }); - let parsed: JournalEntry = serde_json::from_value(old.clone()).unwrap(); - assert!(matches!( - parsed, - JournalEntry::Checkpoint { - provenance: None, - execution_profile: None, - .. - } - )); - assert_eq!(serde_json::to_value(parsed).unwrap(), old); - let restored = WorldCore::restore( - "w", - WorldLimits::default(), - [ - JournalEntry::Created { - world_id: "w".to_owned(), - version: JOURNAL_VERSION, - }, - serde_json::from_value(old).unwrap(), - ], - ) - .unwrap(); - assert_eq!( - restored.core.execution_profile(), - crate::world_limits::WorldExecutionProfile::default() - ); - } - - #[test] - fn execution_profile_survives_checkpoint_compaction_and_restore() { - let profile = crate::world_limits::WorldExecutionProfile { - wasm_fuel: Some(1234), - native_cpu_seconds: Some(3), - ..Default::default() - }; - let mut core = world(8); - core.execution_profile = profile; - core.active_module_hash = Some("h".to_owned()); - let entries = core.checkpoint_entries("state".to_owned()).unwrap(); - let restored = WorldCore::restore("test-world", WorldLimits::default(), entries).unwrap(); - assert_eq!(restored.core.execution_profile(), profile); - } - - #[test] - fn recorded_provenance_survives_checkpoint_compaction_and_restore() { - let provenance = sample_source_provenance(); - let mut core = world(8); - core.active_module_hash = Some("h".to_owned()); - core.active_module_provenance = Some(provenance.clone()); - core.active_seed = 7; - let entries = core.checkpoint_entries("state".to_owned()).unwrap(); - - let restored = WorldCore::restore("test-world", WorldLimits::default(), entries).unwrap(); - assert_eq!( - restored.core.active_module_provenance, - Some(provenance.clone()) - ); - assert_eq!(restored.program.unwrap().provenance, Some(provenance)); - } - - /// A program driven by numeric inputs: each input switches its `wants` - /// script, and every host event is recorded. Request ids embed the input - /// count, so re-sending an input asks again. - struct Mock { - script: u64, - received: Vec, - asks: u64, - } - - impl Mock { - fn new() -> Self { - Self { - script: 0, - received: Vec::new(), - asks: 0, - } - } - } - - impl WorldProgram for Mock { - fn update(&mut self, event: &WorldEvent) -> Result<()> { - match &event.kind { - WorldEventKind::Input(bytes) => { - let text = std::str::from_utf8(bytes)?; - self.script = text.parse().unwrap_or(self.script); - self.asks += 1; - } - WorldEventKind::System { event } => self.received.push(event.clone()), - WorldEventKind::Chat(_) | WorldEventKind::ProgramInstalled { .. } => {} - } - Ok(()) - } - - fn wants(&mut self) -> Result> { - let id = |tag: &str| format!("{tag}-{}", self.asks); - let document = match self.script { - 1 => serde_json::json!({ - "v": 1, - "subscribe": ["players"], - "requests": [{"id": id("now"), "cap": "time.now"}], - }), - 2 => serde_json::json!({ - "requests": [{"id": id("now"), "cap": "time.now"}], - }), - 3 => serde_json::json!({ - "requests": [{ - "id": id("say"), - "cap": "chat.say", - "args": {"text": "hello from the program"}, - }], - }), - 4 => serde_json::json!({"subscribe": ["time.tick:20"]}), - 5 => serde_json::json!({ - "requests": [{ - "id": id("hist"), - "cap": "chat.history", - "args": {"count": 5}, - }], - }), - _ => serde_json::json!({}), - }; - Ok(Some(document.to_string())) - } - } - - async fn caps_world_sync(grant_on_use: bool) -> (WorldHandle, JoinCapability) { - let limits = WorldLimits { - grant_on_use, - ..WorldLimits::default() - }; - let core = WorldCore::new("caps", limits).unwrap(); - let handle = WorldHandle::spawn_with_program(core, Box::new(Mock::new())); - let (_, token) = handle.issue("ann", WorldScopes::GUEST).await.unwrap(); - (handle, token) - } - - #[tokio::test] - async fn an_ungranted_request_is_refused_and_counted() { - let (world, token) = caps_world_sync(false).await; - world.input(token, b"1".to_vec()).await.unwrap(); - // The program hears the refusal as a result event. - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); - loop { - let report = world.caps_report().await.unwrap(); - if report - .usage - .get("time.now") - .is_some_and(|use_| use_.denied > 0) - { - break; - } - assert!(std::time::Instant::now() < deadline, "no refusal recorded"); - tokio::time::sleep(std::time::Duration::from_millis(10)).await; - } - let report = world.caps_report().await.unwrap(); - assert_eq!(report.policy, "deny"); - assert!( - report.missing.contains(&"time.now".to_owned()), - "{report:?}" - ); - } - - #[tokio::test] - async fn a_granted_request_gets_a_real_answer() { - let (world, token) = caps_world_sync(false).await; - world - .update_caps(vec!["time.now".to_owned()], Vec::new()) - .await - .unwrap(); - world.input(token, b"2".to_vec()).await.unwrap(); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); - loop { - if world.caps_report().await.unwrap().usage["time.now"].allowed > 0 { - break; - } - assert!(std::time::Instant::now() < deadline, "no answer recorded"); - tokio::time::sleep(std::time::Duration::from_millis(10)).await; - } - } - - #[test] - fn chat_history_returns_the_newest_lines_oldest_first() { - let mut core = world(16); - for (sequence, participant, text) in - [(1u64, 1u64, "first"), (2, 28, "second"), (3, 1, "third")] - { - core.events.push_back(WorldEvent { - sequence, - participant_id: participant, - kind: WorldEventKind::Chat(text.to_owned()), - }); - } - let newest = chat_history(&core.events, 2); - assert_eq!(newest.len(), 2); - assert_eq!(newest[0]["text"], "second"); - assert_eq!(newest[0]["sequence"], 2); - assert_eq!(newest[1]["text"], "third"); - let all = chat_history(&core.events, 10); - assert_eq!(all.len(), 3); - assert_eq!(all[0]["text"], "first"); - assert_eq!(all[2]["text"], "third"); - assert!(chat_history(&core.events, 0).is_empty()); - } - - #[tokio::test] - async fn a_granted_chat_history_request_is_served_over_the_ledger() { - let (world, token) = caps_world_sync(false).await; - world - .update_caps( - vec!["chat.say".to_owned(), "chat.history".to_owned()], - Vec::new(), - ) - .await - .unwrap(); - // The program says one line first, then asks for the history. - world.input(token.clone(), b"3".to_vec()).await.unwrap(); - world.input(token, b"5".to_vec()).await.unwrap(); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); - loop { - let report = world.caps_report().await.unwrap(); - if report - .usage - .get("chat.history") - .is_some_and(|use_| use_.allowed > 0) - { - break; - } - assert!( - std::time::Instant::now() < deadline, - "no history answer recorded: {report:?}" - ); - tokio::time::sleep(std::time::Duration::from_millis(10)).await; - } - } - - #[tokio::test] - async fn chat_say_commits_a_system_chat_line_that_sessions_see() { - let (world, token) = caps_world_sync(false).await; - world - .update_caps(vec!["chat.say".to_owned()], Vec::new()) - .await - .unwrap(); - let mut events = world.subscribe(); - world.input(token, b"3".to_vec()).await.unwrap(); - // The participant's own input event arrives first; keep waiting for - // the host's chat line. - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); - loop { - let event = tokio::time::timeout(std::time::Duration::from_secs(2), events.recv()) - .await - .expect("no chat event") - .unwrap(); - if let WorldEventKind::Chat(text) = &event.kind { - assert_eq!(text, "hello from the program"); - assert_eq!(event.participant_id, 0, "the host said it"); - break; - } - assert!(std::time::Instant::now() < deadline, "chat never arrived"); - } - } - - #[tokio::test] - async fn a_participant_cannot_make_the_program_do_what_its_scopes_forbid() { - let core = WorldCore::new("caps", WorldLimits::default()).unwrap(); - let world = WorldHandle::spawn_with_program(core, Box::new(Mock::new())); - let (_, token) = world - .issue( - "ann", - WorldScopes(WorldScopes::JOIN.bits() | WorldScopes::INPUT.bits()), - ) - .await - .unwrap(); - world - .update_caps(vec!["chat.say".to_owned()], Vec::new()) - .await - .unwrap(); - world.input(token, b"3".to_vec()).await.unwrap(); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); - loop { - let report = world.caps_report().await.unwrap(); - if report - .usage - .get("chat.say") - .is_some_and(|use_| use_.denied > 0) - { - assert_eq!(report.usage["chat.say"].allowed, 0); - break; - } - assert!(std::time::Instant::now() < deadline, "no refusal recorded"); - tokio::time::sleep(std::time::Duration::from_millis(10)).await; - } - } - - #[tokio::test] - async fn a_participant_with_chat_lets_the_program_say_what_it_asks() { - let core = WorldCore::new("caps", WorldLimits::default()).unwrap(); - let world = WorldHandle::spawn_with_program(core, Box::new(Mock::new())); - let (_, token) = world - .issue( - "ann", - WorldScopes( - WorldScopes::JOIN.bits() | WorldScopes::CHAT.bits() | WorldScopes::INPUT.bits(), - ), - ) - .await - .unwrap(); - world - .update_caps(vec!["chat.say".to_owned()], Vec::new()) - .await - .unwrap(); - world.input(token, b"3".to_vec()).await.unwrap(); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); - loop { - let report = world.caps_report().await.unwrap(); - if report - .usage - .get("chat.say") - .is_some_and(|use_| use_.allowed > 0) - { - assert_eq!(report.usage["chat.say"].denied, 0); - break; - } - assert!( - std::time::Instant::now() < deadline, - "no allowed use recorded" - ); - tokio::time::sleep(std::time::Duration::from_millis(10)).await; - } - } - - #[tokio::test] - async fn grant_on_use_grants_what_the_program_actually_uses() { - let (world, token) = caps_world_sync(true).await; - world.input(token, b"1".to_vec()).await.unwrap(); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); - loop { - if world.caps_report().await.unwrap().usage["time.now"].allowed > 0 { - break; - } - assert!(std::time::Instant::now() < deadline, "never granted"); - tokio::time::sleep(std::time::Duration::from_millis(10)).await; - } - let report = world.caps_report().await.unwrap(); - assert_eq!(report.policy, "grant-on-use"); - assert!(report.granted.contains(&"time.now".to_owned())); - assert!(report.missing.is_empty()); - } - - #[test] - fn system_events_and_grants_survive_a_restore() { - let secret = "ab".repeat(32); - let token = JoinCapability::from_wire(format!("1.{secret}")); - let digest = hex_encode(&token_digest(token.expose())); - let entries = vec![ - JournalEntry::Created { - world_id: "caps".to_owned(), - version: JOURNAL_VERSION, - }, - JournalEntry::CapsGranted { - granted: vec!["time.now".to_owned()], - }, - JournalEntry::Issued { - participant: Participant { - id: 1, - display_name: "ann".to_owned(), - }, - digest, - scopes: WorldScopes::GUEST.0, - parent: None, - expires_at: None, - uses: None, - used: 0, - subject: None, - }, - JournalEntry::System { - event: WorldEvent { - sequence: 0, - participant_id: 0, - kind: WorldEventKind::System { - event: r#"{"cap":"result","id":"now-1","ok":true,"value":{"now":1}}"# - .to_owned(), - }, - }, - }, - ]; - let restored = WorldCore::restore("caps", WorldLimits::default(), entries).unwrap(); - assert!(restored.core.ledger.is_granted("time.now")); - assert_eq!(restored.core.sequence, 0, "system events carry no sequence"); - assert_eq!(restored.replay.len(), 1, "the program must see it again"); - assert!( - restored.core.authorize(&token, WorldScopes::JOIN).is_ok(), - "capabilities restore after a grant entry" - ); - } - - #[test] - fn a_restore_closes_presence_the_journal_left_open() { - let secret = "cd".repeat(32); - let digest = hex_encode(&token_digest(&format!("1.{secret}"))); - let presence = |joined: bool| JournalEntry::System { - event: WorldEvent { - sequence: 0, - participant_id: 0, - kind: WorldEventKind::System { - event: presence_event(1, "ann", joined), - }, - }, - }; - let entries = vec![ - JournalEntry::Created { - world_id: "presence".to_owned(), - version: JOURNAL_VERSION, - }, - JournalEntry::Issued { - participant: Participant { - id: 1, - display_name: "ann".to_owned(), - }, - digest, - scopes: WorldScopes::GUEST.0, - parent: None, - expires_at: None, - uses: None, - used: 0, - subject: None, - }, - presence(true), - presence(false), - presence(true), - ]; - let restored = - WorldCore::restore("presence", WorldLimits::default(), entries.clone()).unwrap(); - let last = restored.replay.last().unwrap(); - assert_eq!( - restored.replay.len(), - 4, - "the open join is closed after the journal's events" - ); - assert_eq!( - last.kind, - WorldEventKind::System { - event: presence_event(1, "ann", false), - } - ); - - let closed = - WorldCore::restore("presence", WorldLimits::default(), entries[..4].to_vec()).unwrap(); - assert_eq!(closed.replay.len(), 2, "a closed join needs no extra leave"); - } - - #[test] - fn a_checkpoint_keeps_the_granted_set() { - let mut core = WorldCore::new("caps", WorldLimits::default()).unwrap(); - core.ledger - .set_granted(BTreeSet::from(["time.now".to_owned()])); - core.active_module_hash = Some("h".to_owned()); - let entries = core.checkpoint_entries("snapshot".to_owned()).unwrap(); - assert!(entries - .iter() - .any(|entry| matches!(entry, JournalEntry::CapsGranted { granted } if granted == &vec!["time.now".to_owned()]))); - // A compacted journal restores with the grant intact. - let restored = WorldCore::restore("caps", WorldLimits::default(), entries).unwrap(); - assert!(restored.core.ledger.is_granted("time.now")); - } - - #[tokio::test] - async fn the_actor_journals_host_events_and_grants() { - #[derive(Default, Clone)] - struct Capturing(Arc>>); - impl WorldJournal for Capturing { - fn append(&mut self, entry: &JournalEntry) -> Result<()> { - self.0.lock().unwrap().push(entry.clone()); - Ok(()) - } - } - let captured = Capturing::default(); - let (world, token) = { - let core = WorldCore::new("j", WorldLimits::default()).unwrap(); - let handle = WorldHandle::spawn_durable( - core, - Box::new(Mock::new()), - Some(Box::new(captured.clone())), - ); - let (_, token) = handle.issue("ann", WorldScopes::GUEST).await.unwrap(); - (handle, token) - }; - world - .update_caps(vec!["chat.say".to_owned()], Vec::new()) - .await - .unwrap(); - world.input(token, b"3".to_vec()).await.unwrap(); - tokio::time::sleep(std::time::Duration::from_millis(100)).await; - world.shutdown().await.unwrap(); - let entries = captured.0.lock().unwrap().clone(); - assert!( - entries - .iter() - .any(|entry| matches!(entry, JournalEntry::CapsGranted { granted } if granted.contains(&"chat.say".to_owned()))), - "{entries:?}" - ); - assert!( - entries - .iter() - .any(|entry| matches!(entry, JournalEntry::System { event } if event.kind == WorldEventKind::System { event: r#"{"cap":"result","ok":true,"value":{"sequence":2}}"#.to_owned() })) - || entries - .iter() - .any(|entry| matches!(entry, JournalEntry::System { .. })), - "the chat.say result is journaled: {entries:?}" - ); - assert!( - entries.iter().any( - |entry| matches!(entry, JournalEntry::Committed { event } if matches!(&event.kind, WorldEventKind::Chat(text) if text == "hello from the program")) - ), - "the host chat line is journaled: {entries:?}" - ); - } - - #[tokio::test] - async fn subscribed_ticks_arrive_only_while_someone_is_present() { - let (world, token) = caps_world_sync(false).await; - world - .update_caps(vec!["time.tick".to_owned()], Vec::new()) - .await - .unwrap(); - world.input(token, b"4".to_vec()).await.unwrap(); - world.presence(1, true).await; - tokio::time::sleep(std::time::Duration::from_millis(150)).await; - world.presence(1, false).await; - // Let any in-flight tick settle, then confirm the world goes quiet. - tokio::time::sleep(std::time::Duration::from_millis(60)).await; - let quiet = { - let mut views = world.watch_views(); - views.borrow_and_update(); - tokio::time::sleep(std::time::Duration::from_millis(60)).await; - views.has_changed().is_ok_and(|changed| !changed) - }; - assert!(quiet, "ticks kept firing with nobody present"); - world.shutdown().await.unwrap(); - } - - #[tokio::test] - async fn ticks_follow_the_world_grant_not_a_participant_capability() { - let core = WorldCore::new("ticks", WorldLimits::default()).unwrap(); - let world = WorldHandle::spawn_with_program(core, Box::new(Mock::new())); - let owner_scopes = WorldScopes(WorldScopes::GUEST.bits() | WorldScopes::DELEGATE.bits()); - let (_, owner) = world.issue("ann", owner_scopes).await.unwrap(); - let short_lived = CapabilityBounds { - expires_at: Some(unix_ms() + 150), - uses: None, - }; - let (_, short) = world - .attenuate(owner.clone(), WorldScopes::GUEST, short_lived, "bo") - .await - .unwrap(); - world - .update_caps(vec!["time.tick".to_owned()], Vec::new()) - .await - .unwrap(); - world.input(owner, b"4".to_vec()).await.unwrap(); - world.presence(1, true).await; - tokio::time::sleep(std::time::Duration::from_millis(300)).await; - assert!(world.chat(short, "late").await.is_err()); - let mut views = world.watch_views(); - views.borrow_and_update(); - tokio::time::sleep(std::time::Duration::from_millis(150)).await; - assert!( - views.has_changed().is_ok_and(|changed| changed), - "ticks stopped when a participant's capability expired" - ); - world.shutdown().await.unwrap(); - } - - #[derive(Debug, Default)] - struct TickSay { - ticks: u64, - } - - impl WorldProgram for TickSay { - fn update(&mut self, event: &WorldEvent) -> Result<()> { - if let WorldEventKind::System { event } = &event.kind - && event.contains("time.tick") - { - self.ticks += 1; - } - Ok(()) - } - - fn wants(&mut self) -> Result> { - let mut document = serde_json::json!({"v": 1, "subscribe": ["time.tick:20"]}); - if self.ticks > 0 { - document["requests"] = serde_json::json!([{ - "id": format!("say-{}", self.ticks), - "cap": "chat.say", - "args": {"text": "tick"}, - }]); - } - Ok(Some(document.to_string())) - } - } - - #[tokio::test] - async fn ticks_speak_for_the_world_not_for_a_present_participant() { - let core = WorldCore::new("tick-attribution", WorldLimits::default()).unwrap(); - let world = WorldHandle::spawn_with_program(core, Box::new(TickSay::default())); - world - .update_caps( - vec!["time.tick".to_owned(), "chat.say".to_owned()], - Vec::new(), - ) - .await - .unwrap(); - let (spectator, _) = world - .issue( - "spectator", - WorldScopes(WorldScopes::JOIN.bits() | WorldScopes::INPUT.bits()), - ) - .await - .unwrap(); - world.presence(spectator.id, true).await; - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); - loop { - let usage = world - .caps_report() - .await - .unwrap() - .usage - .get("chat.say") - .copied() - .unwrap_or_default(); - if usage.allowed > 0 { - assert_eq!(usage.denied, 0, "a tick was refused for a participant"); - break; - } - assert!(std::time::Instant::now() < deadline, "no tick ever spoke"); - tokio::time::sleep(std::time::Duration::from_millis(10)).await; - } - world.shutdown().await.unwrap(); - } - - #[tokio::test] - async fn revoking_a_grant_applies_to_capabilities_already_issued() { - let core = WorldCore::new("ceiling", WorldLimits::default()).unwrap(); - let world = WorldHandle::spawn_with_program(core, Box::new(Mock::new())); - world - .update_caps(vec!["chat.say".to_owned()], Vec::new()) - .await - .unwrap(); - let (_, token) = world.issue("ann", WorldScopes::GUEST).await.unwrap(); - world.input(token.clone(), b"3".to_vec()).await.unwrap(); - let usage = world.caps_report().await.unwrap().usage["chat.say"]; - assert_eq!((usage.allowed, usage.denied), (1, 0)); - world - .update_caps(Vec::new(), vec!["chat.say".to_owned()]) - .await - .unwrap(); - world.input(token, b"3".to_vec()).await.unwrap(); - let usage = world.caps_report().await.unwrap().usage["chat.say"]; - assert_eq!((usage.allowed, usage.denied), (1, 1)); - world.shutdown().await.unwrap(); - } - - #[test] - fn a_caps_ceiling_replays_from_the_journal() { - let restored = WorldCore::restore( - "ceil", - WorldLimits::default(), - [ - JournalEntry::Created { - world_id: "ceil".to_owned(), - version: JOURNAL_VERSION, - }, - JournalEntry::CapsGranted { - granted: vec!["time.now".to_owned(), "chat.say".to_owned()], - }, - JournalEntry::CapsCeiling { - ceiling: vec!["time.now".to_owned()], - }, - ], - ) - .unwrap(); - assert!(restored.core.ledger.is_granted("time.now")); - assert!(!restored.core.ledger.is_granted("chat.say")); - assert!( - restored.core.ledger.granted().contains("chat.say"), - "the grant is kept" - ); - - let refused = WorldCore::restore( - "ceil", - WorldLimits::default(), - [ - JournalEntry::Created { - world_id: "ceil".to_owned(), - version: JOURNAL_VERSION, - }, - JournalEntry::CapsCeiling { - ceiling: vec!["*".to_owned()], - }, - ], - ); - assert!(refused.is_err(), "a journaled ceiling may not use `*`"); - } - - #[test] - fn a_caps_ceiling_survives_checkpoint_compaction_and_restore() { - let mut core = world(8); - core.caps_ceiling = BTreeSet::from(["time.now".to_owned()]); - core.sync_ledger_ceiling(); - core.ledger - .set_granted(BTreeSet::from(["chat.say".to_owned()])); - core.active_module_hash = Some("h".to_owned()); - let entries = core.checkpoint_entries("state".to_owned()).unwrap(); - assert!(entries.iter().any(|entry| matches!( - entry, - JournalEntry::Checkpoint { caps_ceiling: Some(ceiling), .. } - if ceiling == &vec!["time.now".to_owned()] - ))); - // The entry is what makes an older binary fail loudly on this journal. - assert!(entries.iter().any(|entry| matches!( - entry, - JournalEntry::CapsCeiling { ceiling } if ceiling == &vec!["time.now".to_owned()] - ))); - let restored = WorldCore::restore("test-world", WorldLimits::default(), entries).unwrap(); - assert_eq!( - restored.core.ledger.allowed(), - &BTreeSet::from(["time.now".to_owned()]) - ); - assert!(!restored.core.ledger.is_granted("chat.say")); - } - - #[test] - fn a_default_ceiling_is_not_written_and_old_journals_allow_the_whole_catalog() { - let mut core = world(8); - core.active_module_hash = Some("h".to_owned()); - let entries = core.checkpoint_entries("state".to_owned()).unwrap(); - assert!(entries.iter().all(|entry| !matches!( - entry, - JournalEntry::Checkpoint { - caps_ceiling: Some(_), - .. - } - ))); - let old = serde_json::json!({ - "entry": "checkpoint", - "sequence": 0, - "module_hash": "h", - "seed": 1, - "snapshot": "s", - "events": [] - }); - let restored = WorldCore::restore( - "test-world", - WorldLimits::default(), - [ - JournalEntry::Created { - world_id: "test-world".to_owned(), - version: JOURNAL_VERSION, - }, - serde_json::from_value(old).unwrap(), - ], - ) - .unwrap(); - assert_eq!( - restored.core.ledger.allowed(), - &crate::world_caps::catalog_names() - ); - } - - #[test] - fn the_server_ceiling_is_runtime_config_and_bounds_a_restored_grant() { - let entries = [ - JournalEntry::Created { - world_id: "server".to_owned(), - version: JOURNAL_VERSION, - }, - JournalEntry::CapsGranted { - granted: vec!["time.now".to_owned(), "chat.say".to_owned()], - }, - ]; - let lower = WorldLimits { - server_caps: BTreeSet::from(["time.now".to_owned()]), - ..WorldLimits::default() - }; - let restored = WorldCore::restore("server", lower, entries.clone()).unwrap(); - assert!(restored.core.ledger.is_granted("time.now")); - assert!(!restored.core.ledger.is_granted("chat.say")); - assert!(restored.core.ledger.granted().contains("chat.say")); - - // Nothing about the server ceiling was journaled, so the default - // server restores the grant. - let restored = WorldCore::restore("server", WorldLimits::default(), entries).unwrap(); - assert!(restored.core.ledger.is_granted("chat.say")); - } - - #[test] - fn a_server_ceiling_naming_a_wildcard_is_refused() { - let limits = WorldLimits { - server_caps: BTreeSet::from(["*".to_owned()]), - ..WorldLimits::default() - }; - assert!(WorldCore::new("w", limits).is_err()); - } - - #[tokio::test] - async fn a_ceiling_change_denies_a_use_that_a_prior_grant_allowed() { - let core = WorldCore::new("ceiling", WorldLimits::default()).unwrap(); - let world = WorldHandle::spawn_with_program(core, Box::new(Mock::new())); - world - .update_caps(vec!["chat.say".to_owned()], Vec::new()) - .await - .unwrap(); - let (_, token) = world.issue("ann", WorldScopes::GUEST).await.unwrap(); - world.input(token.clone(), b"3".to_vec()).await.unwrap(); - let usage = world.caps_report().await.unwrap().usage["chat.say"]; - assert_eq!((usage.allowed, usage.denied), (1, 0)); - - let report = world - .set_caps_ceiling(vec!["time.now".to_owned()]) - .await - .unwrap(); - assert_eq!(report.ceiling, vec!["time.now".to_owned()]); - assert!( - report.granted.contains(&"chat.say".to_owned()), - "the grant is kept" - ); - assert!(!report.effective.contains(&"chat.say".to_owned())); - world.input(token, b"3".to_vec()).await.unwrap(); - let usage = world.caps_report().await.unwrap().usage["chat.say"]; - assert_eq!((usage.allowed, usage.denied), (1, 1)); - - assert!(world.set_caps_ceiling(vec!["*".to_owned()]).await.is_err()); - assert!( - world - .set_caps_ceiling(vec!["time.nwo".to_owned()]) - .await - .is_err() - ); - world.shutdown().await.unwrap(); - } - - #[tokio::test] - async fn lowering_the_ceiling_stops_an_active_subscription_and_reports_it_refused() { - let core = WorldCore::new("ceiling-ticks", WorldLimits::default()).unwrap(); - let world = WorldHandle::spawn_with_program(core, Box::new(Mock::new())); - world - .update_caps(vec!["time.tick".to_owned()], Vec::new()) - .await - .unwrap(); - let (_, token) = world.issue("ann", WorldScopes::GUEST).await.unwrap(); - world.presence(1, true).await; - let mut views = world.watch_views(); - // Script 4 subscribes to `time.tick:20`, which arms it while someone is present. - world.input(token, b"4".to_vec()).await.unwrap(); - views.borrow_and_update(); - tokio::time::timeout(std::time::Duration::from_secs(2), views.changed()) - .await - .expect("no tick arrived while the ceiling allowed it") - .unwrap(); - - world - .set_caps_ceiling(vec!["time.now".to_owned()]) - .await - .unwrap(); - let report = world.caps_report().await.unwrap(); - assert!( - report - .usage - .get("time.tick") - .is_some_and(|usage| usage.denied > 0), - "{report:?}" - ); - assert!(!report.effective.contains(&"time.tick".to_owned())); - // The refusal reached the program before this report; no tick follows. - views.borrow_and_update(); - tokio::time::sleep(std::time::Duration::from_millis(120)).await; - assert!( - views.has_changed().is_ok_and(|changed| !changed), - "ticks kept firing after the ceiling dropped them" - ); - - // Lifting the ceiling admits the refused subscription again. - let full: Vec = crate::world_caps::catalog_names().into_iter().collect(); - world.set_caps_ceiling(full).await.unwrap(); - views.borrow_and_update(); - tokio::time::timeout(std::time::Duration::from_secs(2), views.changed()) - .await - .expect("ticks did not resume once the ceiling allowed them") - .unwrap(); - world.shutdown().await.unwrap(); - } - - #[test] - fn capability_scopes_isolate_actions() { - let mut core = world(8); - let (_, token) = join(&mut core, "Guest"); - assert!(core.snapshot(&token).is_ok()); - assert!(core.chat(&token, "hello").is_ok()); - assert!(core.input(&token, b"move").is_ok()); - let (_, join_only) = core - .issue_capability("spectator", WorldScopes::JOIN, CapabilityBounds::default()) - .unwrap(); - assert!(core.snapshot(&join_only).is_ok()); - assert!(core.chat(&join_only, "no").is_err()); - assert!(core.input(&join_only, b"no").is_err()); - } - - #[test] - fn chat_is_rate_limited_per_participant_within_a_ten_second_window() { - let mut core = world(64); - let (_, token) = join(&mut core, "Guest"); - for index in 0..CHAT_RATE_BURST { - core.chat(&token, &format!("message {index}")).unwrap(); - } - assert!(core.chat(&token, "one too many").is_err()); - assert_eq!(core.current_sequence(), u64::from(CHAT_RATE_BURST)); - } - - fn in_an_hour() -> u64 { - unix_ms() + 3_600_000 - } - - #[test] - fn an_expired_capability_is_refused_for_every_operation() { - let mut core = world(8); - let (_, token) = core - .issue_capability( - "Ada", - WorldScopes::GUEST, - CapabilityBounds { - expires_at: Some(1), - uses: None, - }, - ) - .unwrap(); - assert!(core.snapshot(&token).is_err()); - assert!(core.chat(&token, "late").is_err()); - assert!(core.input(&token, b"late").is_err()); - } - - #[test] - fn delegation_may_not_outlive_or_expire_in_the_past() { - let mut core = world(8); - let (_, owner) = core - .issue_capability( - "Ada", - WorldScopes(WorldScopes::GUEST.bits() | WorldScopes::DELEGATE.bits()), - CapabilityBounds { - expires_at: Some(in_an_hour()), - uses: None, - }, - ) - .unwrap(); - let later = CapabilityBounds { - expires_at: Some(in_an_hour() + 1), - uses: None, - }; - assert!( - core.attenuate(&owner, WorldScopes::JOIN, later, "Bo") - .is_err() - ); - let past = CapabilityBounds { - expires_at: Some(1), - uses: None, - }; - assert!( - core.attenuate(&owner, WorldScopes::JOIN, past, "Cy") - .is_err() - ); - let sooner = CapabilityBounds { - expires_at: Some(in_an_hour() - 1_000), - uses: None, - }; - assert!( - core.attenuate(&owner, WorldScopes::JOIN, sooner, "Di") - .is_ok() - ); - let inherited = core - .attenuate(&owner, WorldScopes::JOIN, CapabilityBounds::default(), "Ed") - .unwrap() - .1; - assert!(core.snapshot(&inherited).is_ok()); - } - - #[test] - fn a_host_issued_limit_draws_down_through_every_delegation() { - let mut core = world(8); - let (_, owner) = core - .issue_capability( - "Ada", - WorldScopes(WorldScopes::GUEST.bits() | WorldScopes::DELEGATE.bits()), - CapabilityBounds { - expires_at: None, - uses: Some(3), - }, - ) - .unwrap(); - let (_, child) = core - .attenuate( - &owner, - WorldScopes::GUEST, - CapabilityBounds::default(), - "Bo", - ) - .unwrap(); - core.chat(&child, "one").unwrap(); - core.chat(&child, "two").unwrap(); - core.chat(&owner, "last").unwrap(); - assert!( - core.chat(&child, "three").is_err(), - "the host's limit bounds the delegate" - ); - assert!(core.chat(&owner, "over").is_err()); - assert!(core.snapshot(&owner).is_ok(), "reading is not a use"); - } - - #[test] - fn a_delegated_grant_carries_no_use_count() { - let mut core = world(8); - let delegator = WorldScopes(WorldScopes::GUEST.bits() | WorldScopes::DELEGATE.bits()); - let (_, owner) = core - .issue_capability("Ada", delegator, CapabilityBounds::default()) - .unwrap(); - let limited = CapabilityBounds { - expires_at: None, - uses: Some(1), - }; - assert!( - core.attenuate(&owner, WorldScopes::GUEST, limited, "Bo") - .is_err(), - "a delegation carries no use count" - ); - let (child, child_token) = core - .attenuate( - &owner, - WorldScopes::GUEST, - CapabilityBounds::default(), - "Cy", - ) - .unwrap(); - for text in ["one", "two", "three"] { - core.chat(&child_token, text).unwrap(); - } - let record = serde_json::to_value(core.issued_entry(child.id).unwrap()).unwrap(); - assert!( - record.get("uses").is_none(), - "the grant record has no use count: {record}" - ); - } - - #[test] - fn a_grant_without_a_bound_is_never_refused_for_count() { - let mut core = world(8); - let (_, token) = join(&mut core, "Ada"); - for i in 0..50 { - core.chat(&token, &format!("m{i}")).unwrap(); - } - assert!(core.snapshot(&token).is_ok()); - } - - #[test] - fn a_host_issued_limit_is_enforced_by_the_host_alone() { - let mut core = world(8); - let (_, token) = core - .issue_capability( - "Ada", - WorldScopes::GUEST, - CapabilityBounds { - expires_at: None, - uses: Some(2), - }, - ) - .unwrap(); - core.chat(&token, "one").unwrap(); - core.chat(&token, "two").unwrap(); - assert!(core.chat(&token, "three").is_err()); - assert_eq!(core.current_sequence(), 2, "a refused use commits nothing"); - } - - #[test] - fn use_counts_are_local_and_do_not_converge_across_partitions() { - let mut source = world(8); - let (owner, token) = source - .issue_capability( - "Ada", - WorldScopes::GUEST, - CapabilityBounds { - expires_at: None, - uses: Some(1), - }, - ) - .unwrap(); - let entries = vec![ - JournalEntry::Created { - world_id: "test-world".to_owned(), - version: JOURNAL_VERSION, - }, - JournalEntry::Issued { - participant: owner.clone(), - digest: hex_encode(&token_digest(token.expose())), - scopes: WorldScopes::GUEST.bits(), - parent: None, - expires_at: None, - uses: Some(1), - used: 0, - subject: None, - }, - ]; - // Two partitions start from the same journal and do not see each other. - let mut north = WorldCore::restore("test-world", WorldLimits::default(), entries.clone()) - .unwrap() - .core; - let mut south = WorldCore::restore("test-world", WorldLimits::default(), entries) - .unwrap() - .core; - north.chat(&token, "north").unwrap(); - south.chat(&token, "south").unwrap(); - // Each side counted its own use, so the one-use grant was used twice. - assert!(north.chat(&token, "north again").is_err()); - assert!(south.chat(&token, "south again").is_err()); - // Each state is still valid: sequence and tally agree, and the grant is held. - for core in [&north, &south] { - assert_eq!(core.current_sequence(), 1); - assert_eq!(core.capabilities[&owner.id].used, 1); - assert_eq!(core.participants().len(), 1); - } - } - - #[test] - fn use_counts_survive_restore_and_compaction() { - let mut source = world(8); - let (owner, token) = source - .issue_capability( - "Ada", - WorldScopes::GUEST, - CapabilityBounds { - expires_at: None, - uses: Some(2), - }, - ) - .unwrap(); - let digest = hex_encode(&token_digest(token.expose())); - let entries = vec![ - JournalEntry::Created { - world_id: "test-world".to_owned(), - version: JOURNAL_VERSION, - }, - JournalEntry::Issued { - participant: owner, - digest, - scopes: WorldScopes::GUEST.bits(), - parent: None, - expires_at: None, - uses: Some(2), - used: 1, - subject: None, - }, - ]; - let mut restored = - WorldCore::restore("test-world", WorldLimits::default(), entries).unwrap(); - restored.core.chat(&token, "second").unwrap(); - assert!(restored.core.chat(&token, "third").is_err()); - } - - #[test] - fn restore_refuses_a_delegate_outliving_its_parent() { - let mut source = world(8); - let (owner, owner_token) = source - .issue_capability( - "Ada", - WorldScopes(WorldScopes::GUEST.bits() | WorldScopes::DELEGATE.bits()), - CapabilityBounds { - expires_at: Some(in_an_hour()), - uses: None, - }, - ) - .unwrap(); - let (child, child_token) = source - .attenuate( - &owner_token, - WorldScopes::JOIN, - CapabilityBounds::default(), - "Bo", - ) - .unwrap(); - let digest = hex_encode(&token_digest(child_token.expose())); - let entries = vec![ - JournalEntry::Created { - world_id: "test-world".to_owned(), - version: JOURNAL_VERSION, - }, - JournalEntry::Issued { - participant: owner, - digest: hex_encode(&token_digest(owner_token.expose())), - scopes: WorldScopes(WorldScopes::GUEST.bits() | WorldScopes::DELEGATE.bits()) - .bits(), - parent: None, - expires_at: Some(in_an_hour()), - uses: None, - used: 0, - subject: None, - }, - JournalEntry::Issued { - participant: child, - digest, - scopes: WorldScopes::JOIN.bits(), - parent: Some(1), - expires_at: Some(in_an_hour() + 1), - uses: None, - used: 0, - subject: None, - }, - ]; - assert!(WorldCore::restore("test-world", WorldLimits::default(), entries).is_err()); - } - - #[test] - fn events_are_sequenced_and_reconnect_can_catch_up() { - let mut core = world(8); - let (_, token) = join(&mut core, "Ada"); - assert_eq!(core.chat(&token, "hello").unwrap().sequence, 1); - assert_eq!(core.input(&token, b"move").unwrap().sequence, 2); - let page = core.events_after(&token, 1).unwrap(); - assert_eq!(page.current_sequence, 2); - assert!(!page.needs_snapshot); - assert_eq!(page.events.len(), 1); - assert_eq!(page.events[0].sequence, 2); - } - - #[test] - fn reconnect_requires_snapshot_when_cursor_is_older_than_retention() { - let mut core = world(2); - let (_, token) = join(&mut core, "Ada"); - for msg in ["one", "two", "three"] { - core.chat(&token, msg).unwrap(); - } - let page = core.events_after(&token, 0).unwrap(); - assert!(page.needs_snapshot); - assert!(page.events.is_empty()); - let snapshot = core.snapshot(&token).unwrap(); - assert_eq!(snapshot.current_sequence, 3); - assert_eq!(snapshot.oldest_retained_sequence, 2); - assert_eq!(snapshot.events.len(), 2); - } - - #[test] - fn revoked_capabilities_cannot_read_or_write() { - let mut core = world(8); - let (participant, token) = join(&mut core, "Ada"); - assert_eq!(core.revoke_tree(participant.id), vec![participant.id]); - assert!(core.revoke_tree(participant.id).is_empty()); - assert!(core.snapshot(&token).is_err()); - assert!(core.chat(&token, "hello").is_err()); - } - - #[test] - fn content_before_a_removal_is_kept_and_content_after_it_is_refused() { - let mut core = world(8); - let (ada, ada_token) = join(&mut core, "Ada"); - let (_, bo_token) = join(&mut core, "Bo"); - core.chat(&ada_token, "before").unwrap(); - assert_eq!(core.revoke_tree(ada.id), vec![ada.id]); - assert!(core.chat(&ada_token, "after").is_err()); - assert!(core.input(&ada_token, b"move").is_err()); - assert_eq!( - core.current_sequence(), - 1, - "a refused action commits nothing" - ); - let kept: Vec = core - .snapshot(&bo_token) - .unwrap() - .events - .into_iter() - .filter_map(|event| match event.kind { - WorldEventKind::Chat(text) => Some(text), - _ => None, - }) - .collect(); - assert_eq!(kept, vec!["before"]); - assert_eq!(core.events_after(&bo_token, 0).unwrap().events.len(), 1); - } - - #[tokio::test] - async fn a_removal_racing_chat_keeps_every_accepted_line() { - let handle = WorldHandle::spawn(WorldCore::new("w", WorldLimits::default()).unwrap()); - let (ada, ada_token) = handle.issue("Ada", WorldScopes::GUEST).await.unwrap(); - let (_, bo_token) = handle.issue("Bo", WorldScopes::GUEST).await.unwrap(); - let chatter = { - let handle = handle.clone(); - let token = ada_token.clone(); - tokio::spawn(async move { - let mut accepted = 0; - for i in 0..200 { - if handle.chat(token.clone(), format!("m{i}")).await.is_ok() { - accepted += 1; - } - } - accepted - }) - }; - tokio::task::yield_now().await; - assert!(handle.revoke(ada.id).await.unwrap()); - let accepted = chatter.await.unwrap(); - assert!(handle.chat(ada_token, "late").await.is_err()); - let snapshot = handle.snapshot(bo_token).await.unwrap(); - let from_ada = snapshot - .events - .iter() - .filter(|event| event.participant_id == ada.id) - .count(); - assert_eq!( - from_ada, accepted, - "every line accepted before the removal is kept, and none after it" - ); - } - - #[test] - fn role_presets_grant_and_withhold_the_expected_effects() { - let spectator = WorldScopes::from_role("spectator").unwrap(); - assert!(spectator.allows_effect("time.now")); - assert!(!spectator.allows_effect("chat.say")); - assert!(!spectator.allows_effect("chat.history")); - assert!(!spectator.reads_chat()); - assert!(spectator.attenuate(WorldScopes::INPUT).is_none()); - - // An observer reads chat, through the stream and `chat.history` - // alike, and still cannot send it or act. - let observer = WorldScopes::from_role("observer").unwrap(); - assert!(observer.reads_chat()); - assert!(observer.allows_effect("chat.history")); - assert!(!observer.allows_effect("chat.say")); - assert!(!observer.contains(WorldScopes::INPUT)); - - let player = WorldScopes::from_role("player").unwrap(); - assert!(player.contains(WorldScopes::INPUT)); - assert!(!player.contains(WorldScopes::CHAT)); - assert!(!player.contains(WorldScopes::DELEGATE)); - - let guest = WorldScopes::from_role("guest").unwrap(); - assert_eq!(guest, WorldScopes::GUEST); - assert!(guest.allows_effect("chat.say")); - - let delegator = WorldScopes::from_role("delegator").unwrap(); - assert!(delegator.contains(WorldScopes::DELEGATE)); - assert!(delegator.attenuate(WorldScopes::JOIN).is_some()); - - assert_eq!(WorldScopes::from_role("builder"), None); - assert_eq!( - WorldScopes::ROLES, - &["spectator", "observer", "player", "guest", "delegator"] - ); - } - - #[test] - fn attenuation_only_narrows_and_needs_delegate() { - let join = WorldScopes::JOIN; - let delegator = WorldScopes(WorldScopes::GUEST.bits() | WorldScopes::DELEGATE.bits()); - assert_eq!(delegator.attenuate(join), Some(join)); - assert!(delegator.attenuate(WorldScopes::GUEST).is_some()); - assert!( - WorldScopes::GUEST.attenuate(join).is_none(), - "no delegate scope" - ); - assert!( - delegator.attenuate(WorldScopes::CHAT).is_none(), - "must keep join" - ); - let join_only = WorldScopes(WorldScopes::JOIN.bits() | WorldScopes::DELEGATE.bits()); - assert!( - join_only.attenuate(WorldScopes::GUEST).is_none(), - "widening" - ); - } - - #[test] - fn scope_names_and_effects_follow_the_scopes() { - assert_eq!( - WorldScopes::from_names(["join", "delegate"]), - Some(WorldScopes(0b1001)) - ); - assert_eq!(WorldScopes::from_names(["join", "telepathy"]), None); - assert!(WorldScopes::GUEST.allows_effect("chat.say")); - assert!(WorldScopes::GUEST.allows_effect("chat.history")); - let spectator = WorldScopes(WorldScopes::JOIN.bits() | WorldScopes::INPUT.bits()); - assert!(!spectator.allows_effect("chat.say")); - assert!(!spectator.allows_effect("chat.history")); - assert!(spectator.allows_effect("time.now")); - } - - #[test] - fn delegated_capabilities_are_narrow_and_die_with_their_parent() { - let mut core = world(8); - let root = WorldScopes(WorldScopes::GUEST.bits() | WorldScopes::DELEGATE.bits()); - let (owner, owner_token) = core - .issue_capability("Ada", root, CapabilityBounds::default()) - .unwrap(); - let (child, child_token) = core - .attenuate( - &owner_token, - WorldScopes(WorldScopes::JOIN.bits() | WorldScopes::DELEGATE.bits()), - CapabilityBounds::default(), - "Bo", - ) - .unwrap(); - let (grandchild, grandchild_token) = core - .attenuate( - &child_token, - WorldScopes::JOIN, - CapabilityBounds::default(), - "Cy", - ) - .unwrap(); - assert!(core.chat(&grandchild_token, "hi").is_err()); - assert!( - core.attenuate( - &child_token, - WorldScopes::GUEST, - CapabilityBounds::default(), - "Di" - ) - .is_err() - ); - assert!( - core.attenuate( - &grandchild_token, - WorldScopes::JOIN, - CapabilityBounds::default(), - "Ed" - ) - .is_err() - ); - - let mut revoked = core.revoke_tree(owner.id); - revoked.sort_unstable(); - assert_eq!(revoked, vec![owner.id, child.id, grandchild.id]); - assert!(core.snapshot(&child_token).is_err()); - assert!(core.snapshot(&grandchild_token).is_err()); - } - - #[test] - fn delegation_counts_against_the_participant_limit() { - let limits = WorldLimits { - participants: 2, - ..WorldLimits::default() - }; - let mut core = WorldCore::new("limit", limits).unwrap(); - let root = WorldScopes(WorldScopes::GUEST.bits() | WorldScopes::DELEGATE.bits()); - let (_, owner_token) = core - .issue_capability("Ada", root, CapabilityBounds::default()) - .unwrap(); - core.attenuate( - &owner_token, - WorldScopes::JOIN, - CapabilityBounds::default(), - "Bo", - ) - .unwrap(); - assert!( - core.attenuate( - &owner_token, - WorldScopes::JOIN, - CapabilityBounds::default(), - "Cy" - ) - .is_err() - ); - } - - #[test] - fn a_restored_delegation_keeps_its_parent_link() { - let secret = "cd".repeat(32); - let token = JoinCapability::from_wire(format!("2.{secret}")); - let digest = hex_encode(&token_digest(token.expose())); - let entries = vec![ - JournalEntry::Created { - world_id: "delegate".to_owned(), - version: JOURNAL_VERSION, - }, - JournalEntry::Issued { - participant: Participant { - id: 1, - display_name: "ann".to_owned(), - }, - digest: "00".repeat(32), - scopes: WorldScopes::GUEST.bits() | WorldScopes::DELEGATE.bits(), - parent: None, - expires_at: None, - uses: None, - used: 0, - subject: None, - }, - JournalEntry::Issued { - participant: Participant { - id: 2, - display_name: "bo".to_owned(), - }, - digest, - scopes: WorldScopes::JOIN.bits(), - parent: Some(1), - expires_at: None, - uses: None, - used: 0, - subject: None, - }, - ]; - let mut restored = WorldCore::restore("delegate", WorldLimits::default(), entries) - .unwrap() - .core; - assert!(restored.authorize(&token, WorldScopes::JOIN).is_ok()); - assert_eq!(restored.revoke_tree(1), vec![1, 2]); - assert!(restored.authorize(&token, WorldScopes::JOIN).is_err()); - } - - #[test] - fn foreign_and_malformed_capabilities_are_rejected() { - let mut left = world(8); - let right = world(8); - let (_, left_token) = join(&mut left, "Ada"); - let malformed = JoinCapability("not-a-valid-token".to_owned()); - assert!(left.snapshot(&malformed).is_err()); - assert!(right.snapshot(&left_token).is_err()); - } - - #[test] - fn names_chat_and_input_are_sanitized_and_bounded() { - let mut core = world(8); - let (participant, token) = join(&mut core, "\u{1b}[31mAda\n"); - assert_eq!(participant.display_name, "[31mAda"); - assert_eq!( - core.chat(&token, " hi\u{1b}[31m\n").unwrap().kind, - WorldEventKind::Chat("hi[31m".to_owned()) - ); - assert!(core.chat(&token, &"x".repeat(2049)).is_err()); - assert!(core.input(&token, &vec![0; 16 * 1024 + 1]).is_err()); - assert!(core.chat(&token, " \n \t ").is_err()); - } - - #[test] - fn participant_capacity_and_constructor_limits_are_enforced() { - let mut core = WorldCore::new( - "small", - WorldLimits { - participants: 1, - ..WorldLimits::default() - }, - ) - .unwrap(); - join(&mut core, "Ada"); - assert!( - core.issue_capability("Grace", WorldScopes::GUEST, CapabilityBounds::default()) - .is_err() - ); - assert!(WorldCore::new("", WorldLimits::default()).is_err()); - assert!( - WorldCore::new( - "world", - WorldLimits { - retained_events: 0, - ..WorldLimits::default() - } - ) - .is_err() - ); - } - - #[test] - fn join_projections_redact_the_install_seed_but_the_journal_keeps_it() { - // Issue #240: the install seed was serialized to every joiner via - // `events_after` and the snapshot. The journal (and the admin paths - // fed from it) must keep the real seed; join projections must not. - let entries = vec![ - JournalEntry::Created { - world_id: "test-world".to_owned(), - version: JOURNAL_VERSION, - }, - JournalEntry::Committed { - event: WorldEvent { - sequence: 1, - participant_id: 0, - kind: WorldEventKind::ProgramInstalled { - module_hash: "ab".repeat(32), - seed: 424_242, - provenance: None, - }, - }, - }, - ]; - let restored = WorldCore::restore("test-world", WorldLimits::default(), entries).unwrap(); - assert_eq!( - restored.program.as_ref().map(|program| program.seed), - Some(424_242), - "the journal restore path keeps the real seed for the admin" - ); - let mut core = restored.core; - assert_eq!(core.active_seed, 424_242, "the core keeps the real seed"); - let (_, token) = join(&mut core, "Ada"); - let page = core.events_after(&token, 0).unwrap(); - assert_eq!(page.events.len(), 1); - assert!( - matches!( - &page.events[0].kind, - WorldEventKind::ProgramInstalled { module_hash, seed, .. } - if module_hash == &"ab".repeat(32) && *seed == 0 - ), - "events_after must keep the module hash but redact the seed: {:?}", - page.events[0].kind - ); - assert!( - !format!("{page:?}").contains("424242"), - "events_after leaked the install seed" - ); - let snapshot = core.snapshot(&token).unwrap(); - assert_eq!(snapshot.events.len(), 1); - assert!( - !serde_json::to_string(&snapshot).unwrap().contains("424242"), - "the snapshot leaked the install seed" - ); - } - - fn scoped(core: &mut WorldCore, name: &str, names: &[&str]) -> JoinCapability { - let scopes = WorldScopes::from_names(names.iter().copied()).unwrap(); - core.issue_capability(name, scopes, CapabilityBounds::default()) - .unwrap() - .1 - } - - fn chat_texts(events: &[WorldEvent]) -> Vec { - events - .iter() - .filter_map(|event| match &event.kind { - WorldEventKind::Chat(text) => Some(text.clone()), - _ => None, - }) - .collect() - } - - /// Chat line, input, chat line, input: sequences 1..=4. - fn talk(core: &mut WorldCore, speaker: &JoinCapability) { - core.chat(speaker, "one").unwrap(); - core.input(speaker, b"a").unwrap(); - core.chat(speaker, "two").unwrap(); - core.input(speaker, b"b").unwrap(); - } - - #[test] - fn chat_visibility_follows_the_viewers_scopes() { - let mut core = world(16); - let (_, speaker) = join(&mut core, "Ada"); - let watcher = scoped(&mut core, "watch", &["join"]); - let reader = scoped(&mut core, "read", &["join", "history"]); - talk(&mut core, &speaker); - - let sequences = |events: &[WorldEvent]| -> Vec { - events.iter().map(|event| event.sequence).collect() - }; - for (token, sees_chat) in [(&speaker, true), (&reader, true), (&watcher, false)] { - let page = core.events_after(token, 0).unwrap(); - let snapshot = core.snapshot(token).unwrap(); - for events in [&page.events, &snapshot.events] { - let (lines, kept): (Vec<&str>, Vec) = if sees_chat { - (vec!["one", "two"], vec![1, 2, 3, 4]) - } else { - (Vec::new(), vec![2, 4]) - }; - assert_eq!(chat_texts(events), lines); - assert_eq!(sequences(events), kept, "non-chat events are kept"); - } - } - } - - #[test] - fn chat_visibility_history_reads_without_sending() { - let mut core = world(16); - let (_, speaker) = join(&mut core, "Ada"); - let reader = scoped(&mut core, "read", &["join", "history"]); - core.chat(&speaker, "hello").unwrap(); - assert!(core.chat(&reader, "hi").is_err(), "history does not send"); - assert!(core.input(&reader, b"a").is_err()); - assert_eq!( - chat_texts(&core.events_after(&reader, 0).unwrap().events), - ["hello"] - ); - assert_eq!(core.current_sequence(), 1, "a refused line commits nothing"); - } - - #[test] - fn chat_visibility_cursors_advance_across_gaps() { - let mut core = world(16); - let (_, speaker) = join(&mut core, "Ada"); - let watcher = scoped(&mut core, "watch", &["join"]); - core.chat(&speaker, "one").unwrap(); - core.chat(&speaker, "two").unwrap(); - - // Only chat so far: nothing to show, yet the cursor moves to the end - // and retention is judged on the world, not the viewer. - let page = core.events_after(&watcher, 0).unwrap(); - assert!(page.events.is_empty()); - assert!(!page.needs_snapshot); - assert_eq!(page.current_sequence, 2); - assert_eq!(page.oldest_retained_sequence, 1); - let again = core.events_after(&watcher, page.current_sequence).unwrap(); - assert!(again.events.is_empty() && !again.needs_snapshot); - - core.chat(&speaker, "three").unwrap(); - core.input(&speaker, b"a").unwrap(); - let page = core.events_after(&watcher, page.current_sequence).unwrap(); - assert_eq!( - page.events.iter().map(|e| e.sequence).collect::>(), - [4] - ); - // Resuming from the last sequence it was given, across the gap, misses - // nothing and repeats nothing. - let last = page.events[0].sequence; - core.input(&speaker, b"b").unwrap(); - let page = core.events_after(&watcher, last).unwrap(); - assert_eq!( - page.events.iter().map(|e| e.sequence).collect::>(), - [5] - ); - } - - #[test] - fn chat_visibility_retention_does_not_depend_on_the_viewer() { - let mut core = world(3); - let (_, speaker) = join(&mut core, "Ada"); - let watcher = scoped(&mut core, "watch", &["join"]); - for line in ["one", "two", "three", "four"] { - core.chat(&speaker, line).unwrap(); - } - // Sequences 1..=4 committed; 2..=4 retained, all of them chat. - let page = core.events_after(&watcher, 0).unwrap(); - assert!(page.needs_snapshot, "the cursor fell behind retention"); - assert_eq!(page.oldest_retained_sequence, 2); - let snapshot = core.snapshot(&watcher).unwrap(); - assert!(snapshot.events.is_empty()); - assert_eq!(snapshot.current_sequence, 4); - assert_eq!(snapshot.oldest_retained_sequence, 5, "carries no events"); - } - - #[test] - fn chat_visibility_the_snapshot_budget_counts_only_what_it_carries() { - let mut core = WorldCore::new( - "budget", - WorldLimits { - snapshot_bytes: 400, - ..WorldLimits::default() - }, - ) - .unwrap(); - let (_, speaker) = join(&mut core, "Ada"); - let watcher = scoped(&mut core, "watch", &["join"]); - core.input(&speaker, b"a").unwrap(); - core.input(&speaker, b"b").unwrap(); - for _ in 0..20 { - core.chat(&speaker, &"x".repeat(100)).unwrap(); - } - let guest = core.snapshot(&speaker).unwrap(); - assert!( - guest.events.len() < 22 - && guest - .events - .iter() - .all(|e| matches!(e.kind, WorldEventKind::Chat(_))), - "chat fills the budget for a viewer who sees it" - ); - let snapshot = core.snapshot(&watcher).unwrap(); - assert_eq!( - snapshot - .events - .iter() - .map(|e| e.sequence) - .collect::>(), - [1, 2], - "withheld chat spends none of the budget" - ); - assert_eq!(snapshot.oldest_retained_sequence, 1); - } - - #[test] - fn chat_visibility_the_install_seed_stays_secret_for_every_scope() { - let event = WorldEvent { - sequence: 1, - participant_id: 0, - kind: WorldEventKind::ProgramInstalled { - module_hash: "ab".repeat(32), - seed: 424_242, - provenance: None, - }, - }; - for scopes in [WorldScopes::JOIN, WorldScopes::GUEST, WorldScopes::ALL] { - let shown = project_event_for(scopes, &event).unwrap(); - assert_eq!( - shown.kind, - WorldEventKind::ProgramInstalled { - module_hash: "ab".repeat(32), - seed: 0, - provenance: None, - } - ); - } - let chat = WorldEvent { - sequence: 2, - participant_id: 1, - kind: WorldEventKind::Chat("hi".to_owned()), - }; - assert_eq!(project_event_for(WorldScopes::JOIN, &chat), None); - assert_eq!( - project_event_for(WorldScopes::CHAT, &chat), - Some(chat.clone()) - ); - assert_eq!(project_event_for(WorldScopes::HISTORY, &chat), Some(chat)); - } - - #[tokio::test] - async fn chat_visibility_the_live_stream_is_projected_per_viewer() { - let core = world(16); - let world = WorldHandle::spawn(core); - let (_, guest) = world.issue("ann", WorldScopes::GUEST).await.unwrap(); - let (_, watcher) = world.issue("watch", WorldScopes::JOIN).await.unwrap(); - let mut live = world.subscribe(); - - world.chat(guest.clone(), "secret").await.unwrap(); - world - .install_program( - "cd".repeat(32), - 424_242, - Box::new(Counter { - count: 0, - bad: false, - }), - ) - .await - .unwrap(); - - let chat = live.recv().await.unwrap(); - let install = live.recv().await.unwrap(); - // The raw stream is the host's: it carries the line and the real seed. - assert_eq!(chat_texts(std::slice::from_ref(&chat)), ["secret"]); - assert!(matches!( - install.kind, - WorldEventKind::ProgramInstalled { seed: 424_242, .. } - )); - - // What a participant may be sent is the projection. - assert_eq!( - world - .project_event(watcher.clone(), chat.clone()) - .await - .unwrap(), - None - ); - assert_eq!( - world - .project_event(guest.clone(), chat.clone()) - .await - .unwrap(), - Some(chat) - ); - for token in [&guest, &watcher] { - let shown = world - .project_event(token.clone(), install.clone()) - .await - .unwrap() - .unwrap(); - assert!( - matches!(shown.kind, WorldEventKind::ProgramInstalled { seed: 0, .. }), - "{shown:?}" - ); - } - // A revoked participant is an error, so its session ends. - let (revoked, gone) = world.issue("gone", WorldScopes::JOIN).await.unwrap(); - assert!(world.revoke(revoked.id).await.unwrap()); - assert!(world.project_event(gone, install).await.is_err()); - } - - #[test] - fn chat_visibility_scope_names_attenuation_and_chains() { - assert_eq!( - WorldScopes::from_names(["history"]), - Some(WorldScopes::HISTORY) - ); - assert_eq!(WorldScopes::HISTORY.bits(), 0b1_0000); - assert_eq!(WorldScopes::from_names(["join", "telepathy"]), None); - assert_eq!(WorldScopes::from_bits(0b1_0000), Some(WorldScopes::HISTORY)); - assert_eq!(WorldScopes::from_bits(0b10_0000), None); - - let join_history = WorldScopes::JOIN.union(WorldScopes::HISTORY); - let chat_delegator = WorldScopes::GUEST.union(WorldScopes::DELEGATE); - let history_delegator = join_history.union(WorldScopes::DELEGATE); - // A reader delegates what it holds and no more; chat includes history. - assert_eq!( - history_delegator.attenuate(join_history), - Some(join_history) - ); - assert_eq!( - history_delegator.attenuate(WorldScopes::JOIN), - Some(WorldScopes::JOIN) - ); - assert!(history_delegator.attenuate(WorldScopes::GUEST).is_none()); - assert!( - history_delegator - .attenuate(WorldScopes::JOIN.union(WorldScopes::CHAT)) - .is_none(), - "reading does not include sending" - ); - assert_eq!(chat_delegator.attenuate(join_history), Some(join_history)); - assert!( - WorldScopes::GUEST.attenuate(join_history).is_none(), - "no delegate" - ); - assert!(WorldScopes::GUEST.reads_chat() && join_history.reads_chat()); - assert!(!WorldScopes::JOIN.union(WorldScopes::INPUT).reads_chat()); - assert!(WorldScopes::ALL.contains(WorldScopes::HISTORY)); - } - - #[test] - fn chat_visibility_a_guest_can_hand_out_a_read_only_link() { - let mut core = world(16); - let owner = scoped(&mut core, "owner", &["join", "chat", "input", "delegate"]); - let (_, reader) = core - .attenuate( - &owner, - WorldScopes::JOIN.union(WorldScopes::HISTORY), - CapabilityBounds::default(), - "reader", - ) - .unwrap(); - let (_, watcher) = core - .attenuate( - &owner, - WorldScopes::JOIN, - CapabilityBounds::default(), - "watch", - ) - .unwrap(); - core.chat(&owner, "hello").unwrap(); - assert_eq!( - chat_texts(&core.snapshot(&reader).unwrap().events), - ["hello"] - ); - assert!(chat_texts(&core.snapshot(&watcher).unwrap().events).is_empty()); - assert!(core.chat(&reader, "hi").is_err()); - } - - #[test] - fn snapshots_do_not_include_capability_secret() { - let mut core = world(8); - let (participant, token) = join(&mut core, "Ada"); - let serialized = format!("{:?}", core.snapshot(&token).unwrap()); - assert!(!serialized.contains(token.expose())); - assert!(serialized.contains(&participant.display_name)); - assert!(!format!("{token:?}").contains(token.expose())); - } - - #[tokio::test] - async fn actor_serializes_concurrent_event_mutations() { - let actor = WorldHandle::spawn(world(32)); - let (_, token) = actor.issue("Ada", WorldScopes::GUEST).await.unwrap(); - let first = actor.chat(token.clone(), "one"); - let second = actor.input(token.clone(), b"two".to_vec()); - let third = actor.chat(token.clone(), "three"); - let (one, two, three) = tokio::join!(first, second, third); - let mut sequences = [ - one.unwrap().sequence, - two.unwrap().sequence, - three.unwrap().sequence, - ]; - sequences.sort_unstable(); - assert_eq!(sequences, [1, 2, 3]); - assert_eq!(actor.snapshot(token).await.unwrap().current_sequence, 3); - } - - /// Counts inputs; records are the count, or `bad` after an input "bad". - struct Counter { - count: u64, - bad: bool, - } - - impl WorldProgram for Counter { - fn update(&mut self, event: &WorldEvent) -> Result<()> { - if let WorldEventKind::Input(bytes) = &event.kind { - self.count += 1; - self.bad = bytes.as_slice() == b"bad"; - } - Ok(()) - } - fn records(&mut self) -> Result> { - Ok(Some(if self.bad { - "[1,2,3]".to_owned() - } else { - format!("{{\"count\":{}}}", self.count) - })) - } - } - - #[tokio::test] - async fn records_read_returns_a_bounded_prefix_scoped_page() { - struct ReaderProgram { - asks: u64, - read_key: String, - } - impl WorldProgram for ReaderProgram { - fn update(&mut self, event: &WorldEvent) -> Result<()> { - match &event.kind { - WorldEventKind::Input(bytes) => { - if bytes.as_slice() == b"read" { - self.asks += 1; - } - } - WorldEventKind::System { event } => { - let value: serde_json::Value = - serde_json::from_str(event).unwrap_or(serde_json::Value::Null); - if value["cap"] == "result" - && let Some(key) = value["value"]["records"][0]["key"].as_str() - { - self.read_key = key.to_owned(); - } - } - WorldEventKind::Chat(_) | WorldEventKind::ProgramInstalled { .. } => {} - } - Ok(()) - } - - fn records(&mut self) -> Result> { - Ok(Some( - serde_json::json!({ - "count": self.asks, - "read": self.read_key, - }) - .to_string(), - )) - } - - fn wants(&mut self) -> Result> { - if self.asks == 0 { - return Ok(Some("{}".to_owned())); - } - Ok(Some( - serde_json::json!({ - "requests": [{ - "id": format!("read-{}", self.asks), - "cap": "records.read", - "args": {"prefix": "co", "after": ""}, - }], - }) - .to_string(), - )) - } - } - - let world = WorldHandle::spawn_with_program( - world(16), - Box::new(ReaderProgram { - asks: 0, - read_key: String::new(), - }), - ); - let (_, ann) = world.issue("ann", WorldScopes::GUEST).await.unwrap(); - - // Ungranted: the request is refused and counted. - world.input(ann.clone(), b"read".to_vec()).await.unwrap(); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); - loop { - let report = world.caps_report().await.unwrap(); - if report - .usage - .get("records.read") - .is_some_and(|use_| use_.denied > 0) - { - break; - } - assert!(std::time::Instant::now() < deadline, "no refusal recorded"); - tokio::time::sleep(std::time::Duration::from_millis(10)).await; - } - - // Granted: the program reads its own published `count` record. - world - .update_caps(vec!["records.read".to_owned()], Vec::new()) - .await - .unwrap(); - world.input(ann, b"read".to_vec()).await.unwrap(); - loop { - let record = world.records().1["read"].as_str().unwrap_or("").to_owned(); - if record == "count" { - break; - } - assert!( - std::time::Instant::now() < deadline, - "the program never read its record: {record:?}" - ); - tokio::time::sleep(std::time::Duration::from_millis(10)).await; - } - } - - #[tokio::test] - async fn records_follow_committed_inputs_and_bad_output_fails_closed() { - let world = WorldHandle::spawn_with_program( - world(16), - Box::new(Counter { - count: 0, - bad: false, - }), - ); - assert_eq!(world.records().1["count"], 0); - let (_, ann) = world.issue("ann", WorldScopes::GUEST).await.unwrap(); - let event = world.input(ann.clone(), b"go".to_vec()).await.unwrap(); - let (sequence, records) = world.records(); - assert_eq!( - (sequence, records["count"].as_u64()), - (event.sequence, Some(1)) - ); - - // Records that are not a JSON object reject the input and poison the - // program; the previous records stay published. - assert!(world.input(ann.clone(), b"bad".to_vec()).await.is_err()); - assert_eq!(world.records().1["count"], 1); - assert!(world.input(ann.clone(), b"go".to_vec()).await.is_err()); - let snapshot = world.snapshot(ann.clone()).await.unwrap(); - assert_eq!( - snapshot.current_sequence, event.sequence, - "nothing committed" - ); - - // A replacement with valid records restores service. - world - .install_program( - "00".repeat(32), - 0, - Box::new(Counter { - count: 10, - bad: false, - }), - ) - .await - .unwrap(); - assert_eq!(world.records().1["count"], 10); - world.input(ann, b"go".to_vec()).await.unwrap(); - assert_eq!(world.records().1["count"], 11); - } - - #[tokio::test] - async fn installs_with_invalid_records_are_refused() { - let world = WorldHandle::spawn(world(16)); - let err = world - .install_program( - "00".repeat(32), - 0, - Box::new(Counter { - count: 0, - bad: true, - }), - ) - .await - .unwrap_err(); - assert!(format!("{err:#}").contains("records"), "{err:#}"); - let (_, ann) = world.issue("ann", WorldScopes::GUEST).await.unwrap(); - assert_eq!(world.snapshot(ann).await.unwrap().active_module_hash, None); - } - - #[test] - fn record_keys_and_sizes_are_bounded() { - assert!(parse_records(r#"{"a":1,"b":{"c":[true]}}"#).is_ok()); - assert!(parse_records("[]").is_err()); - assert!(parse_records(r#"{"":1}"#).is_err()); - assert!(parse_records("{\"a\\u0000b\":1}").is_err()); - let long_key = format!(r#"{{"{}":1}}"#, "k".repeat(MAX_RECORD_KEY_BYTES + 1)); - assert!(parse_records(&long_key).is_err()); - let big_value = format!(r#"{{"k":"{}"}}"#, "v".repeat(MAX_RECORD_VALUE_BYTES)); - assert!(parse_records(&big_value).is_err()); - let many: Records = (0..=MAX_RECORDS) - .map(|i| (i.to_string(), 0.into())) - .collect(); - assert!(parse_records(&serde_json::to_string(&many).unwrap()).is_err()); - } - - #[test] - fn snapshots_carry_the_newest_events_that_fit_their_budget() { - let mut core = WorldCore::new( - "budget", - WorldLimits { - snapshot_bytes: 1024, - input_bytes: 64, - ..WorldLimits::default() - }, - ) - .unwrap(); - let (_, token) = join(&mut core, "ann"); - for _ in 0..20u8 { - core.input(&token, &[b'x'; 48]).unwrap(); - } - let snapshot = core.snapshot(&token).unwrap(); - assert_eq!(snapshot.current_sequence, 20); - assert!(!snapshot.events.is_empty()); - assert!( - serde_json::to_vec(&snapshot.events).unwrap().len() <= 1024, - "events fit the budget" - ); - assert!( - snapshot.events.len() < 20, - "an oversized log is truncated to the newest events" - ); - let first = snapshot.events.first().unwrap().sequence; - assert_eq!(snapshot.oldest_retained_sequence, first); - assert_eq!(snapshot.events.last().unwrap().sequence, 20); - // The snapshot is a valid rebase point: continuing from its cursor - // yields only new events. - assert!( - core.events_after(&token, snapshot.current_sequence) - .unwrap() - .events - .is_empty() - ); - } -} - -#[cfg(test)] -#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] -mod account_tests { - use super::*; - use crate::directory::{Actor, Tier}; - - fn core() -> WorldCore { - WorldCore::new("w", WorldLimits::default()).unwrap() - } - - fn account(core: &mut WorldCore, name: &str) -> (String, String) { - let (credential, _) = core.directory_mut().sign_up(name).unwrap(); - let id = core.directory().account_for(&credential).unwrap(); - (id, credential) - } - - #[tokio::test] - async fn a_friend_delegation_through_the_handle_is_held_to_the_friendship() { - let mut core = core(); - let (ann, ann_credential) = account(&mut core, "Ann"); - let (bo, bo_credential) = account(&mut core, "Bo"); - let (cy, _) = account(&mut core, "Cy"); - core.directory_mut() - .verify_account(Actor::Server, &ann) - .unwrap(); - befriend(&mut core, &ann, &ann_credential, &bo, &bo_credential); - let (_, ann_token) = core - .issue_for_account( - &ann_credential, - WorldScopes::ALL, - CapabilityBounds::default(), - "Ann", - ) - .unwrap(); - let handle = WorldHandle::spawn(core); - - let (_, bo_token) = handle - .delegate_to_friend( - ann_token.clone(), - bo, - WorldScopes::GUEST, - CapabilityBounds::default(), - "Bo", - ) - .await - .unwrap(); - handle.chat(bo_token, "hi").await.unwrap(); - assert!( - handle - .delegate_to_friend( - ann_token, - cy, - WorldScopes::GUEST, - CapabilityBounds::default(), - "Cy" - ) - .await - .is_err(), - "only friends may be delegated to" - ); - } - - #[tokio::test] - async fn a_bounded_issue_stops_after_its_uses() { - let handle = WorldHandle::spawn(core()); - let bounds = CapabilityBounds { - expires_at: None, - uses: Some(1), - }; - let (_, token) = handle - .issue_bounded("Ann", WorldScopes::GUEST, bounds) - .await - .unwrap(); - handle.chat(token.clone(), "once").await.unwrap(); - assert!(handle.chat(token, "twice").await.is_err()); - } - - fn befriend(core: &mut WorldCore, a: &str, a_credential: &str, b: &str, b_credential: &str) { - let world = core.world_id().to_owned(); - core.directory_mut() - .request_friend(a_credential, b, &world, 1) - .unwrap(); - core.directory_mut() - .accept_friend(b_credential, a, &world, 2) - .unwrap(); - } - - #[test] - fn a_ceiling_that_allows_chat_allows_reading_it() { - let mut core = core(); - let (_, ann_credential) = account(&mut core, "Ann"); - let (_, guest) = core - .issue_for_account( - &ann_credential, - WorldScopes::GUEST, - CapabilityBounds::default(), - "Ann", - ) - .unwrap(); - let (_, reader) = core - .issue_for_account( - &ann_credential, - WorldScopes::JOIN.union(WorldScopes::HISTORY), - CapabilityBounds::default(), - "Ann reads", - ) - .unwrap(); - core.chat(&guest, "hello").unwrap(); - assert_eq!(core.snapshot(&reader).unwrap().events.len(), 1); - assert!(core.chat(&reader, "hi").is_err()); - } - - #[test] - fn an_account_capability_is_held_to_its_ceiling() { - let mut core = core(); - let (_, ann_credential) = account(&mut core, "Ann"); - assert!( - core.issue_for_account( - &ann_credential, - WorldScopes::ALL, - CapabilityBounds::default(), - "Ann" - ) - .is_err(), - "a registered account cannot be issued delegate scope" - ); - assert!( - core.issue_for_account( - "acct.forged.00", - WorldScopes::GUEST, - CapabilityBounds::default(), - "Ann" - ) - .is_err() - ); - let (_, token) = core - .issue_for_account( - &ann_credential, - WorldScopes::GUEST, - CapabilityBounds::default(), - "Ann", - ) - .unwrap(); - core.chat(&token, "hello").unwrap(); - core.directory_mut() - .set_tier(Actor::Server, Tier::Registered, WorldScopes::JOIN) - .unwrap(); - assert!( - core.chat(&token, "again").is_err(), - "a narrowed tier narrows the capability" - ); - assert!(core.snapshot(&token).is_ok()); - } - - #[test] - fn an_account_capability_serializes_its_subject_but_no_secret() { - let mut core = core(); - let (ann, ann_credential) = account(&mut core, "Ann"); - let (participant, _) = core - .issue_for_account( - &ann_credential, - WorldScopes::GUEST, - CapabilityBounds::default(), - "Ann", - ) - .unwrap(); - let entry = core.issued_entry(participant.id).unwrap(); - let text = serde_json::to_string(&entry).unwrap(); - assert!(text.contains(&ann)); - let secret = ann_credential.rsplit('.').next().unwrap(); - assert!(!text.contains(secret)); - let back: JournalEntry = serde_json::from_str(&text).unwrap(); - assert_eq!(back, entry); - } - - #[test] - fn a_delegation_to_a_friend_is_held_to_the_friends_ceiling_and_ends_with_the_friendship() { - let mut core = core(); - let (ann, ann_credential) = account(&mut core, "Ann"); - let (bo, bo_credential) = account(&mut core, "Bo"); - let (cy, _) = account(&mut core, "Cy"); - core.directory_mut() - .verify_account(Actor::Server, &ann) - .unwrap(); - befriend(&mut core, &ann, &ann_credential, &bo, &bo_credential); - let (_, ann_token) = core - .issue_for_account( - &ann_credential, - WorldScopes::ALL, - CapabilityBounds::default(), - "Ann", - ) - .unwrap(); - - assert!( - core.delegate_to_friend( - &ann_token, - &bo, - WorldScopes::ALL, - CapabilityBounds::default(), - "Bo" - ) - .is_err(), - "bo's ceiling does not include delegate" - ); - assert!( - core.delegate_to_friend( - &ann_token, - &cy, - WorldScopes::GUEST, - CapabilityBounds::default(), - "Cy" - ) - .is_err(), - "only friends may be delegated to" - ); - let (_, bo_token) = core - .delegate_to_friend( - &ann_token, - &bo, - WorldScopes::GUEST, - CapabilityBounds::default(), - "Bo", - ) - .unwrap(); - core.chat(&bo_token, "hi").unwrap(); - assert!( - core.attenuate( - &bo_token, - WorldScopes::JOIN, - CapabilityBounds::default(), - "Di" - ) - .is_err(), - "bo's delegation carries no delegate scope" - ); - - core.directory_mut() - .remove_friend(&ann_credential, &bo) - .unwrap(); - assert!( - core.snapshot(&bo_token).is_err(), - "the delegation ends with the friendship" - ); - assert!(core.snapshot(&ann_token).is_ok()); - } - - #[test] - fn only_an_account_capability_may_delegate_to_a_friend() { - let mut core = core(); - let (bo, bo_credential) = account(&mut core, "Bo"); - let (ann, ann_credential) = account(&mut core, "Ann"); - befriend(&mut core, &ann, &ann_credential, &bo, &bo_credential); - let (_, anonymous) = core - .issue_capability("Guest", WorldScopes::ALL, CapabilityBounds::default()) - .unwrap(); - assert!( - core.delegate_to_friend( - &anonymous, - &bo, - WorldScopes::GUEST, - CapabilityBounds::default(), - "Bo" - ) - .is_err() - ); - } -} - -#[cfg(test)] -#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] -mod isolation_tests { - use super::*; - use crate::directory::{Actor, Level, Member, Refusal}; - - struct Staff { - core: WorldCore, - member: String, - writer: String, - manager: String, - moderator: String, - admin: String, - stranger: String, - } - - fn account(core: &mut WorldCore, name: &str) -> String { - let (credential, _) = core.directory_mut().sign_up(name).unwrap(); - core.directory().account_for(&credential).unwrap() - } - - fn seat(core: &mut WorldCore, group: u64, name: &str, level: Level) -> String { - let id = account(core, name); - core.directory_mut() - .set_member( - Actor::Server, - group, - Member::Account { id: id.clone() }, - Some(level), - ) - .unwrap(); - id - } - - /// One group with a holder of each level, plus an account outside it. - fn staffed() -> Staff { - let mut core = WorldCore::new("staffed", WorldLimits::default()).unwrap(); - let founder = account(&mut core, "Founder"); - let (group, _) = core - .directory_mut() - .create_group(&founder, "staff", "", WorldScopes::GUEST) - .unwrap(); - Staff { - member: seat(&mut core, group, "Member", Level::Access), - writer: seat(&mut core, group, "Writer", Level::Write), - manager: seat(&mut core, group, "Manager", Level::Manage), - moderator: seat(&mut core, group, "Moderator", Level::Moderator), - admin: seat(&mut core, group, "Admin", Level::Admin), - stranger: account(&mut core, "Stranger"), - core, - } - } - - #[tokio::test] - async fn worlds_start_isolated() { - assert_eq!(Isolation::default(), Isolation::Isolated); - let handle = WorldHandle::spawn(WorldCore::new("w", WorldLimits::default()).unwrap()); - assert_eq!(handle.isolation().await.unwrap(), Isolation::Isolated); - } - - #[tokio::test] - async fn only_a_moderator_or_an_admin_sets_isolation() { - let staff = staffed(); - let handle = WorldHandle::spawn(staff.core); - for who in [ - &staff.member, - &staff.writer, - &staff.manager, - &staff.stranger, - ] { - let error = handle - .set_isolation(Authority::Signed(who.clone()), Isolation::Unisolated) - .await - .unwrap_err(); - assert!( - matches!(error.downcast_ref::(), Some(Refusal::Forbidden(_))), - "{who} must not change isolation" - ); - } - assert_eq!(handle.isolation().await.unwrap(), Isolation::Isolated); - - assert_eq!( - handle - .set_isolation( - Authority::Signed(staff.moderator.clone()), - Isolation::Unisolated - ) - .await - .unwrap(), - Isolation::Unisolated - ); - assert_eq!( - handle - .set_isolation(Authority::Signed(staff.admin.clone()), Isolation::Isolated) - .await - .unwrap(), - Isolation::Isolated - ); - assert_eq!( - handle - .set_isolation(Authority::Admin, Isolation::Unisolated) - .await - .unwrap(), - Isolation::Unisolated - ); - } - - #[test] - fn a_checkpoint_keeps_the_isolation() { - let mut core = WorldCore::new("iso", WorldLimits::default()).unwrap(); - core.isolation = Isolation::Unisolated; - core.active_module_hash = Some("h".to_owned()); - let entries = core.checkpoint_entries("snapshot".to_owned()).unwrap(); - assert!(entries.iter().any(|entry| matches!( - entry, - JournalEntry::Isolation { - isolation: Isolation::Unisolated - } - ))); - } - - fn forbidden(error: &anyhow::Error) -> bool { - matches!(error.downcast_ref::(), Some(Refusal::Forbidden(_))) - } - - #[tokio::test] - async fn only_a_moderator_or_an_admin_sets_cross_world_write() { - let staff = staffed(); - let handle = WorldHandle::spawn(staff.core); - for who in [ - &staff.member, - &staff.writer, - &staff.manager, - &staff.stranger, - ] { - let error = handle - .set_cross_world_write(Authority::Signed(who.clone()), true) - .await - .unwrap_err(); - assert!( - forbidden(&error), - "{who} must not change cross-world writes" - ); - } - assert!(!handle.policy().await.unwrap().cross_world_write); - - let policy = handle - .set_cross_world_write(Authority::Signed(staff.moderator.clone()), true) - .await - .unwrap(); - assert!(policy.cross_world_write && !policy.cross_world_forced); - let policy = handle - .set_cross_world_write(Authority::Signed(staff.moderator.clone()), false) - .await - .unwrap(); - assert!(!policy.cross_world_write); - } - - #[tokio::test] - async fn only_the_admin_forces_cross_world_writes() { - let staff = staffed(); - let handle = WorldHandle::spawn(staff.core); - handle - .set_isolation(Authority::Admin, Isolation::Unisolated) - .await - .unwrap(); - for who in [&staff.moderator, &staff.admin] { - let error = handle - .force_cross_world_write(Authority::Signed(who.clone())) - .await - .unwrap_err(); - assert!(forbidden(&error), "{who} must not force cross-world writes"); - } - assert!(!handle.policy().await.unwrap().cross_world_forced); - } - - #[tokio::test] - async fn an_isolated_world_cannot_be_forced() { - let handle = WorldHandle::spawn(WorldCore::new("w", WorldLimits::default()).unwrap()); - let error = handle - .force_cross_world_write(Authority::Admin) - .await - .unwrap_err(); - assert!(forbidden(&error)); - assert!(error.to_string().contains("isolated"), "{error}"); - assert!(!handle.policy().await.unwrap().cross_world_forced); - } - - #[tokio::test] - async fn a_forced_write_stays_on_against_a_moderator() { - let staff = staffed(); - let handle = WorldHandle::spawn(staff.core); - handle - .set_isolation(Authority::Admin, Isolation::Unisolated) - .await - .unwrap(); - handle - .force_cross_world_write(Authority::Admin) - .await - .unwrap(); - - let error = handle - .set_cross_world_write(Authority::Signed(staff.moderator.clone()), false) - .await - .unwrap_err(); - assert!(forbidden(&error)); - let policy = handle.policy().await.unwrap(); - assert!(policy.cross_world_write && policy.cross_world_forced); - - let policy = handle - .set_cross_world_write(Authority::Admin, false) - .await - .unwrap(); - assert!(!policy.cross_world_write && !policy.cross_world_forced); - } - - #[tokio::test] - async fn a_moderator_turns_off_a_write_that_was_not_forced() { - let staff = staffed(); - let handle = WorldHandle::spawn(staff.core); - handle - .set_cross_world_write(Authority::Signed(staff.moderator.clone()), true) - .await - .unwrap(); - let policy = handle - .set_cross_world_write(Authority::Signed(staff.moderator.clone()), false) - .await - .unwrap(); - assert!(!policy.cross_world_write); - } - - #[tokio::test] - async fn file_scope_is_moderated_and_the_override_is_admin_only() { - let staff = staffed(); - let handle = WorldHandle::spawn(staff.core); - assert_eq!( - handle.policy().await.unwrap(), - WorldPolicy { - isolation: Isolation::Isolated, - cross_world_write: false, - cross_world_forced: false, - file_scope: FileScope::Confined, - file_write_override: false, - } - ); - for who in [ - &staff.member, - &staff.writer, - &staff.manager, - &staff.stranger, - ] { - let error = handle - .set_file_scope( - Authority::Signed(who.clone()), - FileScope::Unrestricted, - None, - ) - .await - .unwrap_err(); - assert!(forbidden(&error), "{who} must not change the file scope"); - } - - let error = handle - .set_file_scope( - Authority::Signed(staff.moderator.clone()), - FileScope::Unrestricted, - Some(true), - ) - .await - .unwrap_err(); - assert!(forbidden(&error)); - assert_eq!( - handle.policy().await.unwrap().file_scope, - FileScope::Confined - ); - - let policy = handle - .set_file_scope( - Authority::Signed(staff.moderator.clone()), - FileScope::Unrestricted, - None, - ) - .await - .unwrap(); - assert_eq!(policy.file_scope, FileScope::Unrestricted); - assert!(!policy.file_write_override); - - let policy = handle - .set_file_scope(Authority::Admin, FileScope::Unrestricted, Some(true)) - .await - .unwrap(); - assert!(policy.file_write_override); - } - - #[test] - fn file_access_follows_isolation_scope_and_override() { - use FileMode::{Read, Write}; - use FileScope::{Confined, Unrestricted}; - use Isolation::{Isolated, Unisolated}; - let policy = |isolation, file_scope, file_write_override| WorldPolicy { - isolation, - cross_world_write: false, - cross_world_forced: false, - file_scope, - file_write_override, - }; - // (policy, mode, inside own root, allowed) - let cases = [ - (policy(Unisolated, Confined, false), Read, true, true), - (policy(Unisolated, Confined, false), Read, false, false), - (policy(Unisolated, Confined, false), Write, true, true), - (policy(Unisolated, Confined, false), Write, false, false), - (policy(Unisolated, Unrestricted, false), Read, false, true), - (policy(Unisolated, Unrestricted, false), Write, false, true), - (policy(Isolated, Confined, false), Read, true, true), - (policy(Isolated, Confined, false), Read, false, false), - (policy(Isolated, Confined, false), Write, true, false), - (policy(Isolated, Unrestricted, false), Read, false, true), - (policy(Isolated, Unrestricted, false), Write, false, false), - (policy(Isolated, Unrestricted, true), Write, false, true), - (policy(Isolated, Confined, true), Write, true, true), - (policy(Isolated, Confined, true), Write, false, false), - ]; - for (policy, mode, inside_root, expected) in cases { - assert_eq!( - policy.file_allowed(mode, inside_root), - expected, - "{policy:?} {mode:?} inside root {inside_root}" - ); - } - } - - #[test] - fn a_default_world_reads_only_inside_its_root() { - let policy = WorldCore::new("w", WorldLimits::default()) - .unwrap() - .policy(); - assert_eq!(policy.file_scope, FileScope::Confined); - assert!(!policy.file_write_override); - assert!(policy.file_allowed(FileMode::Read, true)); - assert!(!policy.file_allowed(FileMode::Read, false)); - assert!(!policy.file_allowed(FileMode::Write, true)); - } - - #[test] - fn a_checkpoint_keeps_the_sharing_settings() { - for (cross_world_write, cross_world_forced) in [(true, false), (true, true), (false, false)] - { - let mut core = WorldCore::new("share", WorldLimits::default()).unwrap(); - core.isolation = Isolation::Unisolated; - core.cross_world_write = cross_world_write; - core.cross_world_forced = cross_world_forced; - core.file_scope = FileScope::Unrestricted; - core.file_write_override = true; - core.active_module_hash = Some("h".to_owned()); - let entries = core.checkpoint_entries("snapshot".to_owned()).unwrap(); - let restored = WorldCore::restore("share", WorldLimits::default(), entries).unwrap(); - assert_eq!(restored.core.policy(), core.policy()); - } - } -} - -#[cfg(test)] -#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] -mod schedule_tests { - use super::*; - - fn world(retained_events: usize) -> WorldCore { - WorldCore::new( - "test-world", - WorldLimits { - retained_events, - ..WorldLimits::default() - }, - ) - .unwrap() - } - - /// A program for the schedule tests. Each input is a request document, and - /// the program asks for its requests until each one's result arrives. Its - /// records carry every schedule fire and every result, so a test reads them - /// through `WorldHandle::records`. - #[derive(Default)] - struct Scheduler { - requests: Vec, - answered: BTreeSet, - results: BTreeMap, - fires: Vec, - refuse_fires: bool, - } - - impl WorldProgram for Scheduler { - fn update(&mut self, event: &WorldEvent) -> Result<()> { - match &event.kind { - WorldEventKind::Input(bytes) => { - let document: serde_json::Value = serde_json::from_slice(bytes)?; - self.requests = document["requests"].as_array().cloned().unwrap_or_default(); - } - WorldEventKind::System { event: text } => { - let Ok(value) = serde_json::from_str::(text) else { - return Ok(()); - }; - match value["cap"].as_str() { - Some("result") => { - if let Some(id) = value["id"].as_str() { - self.answered.insert(id.to_owned()); - self.results.insert(id.to_owned(), value.clone()); - } - } - Some("schedule") => { - if self.refuse_fires { - bail!("this program refuses schedule fires"); - } - self.fires.push(value.clone()); - } - _ => {} - } - } - WorldEventKind::Chat(_) | WorldEventKind::ProgramInstalled { .. } => {} - } - Ok(()) - } - - fn wants(&mut self) -> Result> { - let pending: Vec<&serde_json::Value> = self - .requests - .iter() - .filter(|request| { - !request["id"] - .as_str() - .is_some_and(|id| self.answered.contains(id)) - }) - .collect(); - Ok(Some( - serde_json::json!({"v": 1, "requests": pending}).to_string(), - )) - } - - fn records(&mut self) -> Result> { - Ok(Some( - serde_json::json!({"fired": self.fires, "results": self.results}).to_string(), - )) - } - } - - /// A journal kept in memory, so a test can restore from what was written. - #[derive(Clone, Default)] - struct Recorded(Arc>>); - - impl Recorded { - /// A journal that starts with the header a real world writes first. - fn for_world(world_id: &str) -> Self { - let journal = Self::default(); - journal.0.lock().unwrap().push(JournalEntry::Created { - world_id: world_id.to_owned(), - version: JOURNAL_VERSION, - }); - journal - } - - fn entries(&self) -> Vec { - self.0.lock().unwrap().clone() - } - } - - impl WorldJournal for Recorded { - fn append(&mut self, entry: &JournalEntry) -> Result<()> { - self.0.lock().unwrap().push(entry.clone()); - Ok(()) - } - } - - /// A journaled world running a `Scheduler`, with one participant and the - /// given grants. - async fn scheduling_world( - id: &str, - grants: &[&str], - refuse_fires: bool, - ) -> (WorldHandle, JoinCapability, Recorded) { - let journal = Recorded::for_world(id); - let core = WorldCore::new(id, WorldLimits::default()).unwrap(); - let program = Scheduler { - refuse_fires, - ..Scheduler::default() - }; - let world = - WorldHandle::spawn_durable(core, Box::new(program), Some(Box::new(journal.clone()))); - let (_, token) = world.issue("ann", WorldScopes::GUEST).await.unwrap(); - if !grants.is_empty() { - world - .update_caps( - grants.iter().map(|grant| (*grant).to_owned()).collect(), - Vec::new(), - ) - .await - .unwrap(); - } - (world, token, journal) - } - - /// Send one request document to the program as a participant's input. - async fn ask(world: &WorldHandle, token: &JoinCapability, document: serde_json::Value) { - world - .input(token.clone(), document.to_string().into_bytes()) - .await - .unwrap(); - } - - /// The schedule fire events the program has received so far. - fn schedule_fires(world: &WorldHandle) -> Vec { - world - .records() - .1 - .get("fired") - .and_then(serde_json::Value::as_array) - .cloned() - .unwrap_or_default() - } - - /// The result event the program received for request `id`, if any. - fn schedule_result(world: &WorldHandle, id: &str) -> Option { - world - .records() - .1 - .get("results") - .and_then(|results| results.get(id)) - .cloned() - } - - /// Poll until `ready` holds, failing after three seconds. - async fn eventually(what: &str, mut ready: impl FnMut() -> bool) { - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3); - while !ready() { - assert!( - std::time::Instant::now() < deadline, - "timed out waiting for {what}" - ); - tokio::time::sleep(std::time::Duration::from_millis(10)).await; - } - } - - #[test] - fn schedule_bounds_refuse_each_violation_with_a_reason() { - let now = 1_000_000_000_000u64; - let horizon = crate::world_caps::MAX_SCHEDULE_HORIZON_MS; - let mut core = world(8); - assert!(core.check_schedule("ok", now, now).is_ok()); - assert!(core.check_schedule(&"x".repeat(64), now, now).is_ok()); - let long = "x".repeat(65); - for bad in ["", "tab\there", long.as_str()] { - let error = core.check_schedule(bad, now, now).unwrap_err(); - assert!(error.to_string().contains("schedule id"), "{error}"); - } - - core.schedules.insert("taken".to_owned(), now + 5); - let error = core.check_schedule("taken", now + 9, now).unwrap_err(); - assert!(error.to_string().contains("already pending"), "{error}"); - assert_eq!( - core.schedules["taken"], - now + 5, - "a duplicate overwrites nothing" - ); - - assert!(core.check_schedule("edge", now + horizon, now).is_ok()); - let error = core - .check_schedule("far", now + horizon + 1, now) - .unwrap_err(); - assert!(error.to_string().contains("days past"), "{error}"); - assert!(core.check_schedule("past", 0, now).is_ok()); - - let mut full = world(8); - for index in 0..crate::world_caps::MAX_PENDING_SCHEDULES - 1 { - full.schedules.insert(format!("s{index}"), now); - } - assert!(full.check_schedule("last", now, now).is_ok()); - full.schedules.insert("last".to_owned(), now); - 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 (world, token, journal) = scheduling_world("sched-refused", &[], false).await; - ask( - &world, - &token, - serde_json::json!({"requests": [ - {"id": "s1", "cap": "schedule.at", "args": {"id": "nap", "at": unix_ms() + 60_000}}, - ]}), - ) - .await; - eventually("the refusal", || schedule_result(&world, "s1").is_some()).await; - assert_eq!( - schedule_result(&world, "s1").unwrap()["error"], - "cap_denied" - ); - let report = world.caps_report().await.unwrap(); - assert!(report.usage["schedule.at"].denied > 0, "{report:?}"); - world.shutdown().await.unwrap(); - assert!( - journal - .entries() - .iter() - .all(|entry| !matches!(entry, JournalEntry::ScheduleSet { .. })), - "a refused request pends nothing" - ); - } - - #[tokio::test] - async fn a_due_schedule_fires_once_and_the_program_receives_it() { - let (world, token, journal) = scheduling_world("sched-fire", &["schedule.at"], false).await; - ask( - &world, - &token, - serde_json::json!({"requests": [ - {"id": "s1", "cap": "schedule.at", "args": {"id": "now", "at": unix_ms()}}, - ]}), - ) - .await; - eventually("the fire", || !schedule_fires(&world).is_empty()).await; - tokio::time::sleep(std::time::Duration::from_millis(100)).await; - let fires = schedule_fires(&world); - assert_eq!(fires.len(), 1, "{fires:?}"); - assert_eq!(fires[0]["id"], "now"); - assert!( - fires[0].get("late").is_none(), - "a fire in this run is not late" - ); - world.shutdown().await.unwrap(); - - let entries = journal.entries(); - let fire = WorldEventKind::System { - event: schedule_fired_event("now", false), - }; - let delivered = entries - .iter() - .position(|entry| matches!(entry, JournalEntry::System { event } if event.kind == fire)) - .expect("the fire is journaled as delivered"); - let consumed = entries - .iter() - .position(|entry| matches!(entry, JournalEntry::ScheduleFired { id } if id == "now")) - .expect("the schedule is consumed"); - assert!(delivered < consumed, "the delivery is journaled first"); - assert_eq!( - entries - .iter() - .filter(|entry| matches!(entry, JournalEntry::ScheduleFired { .. })) - .count(), - 1 - ); - } - - #[tokio::test] - async fn a_cancelled_schedule_never_fires_and_an_unknown_id_says_false() { - let (world, token, _journal) = - scheduling_world("sched-cancel", &["schedule.at", "schedule.cancel"], false).await; - let at = unix_ms(); - // One pass: the cancel runs before any timer can fire the schedule. - ask( - &world, - &token, - serde_json::json!({"requests": [ - {"id": "s1", "cap": "schedule.at", "args": {"id": "soon", "at": at}}, - {"id": "c1", "cap": "schedule.cancel", "args": {"id": "soon"}}, - {"id": "c2", "cap": "schedule.cancel", "args": {"id": "ghost"}}, - ]}), - ) - .await; - eventually("the cancel results", || { - schedule_result(&world, "c2").is_some() - }) - .await; - assert_eq!( - schedule_result(&world, "s1").unwrap()["value"]["fires_at"], - at - ); - assert_eq!( - schedule_result(&world, "c1").unwrap()["value"]["cancelled"], - true - ); - assert_eq!( - schedule_result(&world, "c2").unwrap()["value"]["cancelled"], - false - ); - tokio::time::sleep(std::time::Duration::from_millis(100)).await; - assert!( - schedule_fires(&world).is_empty(), - "a cancelled schedule must not fire" - ); - world.shutdown().await.unwrap(); - } - - #[tokio::test] - async fn refused_schedule_requests_pend_nothing() { - let (world, token, journal) = - scheduling_world("sched-bad", &["schedule.at", "schedule.cancel"], false).await; - let later = unix_ms() + 3_600_000; - let far = unix_ms() + crate::world_caps::MAX_SCHEDULE_HORIZON_MS + 60_000; - let long_id = "x".repeat(65); - ask( - &world, - &token, - serde_json::json!({"requests": [ - {"id": "ok", "cap": "schedule.at", "args": {"id": "kept", "at": later}}, - {"id": "empty", "cap": "schedule.at", "args": {"id": "", "at": later}}, - {"id": "long", "cap": "schedule.at", "args": {"id": long_id, "at": later}}, - {"id": "far", "cap": "schedule.at", "args": {"id": "far", "at": far}}, - {"id": "dup", "cap": "schedule.at", "args": {"id": "kept", "at": later}}, - {"id": "missing", "cap": "schedule.at", "args": {"id": "nothing"}}, - {"id": "text", "cap": "schedule.at", "args": {"id": "t", "at": "soon"}}, - {"id": "bad-cancel", "cap": "schedule.cancel", "args": {"id": "a\nb"}}, - ]}), - ) - .await; - eventually("the last result", || { - schedule_result(&world, "bad-cancel").is_some() - }) - .await; - assert_eq!(schedule_result(&world, "ok").unwrap()["ok"], true); - for id in [ - "empty", - "long", - "far", - "dup", - "missing", - "text", - "bad-cancel", - ] { - assert_eq!( - schedule_result(&world, id).unwrap()["error"], - "bad_args", - "{id}" - ); - } - world.shutdown().await.unwrap(); - let pended: Vec = journal - .entries() - .into_iter() - .filter_map(|entry| match entry { - JournalEntry::ScheduleSet { id, .. } => Some(id), - _ => None, - }) - .collect(); - assert_eq!(pended, ["kept"], "only the accepted request is journaled"); - } - - #[tokio::test] - async fn a_fire_the_program_refuses_stays_pending_in_the_journal() { - let (world, token, journal) = - scheduling_world("sched-refuse", &["schedule.at"], true).await; - ask( - &world, - &token, - serde_json::json!({"requests": [ - {"id": "s1", "cap": "schedule.at", "args": {"id": "stuck", "at": unix_ms()}}, - ]}), - ) - .await; - eventually("the request result", || { - schedule_result(&world, "s1").is_some() - }) - .await; - tokio::time::sleep(std::time::Duration::from_millis(100)).await; - // The program is unavailable now, but the actor still answers. - assert!(world.caps_report().await.is_ok()); - world.shutdown().await.unwrap(); - - let entries = journal.entries(); - assert!( - !entries - .iter() - .any(|entry| matches!(entry, JournalEntry::ScheduleFired { .. })), - "a refused fire is not consumed" - ); - let journaled_fire = entries.iter().any(|entry| match entry { - JournalEntry::System { event } => matches!( - &event.kind, - WorldEventKind::System { event } if event.contains("\"schedule\"") - ), - _ => false, - }); - assert!(!journaled_fire, "a refused fire is not journaled"); - let restored = WorldCore::restore("sched-refuse", WorldLimits::default(), entries).unwrap(); - assert!( - restored.core.schedules.contains_key("stuck"), - "the next run delivers it" - ); - } - - #[tokio::test] - async fn a_schedule_overdue_at_restart_fires_late_on_the_first_wakeup() { - let entries = vec![ - JournalEntry::Created { - world_id: "sched-late".to_owned(), - version: JOURNAL_VERSION, - }, - JournalEntry::ScheduleSet { - id: "overdue".to_owned(), - at_ms: unix_ms() - 5_000, - }, - ]; - let restored = WorldCore::restore("sched-late", WorldLimits::default(), entries).unwrap(); - let journal = Recorded::default(); - let world = WorldHandle::spawn_durable( - restored.core, - Box::new(Scheduler::default()), - Some(Box::new(journal.clone())), - ); - eventually("the late fire", || !schedule_fires(&world).is_empty()).await; - let fires = schedule_fires(&world); - assert_eq!(fires.len(), 1, "{fires:?}"); - assert_eq!(fires[0]["id"], "overdue"); - assert_eq!(fires[0]["late"], true); - world.shutdown().await.unwrap(); - assert!( - journal.entries().iter().any( - |entry| matches!(entry, JournalEntry::ScheduleFired { id } if id == "overdue") - ) - ); - } - - #[tokio::test] - async fn a_pending_schedule_survives_a_restart_and_fires_on_time() { - let at_ms = unix_ms() + 700; - let entries = vec![ - JournalEntry::Created { - world_id: "sched-later".to_owned(), - version: JOURNAL_VERSION, - }, - JournalEntry::ScheduleSet { - id: "later".to_owned(), - at_ms, - }, - ]; - let restored = WorldCore::restore("sched-later", WorldLimits::default(), entries).unwrap(); - assert_eq!(restored.core.schedules.get("later"), Some(&at_ms)); - let world = WorldHandle::spawn_durable(restored.core, Box::new(Scheduler::default()), None); - assert!(schedule_fires(&world).is_empty(), "not due yet"); - eventually("the scheduled fire", || !schedule_fires(&world).is_empty()).await; - let fires = schedule_fires(&world); - assert_eq!(fires[0]["id"], "later"); - assert!(fires[0].get("late").is_none(), "it was not overdue at open"); - world.shutdown().await.unwrap(); - } - - #[tokio::test] - async fn replay_reproduces_the_pending_and_fired_sets() { - let (world, token, journal) = - scheduling_world("sched-replay", &["schedule.at", "schedule.cancel"], false).await; - ask( - &world, - &token, - serde_json::json!({"requests": [ - {"id": "s1", "cap": "schedule.at", "args": {"id": "keep", "at": unix_ms() + 3_600_000}}, - {"id": "s2", "cap": "schedule.at", "args": {"id": "now", "at": unix_ms()}}, - {"id": "s3", "cap": "schedule.at", "args": {"id": "gone", "at": unix_ms() + 3_600_000}}, - {"id": "c3", "cap": "schedule.cancel", "args": {"id": "gone"}}, - ]}), - ) - .await; - eventually("the fire and the cancel", || { - !schedule_fires(&world).is_empty() && schedule_result(&world, "c3").is_some() - }) - .await; - let live_fired: Vec = schedule_fires(&world) - .iter() - .filter_map(|fire| fire["id"].as_str().map(str::to_owned)) - .collect(); - world.shutdown().await.unwrap(); - - let restored = - WorldCore::restore("sched-replay", WorldLimits::default(), journal.entries()).unwrap(); - let pending: Vec = restored.core.schedules.keys().cloned().collect(); - assert_eq!(pending, ["keep"]); - let replayed_fired: Vec = restored - .replay - .iter() - .filter_map(|event| match &event.kind { - WorldEventKind::System { event } => { - serde_json::from_str::(event) - .ok() - .filter(|value| value["cap"] == "schedule") - .and_then(|value| value["id"].as_str().map(str::to_owned)) - } - _ => None, - }) - .collect(); - assert_eq!(live_fired, ["now"]); - assert_eq!(replayed_fired, live_fired); - } - - #[test] - fn a_checkpoint_keeps_pending_schedules_and_writes_their_entries() { - let now = unix_ms(); - let mut core = world(8); - core.active_module_hash = Some("h".to_owned()); - core.schedules.insert("a".to_owned(), now + 100); - core.schedules.insert("b".to_owned(), now + 200); - let entries = core.checkpoint_entries("state".to_owned()).unwrap(); - for (id, at_ms) in [("a", now + 100), ("b", now + 200)] { - let set = JournalEntry::ScheduleSet { - id: id.to_owned(), - at_ms, - }; - assert!( - entries.contains(&set), - "a compacted journal keeps the schedule {id}" - ); - } - let restored = WorldCore::restore("test-world", WorldLimits::default(), entries).unwrap(); - assert_eq!(restored.core.schedules, core.schedules); - } - - #[test] - fn a_checkpoint_that_disagrees_with_its_schedule_entries_is_refused() { - let header = || JournalEntry::Created { - world_id: "w".to_owned(), - version: JOURNAL_VERSION, - }; - let set = || JournalEntry::ScheduleSet { - id: "a".to_owned(), - at_ms: 5, - }; - let checkpoint = |schedules: Option>| JournalEntry::Checkpoint { - sequence: 0, - module_hash: "h".to_owned(), - seed: 1, - provenance: None, - execution_profile: None, - caps_ceiling: None, - schedules, - snapshot: "s".to_owned(), - events: Vec::new(), - }; - let agreed = [header(), set(), checkpoint(Some(vec![("a".to_owned(), 5)]))]; - assert!(WorldCore::restore("w", WorldLimits::default(), agreed).is_ok()); - let omitted = [header(), set(), checkpoint(None)]; - assert!(WorldCore::restore("w", WorldLimits::default(), omitted).is_err()); - let unwritten = [header(), checkpoint(Some(vec![("a".to_owned(), 5)]))]; - assert!(WorldCore::restore("w", WorldLimits::default(), unwritten).is_err()); - let duplicated = [ - header(), - set(), - checkpoint(Some(vec![("a".to_owned(), 5), ("a".to_owned(), 5)])), - ]; - assert!(WorldCore::restore("w", WorldLimits::default(), duplicated).is_err()); - } - - #[test] - fn a_schedule_entry_must_refer_to_a_pending_schedule() { - let header = || JournalEntry::Created { - world_id: "w".to_owned(), - version: JOURNAL_VERSION, - }; - let fired = [header(), JournalEntry::ScheduleFired { id: "x".to_owned() }]; - assert!(WorldCore::restore("w", WorldLimits::default(), fired).is_err()); - let cancelled = [ - header(), - JournalEntry::ScheduleCancelled { id: "x".to_owned() }, - ]; - assert!(WorldCore::restore("w", WorldLimits::default(), cancelled).is_err()); - let twice = [ - header(), - JournalEntry::ScheduleSet { - id: "x".to_owned(), - at_ms: 1, - }, - JournalEntry::ScheduleSet { - id: "x".to_owned(), - at_ms: 2, - }, - ]; - assert!(WorldCore::restore("w", WorldLimits::default(), twice).is_err()); - let malformed = [ - header(), - JournalEntry::ScheduleSet { - id: "a\nb".to_owned(), - at_ms: 1, - }, - ]; - assert!(WorldCore::restore("w", WorldLimits::default(), malformed).is_err()); - } - - #[test] - fn schedules_wake_the_loop_only_while_the_program_can_take_them() { - let mut schedules = BTreeMap::new(); - schedules.insert("a".to_owned(), 2_000u64); - assert!(next_schedule_wake(&schedules, 1_000, true).is_some()); - assert!( - next_schedule_wake(&schedules, 3_000, true).is_some(), - "an overdue schedule wakes the loop now" - ); - assert!( - next_schedule_wake(&schedules, 3_000, false).is_none(), - "a program that refuses fires never wakes the loop for one" - ); - assert!(next_schedule_wake(&BTreeMap::new(), 1_000, true).is_none()); - } - - #[test] - fn schedule_entries_keep_their_journal_tags() { - let set = serde_json::to_value(JournalEntry::ScheduleSet { - id: "a".to_owned(), - at_ms: 7, - }) - .unwrap(); - assert_eq!( - set, - serde_json::json!({"entry": "schedule_set", "id": "a", "at_ms": 7}) - ); - let cancelled = - serde_json::to_value(JournalEntry::ScheduleCancelled { id: "a".to_owned() }).unwrap(); - assert_eq!(cancelled["entry"], "schedule_cancelled"); - let fired = - serde_json::to_value(JournalEntry::ScheduleFired { id: "a".to_owned() }).unwrap(); - assert_eq!(fired["entry"], "schedule_fired"); - } -} diff --git a/pkgs/id/src/world/actor.rs b/pkgs/id/src/world/actor.rs new file mode 100644 index 0000000000..350a610ac7 --- /dev/null +++ b/pkgs/id/src/world/actor.rs @@ -0,0 +1,1369 @@ +use super::*; + +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::sync::Arc; + +use anyhow::{Result, ensure}; +use tokio::sync::{broadcast, mpsc, oneshot, watch}; + +use crate::world_caps::{CapError, CapsReport, Decision, Request, Subscription}; + +pub(crate) enum WorldCommand { + Issue { + name: String, + scopes: WorldScopes, + bounds: CapabilityBounds, + reply: oneshot::Sender>, + }, + Attenuate { + token: JoinCapability, + name: String, + scopes: WorldScopes, + bounds: CapabilityBounds, + reply: oneshot::Sender>, + }, + DelegateToFriend { + token: JoinCapability, + friend: String, + name: String, + scopes: WorldScopes, + bounds: CapabilityBounds, + reply: oneshot::Sender>, + }, + Directory { + caller: crate::directory_auth::Caller, + action: crate::directory_view::DirectoryAction, + /// Whether this server has an outbox to queue what the action sends. + outbox: bool, + reply: oneshot::Sender>, + }, + ApplyDirectory { + entry: crate::directory::DirectoryEntry, + reply: oneshot::Sender>, + }, + Revoke { + participant_id: u64, + reply: oneshot::Sender, + }, + ParticipantId { + token: JoinCapability, + reply: oneshot::Sender>, + }, + Chat { + token: JoinCapability, + text: String, + reply: oneshot::Sender>, + }, + Input { + token: JoinCapability, + input: Vec, + reply: oneshot::Sender>, + }, + Snapshot { + token: JoinCapability, + reply: oneshot::Sender>, + }, + EventsAfter { + token: JoinCapability, + sequence: u64, + reply: oneshot::Sender>, + }, + ProjectEvent { + token: JoinCapability, + event: WorldEvent, + reply: oneshot::Sender>>, + }, + View { + token: JoinCapability, + reply: oneshot::Sender>>, + }, + ViewAt { + token: JoinCapability, + width: u16, + height: u16, + reply: oneshot::Sender>>, + }, + InstallProgram { + module_hash: String, + seed: u64, + provenance: Option, + program: Box, + reply: oneshot::Sender>, + }, + /// A session opened or closed for this participant. + Presence { + participant: u64, + joined: bool, + }, + /// Admin: change the granted capability set. + UpdateCaps { + grant: Vec, + revoke: Vec, + reply: oneshot::Sender>, + }, + /// Admin: replace the world's capability ceiling. It applies immediately. + SetCapsCeiling { + ceiling: Vec, + reply: oneshot::Sender>, + }, + /// Admin: durably replace this world's requested runtime profile. + SetExecutionProfile { + profile: crate::world_limits::WorldExecutionProfile, + reply: oneshot::Sender>, + }, + /// Read this world's requested runtime profile. + ExecutionProfileInfo { + reply: oneshot::Sender, + }, + /// Admin: read the capability report. + CapsInfo { + reply: oneshot::Sender>, + }, + /// Admin or moderator: change the world's isolation. + SetIsolation { + authority: Authority, + isolation: Isolation, + reply: oneshot::Sender>, + }, + IsolationInfo { + reply: oneshot::Sender, + }, + /// Moderator or admin: let other unisolated worlds write here. + SetCrossWorldWrite { + authority: Authority, + enabled: bool, + reply: oneshot::Sender>, + }, + /// Admin: force cross-world writes on. + ForceCrossWorldWrite { + authority: Authority, + reply: oneshot::Sender>, + }, + /// Moderator or admin: set the file scope; the admin alone sets the override. + SetFileScope { + authority: Authority, + scope: FileScope, + write_override: Option, + reply: oneshot::Sender>, + }, + PolicyInfo { + reply: oneshot::Sender, + }, + Shutdown { + reply: oneshot::Sender<()>, + }, +} + +/// Trim `journal` behind a verified snapshot of `program`. `Ok(false)` means +/// the program cannot snapshot. +pub(crate) fn compact_journal( + core: &mut WorldCore, + program: &mut dyn WorldProgram, + journal: &mut dyn WorldJournal, +) -> Result { + let Some(snapshot) = program.snapshot()? else { + return Ok(false); + }; + let entries = core.checkpoint_entries(snapshot)?; + journal.compact(&entries)?; + core.since_checkpoint = 0; + tracing::info!( + "world {}: journal trimmed at sequence {}", + core.world_id, + core.sequence + ); + Ok(true) +} + +/// The world's single authority: owns the core, the program instance and the +/// journal, and runs commands plus the program's capability needs serially. +pub(crate) struct WorldActor { + pub(crate) core: WorldCore, + /// Sessions and pending email codes. In memory only: a restart ends them. + pub(crate) auth: crate::directory_auth::DirectoryAuth, + pub(crate) program: Box, + pub(crate) journal: Option>, + pub(crate) storage_failed: bool, + pub(crate) program_healthy: bool, + /// Times a `view` or `layout` call trapped. Counted for `id world stats` + /// (F11.17): a trapping view degrades to an error screen, not a poisoned + /// world, so this counter is the only place the failure is recorded. + pub(crate) view_failures: u64, + pub(crate) compaction_off: bool, + pub(crate) event_sender: broadcast::Sender, + pub(crate) revocation_sender: broadcast::Sender, + pub(crate) records_sender: watch::Sender<(u64, Arc)>, + pub(crate) view_changed: watch::Sender, + /// Live sessions per participant: presence is refcounted. + pub(crate) presence: HashMap, + /// Subscriptions the program asked for (granted or refused-and-remembered). + pub(crate) active_subs: BTreeSet, + /// Request ids already executed, so `wants` states intent, not polling. + pub(crate) handled_requests: BTreeSet, + /// Subscription specs already reported as refused. + pub(crate) denied_subs: BTreeSet, + /// Armed tick intervals to their next fire time. + pub(crate) ticks: BTreeMap, + /// Restored schedules already overdue when the world opened. Their first + /// fire is marked `late`; a cancel or fire removes the id. + pub(crate) overdue_at_open: BTreeSet, + /// The participant whose input is being processed. Requests the program + /// makes in response are checked against that participant's scopes. + pub(crate) acting: Option, +} + +impl WorldActor { + pub(crate) async fn run(mut self, mut receiver: mpsc::Receiver) { + self.after_change().await; + loop { + // Ticks and schedules sleep until their earliest deadline; with + // neither armed this branch never wakes. + let deadline = self.next_deadline(); + let command = tokio::select! { + command = receiver.recv() => match command { + Some(command) => command, + None => break, + }, + () = Self::sleep_until(deadline) => { + self.fire_ticks().await; + self.fire_schedules().await; + self.after_change().await; + continue; + } + }; + if matches!(command, WorldCommand::Shutdown { .. }) { + if let WorldCommand::Shutdown { reply } = command { + let _ = reply.send(()); + } + break; + } + self.handle(command).await; + self.after_change().await; + self.acting = None; + } + } + + async fn sleep_until(deadline: Option) { + match deadline { + Some(deadline) => { + tokio::time::sleep_until(tokio::time::Instant::from_std(deadline)).await; + } + None => std::future::pending().await, + } + } + + /// The earliest moment the loop must wake: the soonest armed tick or + /// pending schedule. Schedules wait only while the program can take them. + pub(crate) fn next_deadline(&self) -> Option { + let deliverable = self.program_healthy && !self.storage_failed; + let clock = self.core.clock(); + self.ticks + .values() + .min() + .copied() + .into_iter() + .chain(next_schedule_wake( + &self.core.schedules, + clock.now_ms(), + clock.now_instant(), + deliverable, + )) + .min() + } + + fn check_storage(&self) -> Result<()> { + ensure!( + !self.storage_failed, + "world storage failed; the world is read-only" + ); + Ok(()) + } + + fn record_issued( + &mut self, + issued: (Participant, JoinCapability), + ) -> Result<(Participant, JoinCapability)> { + let entry = self + .core + .issued_entry(issued.0.id) + .context("issued capability vanished")?; + self.persist(entry)?; + Ok(issued) + } + + /// Durably record `entry`, or turn the world read-only. + fn persist(&mut self, entry: JournalEntry) -> Result<()> { + ensure!( + !self.storage_failed, + "world storage failed; the world is read-only" + ); + if let Some(journal) = self.journal.as_mut() + && let Err(error) = journal.append(&entry) + { + self.storage_failed = true; + tracing::error!("world journal append failed: {error:#}"); + return Err(error.context("world storage failed; the world is read-only")); + } + Ok(()) + } + + /// Publish freshly recomputed records. Participant events push their own + /// view frame right after the event; host events signal the views watch. + fn republished(&mut self, records: Records, sequence: u64) { + publish_records(&self.records_sender, sequence, records); + } + + /// Deliver a host-originated event to the program: journal it first is + /// impossible (the program must accept it for the journal to be true), so + /// the order is update, then journal, exactly like participant input. + /// Returns whether the program accepted the event and it was journaled. + async fn deliver(&mut self, text: String) -> bool { + if !self.program_healthy || self.storage_failed { + return false; + } + if text.len() > crate::world_caps::MAX_EVENT_BYTES { + tracing::error!("world event exceeds the delivery bound; dropped"); + return false; + } + let event = WorldEvent { + sequence: 0, + participant_id: 0, + kind: WorldEventKind::System { event: text }, + }; + if let Err(error) = self.program.update(&event) { + self.program_healthy = false; + tracing::error!("world program rejected a host event: {error:#}"); + return false; + } + match program_records(self.program.as_mut()) { + Ok(records) => { + let records = records.unwrap_or_default(); + publish_records(&self.records_sender, self.core.sequence, records); + } + Err(error) => { + self.program_healthy = false; + tracing::error!("world program records failed: {error:#}"); + return false; + } + } + let journaled = self.persist(JournalEntry::System { event }).is_ok(); + if journaled { + self.core.since_checkpoint = self.core.since_checkpoint.saturating_add(1); + } + let _ = self.view_changed.send(self.core.sequence); + journaled + } + + /// Recompute the program's `wants` and serve the delta: new subscriptions + /// (armed or refused), new requests (executed, result delivered). Passes + /// repeat while the program reacts to delivered results, so a chain of + /// asks settles inside one change. + pub(crate) async fn after_change(&mut self) { + for _ in 0..64 { + if !self.program_healthy || self.storage_failed { + break; + } + let Some(text) = (match self.program.wants() { + Ok(wants) => wants, + Err(error) => { + self.program_healthy = false; + tracing::error!("world program wants failed: {error:#}"); + break; + } + }) else { + break; + }; + let wants = match crate::world_caps::parse_wants(&text) { + Ok(wants) => wants, + Err(error) => { + self.program_healthy = false; + tracing::error!("world program wants invalid: {error:#}"); + break; + } + }; + self.apply_subscriptions(&wants).await; + let mut fresh = Vec::new(); + for request in &wants.requests { + if self.handled_requests.insert(request.id.clone()) { + fresh.push(request.clone()); + } + } + if fresh.is_empty() { + break; + } + // A program inventing endless request ids cannot grow this set + // without bound; old ids may then re-execute, which is the + // documented at-least-once behavior. + if self.handled_requests.len() > 4096 { + let current: BTreeSet = wants + .requests + .iter() + .map(|request| request.id.clone()) + .collect(); + self.handled_requests.retain(|id| current.contains(id)); + } + for request in fresh { + let outcome = self.execute(&request); + self.deliver(crate::world_caps::result_event(&request.id, outcome)) + .await; + } + } + self.compact_if_due().await; + } + + /// Subscribe new subscriptions, drop removed ones, refuse ungranted ones + /// (once per spec), and keep ticks armed only while someone is present. + async fn apply_subscriptions(&mut self, wants: &crate::world_caps::Wants) { + for sub in &wants.subscribe { + if !self.active_subs.insert(sub.clone()) { + continue; + } + match self.core.ledger.decide(sub.cap()) { + Decision::Allow => self.arm(sub), + Decision::AllowAndGrant => { + let granted: Vec = self.core.ledger.granted().iter().cloned().collect(); + let _ = self.persist(JournalEntry::CapsGranted { granted }); + self.arm(sub); + } + Decision::Deny(error) => { + let spec = sub.spec(); + if self.denied_subs.insert(spec.clone()) { + self.deliver(crate::world_caps::subscription_refused_event(&spec, error)) + .await; + } + } + } + } + let current = wants.subscribe.clone(); + self.active_subs.retain(|sub| current.contains(sub)); + self.denied_subs + .retain(|spec| current.iter().any(|sub| &sub.spec() == spec)); + if self.presence.values().all(|count| *count == 0) { + self.ticks.clear(); + } + } + + /// Arm a granted subscription's timer, if any and if anyone is present. + fn arm(&mut self, sub: &Subscription) { + if let Subscription::Tick(ms) = sub + && !self.presence.is_empty() + && !self.ticks.contains_key(ms) + { + self.ticks.insert( + *ms, + self.core.clock().now_instant() + std::time::Duration::from_millis(*ms), + ); + } + } + + /// Deliver one tick event per due interval and re-arm. + pub(crate) async fn fire_ticks(&mut self) { + let now = self.core.clock().now_instant(); + let due: Vec = self + .ticks + .iter() + .filter(|(_, next)| **next <= now) + .map(|(ms, _)| *ms) + .collect(); + for ms in due { + self.ticks + .insert(ms, now + std::time::Duration::from_millis(ms)); + let event = serde_json::json!({ + "cap": "time.tick", + "interval": ms, + // The tick's "now" reads the injected clock too, so a manual + // clock drives the payload as well as the deadline. + "now": self.core.clock().now_ms(), + }); + self.deliver(event.to_string()).await; + } + } + + /// Fire the schedules that are due, earliest first, at most + /// [`crate::world_caps::MAX_SCHEDULE_FIRES_PER_WAKEUP`] per wakeup. Each + /// fire is delivered as a tick is, and its schedule is consumed only after + /// that delivery is journaled. A refused fire, or one that could not be + /// journaled, leaves its schedule pending, so the next run delivers it. + pub(crate) async fn fire_schedules(&mut self) { + let now = self.core.clock().now_ms(); + let mut due: Vec<(u64, String)> = self + .core + .schedules + .iter() + .filter(|(_, at_ms)| **at_ms <= now) + .map(|(id, at_ms)| (*at_ms, id.clone())) + .collect(); + due.sort_unstable(); + due.truncate(crate::world_caps::MAX_SCHEDULE_FIRES_PER_WAKEUP); + for (_, id) in due { + let late = self.overdue_at_open.contains(&id); + if !self.deliver(schedule_fired_event(&id, late)).await { + break; + } + if self + .persist(JournalEntry::ScheduleFired { id: id.clone() }) + .is_err() + { + break; + } + self.core.schedules.remove(&id); + self.overdue_at_open.remove(&id); + } + } + + /// Execute one capability request. Anything the world has not granted is + /// an error the program sees. + fn execute(&mut self, request: &Request) -> Result { + let actor_permits = match self.acting { + None => true, + Some(participant) => self + .core + .effective_scopes(participant) + .is_some_and(|scopes| scopes.allows_effect(&request.cap)), + }; + match self.core.ledger.decide_for(&request.cap, actor_permits) { + Decision::Allow => {} + Decision::AllowAndGrant => { + let granted: Vec = self.core.ledger.granted().iter().cloned().collect(); + let _ = self.persist(JournalEntry::CapsGranted { granted }); + } + Decision::Deny(error) => return Err(error), + } + match request.cap.as_str() { + "time.now" => Ok(serde_json::json!({"now": unix_ms()})), + "random.u64" => Ok(serde_json::json!({"value": rand::rng().random::()})), + "players.list" => Ok(serde_json::json!({"players": self.players_list()})), + "world.info" => Ok(serde_json::json!({ + "world": self.core.world_id, + "sequence": self.core.sequence, + })), + "chat.say" => self.execute_chat(&request.args), + "chat.history" => Ok(serde_json::json!({ + "lines": chat_history( + &self.core.events, + request + .args + .get("count") + .and_then(serde_json::Value::as_u64) + .unwrap_or(16) + .min(crate::world_caps::MAX_CHAT_HISTORY_LINES as u64) as usize, + ), + })), + "records.read" => self.execute_records_read(&request.args), + "schedule.at" => self.execute_schedule_at(&request.args), + "schedule.cancel" => self.execute_schedule_cancel(&request.args), + _ => Err(CapError::unknown()), + } + } + + fn players_list(&self) -> Vec { + self.core + .participants() + .into_iter() + .map(|participant| { + serde_json::json!({ + "id": participant.id, + "name": participant.display_name, + "present": self.presence.get(&participant.id).is_some_and(|c| *c > 0), + }) + }) + .collect() + } + + /// `records.read`: a byte-bounded, prefix-scoped page of the world's + /// published records, key-ordered with the same exclusive `after` cursor + /// the session protocol uses. Follow `next_after` while it is non-empty. + fn execute_records_read( + &self, + args: &serde_json::Value, + ) -> Result { + let records = self.records_sender.borrow().1.clone(); + let prefix = args.get("prefix").and_then(serde_json::Value::as_str); + let after = args.get("after").and_then(serde_json::Value::as_str); + let mut page: Vec = Vec::new(); + let mut used = 0usize; + let mut last_included: Option = None; + let mut more = false; + for (key, value) in records.iter() { + if let Some(prefix) = prefix + && !key.starts_with(prefix) + { + continue; + } + if let Some(after) = after + && key.as_str() <= after + { + continue; + } + let size = key.len() + serde_json::to_vec(value).map_or(0, |v| v.len()) + 8; + if used + size > crate::world_session::MAX_RECORDS_PAGE_BYTES { + if page.is_empty() { + return Err(CapError::bad_args()); + } + more = true; + break; + } + used += size; + last_included = Some(key.clone()); + page.push(serde_json::json!({"key": key, "value": value})); + } + Ok(serde_json::json!({ + "records": page, + "next_after": more.then_some(last_included).flatten(), + })) + } + + /// `chat.say` commits a host chat line; its result is the new sequence. + fn execute_chat(&mut self, args: &serde_json::Value) -> Result { + let Some(text) = args.get("text").and_then(serde_json::Value::as_str) else { + return Err(CapError::bad_args()); + }; + match self.core.system_chat(text) { + Ok(event) => { + if self + .persist(JournalEntry::Committed { + event: event.clone(), + }) + .is_err() + { + return Err(CapError::failed()); + } + let _ = self.event_sender.send(event.clone()); + Ok(serde_json::json!({"sequence": event.sequence})) + } + Err(_) => Err(CapError::bad_args()), + } + } + + /// `schedule.at`: pend one fire of `id` at `at` (unix ms). The schedule is + /// journaled before the result is delivered. A refused request changes + /// nothing but the usage count. + fn execute_schedule_at( + &mut self, + args: &serde_json::Value, + ) -> Result { + let id = args + .get("id") + .and_then(serde_json::Value::as_str) + .ok_or(CapError::bad_args())?; + let at_ms = args + .get("at") + .and_then(serde_json::Value::as_u64) + .ok_or(CapError::bad_args())?; + if let Err(error) = self + .core + .check_schedule(id, at_ms, self.core.clock().now_ms()) + { + tracing::debug!("world {}: schedule refused: {error:#}", self.core.world_id); + return Err(CapError::bad_args_with(format!("{error:#}"))); + } + if self + .persist(JournalEntry::ScheduleSet { + id: id.to_owned(), + at_ms, + }) + .is_err() + { + return Err(CapError::failed()); + } + self.core.schedules.insert(id.to_owned(), at_ms); + Ok(serde_json::json!({"id": id, "fires_at": at_ms})) + } + + /// `schedule.cancel`: drop a pending schedule before it fires. `cancelled` + /// is false when nothing by that id is pending. + fn execute_schedule_cancel( + &mut self, + args: &serde_json::Value, + ) -> Result { + let id = args + .get("id") + .and_then(serde_json::Value::as_str) + .ok_or(CapError::bad_args())?; + if crate::world_caps::validate_schedule_id(id).is_err() { + return Err(CapError::bad_args()); + } + if !self.core.schedules.contains_key(id) { + return Ok(serde_json::json!({"cancelled": false})); + } + if self + .persist(JournalEntry::ScheduleCancelled { id: id.to_owned() }) + .is_err() + { + return Err(CapError::failed()); + } + self.core.schedules.remove(id); + self.overdue_at_open.remove(id); + Ok(serde_json::json!({"cancelled": true})) + } + + /// A participant opened or closed a session: presence transitions deliver + /// `players` events and arm or disarm ticks. + async fn handle_presence(&mut self, participant: u64, joined: bool) { + let was_present = self + .presence + .get(&participant) + .is_some_and(|count| *count > 0); + let count = self.presence.entry(participant).or_default(); + if joined { + *count += 1; + } else if *count > 0 { + *count -= 1; + } + let now_present = *count > 0; + if *count == 0 { + self.presence.remove(&participant); + } + if now_present && !was_present && self.ticks.is_empty() { + let intervals: Vec = self + .active_subs + .iter() + .filter_map(|sub| match sub { + Subscription::Tick(ms) if self.core.ledger.is_granted(sub.cap()) => Some(*ms), + _ => None, + }) + .collect(); + for ms in intervals { + self.ticks.entry(ms).or_insert_with(|| { + self.core.clock().now_instant() + std::time::Duration::from_millis(ms) + }); + } + } + if self.presence.is_empty() { + self.ticks.clear(); + } + if now_present != was_present + && self.active_subs.contains(&Subscription::Players) + && self.core.ledger.is_granted("players") + { + let name = self + .core + .participant(participant) + .map_or_else(|| participant.to_string(), |p| p.display_name); + self.deliver(presence_event(participant, &name, now_present)) + .await; + } + } + + fn require_moderation(&self, authority: &Authority, what: &str) -> Result<()> { + let directory = self.core.directory(); + let allowed = match authority { + Authority::Admin => true, + Authority::Signed(key) => directory + .account_for_key(key) + .is_some_and(|account| directory.is_moderator(&account)), + }; + if allowed { + Ok(()) + } else { + Err(crate::directory::Refusal::Forbidden(format!( + "only an admin or a moderator {what}" + )) + .into()) + } + } + + fn set_isolation(&mut self, authority: &Authority, isolation: Isolation) -> Result { + self.require_moderation(authority, "changes isolation")?; + self.persist(JournalEntry::Isolation { isolation })?; + self.core.isolation = isolation; + Ok(isolation) + } + + fn set_cross_world_write( + &mut self, + authority: &Authority, + enabled: bool, + ) -> Result { + self.require_moderation(authority, "changes cross-world writes")?; + if !enabled && self.core.cross_world_forced && *authority != Authority::Admin { + return Err(crate::directory::Refusal::Forbidden( + "the admin forced cross-world writes on; only the admin can turn them off" + .to_owned(), + ) + .into()); + } + self.persist(JournalEntry::CrossWorldWrite { enabled })?; + self.core.cross_world_write = enabled; + if !enabled { + self.core.cross_world_forced = false; + } + Ok(self.core.policy()) + } + + fn force_cross_world_write(&mut self, authority: &Authority) -> Result { + if *authority != Authority::Admin { + return Err(crate::directory::Refusal::Forbidden( + "only the admin forces cross-world writes".to_owned(), + ) + .into()); + } + if self.core.isolation == Isolation::Isolated { + return Err(crate::directory::Refusal::Forbidden( + "an isolated world cannot be forced to accept cross-world writes; unisolate it first" + .to_owned(), + ) + .into()); + } + self.persist(JournalEntry::CrossWorldWriteForced)?; + self.core.cross_world_write = true; + self.core.cross_world_forced = true; + Ok(self.core.policy()) + } + + fn set_file_scope( + &mut self, + authority: &Authority, + scope: FileScope, + write_override: Option, + ) -> Result { + self.require_moderation(authority, "changes the file scope")?; + if write_override.is_some() && *authority != Authority::Admin { + return Err(crate::directory::Refusal::Forbidden( + "only the admin sets the file write override".to_owned(), + ) + .into()); + } + self.persist(JournalEntry::FileScope { scope })?; + self.core.file_scope = scope; + if let Some(enabled) = write_override { + self.persist(JournalEntry::FileWriteOverride { enabled })?; + self.core.file_write_override = enabled; + } + Ok(self.core.policy()) + } + + /// Replace the world's capability ceiling. It takes effect now: uses and + /// subscriptions the ceiling excludes are refused from here on. Grants are + /// kept, so lifting the ceiling again restores them. + fn set_caps_ceiling(&mut self, ceiling: Vec) -> Result { + crate::world_caps::validate_ceiling_names(&ceiling)?; + let ceiling: BTreeSet = ceiling.into_iter().collect(); + self.persist(JournalEntry::CapsCeiling { + ceiling: ceiling.iter().cloned().collect(), + })?; + self.core.caps_ceiling = ceiling; + self.core.sync_ledger_ceiling(); + self.reconcile_subscriptions(); + self.caps_report() + } + + /// Re-check subscriptions after an authority change. An armed one that is + /// no longer granted is dropped and its tick disarmed. Every refused one is + /// dropped too, so the next pass decides it again: a refusal that still + /// holds is announced again, and one the change now grants is armed. + fn reconcile_subscriptions(&mut self) { + let ledger = &self.core.ledger; + let refused = &self.denied_subs; + self.active_subs + .retain(|sub| !refused.contains(&sub.spec()) && ledger.is_granted(sub.cap())); + self.denied_subs.clear(); + let active = &self.active_subs; + self.ticks + .retain(|ms, _| active.contains(&Subscription::Tick(*ms))); + } + + /// The capability report an admin sees. + fn caps_report(&mut self) -> Result { + let requested = match self.program.wants() { + Ok(Some(text)) => crate::world_caps::parse_wants(&text) + .map(|wants| wants.caps().into_iter().collect::>()) + .unwrap_or_default(), + Ok(None) => Vec::new(), + Err(_) => Vec::new(), + }; + let granted: Vec = self.core.ledger.granted().iter().cloned().collect(); + let effective: Vec = self.core.ledger.effective().into_iter().collect(); + let missing: Vec = requested + .iter() + .filter(|cap| !effective.contains(cap)) + .cloned() + .collect(); + Ok(CapsReport { + granted, + requested, + missing, + usage: self.core.ledger.usage().clone(), + policy: if self.core.ledger.grant_on_use() { + "grant-on-use" + } else { + "deny" + } + .to_owned(), + catalog: crate::world_caps::CATALOG + .iter() + .map(|name| (*name).to_owned()) + .collect(), + ceiling: self.core.caps_ceiling.iter().cloned().collect(), + effective, + view_failures: self.view_failures, + }) + } + + pub(crate) async fn handle(&mut self, command: WorldCommand) { + match command { + WorldCommand::Issue { + name, + scopes, + bounds, + reply, + } => { + let result = self.check_storage().and_then(|()| { + let issued = self.core.issue_capability(&name, scopes, bounds)?; + self.record_issued(issued) + }); + let _ = reply.send(result); + } + WorldCommand::Attenuate { + token, + name, + scopes, + bounds, + reply, + } => { + let result = self.check_storage().and_then(|()| { + let issued = self.core.attenuate(&token, scopes, bounds, &name)?; + self.record_issued(issued) + }); + let _ = reply.send(result); + } + WorldCommand::DelegateToFriend { + token, + friend, + name, + scopes, + bounds, + reply, + } => { + let result = self.check_storage().and_then(|()| { + let issued = self + .core + .delegate_to_friend(&token, &friend, scopes, bounds, &name)?; + self.record_issued(issued) + }); + let _ = reply.send(result); + } + WorldCommand::Directory { + caller, + action, + outbox, + reply, + } => { + let world = self.core.world_id().to_owned(); + let now = unix_ms(); + let (directory, petnames) = self.core.directory_and_petnames_mut(); + // Refused before the directory changes, so a refused change leaves nothing half-applied. + let result = if !outbox + && action.queues_for_other_servers(directory, &mut self.auth, &caller, now) + { + Err(crate::directory::Refusal::Forbidden( + "this server cannot send to other servers".to_owned(), + ) + .into()) + } else { + crate::directory_view::run( + directory, + petnames, + &mut self.auth, + &caller, + &world, + now, + action, + ) + }; + let _ = reply.send(result); + } + WorldCommand::ApplyDirectory { entry, reply } => { + let _ = reply.send(self.core.directory_mut().apply(&entry)); + } + WorldCommand::Revoke { + participant_id, + reply, + } => { + // Revocation takes effect in memory even if storage failed: + // denying access is always the safe side. + let revoked = self.core.revoke_tree(participant_id); + let was_active = !revoked.is_empty(); + if was_active { + let _ = self.persist(JournalEntry::Revoked { participant_id }); + for id in revoked { + let _ = self.revocation_sender.send(id); + } + } + let _ = reply.send(was_active); + } + WorldCommand::ParticipantId { token, reply } => { + let _ = reply.send(self.core.authorize(&token, WorldScopes::JOIN)); + } + WorldCommand::Presence { + participant, + joined, + } => { + self.handle_presence(participant, joined).await; + } + WorldCommand::Chat { token, text, reply } => { + let result = if self.storage_failed { + Err(anyhow::anyhow!( + "world storage failed; the world is read-only" + )) + } else { + self.core.chat(&token, &text).and_then(|event| { + self.persist(JournalEntry::Committed { + event: event.clone(), + })?; + Ok(event) + }) + }; + if let Ok(event) = &result { + let _ = self.event_sender.send(event.clone()); + } + let _ = reply.send(result); + } + WorldCommand::Input { + token, + input, + reply, + } => { + let result = match self.core.prepare_input(&token, &input) { + Ok(_) if self.storage_failed => Err(anyhow::anyhow!( + "world storage failed; the world is read-only" + )), + Ok(candidate) if self.program_healthy => { + self.acting = Some(candidate.participant_id); + match self + .program + .update(&candidate) + .and_then(|()| program_records(self.program.as_mut())) + { + Ok(records) => self + .persist(JournalEntry::Committed { + event: candidate.clone(), + }) + .and_then(|()| self.core.commit_prepared(candidate)) + .inspect(|event| { + let records = records.unwrap_or_default(); + self.republished(records, event.sequence); + }), + Err(error) => { + self.program_healthy = false; + Err(error.context("world program rejected input")) + } + } + } + Ok(_) => Err(anyhow::anyhow!( + "world program is unavailable after a previous failure" + )), + Err(error) => Err(error), + }; + if let Ok(event) = &result { + let _ = self.event_sender.send(event.clone()); + } + let _ = reply.send(result); + } + WorldCommand::Snapshot { token, reply } => { + let _ = reply.send(self.core.snapshot(&token)); + } + WorldCommand::EventsAfter { + token, + sequence, + reply, + } => { + let _ = reply.send(self.core.events_after(&token, sequence)); + } + WorldCommand::ProjectEvent { + token, + event, + reply, + } => { + let _ = reply.send(self.core.project_for(&token, &event)); + } + WorldCommand::View { token, reply } => { + let result = match self.core.viewer(&token) { + Ok(viewer) if self.program_healthy => match self.program.view(&viewer) { + Ok(view) => { + if let Some(text) = &view { + if text.len() > self.core.limits.presentation_bytes { + self.view_failures = self.view_failures.saturating_add(1); + Err(anyhow::anyhow!( + "world presentation exceeds {} bytes", + self.core.limits.presentation_bytes + )) + } else { + Ok(view) + } + } else { + Ok(None) + } + } + Err(error) => { + // A trapping view degrades to an error screen, not + // a poisoned world: keep the program healthy so the + // next event retries (F11.17). + self.view_failures = self.view_failures.saturating_add(1); + Err(error.context("world program view failed")) + } + }, + Ok(_) => Err(anyhow::anyhow!( + "world program is unavailable after a previous failure" + )), + Err(error) => Err(error), + }; + let _ = reply.send(result); + } + WorldCommand::ViewAt { + token, + width, + height, + reply, + } => { + let result = match self.core.viewer(&token) { + Ok(viewer) if self.program_healthy => { + match self.program.layout(&viewer, width, height) { + Ok(view) => { + if let Some(text) = &view { + if text.len() > self.core.limits.presentation_bytes { + self.view_failures = self.view_failures.saturating_add(1); + Err(anyhow::anyhow!( + "world presentation exceeds {} bytes", + self.core.limits.presentation_bytes + )) + } else { + Ok(view) + } + } else { + Ok(None) + } + } + Err(error) => { + // As with `view`, a trapping layout degrades to + // an error screen and does not poison the world. + self.view_failures = self.view_failures.saturating_add(1); + Err(error.context("world program layout failed")) + } + } + } + Ok(_) => Err(anyhow::anyhow!( + "world program is unavailable after a previous failure" + )), + Err(error) => Err(error), + }; + let _ = reply.send(result); + } + WorldCommand::InstallProgram { + module_hash, + seed, + provenance, + program: mut replacement, + reply, + } => { + // A program whose initial records are invalid is refused + // before anything is journaled. + let new_records = match program_records(replacement.as_mut()) { + Ok(records) => records.unwrap_or_default(), + Err(error) => { + let _ = reply.send(Err(error.context("new world program records failed"))); + return; + } + }; + // Actor serialization makes activation and its event atomic + // with respect to other world commands. + let candidate = WorldEvent { + sequence: self.core.sequence.saturating_add(1), + participant_id: 0, + kind: WorldEventKind::ProgramInstalled { + module_hash, + seed, + provenance: provenance.clone(), + }, + }; + let result = self + .persist(JournalEntry::Committed { + event: candidate.clone(), + }) + .and_then(|()| self.core.commit_prepared(candidate)); + let result = match result { + Ok(event) => { + if let WorldEventKind::ProgramInstalled { module_hash, .. } = &event.kind { + self.core.active_module_hash = Some(module_hash.clone()); + } + self.core.active_module_provenance = provenance; + self.core.active_seed = seed; + self.program = replacement; + self.program_healthy = true; + self.compaction_off = false; + // A new program starts with a clean slate. + self.handled_requests.clear(); + self.denied_subs.clear(); + self.active_subs.clear(); + self.ticks.clear(); + self.republished(new_records, event.sequence); + let _ = self.event_sender.send(event.clone()); + Ok(event) + } + Err(error) => Err(error), + }; + let _ = reply.send(result); + } + WorldCommand::UpdateCaps { + grant, + revoke, + reply, + } => { + let result = (|| -> Result { + crate::world_caps::validate_grant_names(&grant)?; + crate::world_caps::validate_grant_names(&revoke)?; + let mut granted: BTreeSet = + self.core.ledger.granted().iter().cloned().collect(); + for name in revoke { + granted.remove(&name); + } + granted.extend(grant); + self.persist(JournalEntry::CapsGranted { + granted: granted.iter().cloned().collect(), + })?; + self.core.ledger.set_granted(granted); + self.reconcile_subscriptions(); + self.caps_report() + })(); + let _ = reply.send(result); + } + WorldCommand::SetCapsCeiling { ceiling, reply } => { + let result = self.set_caps_ceiling(ceiling); + let _ = reply.send(result); + } + WorldCommand::SetExecutionProfile { profile, reply } => { + let result = self + .persist(JournalEntry::ExecutionProfile { profile }) + .map(|()| { + self.core.execution_profile = profile; + ExecutionProfileUpdate { + requested: profile, + applies_on_next_program_install_or_process_restart: true, + } + }); + let _ = reply.send(result); + } + WorldCommand::ExecutionProfileInfo { reply } => { + let _ = reply.send(self.core.execution_profile); + } + WorldCommand::SetIsolation { + authority, + isolation, + reply, + } => { + let result = self.set_isolation(&authority, isolation); + let _ = reply.send(result); + } + WorldCommand::IsolationInfo { reply } => { + let _ = reply.send(self.core.isolation()); + } + WorldCommand::SetCrossWorldWrite { + authority, + enabled, + reply, + } => { + let result = self.set_cross_world_write(&authority, enabled); + let _ = reply.send(result); + } + WorldCommand::ForceCrossWorldWrite { authority, reply } => { + let result = self.force_cross_world_write(&authority); + let _ = reply.send(result); + } + WorldCommand::SetFileScope { + authority, + scope, + write_override, + reply, + } => { + let result = self.set_file_scope(&authority, scope, write_override); + let _ = reply.send(result); + } + WorldCommand::PolicyInfo { reply } => { + let _ = reply.send(self.core.policy()); + } + WorldCommand::CapsInfo { reply } => { + let _ = reply.send(self.caps_report()); + } + WorldCommand::Shutdown { .. } => unreachable!("handled by run"), + } + } + + /// Trim the journal behind a verified snapshot, at most once per run of + /// commits and never while the program cannot snapshot. + async fn compact_if_due(&mut self) { + if self.compaction_off + || self.storage_failed + || !self.program_healthy + || !self.core.checkpoint_due() + { + return; + } + let Some(journal) = self.journal.as_mut() else { + return; + }; + match compact_journal(&mut self.core, self.program.as_mut(), journal.as_mut()) { + Ok(true) => {} + Ok(false) => self.compaction_off = true, + Err(error) => { + // The journal is still complete; just do not retry until + // something changes. + tracing::warn!("world checkpoint skipped: {error:#}"); + self.compaction_off = true; + } + } + } +} + +#[cfg(test)] +impl WorldActor { + /// Assemble an actor without spawning its run loop, for tests that drive + /// [`WorldActor::handle`], [`WorldActor::after_change`], [`WorldActor::fire_ticks`] + /// and [`WorldActor::fire_schedules`] directly against a [`ManualClock`]. + pub(crate) fn for_test( + core: WorldCore, + mut program: Box, + journal: Option>, + ) -> Self { + let (events, _) = broadcast::channel(256); + let (revocations, _) = broadcast::channel(256); + let (view_changed, _) = watch::channel(core.sequence); + let mut program_healthy = true; + let initial = match program_records(program.as_mut()) { + Ok(records) => records.unwrap_or_default(), + Err(_) => { + program_healthy = false; + Records::new() + } + }; + let (records_sender, _) = watch::channel((core.sequence, Arc::new(initial))); + // Schedules already due when the world opened fire late, judged by the + // injected clock so a manual clock controls this too. + let overdue_at_open: BTreeSet = core + .schedules + .iter() + .filter(|(_, at_ms)| **at_ms <= core.clock().now_ms()) + .map(|(id, _)| id.clone()) + .collect(); + Self { + core, + program, + journal, + storage_failed: false, + program_healthy, + view_failures: 0, + compaction_off: false, + event_sender: events, + revocation_sender: revocations, + records_sender, + view_changed, + presence: HashMap::new(), + active_subs: BTreeSet::new(), + handled_requests: BTreeSet::new(), + denied_subs: BTreeSet::new(), + ticks: BTreeMap::new(), + overdue_at_open, + acting: None, + auth: crate::directory_auth::DirectoryAuth::default(), + } + } +} diff --git a/pkgs/id/src/world/clock.rs b/pkgs/id/src/world/clock.rs new file mode 100644 index 0000000000..dce88dac5d --- /dev/null +++ b/pkgs/id/src/world/clock.rs @@ -0,0 +1,84 @@ +//! Injected clock for the world actor and scheduler. +//! +//! Every *time decision* the actor and scheduler make — when a schedule or +//! tick is due, whether a capability has expired, how long ago a chat line +//! was sent — reads through [`Clock`]. The default is the process's real +//! [`SystemClock`]; tests swap in a [`ManualClock`] they advance by hand, so +//! schedule and tick tests run without sleeping. + +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{Duration, Instant}; + +/// A source of wall-clock and monotonic time for the world runtime. +/// +/// `Debug` is required so a [`crate::world::WorldCore`] holding an +/// `Arc` can keep its derived `Debug`. +pub trait Clock: std::fmt::Debug + Send + Sync + 'static { + /// Milliseconds since the Unix epoch. This is the scheduler's absolute + /// time: schedule due times and capability expiries are compared against + /// it. + fn now_ms(&self) -> u64; + + /// A monotonic instant, used for tick deadlines and loop wakeups. + fn now_instant(&self) -> Instant; +} + +/// The process's real clock. +#[derive(Debug)] +pub struct SystemClock; + +impl Clock for SystemClock { + fn now_ms(&self) -> u64 { + crate::time::unix_ms() + } + + fn now_instant(&self) -> Instant { + Instant::now() + } +} + +/// A clock a test advances by hand. [`ManualClock::advance`] moves `now_ms` +/// and `now_instant` forward together, so a schedule due at `now_ms() + N` +/// also crosses the monotonic deadline `now_instant() + N`. +/// +/// The two faces share a single `AtomicU64` offset over a construction-time +/// base, so an `Arc` can be advanced from the test while the +/// actor reads it through `Arc`. +#[derive(Debug)] +pub struct ManualClock { + /// Milliseconds since the Unix epoch at construction. + epoch_ms: u64, + /// The monotonic instant that `epoch_ms` corresponds to. + base: Instant, + /// Milliseconds advanced past `epoch_ms`, for both faces. + offset_ms: AtomicU64, +} + +impl ManualClock { + /// A clock that starts at `epoch_ms` (unix milliseconds) and the current + /// monotonic instant. + #[must_use] + pub fn new(epoch_ms: u64) -> Self { + Self { + epoch_ms, + base: Instant::now(), + offset_ms: AtomicU64::new(0), + } + } + + /// Advance both faces of the clock by `ms` milliseconds. + pub fn advance(&self, ms: u64) { + self.offset_ms.fetch_add(ms, Ordering::SeqCst); + } +} + +impl Clock for ManualClock { + fn now_ms(&self) -> u64 { + self.epoch_ms + .saturating_add(self.offset_ms.load(Ordering::SeqCst)) + } + + fn now_instant(&self) -> Instant { + self.base + Duration::from_millis(self.offset_ms.load(Ordering::SeqCst)) + } +} diff --git a/pkgs/id/src/world/core.rs b/pkgs/id/src/world/core.rs new file mode 100644 index 0000000000..54ea8cf801 --- /dev/null +++ b/pkgs/id/src/world/core.rs @@ -0,0 +1,1159 @@ +use super::*; + +use anyhow::{Context, Result, ensure}; +use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque}; +use std::sync::Arc; + +/// Mutable world state. Keep it behind one actor/mutex so event sequencing is serialized. +#[derive(Debug)] +pub struct WorldCore { + pub(crate) world_id: String, + pub(crate) limits: WorldLimits, + /// The clock every time decision reads: schedules, ticks, expiries and + /// the chat rate window. [`SystemClock`] by default; tests inject a + /// [`ManualClock`] through [`WorldCore::new_with_clock`]. + pub(crate) clock: Arc, + pub(crate) execution_profile: crate::world_limits::WorldExecutionProfile, + pub(crate) next_participant_id: u64, + pub(crate) sequence: u64, + pub(crate) active_module_hash: Option, + pub(crate) active_module_provenance: Option, + pub(crate) active_seed: u64, + /// What this world's program may ask the server for. + pub(crate) ledger: crate::world_caps::CapLedger, + /// This world's own capability ceiling. The ledger allows the intersection + /// of this and the server's `limits.server_caps`. + pub(crate) caps_ceiling: BTreeSet, + /// Pending `schedule.at` fires: id to due time, in unix milliseconds. + pub(crate) schedules: BTreeMap, + pub(crate) isolation: Isolation, + pub(crate) cross_world_write: bool, + pub(crate) cross_world_forced: bool, + pub(crate) file_scope: FileScope, + pub(crate) file_write_override: bool, + /// Events committed since the journal last started from a checkpoint. + pub(crate) since_checkpoint: u64, + pub(crate) capabilities: HashMap, + /// Recent chat timestamps, pruned to the active rolling window on each send. + pub(crate) chat_rates: HashMap>, + pub(crate) events: VecDeque, + pub(crate) directory: crate::directory::Directory, + pub(crate) petnames: crate::petname::Petnames, +} + +impl WorldCore { + /// Create an empty in-memory world on the real [`SystemClock`]. + pub fn new(world_id: impl Into, limits: WorldLimits) -> Result { + Self::new_with_clock(world_id, limits, Arc::new(SystemClock)) + } + + /// Create an empty in-memory world that reads the time from `clock`. + pub fn new_with_clock( + world_id: impl Into, + limits: WorldLimits, + clock: Arc, + ) -> Result { + let world_id = world_id.into(); + ensure!(!world_id.trim().is_empty(), "world ID must not be empty"); + ensure!( + limits.participants > 0, + "world participant limit must be nonzero" + ); + ensure!(limits.chat_bytes > 0, "world chat limit must be nonzero"); + ensure!(limits.input_bytes > 0, "world input limit must be nonzero"); + ensure!( + limits.retained_events > 0, + "world event retention must be nonzero" + ); + ensure!( + limits.presentation_bytes > 0, + "world presentation limit must be nonzero" + ); + ensure!( + limits.snapshot_bytes > 0, + "world snapshot limit must be nonzero" + ); + let server_caps: Vec = limits.server_caps.iter().cloned().collect(); + crate::world_caps::validate_ceiling_names(&server_caps) + .context("server capability ceiling")?; + let grant_on_use = limits.grant_on_use; + let mut core = Self { + world_id, + limits, + clock, + execution_profile: crate::world_limits::WorldExecutionProfile::default(), + next_participant_id: 1, + sequence: 0, + active_module_hash: None, + active_module_provenance: None, + active_seed: 0, + ledger: crate::world_caps::CapLedger::new(BTreeSet::new(), grant_on_use), + caps_ceiling: crate::world_caps::catalog_names(), + schedules: BTreeMap::new(), + isolation: Isolation::default(), + cross_world_write: false, + cross_world_forced: false, + file_scope: FileScope::default(), + file_write_override: false, + since_checkpoint: 0, + capabilities: HashMap::new(), + chat_rates: HashMap::new(), + events: VecDeque::new(), + directory: crate::directory::Directory::new(), + petnames: crate::petname::Petnames::new(), + }; + core.sync_ledger_ceiling(); + Ok(core) + } + + /// The clock every time decision reads. + pub(crate) fn clock(&self) -> &dyn Clock { + &*self.clock + } + + /// Recompute what the ledger may allow: the server's limit intersected with + /// this world's ceiling. Call whenever either one changes. + pub(crate) fn sync_ledger_ceiling(&mut self) { + let allowed = self + .limits + .server_caps + .intersection(&self.caps_ceiling) + .cloned() + .collect(); + self.ledger.set_allowed(allowed); + } + + /// Rebuild a world from its journal. + /// + /// # Errors + /// + /// Fails if the journal belongs to another world, uses an unknown + /// version, or is internally inconsistent (out-of-order sequences, + /// unknown participants, malformed digests). A bad journal is refused, + /// never partially applied. + pub fn restore( + world_id: impl Into, + limits: WorldLimits, + entries: impl IntoIterator, + ) -> Result { + let mut core = Self::new(world_id, limits)?; + let mut program = None; + let mut replay = Vec::new(); + let mut present: BTreeMap = BTreeMap::new(); + let mut entries = entries.into_iter(); + match entries.next() { + Some(JournalEntry::Created { world_id, version }) => { + ensure!( + world_id == core.world_id, + "journal belongs to world {world_id:?}, not {:?}", + core.world_id + ); + ensure!( + version == JOURNAL_VERSION, + "unsupported world journal version {version}" + ); + } + Some(_) => anyhow::bail!("world journal does not start with a header"), + None => { + return Ok(RestoredWorld { + core, + program, + replay, + }); + } + } + for entry in entries { + match entry { + JournalEntry::Created { .. } => anyhow::bail!("duplicate world journal header"), + JournalEntry::Issued { + participant, + digest, + scopes, + parent, + expires_at, + uses, + used, + subject, + } => { + let digest = hex_decode_32(&digest).context("malformed capability digest")?; + ensure!( + !core.capabilities.contains_key(&participant.id), + "participant {} issued twice", + participant.id + ); + ensure!( + parent.is_none_or(|parent| core.capabilities.contains_key(&parent)), + "participant {} delegated from an unknown capability", + participant.id + ); + ensure!( + uses.is_none_or(|uses| uses >= 1), + "participant {} has an empty use limit", + participant.id + ); + if let Some(parent) = parent.and_then(|id| core.capabilities.get(&id)) { + ensure!( + expires_at.is_none_or(|expires| parent + .bounds + .expires_at + .is_none_or(|limit| expires <= limit)), + "participant {} outlives the capability it was delegated from", + participant.id + ); + } + core.next_participant_id = core.next_participant_id.max( + participant + .id + .checked_add(1) + .context("participant ID exhausted")?, + ); + core.capabilities.insert( + participant.id, + CapabilityRecord { + digest, + participant, + scopes: WorldScopes(scopes), + parent, + revoked: false, + bounds: CapabilityBounds { expires_at, uses }, + used, + subject, + }, + ); + } + JournalEntry::Revoked { participant_id } => { + ensure!( + !core.revoke_tree(participant_id).is_empty(), + "journal revokes unknown or revoked participant {participant_id}" + ); + } + JournalEntry::CapsGranted { granted } => { + for name in &granted { + ensure!( + name == "*" || crate::world_caps::is_known(name), + "journal grants unknown capability {name:?}" + ); + } + core.ledger.set_granted(granted.iter().cloned().collect()); + } + JournalEntry::CapsCeiling { ceiling } => { + crate::world_caps::validate_ceiling_names(&ceiling) + .context("invalid capability ceiling in journal")?; + core.caps_ceiling = ceiling.into_iter().collect(); + } + JournalEntry::ExecutionProfile { profile } => { + profile + .resolve(crate::world_limits::RuntimeLimits::default()) + .context("invalid world execution profile in journal")?; + core.execution_profile = profile; + } + JournalEntry::Isolation { isolation } => core.isolation = isolation, + JournalEntry::CrossWorldWrite { enabled } => { + core.cross_world_write = enabled; + if !enabled { + core.cross_world_forced = false; + } + } + JournalEntry::CrossWorldWriteForced => { + core.cross_world_write = true; + core.cross_world_forced = true; + } + JournalEntry::FileScope { scope } => core.file_scope = scope, + JournalEntry::FileWriteOverride { enabled } => core.file_write_override = enabled, + JournalEntry::ScheduleSet { id, at_ms } => { + crate::world_caps::validate_schedule_id(&id) + .context("invalid schedule id in journal")?; + ensure!( + !core.schedules.contains_key(&id), + "journal schedules {id:?} twice" + ); + ensure!( + core.schedules.len() < crate::world_caps::MAX_PENDING_SCHEDULES, + "journal holds more than {} pending schedules", + crate::world_caps::MAX_PENDING_SCHEDULES + ); + // No clock here: the due time is what the request set, and + // a restore never judges it against now. + core.schedules.insert(id, at_ms); + } + JournalEntry::ScheduleCancelled { id } => { + ensure!( + core.schedules.remove(&id).is_some(), + "journal cancels schedule {id:?}, which is not pending" + ); + } + JournalEntry::ScheduleFired { id } => { + ensure!( + core.schedules.remove(&id).is_some(), + "journal fires schedule {id:?}, which is not pending" + ); + } + JournalEntry::System { event } => { + ensure!( + event.sequence == 0 && event.participant_id == 0, + "journal system event claims a sequence" + ); + let change = match &event.kind { + WorldEventKind::System { event: text } => presence_change(text), + _ => None, + }; + if let Some((participant, joined)) = change { + let count = present.entry(participant).or_insert(0); + if joined { + *count += 1; + } else { + *count = count.saturating_sub(1); + } + if *count == 0 { + present.remove(&participant); + } + } + replay.push(event.clone()); + core.since_checkpoint = core.since_checkpoint.saturating_add(1); + } + JournalEntry::Committed { event } => { + ensure!( + event.sequence == core.sequence.saturating_add(1), + "journal sequence jumps from {} to {}", + core.sequence, + event.sequence + ); + match &event.kind { + WorldEventKind::ProgramInstalled { + module_hash, + seed, + provenance, + } => { + core.active_module_hash = Some(module_hash.clone()); + core.active_module_provenance = provenance.clone(); + core.active_seed = *seed; + program = Some(RestoredProgram { + module_hash: module_hash.clone(), + seed: *seed, + snapshot: None, + provenance: provenance.clone(), + }); + replay.clear(); + } + WorldEventKind::Input(_) => replay.push(event.clone()), + // System events belong to the journal's tail; a + // checkpoint behind them already contains their effect. + WorldEventKind::System { .. } | WorldEventKind::Chat(_) => {} + } + core.commit_prepared(event)?; + } + JournalEntry::Checkpoint { + sequence, + module_hash, + seed, + provenance, + execution_profile, + caps_ceiling, + schedules, + snapshot, + events, + } => { + ensure!( + core.sequence == 0 && program.is_none(), + "journal checkpoint does not come first" + ); + ensure!( + events.last().is_none_or(|last| last.sequence == sequence) + && events + .windows(2) + .all(|pair| pair[1].sequence == pair[0].sequence + 1), + "journal checkpoint events are out of order" + ); + core.sequence = sequence; + core.events = events.into(); + while core.events.len() > core.limits.retained_events { + core.events.pop_front(); + } + core.active_module_hash = Some(module_hash.clone()); + core.active_module_provenance = provenance.clone(); + core.active_seed = seed; + let execution_profile = execution_profile.unwrap_or_default(); + execution_profile + .resolve(crate::world_limits::RuntimeLimits::default()) + .context("invalid world execution profile in checkpoint")?; + core.execution_profile = execution_profile; + // Absent means the whole catalog: older checkpoints and + // default ceilings omit the field. + core.caps_ceiling = match caps_ceiling { + Some(ceiling) => { + crate::world_caps::validate_ceiling_names(&ceiling) + .context("invalid capability ceiling in checkpoint")?; + ceiling.into_iter().collect() + } + None => crate::world_caps::catalog_names(), + }; + // The writer emits one `ScheduleSet` per pending schedule + // before the checkpoint, so the two must agree exactly. + let listed = schedules.unwrap_or_default(); + let declared: BTreeMap = listed.iter().cloned().collect(); + ensure!( + declared.len() == listed.len() && declared == core.schedules, + "journal checkpoint's pending schedules disagree with its schedule entries" + ); + program = Some(RestoredProgram { + module_hash, + seed, + snapshot: Some(snapshot), + provenance, + }); + } + } + } + // Sessions end with the process, and a crash skips their leave, so + // anyone the journal still shows present is gone by now. + for participant in present.into_keys() { + let name = core + .participant(participant) + .map_or_else(|| participant.to_string(), |p| p.display_name); + replay.push(WorldEvent { + sequence: 0, + participant_id: 0, + kind: WorldEventKind::System { + event: presence_event(participant, &name, false), + }, + }); + } + core.sync_ledger_ceiling(); + Ok(RestoredWorld { + core, + program, + replay, + }) + } + + /// Whether enough events piled up behind the last checkpoint to trim. + pub(crate) const fn checkpoint_due(&self) -> bool { + self.limits.checkpoint_every > 0 + && self.active_module_hash.is_some() + && self.since_checkpoint >= self.limits.checkpoint_every + } + + /// The journal that replaces the current one behind `snapshot`: a header, + /// every participant (and revocation), then the checkpoint itself. + pub(crate) fn checkpoint_entries(&self, snapshot: String) -> Result> { + let module_hash = self + .active_module_hash + .clone() + .context("no active program to checkpoint")?; + let mut ids: Vec = self.capabilities.keys().copied().collect(); + ids.sort_unstable(); + let mut entries = vec![JournalEntry::Created { + world_id: self.world_id.clone(), + version: JOURNAL_VERSION, + }]; + for id in ids { + entries.extend(self.issued_entry(id)); + if self + .capabilities + .get(&id) + .is_some_and(|record| record.revoked) + { + entries.push(JournalEntry::Revoked { participant_id: id }); + } + } + let granted: Vec = self.ledger.granted().iter().cloned().collect(); + if !granted.is_empty() { + entries.push(JournalEntry::CapsGranted { granted }); + } + // The ceiling rides on the checkpoint, so compaction keeps it; the + // default is omitted and reads back as the whole catalog. + let caps_ceiling: Option> = (self.caps_ceiling + != crate::world_caps::catalog_names()) + .then(|| self.caps_ceiling.iter().cloned().collect()); + if let Some(ceiling) = &caps_ceiling { + // An older binary cannot read a `CapsCeiling` entry and refuses the + // journal. Without it, the older binary would ignore the checkpoint + // field and restore the whole catalog, widening authority silently. + entries.push(JournalEntry::CapsCeiling { + ceiling: ceiling.clone(), + }); + } + if self.isolation != Isolation::default() { + entries.push(JournalEntry::Isolation { + isolation: self.isolation, + }); + } + if self.cross_world_forced { + entries.push(JournalEntry::CrossWorldWriteForced); + } else if self.cross_world_write { + entries.push(JournalEntry::CrossWorldWrite { enabled: true }); + } + if self.file_scope != FileScope::default() { + entries.push(JournalEntry::FileScope { + scope: self.file_scope, + }); + } + if self.file_write_override { + entries.push(JournalEntry::FileWriteOverride { enabled: true }); + } + if self.execution_profile != crate::world_limits::WorldExecutionProfile::default() { + entries.push(JournalEntry::ExecutionProfile { + profile: self.execution_profile, + }); + } + // One entry per pending schedule, before the checkpoint, mirroring the + // ceiling: an older binary cannot read `ScheduleSet` and refuses the + // journal, instead of restoring without the schedules. + for (id, at_ms) in &self.schedules { + entries.push(JournalEntry::ScheduleSet { + id: id.clone(), + at_ms: *at_ms, + }); + } + let schedules: Option> = (!self.schedules.is_empty()).then(|| { + self.schedules + .iter() + .map(|(id, at_ms)| (id.clone(), *at_ms)) + .collect() + }); + entries.push(JournalEntry::Checkpoint { + sequence: self.sequence, + module_hash, + seed: self.active_seed, + provenance: self.active_module_provenance.clone(), + execution_profile: Some(self.execution_profile), + caps_ceiling, + schedules, + snapshot, + events: self.events.iter().cloned().collect(), + }); + Ok(entries) + } + + /// The world's active (non-revoked) participants. + #[must_use] + pub(crate) fn participants(&self) -> Vec { + self.capabilities + .values() + .filter(|record| !record.revoked) + .map(|record| record.participant.clone()) + .collect() + } + + /// One participant, whether revoked or not. + #[must_use] + pub(crate) fn participant(&self, id: u64) -> Option { + self.capabilities + .get(&id) + .map(|record| record.participant.clone()) + } + + /// Commit a host-authored chat line as participant 0. + /// + /// # Errors + /// + /// Fails when the text is empty, oversized, or entirely sanitized away. + pub(crate) fn system_chat(&mut self, text: &str) -> Result { + ensure!( + text.len() <= self.limits.chat_bytes, + "chat message exceeds {} bytes", + self.limits.chat_bytes + ); + let text = sanitize_chat(text); + ensure!(!text.is_empty(), "chat message must not be empty"); + self.commit(0, WorldEventKind::Chat(text)) + } + + /// Whether a `schedule.at` for `id` may be pended, given the host clock + /// `now_ms`. The error says why; the program sees only `bad_args`. + /// + /// # Errors + /// + /// 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<()> { + crate::world_caps::validate_schedule_id(id)?; + ensure!( + !self.schedules.contains_key(id), + "schedule {id:?} is already pending; cancel it before scheduling it again" + ); + ensure!( + self.schedules.len() < crate::world_caps::MAX_PENDING_SCHEDULES, + "world already has {} pending schedules", + crate::world_caps::MAX_PENDING_SCHEDULES + ); + let horizon = now_ms.saturating_add(crate::world_caps::MAX_SCHEDULE_HORIZON_MS); + ensure!( + at_ms <= horizon, + "schedule {id:?} is more than {} days past the host clock", + crate::world_caps::MAX_SCHEDULE_HORIZON_DAYS + ); + Ok(()) + } + + /// Journal entry for an already-issued capability. + pub(crate) fn issued_entry(&self, participant_id: u64) -> Option { + self.capabilities + .get(&participant_id) + .map(|record| JournalEntry::Issued { + participant: record.participant.clone(), + digest: hex_encode(&record.digest), + scopes: record.scopes.0, + parent: record.parent, + expires_at: record.bounds.expires_at, + uses: record.bounds.uses, + used: record.used, + subject: record.subject.clone(), + }) + } + + /// Latest committed event sequence. + #[must_use] + pub const fn current_sequence(&self) -> u64 { + self.sequence + } + + /// The world's identifier. + #[must_use] + pub fn world_id(&self) -> &str { + &self.world_id + } + + /// The per-world resource requests, independent of current server ceilings. + #[must_use] + pub const fn execution_profile(&self) -> crate::world_limits::WorldExecutionProfile { + self.execution_profile + } + + /// Issue a capability for a participant. Only `JOIN`-scoped capabilities + /// count toward active participant capacity. + pub fn issue_capability( + &mut self, + display_name: &str, + scopes: WorldScopes, + bounds: CapabilityBounds, + ) -> Result<(Participant, JoinCapability)> { + self.mint(display_name, scopes, None, None, bounds) + } + + /// Issue a capability that acts for the account `credential` belongs to. + /// Its scopes may not exceed that account's ceiling. + pub fn issue_for_account( + &mut self, + credential: &str, + scopes: WorldScopes, + bounds: CapabilityBounds, + display_name: &str, + ) -> Result<(Participant, JoinCapability)> { + let account = self + .directory + .account_for(credential) + .context("invalid account credential")?; + ensure!( + self.directory.ceiling(&account).implied().contains(scopes), + "this account may not hold those scopes" + ); + self.mint(display_name, scopes, None, Some(account), bounds) + } + + /// Delegate a capability: a new participant whose scopes are a subset of + /// the delegating capability's, and which is revoked with it. Its expiry + /// may not be later than the delegator's. It carries no use count: each + /// action it takes counts against the host-issued limit above it, if any. + pub fn attenuate( + &mut self, + token: &JoinCapability, + scopes: WorldScopes, + bounds: CapabilityBounds, + display_name: &str, + ) -> Result<(Participant, JoinCapability)> { + self.delegate(token, scopes, bounds, display_name, None) + } + + /// Delegate to a friend of the account this capability acts for. The + /// friend's ceiling must already hold the scopes, and the friendship must + /// still hold each time the capability is used. + pub fn delegate_to_friend( + &mut self, + token: &JoinCapability, + friend: &str, + scopes: WorldScopes, + bounds: CapabilityBounds, + display_name: &str, + ) -> Result<(Participant, JoinCapability)> { + let parent = self.authorize(token, WorldScopes::JOIN)?; + let owner = self + .capabilities + .get(&parent) + .and_then(|record| record.subject.clone()) + .context("only an account's capability can delegate to a friend")?; + ensure!( + self.directory.are_friends(&owner, friend), + "you can only delegate to a friend" + ); + ensure!( + self.directory.ceiling(friend).implied().contains(scopes), + "that friend may not hold those scopes" + ); + self.delegate(token, scopes, bounds, display_name, Some(friend.to_owned())) + } + + pub(crate) fn delegate( + &mut self, + token: &JoinCapability, + scopes: WorldScopes, + bounds: CapabilityBounds, + display_name: &str, + subject: Option, + ) -> Result<(Participant, JoinCapability)> { + let parent = self.authorize(token, WorldScopes::JOIN)?; + let parent_scopes = self + .effective_scopes(parent) + .context("world participant is unavailable")?; + let parent_record = self + .capabilities + .get(&parent) + .context("world participant is unavailable")?; + let scopes = parent_scopes + .attenuate(scopes) + .context("this capability may not delegate those scopes")?; + if let Some(expires_at) = bounds.expires_at { + ensure!( + expires_at > self.clock().now_ms(), + "delegated expiry must be in the future" + ); + ensure!( + parent_record + .bounds + .expires_at + .is_none_or(|limit| expires_at <= limit), + "this capability may not delegate a later expiry" + ); + } + ensure!( + bounds.uses.is_none(), + "a delegated capability carries no use count; the host's limit still applies" + ); + self.mint(display_name, scopes, Some(parent), subject, bounds) + } + + /// What a capability may do right now: its own scopes, held to the ceiling + /// of each account in its chain. A delegation to a friend stops once the + /// friendship ends. + pub(crate) fn effective_scopes(&self, participant_id: u64) -> Option { + self.capabilities.get(&participant_id)?; + let mut scopes = WorldScopes::ALL; + let mut current = Some(participant_id); + while let Some(record) = current.and_then(|id| self.capabilities.get(&id)) { + scopes = scopes.intersect(record.scopes.implied()); + if let Some(subject) = &record.subject { + scopes = scopes.intersect(self.directory.ceiling(subject).implied()); + } + let parent = record.parent.and_then(|id| self.capabilities.get(&id)); + if let Some(subject) = &record.subject + && let Some(parent_subject) = parent.and_then(|p| p.subject.as_ref()) + && subject != parent_subject + && !self.directory.are_friends(parent_subject, subject) + { + return Some(WorldScopes(0)); + } + current = record.parent; + } + Some(scopes) + } + + /// Fewest actions the capability or any ancestor may still take, or `None` + /// if no capability in the chain is limited. + pub(crate) fn uses_left(&self, participant_id: u64) -> Option { + let mut left = None; + let mut current = Some(participant_id); + while let Some(record) = current.and_then(|id| self.capabilities.get(&id)) { + if let Some(limit) = record.bounds.uses { + let remaining = limit.saturating_sub(record.used); + left = Some(left.map_or(remaining, |so_far: u32| so_far.min(remaining))); + } + current = record.parent; + } + left + } + + pub(crate) fn ensure_not_expired(&self, participant_id: u64) -> Result<()> { + 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" + ); + current = record.parent; + } + Ok(()) + } + + pub(crate) fn ensure_uses_left(&self, participant_id: u64) -> Result<()> { + ensure!( + self.uses_left(participant_id).is_none_or(|left| left > 0), + "world capability has no uses left" + ); + Ok(()) + } + + /// Count one committed action against the participant and each ancestor. + pub(crate) fn spend(&mut self, participant_id: u64) { + let mut current = Some(participant_id); + while let Some(record) = current.and_then(|id| self.capabilities.get_mut(&id)) { + record.used = record.used.saturating_add(1); + current = record.parent; + } + } + + pub(crate) fn mint( + &mut self, + display_name: &str, + scopes: WorldScopes, + parent: Option, + subject: Option, + bounds: CapabilityBounds, + ) -> Result<(Participant, JoinCapability)> { + let active = self + .capabilities + .values() + .filter(|record| !record.revoked) + .count(); + ensure!( + active < self.limits.participants, + "world participant limit reached" + ); + ensure!( + scopes.contains(WorldScopes::JOIN), + "world capability must include join scope" + ); + let display_name = sanitize_display_name(display_name); + ensure!( + !display_name.is_empty(), + "participant display name must not be empty" + ); + let id = self.next_participant_id; + self.next_participant_id = self + .next_participant_id + .checked_add(1) + .context("participant ID exhausted")?; + let mut secret = [0_u8; 32]; + rand::rng().fill(&mut secret); + let token = format!("{id}.{}", hex_encode(&secret)); + let digest = token_digest(&token); + let participant = Participant { id, display_name }; + self.capabilities.insert( + id, + CapabilityRecord { + digest, + participant: participant.clone(), + scopes, + parent, + revoked: false, + bounds, + used: 0, + subject, + }, + ); + Ok((participant, JoinCapability(token))) + } + + /// Revoke a capability and every capability delegated from it. Returns + /// the participants newly revoked; empty if none was active. + pub fn revoke_tree(&mut self, participant_id: u64) -> Vec { + let mut revoked = Vec::new(); + let mut pending = vec![participant_id]; + while let Some(id) = pending.pop() { + let Some(record) = self.capabilities.get_mut(&id) else { + continue; + }; + if record.revoked { + continue; + } + record.revoked = true; + revoked.push(id); + pending.extend( + self.capabilities + .values() + .filter(|child| child.parent == Some(id)) + .map(|child| child.participant.id), + ); + } + revoked + } + + /// The world's isolation. + #[must_use] + pub const fn isolation(&self) -> Isolation { + self.isolation + } + + /// The world's sharing and file settings. + #[must_use] + pub const fn policy(&self) -> WorldPolicy { + WorldPolicy { + isolation: self.isolation, + cross_world_write: self.cross_world_write, + cross_world_forced: self.cross_world_forced, + file_scope: self.file_scope, + file_write_override: self.file_write_override, + } + } + + /// The directory of accounts, groups and friends this world is held to. + #[must_use] + pub const fn directory(&self) -> &crate::directory::Directory { + &self.directory + } + + /// The directory of accounts, groups and friends this world is held to. + pub const fn directory_mut(&mut self) -> &mut crate::directory::Directory { + &mut self.directory + } + + /// The directory and the private petnames, borrowed together. + pub const fn directory_and_petnames_mut( + &mut self, + ) -> ( + &mut crate::directory::Directory, + &mut crate::petname::Petnames, + ) { + (&mut self.directory, &mut self.petnames) + } + + /// Replace the petname store, as the world's data directory is opened. + pub fn set_petnames(&mut self, petnames: crate::petname::Petnames) { + self.petnames = petnames; + } + + /// Commit a chat message after validating capability and bounds. + pub fn chat(&mut self, token: &JoinCapability, text: &str) -> Result { + let participant_id = self.authorize(token, WorldScopes::CHAT)?; + self.ensure_uses_left(participant_id)?; + ensure!( + text.len() <= self.limits.chat_bytes, + "chat message exceeds {} bytes", + self.limits.chat_bytes + ); + let text = sanitize_chat(text); + ensure!(!text.is_empty(), "chat message must not be empty"); + let now = self.clock().now_instant(); + self.chat_rates.retain(|_, sent| { + while sent + .front() + .is_some_and(|at| now.duration_since(*at) >= CHAT_RATE_WINDOW) + { + sent.pop_front(); + } + !sent.is_empty() + }); + let current = self.chat_rates.get(&participant_id); + ensure!( + current.is_none_or(|sent| sent.len() < usize::from(CHAT_RATE_BURST)), + "chat rate exceeded; try again later" + ); + let event = self.commit(participant_id, WorldEventKind::Chat(text))?; + self.chat_rates + .entry(participant_id) + .or_default() + .push_back(now); + Ok(event) + } + + /// Commit an opaque game input after validating capability and bounds. + pub fn input(&mut self, token: &JoinCapability, input: &[u8]) -> Result { + let event = self.prepare_input(token, input)?; + self.commit_prepared(event) + } + + pub(crate) fn prepare_input(&self, token: &JoinCapability, input: &[u8]) -> Result { + let participant_id = self.authorize(token, WorldScopes::INPUT)?; + self.ensure_uses_left(participant_id)?; + ensure!( + input.len() <= self.limits.input_bytes, + "world input exceeds {} bytes", + self.limits.input_bytes + ); + ensure!(!input.is_empty(), "world input must not be empty"); + let sequence = self + .sequence + .checked_add(1) + .context("world event sequence exhausted")?; + Ok(WorldEvent { + sequence, + participant_id, + kind: WorldEventKind::Input(input.to_vec()), + }) + } + + pub(crate) fn commit_prepared(&mut self, event: WorldEvent) -> Result { + ensure!( + event.sequence == self.sequence.saturating_add(1), + "prepared world event is stale" + ); + self.sequence = event.sequence; + self.spend(event.participant_id); + self.since_checkpoint = self.since_checkpoint.saturating_add(1); + self.events.push_back(event.clone()); + while self.events.len() > self.limits.retained_events { + self.events.pop_front(); + } + Ok(event) + } + + /// Return the current bounded snapshot after validating join scope. Its + /// events are the viewer's projection: no chat without `chat` or + /// `history`, and no install seeds (#240). + pub fn snapshot(&self, token: &JoinCapability) -> Result { + let participant_id = self.authorize(token, WorldScopes::JOIN)?; + Ok(self.snapshot_unchecked(self.viewer_scopes(participant_id))) + } + + /// What the viewer holding `token` may see of `event`, as it is delivered + /// live. `Err` if the capability no longer joins (revoked, expired, or its + /// chain was cut), so a session can end; `Ok(None)` if the event is not + /// for this viewer. + pub fn project_for( + &self, + token: &JoinCapability, + event: &WorldEvent, + ) -> Result> { + let participant_id = self.authorize(token, WorldScopes::JOIN)?; + Ok(project_event_for(self.viewer_scopes(participant_id), event)) + } + + pub(crate) fn viewer_scopes(&self, participant_id: u64) -> WorldScopes { + self.effective_scopes(participant_id) + .unwrap_or(WorldScopes(0)) + } + + pub(crate) fn viewer(&self, token: &JoinCapability) -> Result { + let id = self.authorize(token, WorldScopes::JOIN)?; + self.capabilities + .get(&id) + .map(|record| record.participant.clone()) + .context("world participant is unavailable") + } + + /// Return retained events newer than `after_sequence`, plus the current + /// cursor. If the cursor fell behind retention, the caller must resnapshot. + /// The events are the viewer's projection (see [`project_event_for`]), so + /// their sequences may skip withheld lines: a caller advances to + /// `current_sequence`, not to the last sequence it was given plus one. + /// Retention and `needs_snapshot` do not depend on the viewer. + pub fn events_after(&self, token: &JoinCapability, after_sequence: u64) -> Result { + let participant_id = self.authorize(token, WorldScopes::JOIN)?; + let scopes = self.viewer_scopes(participant_id); + let oldest = self.oldest_sequence(); + let needs_snapshot = after_sequence.saturating_add(1) < oldest; + let events = if needs_snapshot { + Vec::new() + } else { + self.events + .iter() + .filter(|event| event.sequence > after_sequence) + .filter_map(|event| project_event_for(scopes, event)) + .collect() + }; + Ok(EventPage { + current_sequence: self.sequence, + oldest_retained_sequence: oldest, + needs_snapshot, + events, + }) + } + + pub(crate) fn authorize(&self, token: &JoinCapability, required: WorldScopes) -> Result { + let (participant, _) = token + .expose() + .split_once('.') + .context("malformed world capability")?; + let participant_id = participant + .parse::() + .context("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" + ); + ensure!( + !record.revoked + && self + .effective_scopes(participant_id) + .is_some_and(|scopes| scopes.contains(required)), + "invalid, revoked, or insufficient world capability" + ); + self.ensure_not_expired(participant_id)?; + Ok(participant_id) + } + + pub(crate) fn commit( + &mut self, + participant_id: u64, + kind: WorldEventKind, + ) -> Result { + self.sequence = self + .sequence + .checked_add(1) + .context("world event sequence exhausted")?; + let event = WorldEvent { + sequence: self.sequence, + participant_id, + kind, + }; + self.spend(participant_id); + self.since_checkpoint = self.since_checkpoint.saturating_add(1); + self.events.push_back(event.clone()); + while self.events.len() > self.limits.retained_events { + self.events.pop_front(); + } + Ok(event) + } + + pub(crate) fn oldest_sequence(&self) -> u64 { + self.events + .front() + .map_or_else(|| self.sequence.saturating_add(1), |event| event.sequence) + } + + pub(crate) fn snapshot_unchecked(&self, viewer: WorldScopes) -> WorldSnapshot { + let participants = self + .capabilities + .values() + .filter(|record| !record.revoked && record.scopes.contains(WorldScopes::JOIN)) + .map(|record| record.participant.clone()) + .collect(); + // Take the most recent events that fit the snapshot budget, newest + // first. A snapshot is a baseline, not a complete replay: clients + // adopt its sequence as their cursor. Events the viewer may not see + // are dropped before the budget is spent, so it counts only what the + // snapshot carries. + let mut budget = self.limits.snapshot_bytes; + let mut events: VecDeque = VecDeque::new(); + for event in self + .events + .iter() + .rev() + .filter_map(|event| project_event_for(viewer, event)) + { + let size = serde_json::to_vec(&event).map_or(budget, |encoded| encoded.len()); + if size > budget { + break; + } + budget -= size; + events.push_front(event); + } + let oldest_retained_sequence = events + .front() + .map_or_else(|| self.sequence.saturating_add(1), |event| event.sequence); + WorldSnapshot { + world_id: self.world_id.clone(), + active_module_hash: self.active_module_hash.clone(), + active_module_provenance: self.active_module_provenance.clone(), + current_sequence: self.sequence, + oldest_retained_sequence, + events: events.into_iter().collect(), + participants, + } + } +} diff --git a/pkgs/id/src/world/handle.rs b/pkgs/id/src/world/handle.rs new file mode 100644 index 0000000000..ed0c74468c --- /dev/null +++ b/pkgs/id/src/world/handle.rs @@ -0,0 +1,668 @@ +/// Cloneable, serialized access to a world core. Every request passes through +/// one actor task, which defines the authoritative event order. +#[derive(Clone, Debug)] +pub struct WorldHandle { + commands: mpsc::Sender, + events: broadcast::Sender, + revocations: broadcast::Sender, + records: watch::Receiver<(u64, Arc)>, + view_changed: watch::Receiver, +} + +use super::*; + +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::sync::Arc; + +use anyhow::Result; +use tokio::sync::{broadcast, mpsc, oneshot, watch}; + +use crate::world_caps::CapsReport; + +impl WorldHandle { + /// Spawn a world actor on the current Tokio runtime. + pub fn spawn(core: WorldCore) -> Self { + Self::spawn_with_program(core, Box::::default()) + } + + /// Spawn a world actor with an executable program. Only the actor owns + /// the program instance, so calls are serialized with world mutations. + pub fn spawn_with_program(core: WorldCore, program: Box) -> Self { + Self::spawn_durable(core, program, None) + } + + /// Spawn a world actor that journals every mutation before acknowledging + /// it. `program` must already reflect the journal (see + /// [`WorldCore::restore`]); the actor only appends. + pub fn spawn_durable( + core: WorldCore, + mut program: Box, + journal: Option>, + ) -> Self { + let (commands, receiver) = mpsc::channel(256); + let (events, _) = broadcast::channel(256); + let (revocations, _) = broadcast::channel(256); + let (view_changed_sender, view_changed) = watch::channel(core.sequence); + // Records are recomputed from the (restored) program, so they are a + // pure function of the journal and need no storage of their own here. + let mut program_healthy = true; + let initial = match program_records(program.as_mut()) { + Ok(records) => records.unwrap_or_default(), + Err(error) => { + tracing::error!("world program records failed: {error:#}"); + program_healthy = false; + Records::new() + } + }; + let (records_sender, records) = watch::channel((core.sequence, Arc::new(initial))); + // Schedules the journal left pending that are already due fire late. + let now = core.clock().now_ms(); + let overdue_at_open: BTreeSet = core + .schedules + .iter() + .filter(|(_, at_ms)| **at_ms <= now) + .map(|(id, _)| id.clone()) + .collect(); + let actor = WorldActor { + core, + program, + journal, + storage_failed: false, + program_healthy, + view_failures: 0, + compaction_off: false, + event_sender: events.clone(), + revocation_sender: revocations.clone(), + records_sender, + view_changed: view_changed_sender, + presence: HashMap::new(), + active_subs: BTreeSet::new(), + handled_requests: BTreeSet::new(), + denied_subs: BTreeSet::new(), + ticks: BTreeMap::new(), + overdue_at_open, + acting: None, + auth: crate::directory_auth::DirectoryAuth::default(), + }; + tokio::spawn(actor.run(receiver)); + Self { + commands, + events, + revocations, + records, + view_changed, + } + } + /// The latest `(sequence, records)` published by the world program. + /// Callers must authorize the reader first (see [`Self::participant_id`]). + #[must_use] + pub fn records(&self) -> (u64, Arc) { + let current = self.records.borrow(); + (current.0, Arc::clone(¤t.1)) + } + + /// Watch record changes (coalesced: a slow reader sees the latest set). + #[must_use] + pub fn watch_records(&self) -> watch::Receiver<(u64, Arc)> { + self.records.clone() + } + + /// Subscribe to newly committed world events, as the host committed them: + /// unprojected, with chat and the real install seed. Whatever forwards + /// these to a participant must first pass each through + /// [`WorldHandle::project_event`]. + #[must_use] + pub fn subscribe(&self) -> broadcast::Receiver { + self.events.subscribe() + } + + /// Subscribe to capability revocations. + #[must_use] + pub fn subscribe_revocations(&self) -> broadcast::Receiver { + self.revocations.subscribe() + } + + /// Watch for state changes a rendered view may want to reflect. The value + /// is the world sequence at the change (unchanged for host events). + #[must_use] + pub fn watch_views(&self) -> watch::Receiver { + self.view_changed.clone() + } + + /// Tell the world a participant opened (`true`) or closed (`false`) a + /// session. Drives presence and, while anyone is present, subscribed + /// ticks. + pub async fn presence(&self, participant: u64, joined: bool) { + let _ = self + .commands + .send(WorldCommand::Presence { + participant, + joined, + }) + .await; + } + + /// Grant and revoke capabilities for this world, and return the report. + /// + /// # Errors + /// + /// Fails on unknown capability names or world storage failure. + pub async fn update_caps(&self, grant: Vec, revoke: Vec) -> Result { + let (reply, response) = oneshot::channel(); + self.commands + .send(WorldCommand::UpdateCaps { + grant, + revoke, + reply, + }) + .await + .map_err(|_| anyhow::anyhow!("world actor is closed"))?; + response + .await + .context("world actor dropped caps response")? + } + + /// Replace this world's capability ceiling. It applies immediately to new + /// uses and active subscriptions; it does not rewrite the grants. + /// + /// # Errors + /// + /// Fails on `*`, on unknown names, or on world storage failure. + pub async fn set_caps_ceiling(&self, ceiling: Vec) -> Result { + let (reply, response) = oneshot::channel(); + self.commands + .send(WorldCommand::SetCapsCeiling { ceiling, reply }) + .await + .ok() + .context("world actor is closed")?; + response + .await + .context("world actor dropped caps ceiling response")? + } + + /// Persist this world's requested resource profile. The current program + /// instance is deliberately left untouched. + pub async fn set_execution_profile( + &self, + profile: crate::world_limits::WorldExecutionProfile, + ) -> Result { + let (reply, response) = oneshot::channel(); + self.commands + .send(WorldCommand::SetExecutionProfile { profile, reply }) + .await + .map_err(|_| anyhow::anyhow!("world actor is closed"))?; + response + .await + .context("world actor dropped execution profile response")? + } + + /// Read this world's currently requested resource profile. + pub async fn execution_profile(&self) -> Result { + let (reply, response) = oneshot::channel(); + self.commands + .send(WorldCommand::ExecutionProfileInfo { reply }) + .await + .map_err(|_| anyhow::anyhow!("world actor is closed"))?; + response + .await + .context("world actor dropped execution profile") + } + + /// Change the world's isolation. + /// + /// # Errors + /// + /// Fails with a forbidden refusal unless the authority is an admin or a + /// moderator, or on world storage failure. + pub async fn set_isolation( + &self, + authority: Authority, + isolation: Isolation, + ) -> Result { + let (reply, response) = oneshot::channel(); + self.commands + .send(WorldCommand::SetIsolation { + authority, + isolation, + reply, + }) + .await + .map_err(|_| anyhow::anyhow!("world actor is closed"))?; + response + .await + .context("world actor dropped isolation response")? + } + + /// The world's isolation. + /// + /// # Errors + /// + /// Fails if the world actor is closed. + pub async fn isolation(&self) -> Result { + let (reply, response) = oneshot::channel(); + self.commands + .send(WorldCommand::IsolationInfo { reply }) + .await + .map_err(|_| anyhow::anyhow!("world actor is closed"))?; + response + .await + .context("world actor dropped isolation response") + } + + /// Let other unisolated worlds write here, or stop them. + /// + /// # Errors + /// + /// Fails with a forbidden refusal unless the authority is an admin or a + /// moderator, or if a moderator turns off a forced setting, or on storage failure. + pub async fn set_cross_world_write( + &self, + authority: Authority, + enabled: bool, + ) -> Result { + let (reply, response) = oneshot::channel(); + self.commands + .send(WorldCommand::SetCrossWorldWrite { + authority, + enabled, + reply, + }) + .await + .map_err(|_| anyhow::anyhow!("world actor is closed"))?; + response + .await + .context("world actor dropped cross-world write response")? + } + + /// Force cross-world writes on for an unisolated world. + /// + /// # Errors + /// + /// Fails with a forbidden refusal unless the authority is the admin, or if + /// the world is isolated, or on storage failure. + pub async fn force_cross_world_write(&self, authority: Authority) -> Result { + let (reply, response) = oneshot::channel(); + self.commands + .send(WorldCommand::ForceCrossWorldWrite { authority, reply }) + .await + .map_err(|_| anyhow::anyhow!("world actor is closed"))?; + response + .await + .context("world actor dropped force response")? + } + + /// Set the file scope, and with `write_override` the admin override. + /// + /// # Errors + /// + /// Fails with a forbidden refusal unless the authority is an admin or a + /// moderator, or if a moderator sets the override, or on storage failure. + pub async fn set_file_scope( + &self, + authority: Authority, + scope: FileScope, + write_override: Option, + ) -> Result { + let (reply, response) = oneshot::channel(); + self.commands + .send(WorldCommand::SetFileScope { + authority, + scope, + write_override, + reply, + }) + .await + .map_err(|_| anyhow::anyhow!("world actor is closed"))?; + response + .await + .context("world actor dropped file scope response")? + } + + /// The world's sharing and file settings. + /// + /// # Errors + /// + /// Fails if the world actor is closed. + pub async fn policy(&self) -> Result { + let (reply, response) = oneshot::channel(); + self.commands + .send(WorldCommand::PolicyInfo { reply }) + .await + .map_err(|_| anyhow::anyhow!("world actor is closed"))?; + response + .await + .context("world actor dropped policy response") + } + + /// The world's capability report: grants, what the program wants, and use. + /// + /// # Errors + /// + /// Fails if the world actor is closed. + pub async fn caps_report(&self) -> Result { + let (reply, response) = oneshot::channel(); + self.commands + .send(WorldCommand::CapsInfo { reply }) + .await + .map_err(|_| anyhow::anyhow!("world actor is closed"))?; + response + .await + .context("world actor dropped caps response")? + } + + /// Resolve the participant authorized by a join capability. + pub async fn participant_id(&self, token: JoinCapability) -> Result { + let (reply, response) = oneshot::channel(); + self.commands + .send(WorldCommand::ParticipantId { token, reply }) + .await + .map_err(|_| anyhow::anyhow!("world actor is closed"))?; + response + .await + .context("world actor dropped participant lookup response")? + } + + /// Issue a scoped participant capability. + pub async fn issue( + &self, + name: impl Into, + scopes: WorldScopes, + ) -> Result<(Participant, JoinCapability)> { + self.issue_bounded(name, scopes, CapabilityBounds::default()) + .await + } + + /// Issue a scoped participant capability that stops working at its bounds. + pub async fn issue_bounded( + &self, + name: impl Into, + scopes: WorldScopes, + bounds: CapabilityBounds, + ) -> Result<(Participant, JoinCapability)> { + let (reply, response) = oneshot::channel(); + self.commands + .send(WorldCommand::Issue { + name: name.into(), + scopes, + bounds, + reply, + }) + .await + .map_err(|_| anyhow::anyhow!("world actor is closed"))?; + response + .await + .context("world actor dropped capability response")? + } + + /// Delegate a narrower capability from `token`, which must hold `JOIN`. + pub async fn attenuate( + &self, + token: JoinCapability, + scopes: WorldScopes, + bounds: CapabilityBounds, + name: impl Into, + ) -> Result<(Participant, JoinCapability)> { + let (reply, response) = oneshot::channel(); + self.commands + .send(WorldCommand::Attenuate { + token, + name: name.into(), + scopes, + bounds, + reply, + }) + .await + .map_err(|_| anyhow::anyhow!("world actor is closed"))?; + response + .await + .context("world actor dropped delegation response")? + } + + /// Delegate a narrower capability to a friend of the account `token` + /// acts for. The friendship must still hold when the capability is used. + pub async fn delegate_to_friend( + &self, + token: JoinCapability, + friend: impl Into, + scopes: WorldScopes, + bounds: CapabilityBounds, + name: impl Into, + ) -> Result<(Participant, JoinCapability)> { + let (reply, response) = oneshot::channel(); + self.commands + .send(WorldCommand::DelegateToFriend { + token, + friend: friend.into(), + name: name.into(), + scopes, + bounds, + reply, + }) + .await + .map_err(|_| anyhow::anyhow!("world actor is closed"))?; + response + .await + .context("world actor dropped friend delegation response")? + } + + /// Read or change the directory as the caller. The caller's proof must + /// already be checked by the transport. `outbox` says whether this server + /// can queue what the change sends to other servers. + pub async fn directory( + &self, + caller: crate::directory_auth::Caller, + action: crate::directory_view::DirectoryAction, + outbox: bool, + ) -> Result { + let (reply, response) = oneshot::channel(); + self.commands + .send(WorldCommand::Directory { + caller, + action, + outbox, + reply, + }) + .await + .map_err(|_| anyhow::anyhow!("world actor is closed"))?; + response + .await + .context("world actor dropped directory response")? + } + + /// Apply a change prepared by a remote friend action, once its envelope is queued. + pub async fn apply_directory_entry( + &self, + entry: crate::directory::DirectoryEntry, + ) -> Result<()> { + let (reply, response) = oneshot::channel(); + self.commands + .send(WorldCommand::ApplyDirectory { entry, reply }) + .await + .map_err(|_| anyhow::anyhow!("world actor is closed"))?; + response + .await + .context("world actor dropped directory apply response")? + } + + /// Revoke an active capability and everything delegated from it. + pub async fn revoke(&self, participant_id: u64) -> Result { + let (reply, response) = oneshot::channel(); + self.commands + .send(WorldCommand::Revoke { + participant_id, + reply, + }) + .await + .map_err(|_| anyhow::anyhow!("world actor is closed"))?; + response + .await + .context("world actor dropped revocation response") + } + + /// Submit a bounded chat message. + pub async fn chat(&self, token: JoinCapability, text: impl Into) -> Result { + let (reply, response) = oneshot::channel(); + self.commands + .send(WorldCommand::Chat { + token, + text: text.into(), + reply, + }) + .await + .map_err(|_| anyhow::anyhow!("world actor is closed"))?; + response + .await + .context("world actor dropped chat response")? + } + + /// Submit bounded opaque game input. + pub async fn input(&self, token: JoinCapability, input: Vec) -> Result { + let (reply, response) = oneshot::channel(); + self.commands + .send(WorldCommand::Input { + token, + input, + reply, + }) + .await + .map_err(|_| anyhow::anyhow!("world actor is closed"))?; + response + .await + .context("world actor dropped input response")? + } + + /// Read a world snapshot. + pub async fn snapshot(&self, token: JoinCapability) -> Result { + let (reply, response) = oneshot::channel(); + self.commands + .send(WorldCommand::Snapshot { token, reply }) + .await + .map_err(|_| anyhow::anyhow!("world actor is closed"))?; + response + .await + .context("world actor dropped snapshot response")? + } + + /// What the holder of `token` may see of a live `event` (from + /// [`WorldHandle::subscribe`]): `Ok(None)` if the event is not for this + /// viewer, `Err` if the capability no longer joins. Judged by the + /// viewer's scopes at this moment. + pub async fn project_event( + &self, + token: JoinCapability, + event: WorldEvent, + ) -> Result> { + let (reply, response) = oneshot::channel(); + self.commands + .send(WorldCommand::ProjectEvent { + token, + event, + reply, + }) + .await + .map_err(|_| anyhow::anyhow!("world actor is closed"))?; + response + .await + .context("world actor dropped projection response")? + } + + /// Catch up from an event cursor, or learn that a new snapshot is needed. + pub async fn events_after(&self, token: JoinCapability, sequence: u64) -> Result { + let (reply, response) = oneshot::channel(); + self.commands + .send(WorldCommand::EventsAfter { + token, + sequence, + reply, + }) + .await + .map_err(|_| anyhow::anyhow!("world actor is closed"))?; + response + .await + .context("world actor dropped event response")? + } + + /// Render the current world for an authorized participant. A chat-only + /// world returns `None`. + pub async fn view(&self, token: JoinCapability) -> Result> { + let (reply, response) = oneshot::channel(); + self.commands + .send(WorldCommand::View { token, reply }) + .await + .map_err(|_| anyhow::anyhow!("world actor is closed"))?; + response + .await + .context("world actor dropped view response")? + } + + /// Render for one viewer at a viewport. Programs that cannot reflow fall + /// back to their fixed view, and rendering never advances the sequence. + pub async fn view_at( + &self, + token: JoinCapability, + width: u16, + height: u16, + ) -> Result> { + let (reply, response) = oneshot::channel(); + self.commands + .send(WorldCommand::ViewAt { + token, + width, + height, + reply, + }) + .await + .map_err(|_| anyhow::anyhow!("world actor is closed"))?; + response + .await + .context("world actor dropped layout response")? + } + + /// Atomically replace the active program and sequence a host-authored + /// module-installed event. The new program is used after this command. + pub async fn install_program( + &self, + module_hash: String, + seed: u64, + program: Box, + ) -> Result { + self.install_program_with_provenance(module_hash, seed, None, program) + .await + } + + /// As [`Self::install_program`], preserving server-observed origin metadata. + pub async fn install_program_with_provenance( + &self, + module_hash: String, + seed: u64, + provenance: Option, + program: Box, + ) -> Result { + let (reply, response) = oneshot::channel(); + self.commands + .send(WorldCommand::InstallProgram { + module_hash, + seed, + provenance, + program, + reply, + }) + .await + .map_err(|_| anyhow::anyhow!("world actor is closed"))?; + response + .await + .context("world actor dropped install response")? + } + + /// Stop the actor after processing all commands queued before shutdown. + pub async fn shutdown(&self) -> Result<()> { + let (reply, response) = oneshot::channel(); + self.commands + .send(WorldCommand::Shutdown { reply }) + .await + .map_err(|_| anyhow::anyhow!("world actor is closed"))?; + response + .await + .context("world actor dropped shutdown response") + } +} diff --git a/pkgs/id/src/world/mod.rs b/pkgs/id/src/world/mod.rs new file mode 100644 index 0000000000..33fddf14ee --- /dev/null +++ b/pkgs/id/src/world/mod.rs @@ -0,0 +1,888 @@ +//! Transport-independent, authoritative in-memory world core. +//! +//! A transport should place one `WorldActor` behind its world ID and pass +//! messages to it serially. This module does not open sockets or persist world +//! state. Capability tokens are returned only at issuance and retained only as +//! SHA-256 digests for revocation and membership checks. +//! +//! ## What a grant carries, and what stays local +//! +//! A participant capability is a bearer secret. Its digest, scopes, expiry, +//! parent and subject are the grant, and the journal records them. Nothing +//! about a participant grant is signed here; the signed records are the +//! directory's artifacts (friendships and their removals). A grant carries no +//! use count. A delegation narrows scopes and may set an expiry, nothing else. +//! The host alone enforces a use limit, and only on a capability it issued (an +//! invite or an account grant), by counting actions in its own journal. Those +//! counts are local to the hosting node and need not converge across partitions. + +use std::collections::{BTreeMap, BTreeSet, VecDeque}; + +use anyhow::{Context, Result, bail, ensure}; +use rand::RngExt as _; +use serde::{Deserialize, Serialize}; +use subtle::ConstantTimeEq as _; + +/// Re-exported so `crate::world::Isolation` keeps working: the type now lives +/// in [`crate::groups::worlds`] so the crate builds without this feature. +pub use crate::groups::worlds::Isolation; + +/// Re-exported so `crate::world::unix_ms` keeps working: the function now +/// lives in [`crate::time`] so the crate builds without this feature. +pub(crate) use crate::time::unix_ms; +mod actor; +mod clock; +mod core; +mod handle; +mod util; + +#[cfg(test)] +mod tests; + +pub(crate) use actor::{WorldActor, WorldCommand}; +pub use clock::{Clock, ManualClock, SystemClock}; +pub use core::WorldCore; +pub use handle::WorldHandle; +pub use util::{EventPage, hex_encode, publish_records}; +pub(crate) use util::{ + constant_time_eq, hex_decode_32, sanitize_chat, sanitize_display_name, token_digest, +}; + +/// A chat participant may send at most this many lines during the rolling window. +pub(crate) const CHAT_RATE_BURST: u8 = 50; +pub(crate) const CHAT_RATE_WINDOW: std::time::Duration = std::time::Duration::from_secs(10); + +/// Bounded limits for one world. +#[derive(Clone, Debug)] +pub struct WorldLimits { + /// Maximum number of active capabilities in this world. + pub participants: usize, + /// Maximum UTF-8 chat message length in bytes. + pub chat_bytes: usize, + /// Maximum opaque game input size in bytes. + pub input_bytes: usize, + /// Number of recent events kept for reconnect catch-up. + pub retained_events: usize, + /// Maximum presentation text returned by a world program, in bytes. + pub presentation_bytes: usize, + /// Largest snapshot frame, in bytes. A snapshot carries only the most + /// recent events that fit; a client rebases its cursor on the snapshot, + /// it does not need every retained event. + pub snapshot_bytes: usize, + /// Trim the journal behind a program snapshot once this many events were + /// committed since the last one. `0` disables checkpointing. + pub checkpoint_every: u64, + /// Slowest tick a program may subscribe to, in milliseconds. + pub min_tick_ms: u64, + /// Whether a world's policy grants a capability on its first use. + pub grant_on_use: bool, + /// Capabilities the server allows any world to use. Runtime configuration, + /// not journaled; a world's own ceiling and grants only narrow it. + pub server_caps: BTreeSet, +} + +impl Default for WorldLimits { + fn default() -> Self { + Self { + participants: 256, + chat_bytes: 2048, + input_bytes: 16 * 1024, + retained_events: 1024, + presentation_bytes: 8192, + snapshot_bytes: 512 * 1024, + checkpoint_every: 1000, + min_tick_ms: 1000, + grant_on_use: false, + server_caps: crate::world_caps::catalog_names(), + } + } +} + +/// Permission scopes granted by a world capability. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct WorldScopes(u8); + +impl WorldScopes { + /// Join the world and receive snapshots/events. + pub const JOIN: Self = Self(0b001); + /// Send chat messages. + pub const CHAT: Self = Self(0b010); + /// Submit game input events. + pub const INPUT: Self = Self(0b100); + /// Mint capabilities with a subset of this set. + pub const DELEGATE: Self = Self(0b1000); + /// Read chat lines without being able to send them. `CHAT` also reads. + pub const HISTORY: Self = Self(0b1_0000); + /// Default guest permissions. + pub const GUEST: Self = Self(Self::JOIN.0 | Self::CHAT.0 | Self::INPUT.0); + /// Every scope. + pub const ALL: Self = Self(Self::GUEST.0 | Self::DELEGATE.0 | Self::HISTORY.0); + + /// Role presets used by `id world invite --role`. `spectator` joins and + /// sees the world but not the chat; `observer` also reads chat without + /// sending it; `player` submits input; `guest` (the default) also chats; + /// `delegator` additionally mints narrower capabilities for others. + /// + /// The names are stable; the mapping to scopes is part of the protocol. + #[must_use] + pub fn from_role(name: &str) -> Option { + match name { + "spectator" => Some(Self::JOIN), + "observer" => Some(Self(Self::JOIN.0 | Self::HISTORY.0)), + "player" => Some(Self(Self::JOIN.0 | Self::INPUT.0)), + "guest" => Some(Self::GUEST), + "delegator" => Some(Self(Self::GUEST.0 | Self::DELEGATE.0)), + _ => None, + } + } + + /// The names accepted by [`Self::from_role`]. + pub const ROLES: &'static [&'static str] = + &["spectator", "observer", "player", "guest", "delegator"]; + + /// Raw scope bits, as journaled. + #[must_use] + pub const fn bits(self) -> u8 { + self.0 + } + + /// Scopes from raw bits; `None` if any bit names no scope. + #[must_use] + pub const fn from_bits(bits: u8) -> Option { + if bits & !Self::ALL.0 == 0 { + Some(Self(bits)) + } else { + None + } + } + + /// Every scope either set includes. + #[must_use] + pub const fn union(self, other: Self) -> Self { + Self(self.0 | other.0) + } + + /// Only the scopes both sets include. + #[must_use] + pub const fn intersect(self, other: Self) -> Self { + Self(self.0 & other.0) + } + + /// Whether this scope set includes `required`. + #[must_use] + pub const fn contains(self, required: Self) -> bool { + self.0 & required.0 == required.0 + } + + /// This set with the scopes it includes by implication: `CHAT` reads, so + /// it carries `HISTORY`. Apply it wherever sets are compared as sets. + #[must_use] + pub const fn implied(self) -> Self { + if self.contains(Self::CHAT) { + Self(self.0 | Self::HISTORY.0) + } else { + self + } + } + + /// Whether a participant with this set may see chat lines. + #[must_use] + pub const fn reads_chat(self) -> bool { + self.0 & (Self::CHAT.0 | Self::HISTORY.0) != 0 + } + + /// The scopes a delegate of this set may hold: a subset that keeps `JOIN`. + /// `None` unless this set includes `DELEGATE` and `requested` is a subset. + /// A set with `CHAT` may delegate `HISTORY`, which `CHAT` includes. + #[must_use] + pub const fn attenuate(self, requested: Self) -> Option { + if self.contains(Self::DELEGATE) + && requested.contains(Self::JOIN) + && self.implied().contains(requested) + { + Some(requested) + } else { + None + } + } + + /// Whether a participant with this set may cause the effect `cap`. Every + /// connected participant may read; `chat.say` also needs `CHAT`. + #[must_use] + pub fn allows_effect(self, cap: &str) -> bool { + match cap { + "chat.say" => self.contains(Self::CHAT), + // Reading chat needs only the right to read it (`CHAT` or + // `HISTORY`), the same rule the event stream applies. + "chat.history" => self.reads_chat(), + _ => self.contains(Self::JOIN), + } + } + + /// Scopes named on the wire (`join`, `chat`, `history`, `input`, + /// `delegate`), or `None` if a name is unknown. + #[must_use] + pub fn from_names<'a>(names: impl IntoIterator) -> Option { + names.into_iter().try_fold(Self(0), |scopes, name| { + let bit = match name { + "join" => Self::JOIN, + "chat" => Self::CHAT, + "history" => Self::HISTORY, + "input" => Self::INPUT, + "delegate" => Self::DELEGATE, + _ => return None, + }; + Some(Self(scopes.0 | bit.0)) + }) + } +} + +/// Bearer secret that grants access to one world. Never serialize it into a snapshot. +#[derive(Clone, PartialEq, Eq)] +pub struct JoinCapability(String); + +impl std::fmt::Debug for JoinCapability { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("JoinCapability([REDACTED])") + } +} + +impl JoinCapability { + /// Construct from an untrusted wire token; it is authorized only by its + /// owning [`WorldCore`] or [`WorldHandle`]. + #[must_use] + pub const fn from_wire(token: String) -> Self { + Self(token) + } + + /// Expose the token for a deliberate invitation/transport response. + #[must_use] + pub fn expose(&self) -> &str { + &self.0 + } +} + +/// Public participant summary; it contains no capability material. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Participant { + /// Opaque server-assigned participant identifier. + pub id: u64, + /// Caller-provided display name, sanitized and bounded at issue time. + pub display_name: String, +} + +/// Versioned event committed by the world authority. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct WorldEvent { + /// Monotonic event sequence, starting at one. + pub sequence: u64, + /// Server-assigned participant that caused the event. + pub participant_id: u64, + /// Event payload. + pub kind: WorldEventKind, +} + +/// Participant-originated event data. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", content = "data", rename_all = "snake_case")] +pub enum WorldEventKind { + /// Plain text message, UTF-8 and control-character sanitized. + Chat(String), + /// Opaque input for a future game/world module. + Input(Vec), + /// An event the host originated for the program: capability results, + /// ticks, presence. Delivered with `participant_id` 0; never sequenced, + /// never broadcast to sessions. + System { + /// The event's JSON. + event: String, + }, + /// A world admin installed a new program. `participant_id` is zero for + /// this host-authored event. + ProgramInstalled { + /// Iroh BLAKE3 hash of the newly active module artifact. + module_hash: String, + /// Seed passed to the program's `init`; with the module and the + /// inputs after this event it reproduces the program state exactly. + /// Journal/admin only: join projections redact it to zero (#240). + #[serde(default)] + seed: u64, + /// Server-observed origin metadata. Absent on older journal entries. + #[serde(default, skip_serializing_if = "Option::is_none")] + provenance: Option, + }, +} + +/// How the active module artifact entered the world. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "origin", content = "build", rename_all = "snake_case")] +pub enum ModuleProvenance { + /// A raw module artifact was installed; no compiler identity is asserted. + Artifact, + /// The server observed a successful source build. These hashes identify + /// inputs; they are not a signature or a trust attestation. + SourceBuild(SourceBuildProvenance), +} + +/// Bounded, deterministic metadata observed for one source compilation. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct SourceBuildProvenance { + /// Provenance record schema, independent of the world journal version. + pub schema_version: u8, + /// Domain-separated BLAKE3 digest of the compiler executable bytes. + pub compiler_blake3: String, + /// BLAKE3 digest of the platform tree, including relative paths. + pub platform_blake3: String, + /// BLAKE3 digest of the submitted source filenames and contents. + pub source_blake3: String, + /// Compiler target (`wasm32` or `x64musl`). + pub target: String, + /// Stable compiler arguments, excluding the temporary output path. + pub arguments: Vec, +} + +/// Which paths a world's files may name. +/// +/// No world file capability exists yet; this is the policy one must check. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum FileScope { + /// Only the world's own sandbox root. + #[default] + Confined, + /// Any path. + Unrestricted, +} + +/// Whether a file access reads or writes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FileMode { + /// Reading a file. + Read, + /// Creating, changing or deleting a file. + Write, +} + +/// A world's sharing and file settings, read in one step. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +pub struct WorldPolicy { + /// Whether other worlds may read this one. + pub isolation: Isolation, + /// Whether other unisolated worlds may write here. + pub cross_world_write: bool, + /// Whether an admin forced `cross_world_write` on, so a moderator cannot turn it off. + pub cross_world_forced: bool, + /// Which paths the world's files may name. + pub file_scope: FileScope, + /// Whether the admin let an isolated world write files. + pub file_write_override: bool, +} + +impl WorldPolicy { + /// Whether a file access is allowed. Isolated worlds only read unless the + /// admin override is set; the scope then decides which paths. + #[must_use] + pub const fn file_allowed(self, mode: FileMode, inside_root: bool) -> bool { + let in_scope = match self.file_scope { + FileScope::Confined => inside_root, + FileScope::Unrestricted => true, + }; + let writable = match mode { + FileMode::Read => true, + FileMode::Write => { + matches!(self.isolation, Isolation::Unisolated) || self.file_write_override + } + }; + in_scope && writable + } +} + +/// Who asks for a change only an admin or a moderator may make. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Authority { + /// The process admin token, already checked by the transport. + Admin, + /// A signed request made with this public key, as lower-case hex. + Signed(String), +} + +/// One durable fact about a world, in commit order. +/// +/// Capability secrets are never journaled, only their SHA-256 digests, so a +/// leaked journal cannot be used to join. Replaying a journal rebuilds the +/// participants, the event sequence, and (with the module bytes) the program. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "entry", rename_all = "snake_case")] +pub enum JournalEntry { + /// First entry of every journal. + Created { + /// World this journal belongs to. + world_id: String, + /// Journal format version. + version: u32, + }, + /// A capability was issued. + Issued { + /// The new participant. + participant: Participant, + /// Hex SHA-256 of the bearer capability. + digest: String, + /// Granted scopes (bit set). + scopes: u8, + /// The capability this one was delegated from, if any. + #[serde(default, skip_serializing_if = "Option::is_none")] + parent: Option, + /// Unix milliseconds at which the capability stops working. + #[serde(default, skip_serializing_if = "Option::is_none")] + expires_at: Option, + /// Committed chat and input actions the capability may take. Host-local: + /// only a capability the host issued has one, never a delegation. + #[serde(default, skip_serializing_if = "Option::is_none")] + uses: Option, + /// Actions already taken, written at checkpoint so counts survive compaction. + /// Host-local, like `uses`. + #[serde(default)] + used: u32, + /// Account the capability acts for; its ceiling and friendships bound it. + #[serde(default, skip_serializing_if = "Option::is_none")] + subject: Option, + }, + /// A capability was revoked, with every capability delegated from it. + /// Replay revokes the same tree. + Revoked { + /// Participant whose capability was revoked. + participant_id: u64, + }, + /// A sequenced event was committed. + Committed { + /// The event. + event: WorldEvent, + }, + /// A host event delivered to the program (capability result, tick, + /// presence). Delivered with sequence 0; the program saw it, so replay + /// must too. + System { + /// The event as it was delivered. + event: WorldEvent, + }, + /// The world's granted capability set, written whole on every change. + CapsGranted { + /// Capability names. + granted: Vec, + }, + /// The world's capability ceiling, written whole on every change. Absent + /// means the whole catalog. Checkpoints carry it in `caps_ceiling`. + CapsCeiling { + /// Capability names the world allows. + ceiling: Vec, + }, + /// The world's requested execution profile. Limits are resolved against + /// the current server hard ceilings when a program instance is created. + ExecutionProfile { + /// Per-world resource requests; omitted fields inherit server limits. + profile: crate::world_limits::WorldExecutionProfile, + }, + /// The world's isolation, written whole on every change. Absent means + /// [`Isolation::Isolated`]. + Isolation { + /// The new isolation. + isolation: Isolation, + }, + /// Whether other unisolated worlds may write here, set by a moderator or + /// the admin. `enabled: false` also clears a force. Absent means off. + CrossWorldWrite { + /// The new setting. + enabled: bool, + }, + /// The admin forced cross-world writes on. Absent means not forced. + CrossWorldWriteForced, + /// The world's file scope, written whole on every change. Absent means confined. + FileScope { + /// The new scope. + scope: FileScope, + }, + /// Whether the admin let an isolated world write files. Absent means off. + FileWriteOverride { + /// The new setting. + enabled: bool, + }, + /// A `schedule.at` request was accepted: `id` fires once, at `at_ms` (unix + /// milliseconds). Written before the request's result is delivered. + ScheduleSet { + /// The schedule's id, unique among pending schedules. + id: String, + /// When it fires, in unix milliseconds. + at_ms: u64, + }, + /// A pending schedule was cancelled before it fired. + ScheduleCancelled { + /// The cancelled schedule's id. + id: String, + }, + /// A pending schedule fired. It follows the fire's `System` entry, which + /// the program accepted first, so the schedule is consumed only once its + /// delivery is durable. + ScheduleFired { + /// The fired schedule's id. + id: String, + }, + /// The world as of `sequence`, standing in for every event up to it. Only + /// ever written by compaction, directly after the participant entries. + Checkpoint { + /// Sequence of the last event the checkpoint covers. + sequence: u64, + /// Active program. + module_hash: String, + /// Seed the program was initialized with. + seed: u64, + /// Provenance of the active module, if it was recorded. + #[serde(default, skip_serializing_if = "Option::is_none")] + provenance: Option, + /// Requested resource profile. Absent in older checkpoints. + #[serde(default, skip_serializing_if = "Option::is_none")] + execution_profile: Option, + /// The world's capability ceiling. Absent in older checkpoints, and + /// when it is the whole catalog. + #[serde(default, skip_serializing_if = "Option::is_none")] + caps_ceiling: Option>, + /// Pending schedules as `(id, at_ms)`. Absent when none are pending, + /// and it must match the `ScheduleSet` entries before it. + #[serde(default, skip_serializing_if = "Option::is_none")] + schedules: Option>, + /// The program's own serialization of its state. + snapshot: String, + /// Recent events kept for reconnect catch-up. + events: Vec, + }, +} + +/// Current [`JournalEntry::Created`] version. +pub const JOURNAL_VERSION: u32 = 1; + +/// Durable, append-only record of a world's history. +/// +/// The actor calls `append` before acknowledging or broadcasting a mutation. +/// If `append` fails, the world turns read-only: acknowledged history must +/// never get ahead of durable history. +pub trait WorldJournal: Send + 'static { + /// Durably append one entry. + /// + /// # Errors + /// + /// Any I/O failure; the actor then refuses further mutations. + fn append(&mut self, entry: &JournalEntry) -> Result<()>; + + /// Atomically replace the whole journal with `entries` (a header, the + /// participants and a [`JournalEntry::Checkpoint`]). Either the old or + /// the new journal survives a crash, never a mixture. + /// + /// # Errors + /// + /// Journals that cannot compact (the default), or any I/O failure. After + /// an error the journal must still be a complete record of the world. + fn compact(&mut self, _entries: &[JournalEntry]) -> Result<()> { + bail!("this journal cannot be compacted") + } +} + +/// The program a journal says was running, and where to resume it from. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RestoredProgram { + /// Content hash of the module. + pub module_hash: String, + /// Seed it was initialized with. + pub seed: u64, + /// State to restore before replaying, if the journal was compacted behind + /// a checkpoint; otherwise the program starts from `init(seed)`. + pub snapshot: Option, + /// Server-observed module origin, if this journal version recorded it. + pub provenance: Option, +} + +/// A world rebuilt from its journal, before its program is re-instantiated. +#[derive(Debug)] +pub struct RestoredWorld { + /// Participants, sequence and retained events as of the last entry. + pub core: WorldCore, + /// The last installed program, if any. + pub program: Option, + /// Inputs committed after the install or checkpoint, in order, to replay + /// through it. + pub replay: Vec, +} + +/// The profile requested by the world admin and when it takes effect. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ExecutionProfileUpdate { + /// Requested profile; this is not necessarily the active instance's limits. + pub requested: crate::world_limits::WorldExecutionProfile, + /// True when a program is currently running with its previously resolved limits. + pub applies_on_next_program_install_or_process_restart: bool, +} + +/// Structured records a program publishes: key to JSON value, key-ordered. +pub type Records = BTreeMap; + +pub(crate) fn presence_event(participant: u64, name: &str, joined: bool) -> String { + serde_json::json!({ + "cap": "players", + "event": if joined { "joined" } else { "left" }, + "participant": {"id": participant, "name": name}, + }) + .to_string() +} + +pub(crate) fn presence_change(text: &str) -> Option<(u64, bool)> { + let value: serde_json::Value = serde_json::from_str(text).ok()?; + if value.get("cap")?.as_str()? != "players" { + return None; + } + let joined = match value.get("event")?.as_str()? { + "joined" => true, + "left" => false, + _ => return None, + }; + Some((value.get("participant")?.get("id")?.as_u64()?, joined)) +} + +/// The host event a program receives when schedule `id` fires. `late` is set +/// only for a schedule the journal left overdue when the world reopened. +pub(crate) fn schedule_fired_event(id: &str, late: bool) -> String { + let mut event = serde_json::json!({"cap": "schedule", "event": "fired", "id": id}); + if late { + event["late"] = serde_json::Value::Bool(true); + } + event.to_string() +} + +/// When the earliest pending schedule is due, as a monotonic deadline. Nothing +/// waits while the program cannot take a fire (`deliverable` is false): a due +/// schedule that cannot be delivered would otherwise wake the loop without end. +/// +/// The deadline is anchored to `now_instant` (the injected clock's monotonic +/// face), so a manual clock advancing `now_ms` past a schedule also advances +/// this deadline. +pub(crate) fn next_schedule_wake( + schedules: &BTreeMap, + now_ms: u64, + now_instant: std::time::Instant, + deliverable: bool, +) -> Option { + if !deliverable { + return None; + } + let earliest = schedules.values().min().copied()?; + let wait = std::time::Duration::from_millis(earliest.saturating_sub(now_ms)); + Some(now_instant + wait) +} + +/// The newest `count` chat lines in `events`, oldest first, each carrying its +/// sequence, participant id, and text. The retained-events buffer is itself +/// bounded by the world's limits, so a request can never see unbounded history. +pub(crate) fn chat_history(events: &VecDeque, count: usize) -> Vec { + let mut lines: Vec = Vec::new(); + for event in events.iter().rev() { + if lines.len() >= count { + break; + } + if let WorldEventKind::Chat(text) = &event.kind { + lines.push(serde_json::json!({ + "sequence": event.sequence, + "participant": event.participant_id, + "text": text, + })); + } + } + lines.reverse(); + lines +} + +/// Most records one world may publish. +pub const MAX_RECORDS: usize = 4096; +/// Longest record key, in bytes. +pub const MAX_RECORD_KEY_BYTES: usize = 256; +/// Largest single record value (serialized JSON), in bytes. +pub const MAX_RECORD_VALUE_BYTES: usize = 8 * 1024; + +/// Parse and bound a program's records output. Keys must be non-empty, +/// at most [`MAX_RECORD_KEY_BYTES`], and free of control characters (the +/// storage layer uses `\0` as a key terminator). +/// +/// # Errors +/// +/// Anything that is not a bounded JSON object of valid keys. +pub fn parse_records(text: &str) -> Result { + let records: Records = + serde_json::from_str(text).context("world records must be a JSON object")?; + ensure!( + records.len() <= MAX_RECORDS, + "world publishes {} records; the limit is {MAX_RECORDS}", + records.len() + ); + for (key, value) in &records { + ensure!( + !key.is_empty() && key.len() <= MAX_RECORD_KEY_BYTES, + "record key must be 1..={MAX_RECORD_KEY_BYTES} bytes" + ); + ensure!( + !key.chars().any(char::is_control), + "record key {key:?} contains a control character" + ); + let size = serde_json::to_vec(value).map_or(usize::MAX, |v| v.len()); + ensure!( + size <= MAX_RECORD_VALUE_BYTES, + "record {key:?} is {size} bytes; the limit is {MAX_RECORD_VALUE_BYTES}" + ); + } + Ok(records) +} + +/// Records of `program`, validated; `Ok(None)` when it keeps none. +pub(crate) fn program_records(program: &mut dyn WorldProgram) -> Result> { + program + .records()? + .map(|text| parse_records(&text)) + .transpose() +} + +/// Behavior supplied by the running world program. +/// +/// Implementations execute inside the actor's serial command loop. They must +/// not perform network or filesystem I/O. An error from `update` rejects the +/// candidate input before it is committed to the event log. An error from +/// `view` or `layout` does not poison the world: the host renders an error +/// screen naming the failing call, keeps the program's state, and retries on +/// the next event (see F11.17). +pub trait WorldProgram: Send + 'static { + /// Apply an opaque participant input. Chat is managed by the host and is + /// not passed to the game program. + fn update(&mut self, _event: &WorldEvent) -> Result<()> { + Ok(()) + } + + /// Return this participant's presentation, or `None` for a chat-only + /// world. The presentation must be UTF-8 and fit `presentation_bytes`. + fn view(&mut self, _viewer: &Participant) -> Result> { + Ok(None) + } + + /// Return this participant's presentation laid out for a `width` by + /// `height` viewport. Defaults to [`Self::view`]; a program that can reflow + /// overrides it. Rendering must not change state. + fn layout( + &mut self, + viewer: &Participant, + _width: u16, + _height: u16, + ) -> Result> { + self.view(viewer) + } + + /// Structured records projected from the program state: a JSON object + /// mapping record keys to JSON values, or `None` if the program keeps no + /// records. Must be a pure function of state (it is recomputed on replay). + fn records(&mut self) -> Result> { + Ok(None) + } + + /// The program's state as text that [`crate::world_store`] can restore it + /// from, or `None` if it cannot snapshot (its journal then keeps growing). + /// An implementation must only return a snapshot it has verified restores + /// faithfully: the journal is trimmed behind it. + fn snapshot(&mut self) -> Result> { + Ok(None) + } + + /// What the program wants from the server right now (see + /// [`crate::world_caps`]), or `None` if it makes no use of capabilities. + /// Must be a pure function of state: the host re-reads it after every + /// change and after a restart. + fn wants(&mut self) -> Result> { + Ok(None) + } +} + +#[derive(Debug, Default)] +pub(crate) struct EmptyWorldProgram; + +impl WorldProgram for EmptyWorldProgram {} + +/// Snapshot returned on join or reconnect. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct WorldSnapshot { + /// Stable world identifier. + pub world_id: String, + /// Content hash of the active program, if this world executes one. + pub active_module_hash: Option, + /// Provenance for the active module, when recorded. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub active_module_provenance: Option, + /// Latest committed sequence at snapshot time. + pub current_sequence: u64, + /// Earliest event sequence present in this snapshot, or the current + /// sequence + 1 when it carries no events. + pub oldest_retained_sequence: u64, + /// Recent events, bounded by [`WorldLimits::retained_events`] and + /// [`WorldLimits::snapshot_bytes`] (the newest that fit). + pub events: Vec, + /// Public participant list. + pub participants: Vec, +} + +/// The one projection of an event onto a viewer holding `scopes`. +/// +/// Every path that hands an event to a participant — the snapshot, catch-up +/// pages and the live stream — goes through it. +/// +/// - A chat line is `None` unless `scopes` may read chat (`CHAT` or +/// `HISTORY`): a join-only participant sees the world, not the talk. +/// - A `ProgramInstalled` event keeps its module hash — joiners need it to +/// fetch the module — but its install seed is zeroed (#240), because a +/// program whose hidden state derives from `init(seed)` must not leak that +/// state to every participant. +/// - Anything else is returned as is. +/// +/// The journal, the core's retained events and the admin paths keep the real +/// events; replay that needs the seed uses the seed the admin installed with, +/// through the journal/admin path. +#[must_use] +pub fn project_event_for(scopes: WorldScopes, event: &WorldEvent) -> Option { + match &event.kind { + WorldEventKind::Chat(_) if !scopes.reads_chat() => None, + WorldEventKind::ProgramInstalled { .. } => { + // Mutate in place so every other field, including the observed + // build provenance, is kept as it is. + let mut shown = event.clone(); + if let WorldEventKind::ProgramInstalled { seed, .. } = &mut shown.kind { + *seed = 0; + } + Some(shown) + } + _ => Some(event.clone()), + } +} + +/// Limits on what a capability may do before it stops working. +/// +/// Only the host sets `uses`, on a capability it issues. A delegation may set +/// `expires_at` and never `uses` (see [`WorldCore::attenuate`]). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct CapabilityBounds { + /// Unix milliseconds at which the capability stops working. + pub expires_at: Option, + /// Committed chat and input actions the capability may take. Enforced by + /// the host alone, from its own journal. + pub uses: Option, +} + +#[derive(Clone, Debug)] +pub(crate) struct CapabilityRecord { + digest: [u8; 32], + participant: Participant, + scopes: WorldScopes, + parent: Option, + revoked: bool, + bounds: CapabilityBounds, + used: u32, + subject: Option, +} diff --git a/pkgs/id/src/world/tests.rs b/pkgs/id/src/world/tests.rs new file mode 100644 index 0000000000..2b298e655e --- /dev/null +++ b/pkgs/id/src/world/tests.rs @@ -0,0 +1,3845 @@ +#[cfg(test)] +use crate::world::*; +use std::sync::Arc; + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + + fn world(retained_events: usize) -> WorldCore { + WorldCore::new( + "test-world", + WorldLimits { + retained_events, + ..WorldLimits::default() + }, + ) + .unwrap() + } + + fn join(core: &mut WorldCore, name: &str) -> (Participant, JoinCapability) { + core.issue_capability(name, WorldScopes::GUEST, CapabilityBounds::default()) + .unwrap() + } + + fn sample_source_provenance() -> ModuleProvenance { + ModuleProvenance::SourceBuild(SourceBuildProvenance { + schema_version: 1, + compiler_blake3: "compiler".to_owned(), + platform_blake3: "platform".to_owned(), + source_blake3: "source".to_owned(), + target: "wasm32".to_owned(), + arguments: vec!["build".to_owned(), "main.roc".to_owned()], + }) + } + + #[test] + fn provenance_is_optional_and_old_install_events_keep_their_wire_shape() { + let old = serde_json::json!({ + "sequence": 1, + "participant_id": 0, + "kind": { "kind": "program_installed", "data": { "module_hash": "h", "seed": 3 } } + }); + let parsed: WorldEvent = serde_json::from_value(old.clone()).unwrap(); + assert!(matches!( + parsed.kind, + WorldEventKind::ProgramInstalled { + provenance: None, + .. + } + )); + assert_eq!(serde_json::to_value(parsed).unwrap(), old); + + let event = WorldEvent { + sequence: 1, + participant_id: 0, + kind: WorldEventKind::ProgramInstalled { + module_hash: "h".to_owned(), + seed: 3, + provenance: Some(sample_source_provenance()), + }, + }; + let encoded = serde_json::to_value(&event).unwrap(); + assert_eq!( + serde_json::from_value::(encoded).unwrap(), + event + ); + } + + #[test] + fn checkpoint_defaults_missing_provenance_and_round_trips_recorded_provenance() { + let old = serde_json::json!({ + "entry": "checkpoint", + "sequence": 0, + "module_hash": "h", + "seed": 1, + "snapshot": "s", + "events": [] + }); + let parsed: JournalEntry = serde_json::from_value(old.clone()).unwrap(); + assert!(matches!( + parsed, + JournalEntry::Checkpoint { + provenance: None, + execution_profile: None, + .. + } + )); + assert_eq!(serde_json::to_value(parsed).unwrap(), old); + let restored = WorldCore::restore( + "w", + WorldLimits::default(), + [ + JournalEntry::Created { + world_id: "w".to_owned(), + version: JOURNAL_VERSION, + }, + serde_json::from_value(old).unwrap(), + ], + ) + .unwrap(); + assert_eq!( + restored.core.execution_profile(), + crate::world_limits::WorldExecutionProfile::default() + ); + } + + #[test] + fn execution_profile_survives_checkpoint_compaction_and_restore() { + let profile = crate::world_limits::WorldExecutionProfile { + wasm_fuel: Some(1234), + native_cpu_seconds: Some(3), + ..Default::default() + }; + let mut core = world(8); + core.execution_profile = profile; + core.active_module_hash = Some("h".to_owned()); + let entries = core.checkpoint_entries("state".to_owned()).unwrap(); + let restored = WorldCore::restore("test-world", WorldLimits::default(), entries).unwrap(); + assert_eq!(restored.core.execution_profile(), profile); + } + + #[test] + fn recorded_provenance_survives_checkpoint_compaction_and_restore() { + let provenance = sample_source_provenance(); + let mut core = world(8); + core.active_module_hash = Some("h".to_owned()); + core.active_module_provenance = Some(provenance.clone()); + core.active_seed = 7; + let entries = core.checkpoint_entries("state".to_owned()).unwrap(); + + let restored = WorldCore::restore("test-world", WorldLimits::default(), entries).unwrap(); + assert_eq!( + restored.core.active_module_provenance, + Some(provenance.clone()) + ); + assert_eq!(restored.program.unwrap().provenance, Some(provenance)); + } + + /// A program driven by numeric inputs: each input switches its `wants` + /// script, and every host event is recorded. Request ids embed the input + /// count, so re-sending an input asks again. + struct Mock { + script: u64, + received: Vec, + asks: u64, + } + + impl Mock { + fn new() -> Self { + Self { + script: 0, + received: Vec::new(), + asks: 0, + } + } + } + + impl WorldProgram for Mock { + fn update(&mut self, event: &WorldEvent) -> Result<()> { + match &event.kind { + WorldEventKind::Input(bytes) => { + let text = std::str::from_utf8(bytes)?; + self.script = text.parse().unwrap_or(self.script); + self.asks += 1; + } + WorldEventKind::System { event } => self.received.push(event.clone()), + WorldEventKind::Chat(_) | WorldEventKind::ProgramInstalled { .. } => {} + } + Ok(()) + } + + fn wants(&mut self) -> Result> { + let id = |tag: &str| format!("{tag}-{}", self.asks); + let document = match self.script { + 1 => serde_json::json!({ + "v": 1, + "subscribe": ["players"], + "requests": [{"id": id("now"), "cap": "time.now"}], + }), + 2 => serde_json::json!({ + "requests": [{"id": id("now"), "cap": "time.now"}], + }), + 3 => serde_json::json!({ + "requests": [{ + "id": id("say"), + "cap": "chat.say", + "args": {"text": "hello from the program"}, + }], + }), + 4 => serde_json::json!({"subscribe": ["time.tick:20"]}), + 5 => serde_json::json!({ + "requests": [{ + "id": id("hist"), + "cap": "chat.history", + "args": {"count": 5}, + }], + }), + _ => serde_json::json!({}), + }; + Ok(Some(document.to_string())) + } + } + + async fn caps_world_sync(grant_on_use: bool) -> (WorldHandle, JoinCapability) { + let limits = WorldLimits { + grant_on_use, + ..WorldLimits::default() + }; + let core = WorldCore::new("caps", limits).unwrap(); + let handle = WorldHandle::spawn_with_program(core, Box::new(Mock::new())); + let (_, token) = handle.issue("ann", WorldScopes::GUEST).await.unwrap(); + (handle, token) + } + + #[tokio::test] + async fn an_ungranted_request_is_refused_and_counted() { + let (world, token) = caps_world_sync(false).await; + world.input(token, b"1".to_vec()).await.unwrap(); + // The program hears the refusal as a result event. + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); + loop { + let report = world.caps_report().await.unwrap(); + if report + .usage + .get("time.now") + .is_some_and(|use_| use_.denied > 0) + { + break; + } + assert!(std::time::Instant::now() < deadline, "no refusal recorded"); + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + let report = world.caps_report().await.unwrap(); + assert_eq!(report.policy, "deny"); + assert!( + report.missing.contains(&"time.now".to_owned()), + "{report:?}" + ); + } + + #[tokio::test] + async fn a_granted_request_gets_a_real_answer() { + let (world, token) = caps_world_sync(false).await; + world + .update_caps(vec!["time.now".to_owned()], Vec::new()) + .await + .unwrap(); + world.input(token, b"2".to_vec()).await.unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); + loop { + if world.caps_report().await.unwrap().usage["time.now"].allowed > 0 { + break; + } + assert!(std::time::Instant::now() < deadline, "no answer recorded"); + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + } + + #[test] + fn chat_history_returns_the_newest_lines_oldest_first() { + let mut core = world(16); + for (sequence, participant, text) in + [(1u64, 1u64, "first"), (2, 28, "second"), (3, 1, "third")] + { + core.events.push_back(WorldEvent { + sequence, + participant_id: participant, + kind: WorldEventKind::Chat(text.to_owned()), + }); + } + let newest = chat_history(&core.events, 2); + assert_eq!(newest.len(), 2); + assert_eq!(newest[0]["text"], "second"); + assert_eq!(newest[0]["sequence"], 2); + assert_eq!(newest[1]["text"], "third"); + let all = chat_history(&core.events, 10); + assert_eq!(all.len(), 3); + assert_eq!(all[0]["text"], "first"); + assert_eq!(all[2]["text"], "third"); + assert!(chat_history(&core.events, 0).is_empty()); + } + + #[tokio::test] + async fn a_granted_chat_history_request_is_served_over_the_ledger() { + let (world, token) = caps_world_sync(false).await; + world + .update_caps( + vec!["chat.say".to_owned(), "chat.history".to_owned()], + Vec::new(), + ) + .await + .unwrap(); + // The program says one line first, then asks for the history. + world.input(token.clone(), b"3".to_vec()).await.unwrap(); + world.input(token, b"5".to_vec()).await.unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); + loop { + let report = world.caps_report().await.unwrap(); + if report + .usage + .get("chat.history") + .is_some_and(|use_| use_.allowed > 0) + { + break; + } + assert!( + std::time::Instant::now() < deadline, + "no history answer recorded: {report:?}" + ); + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + } + + #[tokio::test] + async fn chat_say_commits_a_system_chat_line_that_sessions_see() { + let (world, token) = caps_world_sync(false).await; + world + .update_caps(vec!["chat.say".to_owned()], Vec::new()) + .await + .unwrap(); + let mut events = world.subscribe(); + world.input(token, b"3".to_vec()).await.unwrap(); + // The participant's own input event arrives first; keep waiting for + // the host's chat line. + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); + loop { + let event = tokio::time::timeout(std::time::Duration::from_secs(2), events.recv()) + .await + .expect("no chat event") + .unwrap(); + if let WorldEventKind::Chat(text) = &event.kind { + assert_eq!(text, "hello from the program"); + assert_eq!(event.participant_id, 0, "the host said it"); + break; + } + assert!(std::time::Instant::now() < deadline, "chat never arrived"); + } + } + + #[tokio::test] + async fn a_participant_cannot_make_the_program_do_what_its_scopes_forbid() { + let core = WorldCore::new("caps", WorldLimits::default()).unwrap(); + let world = WorldHandle::spawn_with_program(core, Box::new(Mock::new())); + let (_, token) = world + .issue( + "ann", + WorldScopes(WorldScopes::JOIN.bits() | WorldScopes::INPUT.bits()), + ) + .await + .unwrap(); + world + .update_caps(vec!["chat.say".to_owned()], Vec::new()) + .await + .unwrap(); + world.input(token, b"3".to_vec()).await.unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); + loop { + let report = world.caps_report().await.unwrap(); + if report + .usage + .get("chat.say") + .is_some_and(|use_| use_.denied > 0) + { + assert_eq!(report.usage["chat.say"].allowed, 0); + break; + } + assert!(std::time::Instant::now() < deadline, "no refusal recorded"); + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + } + + #[tokio::test] + async fn a_participant_with_chat_lets_the_program_say_what_it_asks() { + let core = WorldCore::new("caps", WorldLimits::default()).unwrap(); + let world = WorldHandle::spawn_with_program(core, Box::new(Mock::new())); + let (_, token) = world + .issue( + "ann", + WorldScopes( + WorldScopes::JOIN.bits() | WorldScopes::CHAT.bits() | WorldScopes::INPUT.bits(), + ), + ) + .await + .unwrap(); + world + .update_caps(vec!["chat.say".to_owned()], Vec::new()) + .await + .unwrap(); + world.input(token, b"3".to_vec()).await.unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); + loop { + let report = world.caps_report().await.unwrap(); + if report + .usage + .get("chat.say") + .is_some_and(|use_| use_.allowed > 0) + { + assert_eq!(report.usage["chat.say"].denied, 0); + break; + } + assert!( + std::time::Instant::now() < deadline, + "no allowed use recorded" + ); + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + } + + #[tokio::test] + async fn grant_on_use_grants_what_the_program_actually_uses() { + let (world, token) = caps_world_sync(true).await; + world.input(token, b"1".to_vec()).await.unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); + loop { + if world.caps_report().await.unwrap().usage["time.now"].allowed > 0 { + break; + } + assert!(std::time::Instant::now() < deadline, "never granted"); + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + let report = world.caps_report().await.unwrap(); + assert_eq!(report.policy, "grant-on-use"); + assert!(report.granted.contains(&"time.now".to_owned())); + assert!(report.missing.is_empty()); + } + + #[test] + fn system_events_and_grants_survive_a_restore() { + let secret = "ab".repeat(32); + let token = JoinCapability::from_wire(format!("1.{secret}")); + let digest = hex_encode(&token_digest(token.expose())); + let entries = vec![ + JournalEntry::Created { + world_id: "caps".to_owned(), + version: JOURNAL_VERSION, + }, + JournalEntry::CapsGranted { + granted: vec!["time.now".to_owned()], + }, + JournalEntry::Issued { + participant: Participant { + id: 1, + display_name: "ann".to_owned(), + }, + digest, + scopes: WorldScopes::GUEST.0, + parent: None, + expires_at: None, + uses: None, + used: 0, + subject: None, + }, + JournalEntry::System { + event: WorldEvent { + sequence: 0, + participant_id: 0, + kind: WorldEventKind::System { + event: r#"{"cap":"result","id":"now-1","ok":true,"value":{"now":1}}"# + .to_owned(), + }, + }, + }, + ]; + let restored = WorldCore::restore("caps", WorldLimits::default(), entries).unwrap(); + assert!(restored.core.ledger.is_granted("time.now")); + assert_eq!(restored.core.sequence, 0, "system events carry no sequence"); + assert_eq!(restored.replay.len(), 1, "the program must see it again"); + assert!( + restored.core.authorize(&token, WorldScopes::JOIN).is_ok(), + "capabilities restore after a grant entry" + ); + } + + #[test] + fn a_restore_closes_presence_the_journal_left_open() { + let secret = "cd".repeat(32); + let digest = hex_encode(&token_digest(&format!("1.{secret}"))); + let presence = |joined: bool| JournalEntry::System { + event: WorldEvent { + sequence: 0, + participant_id: 0, + kind: WorldEventKind::System { + event: presence_event(1, "ann", joined), + }, + }, + }; + let entries = vec![ + JournalEntry::Created { + world_id: "presence".to_owned(), + version: JOURNAL_VERSION, + }, + JournalEntry::Issued { + participant: Participant { + id: 1, + display_name: "ann".to_owned(), + }, + digest, + scopes: WorldScopes::GUEST.0, + parent: None, + expires_at: None, + uses: None, + used: 0, + subject: None, + }, + presence(true), + presence(false), + presence(true), + ]; + let restored = + WorldCore::restore("presence", WorldLimits::default(), entries.clone()).unwrap(); + let last = restored.replay.last().unwrap(); + assert_eq!( + restored.replay.len(), + 4, + "the open join is closed after the journal's events" + ); + assert_eq!( + last.kind, + WorldEventKind::System { + event: presence_event(1, "ann", false), + } + ); + + let closed = + WorldCore::restore("presence", WorldLimits::default(), entries[..4].to_vec()).unwrap(); + assert_eq!(closed.replay.len(), 2, "a closed join needs no extra leave"); + } + + #[test] + fn a_checkpoint_keeps_the_granted_set() { + let mut core = WorldCore::new("caps", WorldLimits::default()).unwrap(); + core.ledger + .set_granted(BTreeSet::from(["time.now".to_owned()])); + core.active_module_hash = Some("h".to_owned()); + let entries = core.checkpoint_entries("snapshot".to_owned()).unwrap(); + assert!(entries + .iter() + .any(|entry| matches!(entry, JournalEntry::CapsGranted { granted } if granted == &vec!["time.now".to_owned()]))); + // A compacted journal restores with the grant intact. + let restored = WorldCore::restore("caps", WorldLimits::default(), entries).unwrap(); + assert!(restored.core.ledger.is_granted("time.now")); + } + + #[tokio::test] + async fn the_actor_journals_host_events_and_grants() { + #[derive(Default, Clone)] + struct Capturing(Arc>>); + impl WorldJournal for Capturing { + fn append(&mut self, entry: &JournalEntry) -> Result<()> { + self.0.lock().unwrap().push(entry.clone()); + Ok(()) + } + } + let captured = Capturing::default(); + let (world, token) = { + let core = WorldCore::new("j", WorldLimits::default()).unwrap(); + let handle = WorldHandle::spawn_durable( + core, + Box::new(Mock::new()), + Some(Box::new(captured.clone())), + ); + let (_, token) = handle.issue("ann", WorldScopes::GUEST).await.unwrap(); + (handle, token) + }; + world + .update_caps(vec!["chat.say".to_owned()], Vec::new()) + .await + .unwrap(); + world.input(token, b"3".to_vec()).await.unwrap(); + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + world.shutdown().await.unwrap(); + let entries = captured.0.lock().unwrap().clone(); + assert!( + entries + .iter() + .any(|entry| matches!(entry, JournalEntry::CapsGranted { granted } if granted.contains(&"chat.say".to_owned()))), + "{entries:?}" + ); + assert!( + entries + .iter() + .any(|entry| matches!(entry, JournalEntry::System { event } if event.kind == WorldEventKind::System { event: r#"{"cap":"result","ok":true,"value":{"sequence":2}}"#.to_owned() })) + || entries + .iter() + .any(|entry| matches!(entry, JournalEntry::System { .. })), + "the chat.say result is journaled: {entries:?}" + ); + assert!( + entries.iter().any( + |entry| matches!(entry, JournalEntry::Committed { event } if matches!(&event.kind, WorldEventKind::Chat(text) if text == "hello from the program")) + ), + "the host chat line is journaled: {entries:?}" + ); + } + + /// A program that only counts `time.tick` deliveries and publishes the count. + #[derive(Debug, Default)] + struct TickCounter { + ticks: u64, + } + + impl WorldProgram for TickCounter { + fn update(&mut self, event: &WorldEvent) -> Result<()> { + if let WorldEventKind::System { event } = &event.kind { + let value: serde_json::Value = + serde_json::from_str(event).unwrap_or(serde_json::Value::Null); + if value["cap"] == "time.tick" { + self.ticks += 1; + } + } + Ok(()) + } + + fn wants(&mut self) -> Result> { + Ok(Some( + serde_json::json!({"v": 1, "subscribe": ["time.tick:20"]}).to_string(), + )) + } + + fn records(&mut self) -> Result> { + Ok(Some(serde_json::json!({"ticks": self.ticks}).to_string())) + } + } + + /// The number of ticks a [`TickCounter`] actor has delivered, via its records. + fn tick_count(actor: &WorldActor) -> u64 { + actor + .records_sender + .borrow() + .1 + .get("ticks") + .and_then(serde_json::Value::as_u64) + .unwrap_or(0) + } + + #[tokio::test] + async fn subscribed_ticks_arrive_only_while_someone_is_present() { + let clock: Arc = Arc::new(ManualClock::new(0)); + let mut core = + WorldCore::new_with_clock("ticks", WorldLimits::default(), clock.clone()).unwrap(); + core.ledger + .set_granted(BTreeSet::from(["time.tick".to_owned()])); + let (_, _token) = core + .issue_capability("ann", WorldScopes::GUEST, CapabilityBounds::default()) + .unwrap(); + let mut actor = WorldActor::for_test(core, Box::new(TickCounter::default()), None); + + // The subscription is known but not armed while nobody is present. + actor.after_change().await; + assert!(actor.ticks.is_empty(), "no tick while nobody is present"); + + // A presence transition arms the tick. + actor + .handle(WorldCommand::Presence { + participant: 1, + joined: true, + }) + .await; + assert!(actor.ticks.contains_key(&20), "the tick armed on presence"); + + clock.advance(20); + actor.fire_ticks().await; + assert_eq!(tick_count(&actor), 1, "the tick fired while present"); + + // The last participant leaving disarms the tick for good. + actor + .handle(WorldCommand::Presence { + participant: 1, + joined: false, + }) + .await; + assert!(actor.ticks.is_empty(), "the tick disarmed on leave"); + clock.advance(20); + actor.fire_ticks().await; + assert_eq!( + tick_count(&actor), + 1, + "ticks kept firing with nobody present" + ); + } + + #[tokio::test] + async fn ticks_follow_the_world_grant_not_a_participant_capability() { + let clock: Arc = Arc::new(ManualClock::new(0)); + let mut core = + WorldCore::new_with_clock("ticks", WorldLimits::default(), clock.clone()).unwrap(); + core.ledger + .set_granted(BTreeSet::from(["time.tick".to_owned()])); + let owner_scopes = WorldScopes(WorldScopes::GUEST.bits() | WorldScopes::DELEGATE.bits()); + let (_, owner) = core + .issue_capability("ann", owner_scopes, CapabilityBounds::default()) + .unwrap(); + let short_lived = CapabilityBounds { + expires_at: Some(150), + uses: None, + }; + let (_, short) = core + .attenuate(&owner, WorldScopes::GUEST, short_lived, "bo") + .unwrap(); + let mut actor = WorldActor::for_test(core, Box::new(TickCounter::default()), None); + + actor.after_change().await; + actor + .handle(WorldCommand::Presence { + participant: 1, + joined: true, + }) + .await; + // The short-lived delegation expires before the tick fires. + clock.advance(150); + assert!( + actor.core.chat(&short, "late").is_err(), + "the delegation expired" + ); + // The world's tick grant still drives the tick while the owner is + // present: a tick is not tied to a participant's capability. + actor.fire_ticks().await; + assert_eq!( + tick_count(&actor), + 1, + "the tick follows the world grant, not a capability" + ); + } + + #[derive(Debug, Default)] + struct TickSay { + ticks: u64, + } + + impl WorldProgram for TickSay { + fn update(&mut self, event: &WorldEvent) -> Result<()> { + if let WorldEventKind::System { event } = &event.kind + && event.contains("time.tick") + { + self.ticks += 1; + } + Ok(()) + } + + fn wants(&mut self) -> Result> { + let mut document = serde_json::json!({"v": 1, "subscribe": ["time.tick:20"]}); + if self.ticks > 0 { + document["requests"] = serde_json::json!([{ + "id": format!("say-{}", self.ticks), + "cap": "chat.say", + "args": {"text": "tick"}, + }]); + } + Ok(Some(document.to_string())) + } + } + + #[tokio::test] + async fn ticks_speak_for_the_world_not_for_a_present_participant() { + let clock: Arc = Arc::new(ManualClock::new(0)); + let mut core = + WorldCore::new_with_clock("tick-attribution", WorldLimits::default(), clock.clone()) + .unwrap(); + core.ledger.set_granted(BTreeSet::from([ + "time.tick".to_owned(), + "chat.say".to_owned(), + ])); + let (spectator, _) = core + .issue_capability( + "spectator", + WorldScopes(WorldScopes::JOIN.bits() | WorldScopes::INPUT.bits()), + CapabilityBounds::default(), + ) + .unwrap(); + let mut actor = WorldActor::for_test(core, Box::new(TickSay::default()), None); + + actor.after_change().await; + actor + .handle(WorldCommand::Presence { + participant: spectator.id, + joined: true, + }) + .await; + clock.advance(20); + actor.fire_ticks().await; + // The tick's follow-up request runs on the next change, with no acting + // participant, so the world's grant decides it — not the spectator's scopes. + actor.after_change().await; + let usage = actor.core.ledger.usage()["chat.say"]; + assert_eq!(usage.allowed, 1, "the tick spoke for the world"); + assert_eq!(usage.denied, 0, "a tick was refused for a participant"); + } + + #[tokio::test] + async fn revoking_a_grant_applies_to_capabilities_already_issued() { + let core = WorldCore::new("ceiling", WorldLimits::default()).unwrap(); + let world = WorldHandle::spawn_with_program(core, Box::new(Mock::new())); + world + .update_caps(vec!["chat.say".to_owned()], Vec::new()) + .await + .unwrap(); + let (_, token) = world.issue("ann", WorldScopes::GUEST).await.unwrap(); + world.input(token.clone(), b"3".to_vec()).await.unwrap(); + let usage = world.caps_report().await.unwrap().usage["chat.say"]; + assert_eq!((usage.allowed, usage.denied), (1, 0)); + world + .update_caps(Vec::new(), vec!["chat.say".to_owned()]) + .await + .unwrap(); + world.input(token, b"3".to_vec()).await.unwrap(); + let usage = world.caps_report().await.unwrap().usage["chat.say"]; + assert_eq!((usage.allowed, usage.denied), (1, 1)); + world.shutdown().await.unwrap(); + } + + #[test] + fn a_caps_ceiling_replays_from_the_journal() { + let restored = WorldCore::restore( + "ceil", + WorldLimits::default(), + [ + JournalEntry::Created { + world_id: "ceil".to_owned(), + version: JOURNAL_VERSION, + }, + JournalEntry::CapsGranted { + granted: vec!["time.now".to_owned(), "chat.say".to_owned()], + }, + JournalEntry::CapsCeiling { + ceiling: vec!["time.now".to_owned()], + }, + ], + ) + .unwrap(); + assert!(restored.core.ledger.is_granted("time.now")); + assert!(!restored.core.ledger.is_granted("chat.say")); + assert!( + restored.core.ledger.granted().contains("chat.say"), + "the grant is kept" + ); + + let refused = WorldCore::restore( + "ceil", + WorldLimits::default(), + [ + JournalEntry::Created { + world_id: "ceil".to_owned(), + version: JOURNAL_VERSION, + }, + JournalEntry::CapsCeiling { + ceiling: vec!["*".to_owned()], + }, + ], + ); + assert!(refused.is_err(), "a journaled ceiling may not use `*`"); + } + + #[test] + fn a_caps_ceiling_survives_checkpoint_compaction_and_restore() { + let mut core = world(8); + core.caps_ceiling = BTreeSet::from(["time.now".to_owned()]); + core.sync_ledger_ceiling(); + core.ledger + .set_granted(BTreeSet::from(["chat.say".to_owned()])); + core.active_module_hash = Some("h".to_owned()); + let entries = core.checkpoint_entries("state".to_owned()).unwrap(); + assert!(entries.iter().any(|entry| matches!( + entry, + JournalEntry::Checkpoint { caps_ceiling: Some(ceiling), .. } + if ceiling == &vec!["time.now".to_owned()] + ))); + // The entry is what makes an older binary fail loudly on this journal. + assert!(entries.iter().any(|entry| matches!( + entry, + JournalEntry::CapsCeiling { ceiling } if ceiling == &vec!["time.now".to_owned()] + ))); + let restored = WorldCore::restore("test-world", WorldLimits::default(), entries).unwrap(); + assert_eq!( + restored.core.ledger.allowed(), + &BTreeSet::from(["time.now".to_owned()]) + ); + assert!(!restored.core.ledger.is_granted("chat.say")); + } + + #[test] + fn a_default_ceiling_is_not_written_and_old_journals_allow_the_whole_catalog() { + let mut core = world(8); + core.active_module_hash = Some("h".to_owned()); + let entries = core.checkpoint_entries("state".to_owned()).unwrap(); + assert!(entries.iter().all(|entry| !matches!( + entry, + JournalEntry::Checkpoint { + caps_ceiling: Some(_), + .. + } + ))); + let old = serde_json::json!({ + "entry": "checkpoint", + "sequence": 0, + "module_hash": "h", + "seed": 1, + "snapshot": "s", + "events": [] + }); + let restored = WorldCore::restore( + "test-world", + WorldLimits::default(), + [ + JournalEntry::Created { + world_id: "test-world".to_owned(), + version: JOURNAL_VERSION, + }, + serde_json::from_value(old).unwrap(), + ], + ) + .unwrap(); + assert_eq!( + restored.core.ledger.allowed(), + &crate::world_caps::catalog_names() + ); + } + + #[test] + fn the_server_ceiling_is_runtime_config_and_bounds_a_restored_grant() { + let entries = [ + JournalEntry::Created { + world_id: "server".to_owned(), + version: JOURNAL_VERSION, + }, + JournalEntry::CapsGranted { + granted: vec!["time.now".to_owned(), "chat.say".to_owned()], + }, + ]; + let lower = WorldLimits { + server_caps: BTreeSet::from(["time.now".to_owned()]), + ..WorldLimits::default() + }; + let restored = WorldCore::restore("server", lower, entries.clone()).unwrap(); + assert!(restored.core.ledger.is_granted("time.now")); + assert!(!restored.core.ledger.is_granted("chat.say")); + assert!(restored.core.ledger.granted().contains("chat.say")); + + // Nothing about the server ceiling was journaled, so the default + // server restores the grant. + let restored = WorldCore::restore("server", WorldLimits::default(), entries).unwrap(); + assert!(restored.core.ledger.is_granted("chat.say")); + } + + #[test] + fn a_server_ceiling_naming_a_wildcard_is_refused() { + let limits = WorldLimits { + server_caps: BTreeSet::from(["*".to_owned()]), + ..WorldLimits::default() + }; + assert!(WorldCore::new("w", limits).is_err()); + } + + #[tokio::test] + async fn a_ceiling_change_denies_a_use_that_a_prior_grant_allowed() { + let core = WorldCore::new("ceiling", WorldLimits::default()).unwrap(); + let world = WorldHandle::spawn_with_program(core, Box::new(Mock::new())); + world + .update_caps(vec!["chat.say".to_owned()], Vec::new()) + .await + .unwrap(); + let (_, token) = world.issue("ann", WorldScopes::GUEST).await.unwrap(); + world.input(token.clone(), b"3".to_vec()).await.unwrap(); + let usage = world.caps_report().await.unwrap().usage["chat.say"]; + assert_eq!((usage.allowed, usage.denied), (1, 0)); + + let report = world + .set_caps_ceiling(vec!["time.now".to_owned()]) + .await + .unwrap(); + assert_eq!(report.ceiling, vec!["time.now".to_owned()]); + assert!( + report.granted.contains(&"chat.say".to_owned()), + "the grant is kept" + ); + assert!(!report.effective.contains(&"chat.say".to_owned())); + world.input(token, b"3".to_vec()).await.unwrap(); + let usage = world.caps_report().await.unwrap().usage["chat.say"]; + assert_eq!((usage.allowed, usage.denied), (1, 1)); + + assert!(world.set_caps_ceiling(vec!["*".to_owned()]).await.is_err()); + assert!( + world + .set_caps_ceiling(vec!["time.nwo".to_owned()]) + .await + .is_err() + ); + world.shutdown().await.unwrap(); + } + + #[tokio::test] + async fn lowering_the_ceiling_stops_an_active_subscription_and_reports_it_refused() { + let clock: Arc = Arc::new(ManualClock::new(0)); + let mut core = + WorldCore::new_with_clock("ceiling-ticks", WorldLimits::default(), clock.clone()) + .unwrap(); + core.ledger + .set_granted(BTreeSet::from(["time.tick".to_owned()])); + let (_, _token) = core + .issue_capability("ann", WorldScopes::GUEST, CapabilityBounds::default()) + .unwrap(); + let mut actor = WorldActor::for_test(core, Box::new(TickCounter::default()), None); + + actor.after_change().await; + actor + .handle(WorldCommand::Presence { + participant: 1, + joined: true, + }) + .await; + clock.advance(20); + actor.fire_ticks().await; + assert_eq!( + tick_count(&actor), + 1, + "the tick arrived while the ceiling allowed it" + ); + + // Lowering the ceiling drops the subscription and reports it refused. + let (reply, response) = tokio::sync::oneshot::channel(); + actor + .handle(WorldCommand::SetCapsCeiling { + ceiling: vec!["time.now".to_owned()], + reply, + }) + .await; + let _ = response.await.unwrap().unwrap(); + actor.after_change().await; + assert!(actor.core.ledger.usage()["time.tick"].denied > 0); + assert!(!actor.core.ledger.effective().contains("time.tick")); + // No tick follows while the ceiling excludes it. + clock.advance(20); + actor.fire_ticks().await; + assert_eq!( + tick_count(&actor), + 1, + "ticks kept firing after the ceiling dropped them" + ); + + // Lifting the ceiling admits the refused subscription again. + let full: Vec = crate::world_caps::catalog_names().into_iter().collect(); + let (reply, response) = tokio::sync::oneshot::channel(); + actor + .handle(WorldCommand::SetCapsCeiling { + ceiling: full, + reply, + }) + .await; + let _ = response.await.unwrap().unwrap(); + actor.after_change().await; + clock.advance(20); + actor.fire_ticks().await; + assert_eq!( + tick_count(&actor), + 2, + "ticks did not resume once the ceiling allowed them" + ); + } + + #[test] + fn capability_scopes_isolate_actions() { + let mut core = world(8); + let (_, token) = join(&mut core, "Guest"); + assert!(core.snapshot(&token).is_ok()); + assert!(core.chat(&token, "hello").is_ok()); + assert!(core.input(&token, b"move").is_ok()); + let (_, join_only) = core + .issue_capability("spectator", WorldScopes::JOIN, CapabilityBounds::default()) + .unwrap(); + assert!(core.snapshot(&join_only).is_ok()); + assert!(core.chat(&join_only, "no").is_err()); + assert!(core.input(&join_only, b"no").is_err()); + } + + #[test] + fn chat_is_rate_limited_per_participant_within_a_ten_second_window() { + let mut core = world(64); + let (_, token) = join(&mut core, "Guest"); + for index in 0..CHAT_RATE_BURST { + core.chat(&token, &format!("message {index}")).unwrap(); + } + assert!(core.chat(&token, "one too many").is_err()); + assert_eq!(core.current_sequence(), u64::from(CHAT_RATE_BURST)); + } + + fn in_an_hour() -> u64 { + unix_ms() + 3_600_000 + } + + #[test] + fn an_expired_capability_is_refused_for_every_operation() { + let mut core = world(8); + let (_, token) = core + .issue_capability( + "Ada", + WorldScopes::GUEST, + CapabilityBounds { + expires_at: Some(1), + uses: None, + }, + ) + .unwrap(); + assert!(core.snapshot(&token).is_err()); + assert!(core.chat(&token, "late").is_err()); + assert!(core.input(&token, b"late").is_err()); + } + + #[test] + fn delegation_may_not_outlive_or_expire_in_the_past() { + let mut core = world(8); + let (_, owner) = core + .issue_capability( + "Ada", + WorldScopes(WorldScopes::GUEST.bits() | WorldScopes::DELEGATE.bits()), + CapabilityBounds { + expires_at: Some(in_an_hour()), + uses: None, + }, + ) + .unwrap(); + let later = CapabilityBounds { + expires_at: Some(in_an_hour() + 1), + uses: None, + }; + assert!( + core.attenuate(&owner, WorldScopes::JOIN, later, "Bo") + .is_err() + ); + let past = CapabilityBounds { + expires_at: Some(1), + uses: None, + }; + assert!( + core.attenuate(&owner, WorldScopes::JOIN, past, "Cy") + .is_err() + ); + let sooner = CapabilityBounds { + expires_at: Some(in_an_hour() - 1_000), + uses: None, + }; + assert!( + core.attenuate(&owner, WorldScopes::JOIN, sooner, "Di") + .is_ok() + ); + let inherited = core + .attenuate(&owner, WorldScopes::JOIN, CapabilityBounds::default(), "Ed") + .unwrap() + .1; + assert!(core.snapshot(&inherited).is_ok()); + } + + #[test] + fn a_host_issued_limit_draws_down_through_every_delegation() { + let mut core = world(8); + let (_, owner) = core + .issue_capability( + "Ada", + WorldScopes(WorldScopes::GUEST.bits() | WorldScopes::DELEGATE.bits()), + CapabilityBounds { + expires_at: None, + uses: Some(3), + }, + ) + .unwrap(); + let (_, child) = core + .attenuate( + &owner, + WorldScopes::GUEST, + CapabilityBounds::default(), + "Bo", + ) + .unwrap(); + core.chat(&child, "one").unwrap(); + core.chat(&child, "two").unwrap(); + core.chat(&owner, "last").unwrap(); + assert!( + core.chat(&child, "three").is_err(), + "the host's limit bounds the delegate" + ); + assert!(core.chat(&owner, "over").is_err()); + assert!(core.snapshot(&owner).is_ok(), "reading is not a use"); + } + + #[test] + fn a_delegated_grant_carries_no_use_count() { + let mut core = world(8); + let delegator = WorldScopes(WorldScopes::GUEST.bits() | WorldScopes::DELEGATE.bits()); + let (_, owner) = core + .issue_capability("Ada", delegator, CapabilityBounds::default()) + .unwrap(); + let limited = CapabilityBounds { + expires_at: None, + uses: Some(1), + }; + assert!( + core.attenuate(&owner, WorldScopes::GUEST, limited, "Bo") + .is_err(), + "a delegation carries no use count" + ); + let (child, child_token) = core + .attenuate( + &owner, + WorldScopes::GUEST, + CapabilityBounds::default(), + "Cy", + ) + .unwrap(); + for text in ["one", "two", "three"] { + core.chat(&child_token, text).unwrap(); + } + let record = serde_json::to_value(core.issued_entry(child.id).unwrap()).unwrap(); + assert!( + record.get("uses").is_none(), + "the grant record has no use count: {record}" + ); + } + + #[test] + fn a_grant_without_a_bound_is_never_refused_for_count() { + let mut core = world(8); + let (_, token) = join(&mut core, "Ada"); + for i in 0..50 { + core.chat(&token, &format!("m{i}")).unwrap(); + } + assert!(core.snapshot(&token).is_ok()); + } + + #[test] + fn a_host_issued_limit_is_enforced_by_the_host_alone() { + let mut core = world(8); + let (_, token) = core + .issue_capability( + "Ada", + WorldScopes::GUEST, + CapabilityBounds { + expires_at: None, + uses: Some(2), + }, + ) + .unwrap(); + core.chat(&token, "one").unwrap(); + core.chat(&token, "two").unwrap(); + assert!(core.chat(&token, "three").is_err()); + assert_eq!(core.current_sequence(), 2, "a refused use commits nothing"); + } + + #[test] + fn use_counts_are_local_and_do_not_converge_across_partitions() { + let mut source = world(8); + let (owner, token) = source + .issue_capability( + "Ada", + WorldScopes::GUEST, + CapabilityBounds { + expires_at: None, + uses: Some(1), + }, + ) + .unwrap(); + let entries = vec![ + JournalEntry::Created { + world_id: "test-world".to_owned(), + version: JOURNAL_VERSION, + }, + JournalEntry::Issued { + participant: owner.clone(), + digest: hex_encode(&token_digest(token.expose())), + scopes: WorldScopes::GUEST.bits(), + parent: None, + expires_at: None, + uses: Some(1), + used: 0, + subject: None, + }, + ]; + // Two partitions start from the same journal and do not see each other. + let mut north = WorldCore::restore("test-world", WorldLimits::default(), entries.clone()) + .unwrap() + .core; + let mut south = WorldCore::restore("test-world", WorldLimits::default(), entries) + .unwrap() + .core; + north.chat(&token, "north").unwrap(); + south.chat(&token, "south").unwrap(); + // Each side counted its own use, so the one-use grant was used twice. + assert!(north.chat(&token, "north again").is_err()); + assert!(south.chat(&token, "south again").is_err()); + // Each state is still valid: sequence and tally agree, and the grant is held. + for core in [&north, &south] { + assert_eq!(core.current_sequence(), 1); + assert_eq!(core.capabilities[&owner.id].used, 1); + assert_eq!(core.participants().len(), 1); + } + } + + #[test] + fn use_counts_survive_restore_and_compaction() { + let mut source = world(8); + let (owner, token) = source + .issue_capability( + "Ada", + WorldScopes::GUEST, + CapabilityBounds { + expires_at: None, + uses: Some(2), + }, + ) + .unwrap(); + let digest = hex_encode(&token_digest(token.expose())); + let entries = vec![ + JournalEntry::Created { + world_id: "test-world".to_owned(), + version: JOURNAL_VERSION, + }, + JournalEntry::Issued { + participant: owner, + digest, + scopes: WorldScopes::GUEST.bits(), + parent: None, + expires_at: None, + uses: Some(2), + used: 1, + subject: None, + }, + ]; + let mut restored = + WorldCore::restore("test-world", WorldLimits::default(), entries).unwrap(); + restored.core.chat(&token, "second").unwrap(); + assert!(restored.core.chat(&token, "third").is_err()); + } + + #[test] + fn restore_refuses_a_delegate_outliving_its_parent() { + let mut source = world(8); + let (owner, owner_token) = source + .issue_capability( + "Ada", + WorldScopes(WorldScopes::GUEST.bits() | WorldScopes::DELEGATE.bits()), + CapabilityBounds { + expires_at: Some(in_an_hour()), + uses: None, + }, + ) + .unwrap(); + let (child, child_token) = source + .attenuate( + &owner_token, + WorldScopes::JOIN, + CapabilityBounds::default(), + "Bo", + ) + .unwrap(); + let digest = hex_encode(&token_digest(child_token.expose())); + let entries = vec![ + JournalEntry::Created { + world_id: "test-world".to_owned(), + version: JOURNAL_VERSION, + }, + JournalEntry::Issued { + participant: owner, + digest: hex_encode(&token_digest(owner_token.expose())), + scopes: WorldScopes(WorldScopes::GUEST.bits() | WorldScopes::DELEGATE.bits()) + .bits(), + parent: None, + expires_at: Some(in_an_hour()), + uses: None, + used: 0, + subject: None, + }, + JournalEntry::Issued { + participant: child, + digest, + scopes: WorldScopes::JOIN.bits(), + parent: Some(1), + expires_at: Some(in_an_hour() + 1), + uses: None, + used: 0, + subject: None, + }, + ]; + assert!(WorldCore::restore("test-world", WorldLimits::default(), entries).is_err()); + } + + #[test] + fn events_are_sequenced_and_reconnect_can_catch_up() { + let mut core = world(8); + let (_, token) = join(&mut core, "Ada"); + assert_eq!(core.chat(&token, "hello").unwrap().sequence, 1); + assert_eq!(core.input(&token, b"move").unwrap().sequence, 2); + let page = core.events_after(&token, 1).unwrap(); + assert_eq!(page.current_sequence, 2); + assert!(!page.needs_snapshot); + assert_eq!(page.events.len(), 1); + assert_eq!(page.events[0].sequence, 2); + } + + #[test] + fn reconnect_requires_snapshot_when_cursor_is_older_than_retention() { + let mut core = world(2); + let (_, token) = join(&mut core, "Ada"); + for msg in ["one", "two", "three"] { + core.chat(&token, msg).unwrap(); + } + let page = core.events_after(&token, 0).unwrap(); + assert!(page.needs_snapshot); + assert!(page.events.is_empty()); + let snapshot = core.snapshot(&token).unwrap(); + assert_eq!(snapshot.current_sequence, 3); + assert_eq!(snapshot.oldest_retained_sequence, 2); + assert_eq!(snapshot.events.len(), 2); + } + + #[test] + fn revoked_capabilities_cannot_read_or_write() { + let mut core = world(8); + let (participant, token) = join(&mut core, "Ada"); + assert_eq!(core.revoke_tree(participant.id), vec![participant.id]); + assert!(core.revoke_tree(participant.id).is_empty()); + assert!(core.snapshot(&token).is_err()); + assert!(core.chat(&token, "hello").is_err()); + } + + #[test] + fn content_before_a_removal_is_kept_and_content_after_it_is_refused() { + let mut core = world(8); + let (ada, ada_token) = join(&mut core, "Ada"); + let (_, bo_token) = join(&mut core, "Bo"); + core.chat(&ada_token, "before").unwrap(); + assert_eq!(core.revoke_tree(ada.id), vec![ada.id]); + assert!(core.chat(&ada_token, "after").is_err()); + assert!(core.input(&ada_token, b"move").is_err()); + assert_eq!( + core.current_sequence(), + 1, + "a refused action commits nothing" + ); + let kept: Vec = core + .snapshot(&bo_token) + .unwrap() + .events + .into_iter() + .filter_map(|event| match event.kind { + WorldEventKind::Chat(text) => Some(text), + _ => None, + }) + .collect(); + assert_eq!(kept, vec!["before"]); + assert_eq!(core.events_after(&bo_token, 0).unwrap().events.len(), 1); + } + + #[tokio::test] + async fn a_removal_racing_chat_keeps_every_accepted_line() { + let handle = WorldHandle::spawn(WorldCore::new("w", WorldLimits::default()).unwrap()); + let (ada, ada_token) = handle.issue("Ada", WorldScopes::GUEST).await.unwrap(); + let (_, bo_token) = handle.issue("Bo", WorldScopes::GUEST).await.unwrap(); + let chatter = { + let handle = handle.clone(); + let token = ada_token.clone(); + tokio::spawn(async move { + let mut accepted = 0; + for i in 0..200 { + if handle.chat(token.clone(), format!("m{i}")).await.is_ok() { + accepted += 1; + } + } + accepted + }) + }; + tokio::task::yield_now().await; + assert!(handle.revoke(ada.id).await.unwrap()); + let accepted = chatter.await.unwrap(); + assert!(handle.chat(ada_token, "late").await.is_err()); + let snapshot = handle.snapshot(bo_token).await.unwrap(); + let from_ada = snapshot + .events + .iter() + .filter(|event| event.participant_id == ada.id) + .count(); + assert_eq!( + from_ada, accepted, + "every line accepted before the removal is kept, and none after it" + ); + } + + #[test] + fn role_presets_grant_and_withhold_the_expected_effects() { + let spectator = WorldScopes::from_role("spectator").unwrap(); + assert!(spectator.allows_effect("time.now")); + assert!(!spectator.allows_effect("chat.say")); + assert!(!spectator.allows_effect("chat.history")); + assert!(!spectator.reads_chat()); + assert!(spectator.attenuate(WorldScopes::INPUT).is_none()); + + // An observer reads chat, through the stream and `chat.history` + // alike, and still cannot send it or act. + let observer = WorldScopes::from_role("observer").unwrap(); + assert!(observer.reads_chat()); + assert!(observer.allows_effect("chat.history")); + assert!(!observer.allows_effect("chat.say")); + assert!(!observer.contains(WorldScopes::INPUT)); + + let player = WorldScopes::from_role("player").unwrap(); + assert!(player.contains(WorldScopes::INPUT)); + assert!(!player.contains(WorldScopes::CHAT)); + assert!(!player.contains(WorldScopes::DELEGATE)); + + let guest = WorldScopes::from_role("guest").unwrap(); + assert_eq!(guest, WorldScopes::GUEST); + assert!(guest.allows_effect("chat.say")); + + let delegator = WorldScopes::from_role("delegator").unwrap(); + assert!(delegator.contains(WorldScopes::DELEGATE)); + assert!(delegator.attenuate(WorldScopes::JOIN).is_some()); + + assert_eq!(WorldScopes::from_role("builder"), None); + assert_eq!( + WorldScopes::ROLES, + &["spectator", "observer", "player", "guest", "delegator"] + ); + } + + #[test] + fn attenuation_only_narrows_and_needs_delegate() { + let join = WorldScopes::JOIN; + let delegator = WorldScopes(WorldScopes::GUEST.bits() | WorldScopes::DELEGATE.bits()); + assert_eq!(delegator.attenuate(join), Some(join)); + assert!(delegator.attenuate(WorldScopes::GUEST).is_some()); + assert!( + WorldScopes::GUEST.attenuate(join).is_none(), + "no delegate scope" + ); + assert!( + delegator.attenuate(WorldScopes::CHAT).is_none(), + "must keep join" + ); + let join_only = WorldScopes(WorldScopes::JOIN.bits() | WorldScopes::DELEGATE.bits()); + assert!( + join_only.attenuate(WorldScopes::GUEST).is_none(), + "widening" + ); + } + + #[test] + fn scope_names_and_effects_follow_the_scopes() { + assert_eq!( + WorldScopes::from_names(["join", "delegate"]), + Some(WorldScopes(0b1001)) + ); + assert_eq!(WorldScopes::from_names(["join", "telepathy"]), None); + assert!(WorldScopes::GUEST.allows_effect("chat.say")); + assert!(WorldScopes::GUEST.allows_effect("chat.history")); + let spectator = WorldScopes(WorldScopes::JOIN.bits() | WorldScopes::INPUT.bits()); + assert!(!spectator.allows_effect("chat.say")); + assert!(!spectator.allows_effect("chat.history")); + assert!(spectator.allows_effect("time.now")); + } + + #[test] + fn delegated_capabilities_are_narrow_and_die_with_their_parent() { + let mut core = world(8); + let root = WorldScopes(WorldScopes::GUEST.bits() | WorldScopes::DELEGATE.bits()); + let (owner, owner_token) = core + .issue_capability("Ada", root, CapabilityBounds::default()) + .unwrap(); + let (child, child_token) = core + .attenuate( + &owner_token, + WorldScopes(WorldScopes::JOIN.bits() | WorldScopes::DELEGATE.bits()), + CapabilityBounds::default(), + "Bo", + ) + .unwrap(); + let (grandchild, grandchild_token) = core + .attenuate( + &child_token, + WorldScopes::JOIN, + CapabilityBounds::default(), + "Cy", + ) + .unwrap(); + assert!(core.chat(&grandchild_token, "hi").is_err()); + assert!( + core.attenuate( + &child_token, + WorldScopes::GUEST, + CapabilityBounds::default(), + "Di" + ) + .is_err() + ); + assert!( + core.attenuate( + &grandchild_token, + WorldScopes::JOIN, + CapabilityBounds::default(), + "Ed" + ) + .is_err() + ); + + let mut revoked = core.revoke_tree(owner.id); + revoked.sort_unstable(); + assert_eq!(revoked, vec![owner.id, child.id, grandchild.id]); + assert!(core.snapshot(&child_token).is_err()); + assert!(core.snapshot(&grandchild_token).is_err()); + } + + #[test] + fn delegation_counts_against_the_participant_limit() { + let limits = WorldLimits { + participants: 2, + ..WorldLimits::default() + }; + let mut core = WorldCore::new("limit", limits).unwrap(); + let root = WorldScopes(WorldScopes::GUEST.bits() | WorldScopes::DELEGATE.bits()); + let (_, owner_token) = core + .issue_capability("Ada", root, CapabilityBounds::default()) + .unwrap(); + core.attenuate( + &owner_token, + WorldScopes::JOIN, + CapabilityBounds::default(), + "Bo", + ) + .unwrap(); + assert!( + core.attenuate( + &owner_token, + WorldScopes::JOIN, + CapabilityBounds::default(), + "Cy" + ) + .is_err() + ); + } + + #[test] + fn a_restored_delegation_keeps_its_parent_link() { + let secret = "cd".repeat(32); + let token = JoinCapability::from_wire(format!("2.{secret}")); + let digest = hex_encode(&token_digest(token.expose())); + let entries = vec![ + JournalEntry::Created { + world_id: "delegate".to_owned(), + version: JOURNAL_VERSION, + }, + JournalEntry::Issued { + participant: Participant { + id: 1, + display_name: "ann".to_owned(), + }, + digest: "00".repeat(32), + scopes: WorldScopes::GUEST.bits() | WorldScopes::DELEGATE.bits(), + parent: None, + expires_at: None, + uses: None, + used: 0, + subject: None, + }, + JournalEntry::Issued { + participant: Participant { + id: 2, + display_name: "bo".to_owned(), + }, + digest, + scopes: WorldScopes::JOIN.bits(), + parent: Some(1), + expires_at: None, + uses: None, + used: 0, + subject: None, + }, + ]; + let mut restored = WorldCore::restore("delegate", WorldLimits::default(), entries) + .unwrap() + .core; + assert!(restored.authorize(&token, WorldScopes::JOIN).is_ok()); + assert_eq!(restored.revoke_tree(1), vec![1, 2]); + assert!(restored.authorize(&token, WorldScopes::JOIN).is_err()); + } + + #[test] + fn foreign_and_malformed_capabilities_are_rejected() { + let mut left = world(8); + let right = world(8); + let (_, left_token) = join(&mut left, "Ada"); + let malformed = JoinCapability("not-a-valid-token".to_owned()); + assert!(left.snapshot(&malformed).is_err()); + assert!(right.snapshot(&left_token).is_err()); + } + + #[test] + fn names_chat_and_input_are_sanitized_and_bounded() { + let mut core = world(8); + let (participant, token) = join(&mut core, "\u{1b}[31mAda\n"); + assert_eq!(participant.display_name, "[31mAda"); + assert_eq!( + core.chat(&token, " hi\u{1b}[31m\n").unwrap().kind, + WorldEventKind::Chat("hi[31m".to_owned()) + ); + assert!(core.chat(&token, &"x".repeat(2049)).is_err()); + assert!(core.input(&token, &vec![0; 16 * 1024 + 1]).is_err()); + assert!(core.chat(&token, " \n \t ").is_err()); + } + + #[test] + fn participant_capacity_and_constructor_limits_are_enforced() { + let mut core = WorldCore::new( + "small", + WorldLimits { + participants: 1, + ..WorldLimits::default() + }, + ) + .unwrap(); + join(&mut core, "Ada"); + assert!( + core.issue_capability("Grace", WorldScopes::GUEST, CapabilityBounds::default()) + .is_err() + ); + assert!(WorldCore::new("", WorldLimits::default()).is_err()); + assert!( + WorldCore::new( + "world", + WorldLimits { + retained_events: 0, + ..WorldLimits::default() + } + ) + .is_err() + ); + } + + #[test] + fn join_projections_redact_the_install_seed_but_the_journal_keeps_it() { + // Issue #240: the install seed was serialized to every joiner via + // `events_after` and the snapshot. The journal (and the admin paths + // fed from it) must keep the real seed; join projections must not. + let entries = vec![ + JournalEntry::Created { + world_id: "test-world".to_owned(), + version: JOURNAL_VERSION, + }, + JournalEntry::Committed { + event: WorldEvent { + sequence: 1, + participant_id: 0, + kind: WorldEventKind::ProgramInstalled { + module_hash: "ab".repeat(32), + seed: 424_242, + provenance: None, + }, + }, + }, + ]; + let restored = WorldCore::restore("test-world", WorldLimits::default(), entries).unwrap(); + assert_eq!( + restored.program.as_ref().map(|program| program.seed), + Some(424_242), + "the journal restore path keeps the real seed for the admin" + ); + let mut core = restored.core; + assert_eq!(core.active_seed, 424_242, "the core keeps the real seed"); + let (_, token) = join(&mut core, "Ada"); + let page = core.events_after(&token, 0).unwrap(); + assert_eq!(page.events.len(), 1); + assert!( + matches!( + &page.events[0].kind, + WorldEventKind::ProgramInstalled { module_hash, seed, .. } + if module_hash == &"ab".repeat(32) && *seed == 0 + ), + "events_after must keep the module hash but redact the seed: {:?}", + page.events[0].kind + ); + assert!( + !format!("{page:?}").contains("424242"), + "events_after leaked the install seed" + ); + let snapshot = core.snapshot(&token).unwrap(); + assert_eq!(snapshot.events.len(), 1); + assert!( + !serde_json::to_string(&snapshot).unwrap().contains("424242"), + "the snapshot leaked the install seed" + ); + } + + fn scoped(core: &mut WorldCore, name: &str, names: &[&str]) -> JoinCapability { + let scopes = WorldScopes::from_names(names.iter().copied()).unwrap(); + core.issue_capability(name, scopes, CapabilityBounds::default()) + .unwrap() + .1 + } + + fn chat_texts(events: &[WorldEvent]) -> Vec { + events + .iter() + .filter_map(|event| match &event.kind { + WorldEventKind::Chat(text) => Some(text.clone()), + _ => None, + }) + .collect() + } + + /// Chat line, input, chat line, input: sequences 1..=4. + fn talk(core: &mut WorldCore, speaker: &JoinCapability) { + core.chat(speaker, "one").unwrap(); + core.input(speaker, b"a").unwrap(); + core.chat(speaker, "two").unwrap(); + core.input(speaker, b"b").unwrap(); + } + + #[test] + fn chat_visibility_follows_the_viewers_scopes() { + let mut core = world(16); + let (_, speaker) = join(&mut core, "Ada"); + let watcher = scoped(&mut core, "watch", &["join"]); + let reader = scoped(&mut core, "read", &["join", "history"]); + talk(&mut core, &speaker); + + let sequences = |events: &[WorldEvent]| -> Vec { + events.iter().map(|event| event.sequence).collect() + }; + for (token, sees_chat) in [(&speaker, true), (&reader, true), (&watcher, false)] { + let page = core.events_after(token, 0).unwrap(); + let snapshot = core.snapshot(token).unwrap(); + for events in [&page.events, &snapshot.events] { + let (lines, kept): (Vec<&str>, Vec) = if sees_chat { + (vec!["one", "two"], vec![1, 2, 3, 4]) + } else { + (Vec::new(), vec![2, 4]) + }; + assert_eq!(chat_texts(events), lines); + assert_eq!(sequences(events), kept, "non-chat events are kept"); + } + } + } + + #[test] + fn chat_visibility_history_reads_without_sending() { + let mut core = world(16); + let (_, speaker) = join(&mut core, "Ada"); + let reader = scoped(&mut core, "read", &["join", "history"]); + core.chat(&speaker, "hello").unwrap(); + assert!(core.chat(&reader, "hi").is_err(), "history does not send"); + assert!(core.input(&reader, b"a").is_err()); + assert_eq!( + chat_texts(&core.events_after(&reader, 0).unwrap().events), + ["hello"] + ); + assert_eq!(core.current_sequence(), 1, "a refused line commits nothing"); + } + + #[test] + fn chat_visibility_cursors_advance_across_gaps() { + let mut core = world(16); + let (_, speaker) = join(&mut core, "Ada"); + let watcher = scoped(&mut core, "watch", &["join"]); + core.chat(&speaker, "one").unwrap(); + core.chat(&speaker, "two").unwrap(); + + // Only chat so far: nothing to show, yet the cursor moves to the end + // and retention is judged on the world, not the viewer. + let page = core.events_after(&watcher, 0).unwrap(); + assert!(page.events.is_empty()); + assert!(!page.needs_snapshot); + assert_eq!(page.current_sequence, 2); + assert_eq!(page.oldest_retained_sequence, 1); + let again = core.events_after(&watcher, page.current_sequence).unwrap(); + assert!(again.events.is_empty() && !again.needs_snapshot); + + core.chat(&speaker, "three").unwrap(); + core.input(&speaker, b"a").unwrap(); + let page = core.events_after(&watcher, page.current_sequence).unwrap(); + assert_eq!( + page.events.iter().map(|e| e.sequence).collect::>(), + [4] + ); + // Resuming from the last sequence it was given, across the gap, misses + // nothing and repeats nothing. + let last = page.events[0].sequence; + core.input(&speaker, b"b").unwrap(); + let page = core.events_after(&watcher, last).unwrap(); + assert_eq!( + page.events.iter().map(|e| e.sequence).collect::>(), + [5] + ); + } + + #[test] + fn chat_visibility_retention_does_not_depend_on_the_viewer() { + let mut core = world(3); + let (_, speaker) = join(&mut core, "Ada"); + let watcher = scoped(&mut core, "watch", &["join"]); + for line in ["one", "two", "three", "four"] { + core.chat(&speaker, line).unwrap(); + } + // Sequences 1..=4 committed; 2..=4 retained, all of them chat. + let page = core.events_after(&watcher, 0).unwrap(); + assert!(page.needs_snapshot, "the cursor fell behind retention"); + assert_eq!(page.oldest_retained_sequence, 2); + let snapshot = core.snapshot(&watcher).unwrap(); + assert!(snapshot.events.is_empty()); + assert_eq!(snapshot.current_sequence, 4); + assert_eq!(snapshot.oldest_retained_sequence, 5, "carries no events"); + } + + #[test] + fn chat_visibility_the_snapshot_budget_counts_only_what_it_carries() { + let mut core = WorldCore::new( + "budget", + WorldLimits { + snapshot_bytes: 400, + ..WorldLimits::default() + }, + ) + .unwrap(); + let (_, speaker) = join(&mut core, "Ada"); + let watcher = scoped(&mut core, "watch", &["join"]); + core.input(&speaker, b"a").unwrap(); + core.input(&speaker, b"b").unwrap(); + for _ in 0..20 { + core.chat(&speaker, &"x".repeat(100)).unwrap(); + } + let guest = core.snapshot(&speaker).unwrap(); + assert!( + guest.events.len() < 22 + && guest + .events + .iter() + .all(|e| matches!(e.kind, WorldEventKind::Chat(_))), + "chat fills the budget for a viewer who sees it" + ); + let snapshot = core.snapshot(&watcher).unwrap(); + assert_eq!( + snapshot + .events + .iter() + .map(|e| e.sequence) + .collect::>(), + [1, 2], + "withheld chat spends none of the budget" + ); + assert_eq!(snapshot.oldest_retained_sequence, 1); + } + + #[test] + fn chat_visibility_the_install_seed_stays_secret_for_every_scope() { + let event = WorldEvent { + sequence: 1, + participant_id: 0, + kind: WorldEventKind::ProgramInstalled { + module_hash: "ab".repeat(32), + seed: 424_242, + provenance: None, + }, + }; + for scopes in [WorldScopes::JOIN, WorldScopes::GUEST, WorldScopes::ALL] { + let shown = project_event_for(scopes, &event).unwrap(); + assert_eq!( + shown.kind, + WorldEventKind::ProgramInstalled { + module_hash: "ab".repeat(32), + seed: 0, + provenance: None, + } + ); + } + let chat = WorldEvent { + sequence: 2, + participant_id: 1, + kind: WorldEventKind::Chat("hi".to_owned()), + }; + assert_eq!(project_event_for(WorldScopes::JOIN, &chat), None); + assert_eq!( + project_event_for(WorldScopes::CHAT, &chat), + Some(chat.clone()) + ); + assert_eq!(project_event_for(WorldScopes::HISTORY, &chat), Some(chat)); + } + + #[tokio::test] + async fn chat_visibility_the_live_stream_is_projected_per_viewer() { + let core = world(16); + let world = WorldHandle::spawn(core); + let (_, guest) = world.issue("ann", WorldScopes::GUEST).await.unwrap(); + let (_, watcher) = world.issue("watch", WorldScopes::JOIN).await.unwrap(); + let mut live = world.subscribe(); + + world.chat(guest.clone(), "secret").await.unwrap(); + world + .install_program( + "cd".repeat(32), + 424_242, + Box::new(Counter { + count: 0, + bad: false, + }), + ) + .await + .unwrap(); + + let chat = live.recv().await.unwrap(); + let install = live.recv().await.unwrap(); + // The raw stream is the host's: it carries the line and the real seed. + assert_eq!(chat_texts(std::slice::from_ref(&chat)), ["secret"]); + assert!(matches!( + install.kind, + WorldEventKind::ProgramInstalled { seed: 424_242, .. } + )); + + // What a participant may be sent is the projection. + assert_eq!( + world + .project_event(watcher.clone(), chat.clone()) + .await + .unwrap(), + None + ); + assert_eq!( + world + .project_event(guest.clone(), chat.clone()) + .await + .unwrap(), + Some(chat) + ); + for token in [&guest, &watcher] { + let shown = world + .project_event(token.clone(), install.clone()) + .await + .unwrap() + .unwrap(); + assert!( + matches!(shown.kind, WorldEventKind::ProgramInstalled { seed: 0, .. }), + "{shown:?}" + ); + } + // A revoked participant is an error, so its session ends. + let (revoked, gone) = world.issue("gone", WorldScopes::JOIN).await.unwrap(); + assert!(world.revoke(revoked.id).await.unwrap()); + assert!(world.project_event(gone, install).await.is_err()); + } + + #[test] + fn chat_visibility_scope_names_attenuation_and_chains() { + assert_eq!( + WorldScopes::from_names(["history"]), + Some(WorldScopes::HISTORY) + ); + assert_eq!(WorldScopes::HISTORY.bits(), 0b1_0000); + assert_eq!(WorldScopes::from_names(["join", "telepathy"]), None); + assert_eq!(WorldScopes::from_bits(0b1_0000), Some(WorldScopes::HISTORY)); + assert_eq!(WorldScopes::from_bits(0b10_0000), None); + + let join_history = WorldScopes::JOIN.union(WorldScopes::HISTORY); + let chat_delegator = WorldScopes::GUEST.union(WorldScopes::DELEGATE); + let history_delegator = join_history.union(WorldScopes::DELEGATE); + // A reader delegates what it holds and no more; chat includes history. + assert_eq!( + history_delegator.attenuate(join_history), + Some(join_history) + ); + assert_eq!( + history_delegator.attenuate(WorldScopes::JOIN), + Some(WorldScopes::JOIN) + ); + assert!(history_delegator.attenuate(WorldScopes::GUEST).is_none()); + assert!( + history_delegator + .attenuate(WorldScopes::JOIN.union(WorldScopes::CHAT)) + .is_none(), + "reading does not include sending" + ); + assert_eq!(chat_delegator.attenuate(join_history), Some(join_history)); + assert!( + WorldScopes::GUEST.attenuate(join_history).is_none(), + "no delegate" + ); + assert!(WorldScopes::GUEST.reads_chat() && join_history.reads_chat()); + assert!(!WorldScopes::JOIN.union(WorldScopes::INPUT).reads_chat()); + assert!(WorldScopes::ALL.contains(WorldScopes::HISTORY)); + } + + #[test] + fn chat_visibility_a_guest_can_hand_out_a_read_only_link() { + let mut core = world(16); + let owner = scoped(&mut core, "owner", &["join", "chat", "input", "delegate"]); + let (_, reader) = core + .attenuate( + &owner, + WorldScopes::JOIN.union(WorldScopes::HISTORY), + CapabilityBounds::default(), + "reader", + ) + .unwrap(); + let (_, watcher) = core + .attenuate( + &owner, + WorldScopes::JOIN, + CapabilityBounds::default(), + "watch", + ) + .unwrap(); + core.chat(&owner, "hello").unwrap(); + assert_eq!( + chat_texts(&core.snapshot(&reader).unwrap().events), + ["hello"] + ); + assert!(chat_texts(&core.snapshot(&watcher).unwrap().events).is_empty()); + assert!(core.chat(&reader, "hi").is_err()); + } + + #[test] + fn snapshots_do_not_include_capability_secret() { + let mut core = world(8); + let (participant, token) = join(&mut core, "Ada"); + let serialized = format!("{:?}", core.snapshot(&token).unwrap()); + assert!(!serialized.contains(token.expose())); + assert!(serialized.contains(&participant.display_name)); + assert!(!format!("{token:?}").contains(token.expose())); + } + + #[tokio::test] + async fn actor_serializes_concurrent_event_mutations() { + let actor = WorldHandle::spawn(world(32)); + let (_, token) = actor.issue("Ada", WorldScopes::GUEST).await.unwrap(); + let first = actor.chat(token.clone(), "one"); + let second = actor.input(token.clone(), b"two".to_vec()); + let third = actor.chat(token.clone(), "three"); + let (one, two, three) = tokio::join!(first, second, third); + let mut sequences = [ + one.unwrap().sequence, + two.unwrap().sequence, + three.unwrap().sequence, + ]; + sequences.sort_unstable(); + assert_eq!(sequences, [1, 2, 3]); + assert_eq!(actor.snapshot(token).await.unwrap().current_sequence, 3); + } + + /// Counts inputs; records are the count, or `bad` after an input "bad". + struct Counter { + count: u64, + bad: bool, + } + + impl WorldProgram for Counter { + fn update(&mut self, event: &WorldEvent) -> Result<()> { + if let WorldEventKind::Input(bytes) = &event.kind { + self.count += 1; + self.bad = bytes.as_slice() == b"bad"; + } + Ok(()) + } + fn records(&mut self) -> Result> { + Ok(Some(if self.bad { + "[1,2,3]".to_owned() + } else { + format!("{{\"count\":{}}}", self.count) + })) + } + } + + #[tokio::test] + async fn records_read_returns_a_bounded_prefix_scoped_page() { + struct ReaderProgram { + asks: u64, + read_key: String, + } + impl WorldProgram for ReaderProgram { + fn update(&mut self, event: &WorldEvent) -> Result<()> { + match &event.kind { + WorldEventKind::Input(bytes) => { + if bytes.as_slice() == b"read" { + self.asks += 1; + } + } + WorldEventKind::System { event } => { + let value: serde_json::Value = + serde_json::from_str(event).unwrap_or(serde_json::Value::Null); + if value["cap"] == "result" + && let Some(key) = value["value"]["records"][0]["key"].as_str() + { + self.read_key = key.to_owned(); + } + } + WorldEventKind::Chat(_) | WorldEventKind::ProgramInstalled { .. } => {} + } + Ok(()) + } + + fn records(&mut self) -> Result> { + Ok(Some( + serde_json::json!({ + "count": self.asks, + "read": self.read_key, + }) + .to_string(), + )) + } + + fn wants(&mut self) -> Result> { + if self.asks == 0 { + return Ok(Some("{}".to_owned())); + } + Ok(Some( + serde_json::json!({ + "requests": [{ + "id": format!("read-{}", self.asks), + "cap": "records.read", + "args": {"prefix": "co", "after": ""}, + }], + }) + .to_string(), + )) + } + } + + let world = WorldHandle::spawn_with_program( + world(16), + Box::new(ReaderProgram { + asks: 0, + read_key: String::new(), + }), + ); + let (_, ann) = world.issue("ann", WorldScopes::GUEST).await.unwrap(); + + // Ungranted: the request is refused and counted. + world.input(ann.clone(), b"read".to_vec()).await.unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); + loop { + let report = world.caps_report().await.unwrap(); + if report + .usage + .get("records.read") + .is_some_and(|use_| use_.denied > 0) + { + break; + } + assert!(std::time::Instant::now() < deadline, "no refusal recorded"); + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + + // Granted: the program reads its own published `count` record. + world + .update_caps(vec!["records.read".to_owned()], Vec::new()) + .await + .unwrap(); + world.input(ann, b"read".to_vec()).await.unwrap(); + loop { + let record = world.records().1["read"].as_str().unwrap_or("").to_owned(); + if record == "count" { + break; + } + assert!( + std::time::Instant::now() < deadline, + "the program never read its record: {record:?}" + ); + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + } + + #[tokio::test] + async fn records_follow_committed_inputs_and_bad_output_fails_closed() { + let world = WorldHandle::spawn_with_program( + world(16), + Box::new(Counter { + count: 0, + bad: false, + }), + ); + assert_eq!(world.records().1["count"], 0); + let (_, ann) = world.issue("ann", WorldScopes::GUEST).await.unwrap(); + let event = world.input(ann.clone(), b"go".to_vec()).await.unwrap(); + let (sequence, records) = world.records(); + assert_eq!( + (sequence, records["count"].as_u64()), + (event.sequence, Some(1)) + ); + + // Records that are not a JSON object reject the input and poison the + // program; the previous records stay published. + assert!(world.input(ann.clone(), b"bad".to_vec()).await.is_err()); + assert_eq!(world.records().1["count"], 1); + assert!(world.input(ann.clone(), b"go".to_vec()).await.is_err()); + let snapshot = world.snapshot(ann.clone()).await.unwrap(); + assert_eq!( + snapshot.current_sequence, event.sequence, + "nothing committed" + ); + + // A replacement with valid records restores service. + world + .install_program( + "00".repeat(32), + 0, + Box::new(Counter { + count: 10, + bad: false, + }), + ) + .await + .unwrap(); + assert_eq!(world.records().1["count"], 10); + world.input(ann, b"go".to_vec()).await.unwrap(); + assert_eq!(world.records().1["count"], 11); + } + + #[tokio::test] + async fn installs_with_invalid_records_are_refused() { + let world = WorldHandle::spawn(world(16)); + let err = world + .install_program( + "00".repeat(32), + 0, + Box::new(Counter { + count: 0, + bad: true, + }), + ) + .await + .unwrap_err(); + assert!(format!("{err:#}").contains("records"), "{err:#}"); + let (_, ann) = world.issue("ann", WorldScopes::GUEST).await.unwrap(); + assert_eq!(world.snapshot(ann).await.unwrap().active_module_hash, None); + } + + #[test] + fn record_keys_and_sizes_are_bounded() { + assert!(parse_records(r#"{"a":1,"b":{"c":[true]}}"#).is_ok()); + assert!(parse_records("[]").is_err()); + assert!(parse_records(r#"{"":1}"#).is_err()); + assert!(parse_records("{\"a\\u0000b\":1}").is_err()); + let long_key = format!(r#"{{"{}":1}}"#, "k".repeat(MAX_RECORD_KEY_BYTES + 1)); + assert!(parse_records(&long_key).is_err()); + let big_value = format!(r#"{{"k":"{}"}}"#, "v".repeat(MAX_RECORD_VALUE_BYTES)); + assert!(parse_records(&big_value).is_err()); + let many: Records = (0..=MAX_RECORDS) + .map(|i| (i.to_string(), 0.into())) + .collect(); + assert!(parse_records(&serde_json::to_string(&many).unwrap()).is_err()); + } + + #[test] + fn snapshots_carry_the_newest_events_that_fit_their_budget() { + let mut core = WorldCore::new( + "budget", + WorldLimits { + snapshot_bytes: 1024, + input_bytes: 64, + ..WorldLimits::default() + }, + ) + .unwrap(); + let (_, token) = join(&mut core, "ann"); + for _ in 0..20u8 { + core.input(&token, &[b'x'; 48]).unwrap(); + } + let snapshot = core.snapshot(&token).unwrap(); + assert_eq!(snapshot.current_sequence, 20); + assert!(!snapshot.events.is_empty()); + assert!( + serde_json::to_vec(&snapshot.events).unwrap().len() <= 1024, + "events fit the budget" + ); + assert!( + snapshot.events.len() < 20, + "an oversized log is truncated to the newest events" + ); + let first = snapshot.events.first().unwrap().sequence; + assert_eq!(snapshot.oldest_retained_sequence, first); + assert_eq!(snapshot.events.last().unwrap().sequence, 20); + // The snapshot is a valid rebase point: continuing from its cursor + // yields only new events. + assert!( + core.events_after(&token, snapshot.current_sequence) + .unwrap() + .events + .is_empty() + ); + } + + /// A program whose `view` traps exactly once, then recovers. Used to prove + /// a trapping view does not poison the world (F11.17). + #[derive(Default)] + struct TrapsOnce { + calls: u64, + } + + impl WorldProgram for TrapsOnce { + fn view(&mut self, _viewer: &Participant) -> Result> { + self.calls += 1; + if self.calls == 1 { + anyhow::bail!("boom on the first view"); + } + Ok(Some("recovered view".to_owned())) + } + } + + #[tokio::test] + async fn a_trapping_view_degrades_to_an_error_and_recovers_on_the_next_event() { + let mut core = WorldCore::new("trap", WorldLimits::default()).unwrap(); + let (_, token) = join(&mut core, "ann"); + let mut actor = WorldActor::for_test(core, Box::new(TrapsOnce::default()), None); + + let (reply, rx) = tokio::sync::oneshot::channel(); + actor + .handle(WorldCommand::View { + token: token.clone(), + reply, + }) + .await; + let first = rx.await.unwrap(); + assert!( + matches!(&first, Err(e) if e.to_string().contains("view failed")), + "the trap is reported as a view failure: {first:?}" + ); + assert!( + actor.program_healthy, + "a trapping view must not poison the world" + ); + assert_eq!(actor.view_failures, 1, "the trap is counted"); + + // The next event retries the view and recovers, no reinstall needed. + let (reply, rx) = tokio::sync::oneshot::channel(); + actor + .handle(WorldCommand::View { + token: token.clone(), + reply, + }) + .await; + let second = rx.await.unwrap(); + assert!( + matches!(&second, Ok(Some(text)) if text == "recovered view"), + "the next view recovers: {second:?}" + ); + assert_eq!(actor.view_failures, 1, "only the one trap is counted"); + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod account_tests { + use super::*; + use crate::directory::{Actor, Tier}; + use crate::world::*; + + fn core() -> WorldCore { + WorldCore::new("w", WorldLimits::default()).unwrap() + } + + fn account(core: &mut WorldCore, name: &str) -> (String, String) { + let (credential, _) = core.directory_mut().sign_up(name).unwrap(); + let id = core.directory().account_for(&credential).unwrap(); + (id, credential) + } + + #[tokio::test] + async fn a_friend_delegation_through_the_handle_is_held_to_the_friendship() { + let mut core = core(); + let (ann, ann_credential) = account(&mut core, "Ann"); + let (bo, bo_credential) = account(&mut core, "Bo"); + let (cy, _) = account(&mut core, "Cy"); + core.directory_mut() + .verify_account(Actor::Server, &ann) + .unwrap(); + befriend(&mut core, &ann, &ann_credential, &bo, &bo_credential); + let (_, ann_token) = core + .issue_for_account( + &ann_credential, + WorldScopes::ALL, + CapabilityBounds::default(), + "Ann", + ) + .unwrap(); + let handle = WorldHandle::spawn(core); + + let (_, bo_token) = handle + .delegate_to_friend( + ann_token.clone(), + bo, + WorldScopes::GUEST, + CapabilityBounds::default(), + "Bo", + ) + .await + .unwrap(); + handle.chat(bo_token, "hi").await.unwrap(); + assert!( + handle + .delegate_to_friend( + ann_token, + cy, + WorldScopes::GUEST, + CapabilityBounds::default(), + "Cy" + ) + .await + .is_err(), + "only friends may be delegated to" + ); + } + + #[tokio::test] + async fn a_bounded_issue_stops_after_its_uses() { + let handle = WorldHandle::spawn(core()); + let bounds = CapabilityBounds { + expires_at: None, + uses: Some(1), + }; + let (_, token) = handle + .issue_bounded("Ann", WorldScopes::GUEST, bounds) + .await + .unwrap(); + handle.chat(token.clone(), "once").await.unwrap(); + assert!(handle.chat(token, "twice").await.is_err()); + } + + fn befriend(core: &mut WorldCore, a: &str, a_credential: &str, b: &str, b_credential: &str) { + let world = core.world_id().to_owned(); + core.directory_mut() + .request_friend(a_credential, b, &world, 1) + .unwrap(); + core.directory_mut() + .accept_friend(b_credential, a, &world, 2) + .unwrap(); + } + + #[test] + fn a_ceiling_that_allows_chat_allows_reading_it() { + let mut core = core(); + let (_, ann_credential) = account(&mut core, "Ann"); + let (_, guest) = core + .issue_for_account( + &ann_credential, + WorldScopes::GUEST, + CapabilityBounds::default(), + "Ann", + ) + .unwrap(); + let (_, reader) = core + .issue_for_account( + &ann_credential, + WorldScopes::JOIN.union(WorldScopes::HISTORY), + CapabilityBounds::default(), + "Ann reads", + ) + .unwrap(); + core.chat(&guest, "hello").unwrap(); + assert_eq!(core.snapshot(&reader).unwrap().events.len(), 1); + assert!(core.chat(&reader, "hi").is_err()); + } + + #[test] + fn an_account_capability_is_held_to_its_ceiling() { + let mut core = core(); + let (_, ann_credential) = account(&mut core, "Ann"); + assert!( + core.issue_for_account( + &ann_credential, + WorldScopes::ALL, + CapabilityBounds::default(), + "Ann" + ) + .is_err(), + "a registered account cannot be issued delegate scope" + ); + assert!( + core.issue_for_account( + "acct.forged.00", + WorldScopes::GUEST, + CapabilityBounds::default(), + "Ann" + ) + .is_err() + ); + let (_, token) = core + .issue_for_account( + &ann_credential, + WorldScopes::GUEST, + CapabilityBounds::default(), + "Ann", + ) + .unwrap(); + core.chat(&token, "hello").unwrap(); + core.directory_mut() + .set_tier(Actor::Server, Tier::Registered, WorldScopes::JOIN) + .unwrap(); + assert!( + core.chat(&token, "again").is_err(), + "a narrowed tier narrows the capability" + ); + assert!(core.snapshot(&token).is_ok()); + } + + #[test] + fn an_account_capability_serializes_its_subject_but_no_secret() { + let mut core = core(); + let (ann, ann_credential) = account(&mut core, "Ann"); + let (participant, _) = core + .issue_for_account( + &ann_credential, + WorldScopes::GUEST, + CapabilityBounds::default(), + "Ann", + ) + .unwrap(); + let entry = core.issued_entry(participant.id).unwrap(); + let text = serde_json::to_string(&entry).unwrap(); + assert!(text.contains(&ann)); + let secret = ann_credential.rsplit('.').next().unwrap(); + assert!(!text.contains(secret)); + let back: JournalEntry = serde_json::from_str(&text).unwrap(); + assert_eq!(back, entry); + } + + #[test] + fn a_delegation_to_a_friend_is_held_to_the_friends_ceiling_and_ends_with_the_friendship() { + let mut core = core(); + let (ann, ann_credential) = account(&mut core, "Ann"); + let (bo, bo_credential) = account(&mut core, "Bo"); + let (cy, _) = account(&mut core, "Cy"); + core.directory_mut() + .verify_account(Actor::Server, &ann) + .unwrap(); + befriend(&mut core, &ann, &ann_credential, &bo, &bo_credential); + let (_, ann_token) = core + .issue_for_account( + &ann_credential, + WorldScopes::ALL, + CapabilityBounds::default(), + "Ann", + ) + .unwrap(); + + assert!( + core.delegate_to_friend( + &ann_token, + &bo, + WorldScopes::ALL, + CapabilityBounds::default(), + "Bo" + ) + .is_err(), + "bo's ceiling does not include delegate" + ); + assert!( + core.delegate_to_friend( + &ann_token, + &cy, + WorldScopes::GUEST, + CapabilityBounds::default(), + "Cy" + ) + .is_err(), + "only friends may be delegated to" + ); + let (_, bo_token) = core + .delegate_to_friend( + &ann_token, + &bo, + WorldScopes::GUEST, + CapabilityBounds::default(), + "Bo", + ) + .unwrap(); + core.chat(&bo_token, "hi").unwrap(); + assert!( + core.attenuate( + &bo_token, + WorldScopes::JOIN, + CapabilityBounds::default(), + "Di" + ) + .is_err(), + "bo's delegation carries no delegate scope" + ); + + core.directory_mut() + .remove_friend(&ann_credential, &bo) + .unwrap(); + assert!( + core.snapshot(&bo_token).is_err(), + "the delegation ends with the friendship" + ); + assert!(core.snapshot(&ann_token).is_ok()); + } + + #[test] + fn only_an_account_capability_may_delegate_to_a_friend() { + let mut core = core(); + let (bo, bo_credential) = account(&mut core, "Bo"); + let (ann, ann_credential) = account(&mut core, "Ann"); + befriend(&mut core, &ann, &ann_credential, &bo, &bo_credential); + let (_, anonymous) = core + .issue_capability("Guest", WorldScopes::ALL, CapabilityBounds::default()) + .unwrap(); + assert!( + core.delegate_to_friend( + &anonymous, + &bo, + WorldScopes::GUEST, + CapabilityBounds::default(), + "Bo" + ) + .is_err() + ); + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod isolation_tests { + use super::*; + use crate::directory::{Actor, Level, Member, Refusal}; + use crate::world::*; + + struct Staff { + core: WorldCore, + member: String, + writer: String, + manager: String, + moderator: String, + admin: String, + stranger: String, + } + + fn account(core: &mut WorldCore, name: &str) -> String { + let (credential, _) = core.directory_mut().sign_up(name).unwrap(); + core.directory().account_for(&credential).unwrap() + } + + fn seat(core: &mut WorldCore, group: u64, name: &str, level: Level) -> String { + let id = account(core, name); + core.directory_mut() + .set_member( + Actor::Server, + group, + Member::Account { id: id.clone() }, + Some(level), + ) + .unwrap(); + id + } + + /// One group with a holder of each level, plus an account outside it. + fn staffed() -> Staff { + let mut core = WorldCore::new("staffed", WorldLimits::default()).unwrap(); + let founder = account(&mut core, "Founder"); + let (group, _) = core + .directory_mut() + .create_group(&founder, "staff", "", WorldScopes::GUEST) + .unwrap(); + Staff { + member: seat(&mut core, group, "Member", Level::Access), + writer: seat(&mut core, group, "Writer", Level::Write), + manager: seat(&mut core, group, "Manager", Level::Manage), + moderator: seat(&mut core, group, "Moderator", Level::Moderator), + admin: seat(&mut core, group, "Admin", Level::Admin), + stranger: account(&mut core, "Stranger"), + core, + } + } + + #[tokio::test] + async fn worlds_start_isolated() { + assert_eq!(Isolation::default(), Isolation::Isolated); + let handle = WorldHandle::spawn(WorldCore::new("w", WorldLimits::default()).unwrap()); + assert_eq!(handle.isolation().await.unwrap(), Isolation::Isolated); + } + + #[tokio::test] + async fn only_a_moderator_or_an_admin_sets_isolation() { + let staff = staffed(); + let handle = WorldHandle::spawn(staff.core); + for who in [ + &staff.member, + &staff.writer, + &staff.manager, + &staff.stranger, + ] { + let error = handle + .set_isolation(Authority::Signed(who.clone()), Isolation::Unisolated) + .await + .unwrap_err(); + assert!( + matches!(error.downcast_ref::(), Some(Refusal::Forbidden(_))), + "{who} must not change isolation" + ); + } + assert_eq!(handle.isolation().await.unwrap(), Isolation::Isolated); + + assert_eq!( + handle + .set_isolation( + Authority::Signed(staff.moderator.clone()), + Isolation::Unisolated + ) + .await + .unwrap(), + Isolation::Unisolated + ); + assert_eq!( + handle + .set_isolation(Authority::Signed(staff.admin.clone()), Isolation::Isolated) + .await + .unwrap(), + Isolation::Isolated + ); + assert_eq!( + handle + .set_isolation(Authority::Admin, Isolation::Unisolated) + .await + .unwrap(), + Isolation::Unisolated + ); + } + + #[test] + fn a_checkpoint_keeps_the_isolation() { + let mut core = WorldCore::new("iso", WorldLimits::default()).unwrap(); + core.isolation = Isolation::Unisolated; + core.active_module_hash = Some("h".to_owned()); + let entries = core.checkpoint_entries("snapshot".to_owned()).unwrap(); + assert!(entries.iter().any(|entry| matches!( + entry, + JournalEntry::Isolation { + isolation: Isolation::Unisolated + } + ))); + } + + fn forbidden(error: &anyhow::Error) -> bool { + matches!(error.downcast_ref::(), Some(Refusal::Forbidden(_))) + } + + #[tokio::test] + async fn only_a_moderator_or_an_admin_sets_cross_world_write() { + let staff = staffed(); + let handle = WorldHandle::spawn(staff.core); + for who in [ + &staff.member, + &staff.writer, + &staff.manager, + &staff.stranger, + ] { + let error = handle + .set_cross_world_write(Authority::Signed(who.clone()), true) + .await + .unwrap_err(); + assert!( + forbidden(&error), + "{who} must not change cross-world writes" + ); + } + assert!(!handle.policy().await.unwrap().cross_world_write); + + let policy = handle + .set_cross_world_write(Authority::Signed(staff.moderator.clone()), true) + .await + .unwrap(); + assert!(policy.cross_world_write && !policy.cross_world_forced); + let policy = handle + .set_cross_world_write(Authority::Signed(staff.moderator.clone()), false) + .await + .unwrap(); + assert!(!policy.cross_world_write); + } + + #[tokio::test] + async fn only_the_admin_forces_cross_world_writes() { + let staff = staffed(); + let handle = WorldHandle::spawn(staff.core); + handle + .set_isolation(Authority::Admin, Isolation::Unisolated) + .await + .unwrap(); + for who in [&staff.moderator, &staff.admin] { + let error = handle + .force_cross_world_write(Authority::Signed(who.clone())) + .await + .unwrap_err(); + assert!(forbidden(&error), "{who} must not force cross-world writes"); + } + assert!(!handle.policy().await.unwrap().cross_world_forced); + } + + #[tokio::test] + async fn an_isolated_world_cannot_be_forced() { + let handle = WorldHandle::spawn(WorldCore::new("w", WorldLimits::default()).unwrap()); + let error = handle + .force_cross_world_write(Authority::Admin) + .await + .unwrap_err(); + assert!(forbidden(&error)); + assert!(error.to_string().contains("isolated"), "{error}"); + assert!(!handle.policy().await.unwrap().cross_world_forced); + } + + #[tokio::test] + async fn a_forced_write_stays_on_against_a_moderator() { + let staff = staffed(); + let handle = WorldHandle::spawn(staff.core); + handle + .set_isolation(Authority::Admin, Isolation::Unisolated) + .await + .unwrap(); + handle + .force_cross_world_write(Authority::Admin) + .await + .unwrap(); + + let error = handle + .set_cross_world_write(Authority::Signed(staff.moderator.clone()), false) + .await + .unwrap_err(); + assert!(forbidden(&error)); + let policy = handle.policy().await.unwrap(); + assert!(policy.cross_world_write && policy.cross_world_forced); + + let policy = handle + .set_cross_world_write(Authority::Admin, false) + .await + .unwrap(); + assert!(!policy.cross_world_write && !policy.cross_world_forced); + } + + #[tokio::test] + async fn a_moderator_turns_off_a_write_that_was_not_forced() { + let staff = staffed(); + let handle = WorldHandle::spawn(staff.core); + handle + .set_cross_world_write(Authority::Signed(staff.moderator.clone()), true) + .await + .unwrap(); + let policy = handle + .set_cross_world_write(Authority::Signed(staff.moderator.clone()), false) + .await + .unwrap(); + assert!(!policy.cross_world_write); + } + + #[tokio::test] + async fn file_scope_is_moderated_and_the_override_is_admin_only() { + let staff = staffed(); + let handle = WorldHandle::spawn(staff.core); + assert_eq!( + handle.policy().await.unwrap(), + WorldPolicy { + isolation: Isolation::Isolated, + cross_world_write: false, + cross_world_forced: false, + file_scope: FileScope::Confined, + file_write_override: false, + } + ); + for who in [ + &staff.member, + &staff.writer, + &staff.manager, + &staff.stranger, + ] { + let error = handle + .set_file_scope( + Authority::Signed(who.clone()), + FileScope::Unrestricted, + None, + ) + .await + .unwrap_err(); + assert!(forbidden(&error), "{who} must not change the file scope"); + } + + let error = handle + .set_file_scope( + Authority::Signed(staff.moderator.clone()), + FileScope::Unrestricted, + Some(true), + ) + .await + .unwrap_err(); + assert!(forbidden(&error)); + assert_eq!( + handle.policy().await.unwrap().file_scope, + FileScope::Confined + ); + + let policy = handle + .set_file_scope( + Authority::Signed(staff.moderator.clone()), + FileScope::Unrestricted, + None, + ) + .await + .unwrap(); + assert_eq!(policy.file_scope, FileScope::Unrestricted); + assert!(!policy.file_write_override); + + let policy = handle + .set_file_scope(Authority::Admin, FileScope::Unrestricted, Some(true)) + .await + .unwrap(); + assert!(policy.file_write_override); + } + + #[test] + fn file_access_follows_isolation_scope_and_override() { + use FileMode::{Read, Write}; + use FileScope::{Confined, Unrestricted}; + use Isolation::{Isolated, Unisolated}; + let policy = |isolation, file_scope, file_write_override| WorldPolicy { + isolation, + cross_world_write: false, + cross_world_forced: false, + file_scope, + file_write_override, + }; + // (policy, mode, inside own root, allowed) + let cases = [ + (policy(Unisolated, Confined, false), Read, true, true), + (policy(Unisolated, Confined, false), Read, false, false), + (policy(Unisolated, Confined, false), Write, true, true), + (policy(Unisolated, Confined, false), Write, false, false), + (policy(Unisolated, Unrestricted, false), Read, false, true), + (policy(Unisolated, Unrestricted, false), Write, false, true), + (policy(Isolated, Confined, false), Read, true, true), + (policy(Isolated, Confined, false), Read, false, false), + (policy(Isolated, Confined, false), Write, true, false), + (policy(Isolated, Unrestricted, false), Read, false, true), + (policy(Isolated, Unrestricted, false), Write, false, false), + (policy(Isolated, Unrestricted, true), Write, false, true), + (policy(Isolated, Confined, true), Write, true, true), + (policy(Isolated, Confined, true), Write, false, false), + ]; + for (policy, mode, inside_root, expected) in cases { + assert_eq!( + policy.file_allowed(mode, inside_root), + expected, + "{policy:?} {mode:?} inside root {inside_root}" + ); + } + } + + #[test] + fn a_default_world_reads_only_inside_its_root() { + let policy = WorldCore::new("w", WorldLimits::default()) + .unwrap() + .policy(); + assert_eq!(policy.file_scope, FileScope::Confined); + assert!(!policy.file_write_override); + assert!(policy.file_allowed(FileMode::Read, true)); + assert!(!policy.file_allowed(FileMode::Read, false)); + assert!(!policy.file_allowed(FileMode::Write, true)); + } + + #[test] + fn a_checkpoint_keeps_the_sharing_settings() { + for (cross_world_write, cross_world_forced) in [(true, false), (true, true), (false, false)] + { + let mut core = WorldCore::new("share", WorldLimits::default()).unwrap(); + core.isolation = Isolation::Unisolated; + core.cross_world_write = cross_world_write; + core.cross_world_forced = cross_world_forced; + core.file_scope = FileScope::Unrestricted; + core.file_write_override = true; + core.active_module_hash = Some("h".to_owned()); + let entries = core.checkpoint_entries("snapshot".to_owned()).unwrap(); + let restored = WorldCore::restore("share", WorldLimits::default(), entries).unwrap(); + assert_eq!(restored.core.policy(), core.policy()); + } + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod schedule_tests { + use super::*; + use crate::world::*; + + fn world(retained_events: usize) -> WorldCore { + WorldCore::new( + "test-world", + WorldLimits { + retained_events, + ..WorldLimits::default() + }, + ) + .unwrap() + } + + /// A program for the schedule tests. Each input is a request document, and + /// the program asks for its requests until each one's result arrives. Its + /// records carry every schedule fire and every result, so a test reads them + /// through `WorldHandle::records`. + #[derive(Default)] + struct Scheduler { + requests: Vec, + answered: BTreeSet, + results: BTreeMap, + fires: Vec, + refuse_fires: bool, + } + + impl WorldProgram for Scheduler { + fn update(&mut self, event: &WorldEvent) -> Result<()> { + match &event.kind { + WorldEventKind::Input(bytes) => { + let document: serde_json::Value = serde_json::from_slice(bytes)?; + self.requests = document["requests"].as_array().cloned().unwrap_or_default(); + } + WorldEventKind::System { event: text } => { + let Ok(value) = serde_json::from_str::(text) else { + return Ok(()); + }; + match value["cap"].as_str() { + Some("result") => { + if let Some(id) = value["id"].as_str() { + self.answered.insert(id.to_owned()); + self.results.insert(id.to_owned(), value.clone()); + } + } + Some("schedule") => { + if self.refuse_fires { + bail!("this program refuses schedule fires"); + } + self.fires.push(value.clone()); + } + _ => {} + } + } + WorldEventKind::Chat(_) | WorldEventKind::ProgramInstalled { .. } => {} + } + Ok(()) + } + + fn wants(&mut self) -> Result> { + let pending: Vec<&serde_json::Value> = self + .requests + .iter() + .filter(|request| { + !request["id"] + .as_str() + .is_some_and(|id| self.answered.contains(id)) + }) + .collect(); + Ok(Some( + serde_json::json!({"v": 1, "requests": pending}).to_string(), + )) + } + + fn records(&mut self) -> Result> { + Ok(Some( + serde_json::json!({"fired": self.fires, "results": self.results}).to_string(), + )) + } + } + + /// A journal kept in memory, so a test can restore from what was written. + #[derive(Clone, Default)] + struct Recorded(Arc>>); + + impl Recorded { + /// A journal that starts with the header a real world writes first. + fn for_world(world_id: &str) -> Self { + let journal = Self::default(); + journal.0.lock().unwrap().push(JournalEntry::Created { + world_id: world_id.to_owned(), + version: JOURNAL_VERSION, + }); + journal + } + + fn entries(&self) -> Vec { + self.0.lock().unwrap().clone() + } + } + + impl WorldJournal for Recorded { + fn append(&mut self, entry: &JournalEntry) -> Result<()> { + self.0.lock().unwrap().push(entry.clone()); + Ok(()) + } + } + + /// The manual clock's start time, in unix milliseconds. + const EPOCH_MS: u64 = 1_000_000_000_000; + + /// A journaled actor running a `Scheduler` on a manual clock, with one + /// participant and the given grants. Nothing is spawned: the test drives + /// [`WorldActor::handle`], [`WorldActor::after_change`] and + /// [`WorldActor::fire_schedules`] directly, advancing the clock by hand. + fn scheduling_actor( + id: &str, + grants: &[&str], + refuse_fires: bool, + ) -> (WorldActor, Arc, JoinCapability, Recorded) { + let journal = Recorded::for_world(id); + let clock: Arc = Arc::new(ManualClock::new(EPOCH_MS)); + let mut core = + WorldCore::new_with_clock(id, WorldLimits::default(), clock.clone()).unwrap(); + core.ledger + .set_granted(grants.iter().map(|grant| (*grant).to_owned()).collect()); + let (_, token) = core + .issue_capability("ann", WorldScopes::GUEST, CapabilityBounds::default()) + .unwrap(); + let program = Scheduler { + refuse_fires, + ..Scheduler::default() + }; + let actor = WorldActor::for_test(core, Box::new(program), Some(Box::new(journal.clone()))); + (actor, clock, token, journal) + } + + /// Drive one input document through the actor exactly as its run loop + /// would: handle, settle the program's wants, then clear `acting`. + async fn ask(actor: &mut WorldActor, token: &JoinCapability, document: serde_json::Value) { + let (reply, response) = tokio::sync::oneshot::channel(); + actor + .handle(WorldCommand::Input { + token: token.clone(), + input: document.to_string().into_bytes(), + reply, + }) + .await; + actor.after_change().await; + actor.acting = None; + let _ = response.await.unwrap().unwrap(); + } + + /// The records the program last published. + fn records(actor: &WorldActor) -> Arc { + actor.records_sender.borrow().1.clone() + } + + /// The schedule fire events the program has received so far. + fn schedule_fires(actor: &WorldActor) -> Vec { + records(actor) + .get("fired") + .and_then(serde_json::Value::as_array) + .cloned() + .unwrap_or_default() + } + + /// The result event the program received for request `id`, if any. + fn schedule_result(actor: &WorldActor, id: &str) -> Option { + records(actor) + .get("results") + .and_then(|results| results.get(id)) + .cloned() + } + + #[test] + fn schedule_bounds_refuse_each_violation_with_a_reason() { + let now = 1_000_000_000_000u64; + let horizon = crate::world_caps::MAX_SCHEDULE_HORIZON_MS; + let mut core = world(8); + assert!(core.check_schedule("ok", now, now).is_ok()); + assert!(core.check_schedule(&"x".repeat(64), now, now).is_ok()); + let long = "x".repeat(65); + for bad in ["", "tab\there", long.as_str()] { + let error = core.check_schedule(bad, now, now).unwrap_err(); + assert!(error.to_string().contains("schedule id"), "{error}"); + } + + core.schedules.insert("taken".to_owned(), now + 5); + let error = core.check_schedule("taken", now + 9, now).unwrap_err(); + assert!(error.to_string().contains("already pending"), "{error}"); + assert_eq!( + core.schedules["taken"], + now + 5, + "a duplicate overwrites nothing" + ); + + assert!(core.check_schedule("edge", now + horizon, now).is_ok()); + let error = core + .check_schedule("far", now + horizon + 1, now) + .unwrap_err(); + assert!(error.to_string().contains("days past"), "{error}"); + assert!(core.check_schedule("past", 0, now).is_ok()); + + let mut full = world(8); + for index in 0..crate::world_caps::MAX_PENDING_SCHEDULES - 1 { + full.schedules.insert(format!("s{index}"), now); + } + assert!(full.check_schedule("last", now, now).is_ok()); + full.schedules.insert("last".to_owned(), now); + 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); + ask( + &mut actor, + &token, + serde_json::json!({"requests": [ + {"id": "s1", "cap": "schedule.at", "args": {"id": "nap", "at": EPOCH_MS + 60_000}}, + ]}), + ) + .await; + assert_eq!( + schedule_result(&actor, "s1").unwrap()["error"], + "cap_denied" + ); + assert!( + actor.core.ledger.usage()["schedule.at"].denied > 0, + "{:?}", + actor.core.ledger.usage() + ); + assert!( + journal + .entries() + .iter() + .all(|entry| !matches!(entry, JournalEntry::ScheduleSet { .. })), + "a refused request pends nothing" + ); + } + + #[tokio::test] + async fn a_due_schedule_fires_once_and_the_program_receives_it() { + let (mut actor, clock, token, journal) = + scheduling_actor("sched-fire", &["schedule.at"], false); + ask( + &mut actor, + &token, + serde_json::json!({"requests": [ + {"id": "s1", "cap": "schedule.at", "args": {"id": "now", "at": EPOCH_MS + 1}}, + ]}), + ) + .await; + // Not due at the epoch; only after the clock passes the due time. + actor.fire_schedules().await; + assert!(schedule_fires(&actor).is_empty(), "not due yet"); + clock.advance(1); + actor.fire_schedules().await; + let fires = schedule_fires(&actor); + assert_eq!(fires.len(), 1, "{fires:?}"); + assert_eq!(fires[0]["id"], "now"); + assert!( + fires[0].get("late").is_none(), + "a fire in this run is not late" + ); + // A second wakeup fires nothing: the schedule was consumed. + actor.fire_schedules().await; + assert_eq!(schedule_fires(&actor).len(), 1); + + let entries = journal.entries(); + let fire = WorldEventKind::System { + event: schedule_fired_event("now", false), + }; + let delivered = entries + .iter() + .position(|entry| matches!(entry, JournalEntry::System { event } if event.kind == fire)) + .expect("the fire is journaled as delivered"); + let consumed = entries + .iter() + .position(|entry| matches!(entry, JournalEntry::ScheduleFired { id } if id == "now")) + .expect("the schedule is consumed"); + assert!(delivered < consumed, "the delivery is journaled first"); + assert_eq!( + entries + .iter() + .filter(|entry| matches!(entry, JournalEntry::ScheduleFired { .. })) + .count(), + 1 + ); + } + + #[tokio::test] + async fn a_cancelled_schedule_never_fires_and_an_unknown_id_says_false() { + let (mut actor, clock, token, _journal) = + scheduling_actor("sched-cancel", &["schedule.at", "schedule.cancel"], false); + let at = EPOCH_MS; + // One pass: the cancel runs before any fire can fire the schedule. + ask( + &mut actor, + &token, + serde_json::json!({"requests": [ + {"id": "s1", "cap": "schedule.at", "args": {"id": "soon", "at": at}}, + {"id": "c1", "cap": "schedule.cancel", "args": {"id": "soon"}}, + {"id": "c2", "cap": "schedule.cancel", "args": {"id": "ghost"}}, + ]}), + ) + .await; + assert_eq!( + schedule_result(&actor, "s1").unwrap()["value"]["fires_at"], + at + ); + assert_eq!( + schedule_result(&actor, "c1").unwrap()["value"]["cancelled"], + true + ); + assert_eq!( + schedule_result(&actor, "c2").unwrap()["value"]["cancelled"], + false + ); + clock.advance(10_000); + actor.fire_schedules().await; + assert!( + schedule_fires(&actor).is_empty(), + "a cancelled schedule must not fire" + ); + } + + #[tokio::test] + async fn refused_schedule_requests_pend_nothing() { + let (mut actor, _clock, token, journal) = + scheduling_actor("sched-bad", &["schedule.at", "schedule.cancel"], false); + let later = EPOCH_MS + 3_600_000; + let far = EPOCH_MS + crate::world_caps::MAX_SCHEDULE_HORIZON_MS + 60_000; + let long_id = "x".repeat(65); + ask( + &mut actor, + &token, + serde_json::json!({"requests": [ + {"id": "ok", "cap": "schedule.at", "args": {"id": "kept", "at": later}}, + {"id": "empty", "cap": "schedule.at", "args": {"id": "", "at": later}}, + {"id": "long", "cap": "schedule.at", "args": {"id": long_id, "at": later}}, + {"id": "far", "cap": "schedule.at", "args": {"id": "far", "at": far}}, + {"id": "dup", "cap": "schedule.at", "args": {"id": "kept", "at": later}}, + {"id": "missing", "cap": "schedule.at", "args": {"id": "nothing"}}, + {"id": "text", "cap": "schedule.at", "args": {"id": "t", "at": "soon"}}, + {"id": "bad-cancel", "cap": "schedule.cancel", "args": {"id": "a\nb"}}, + ]}), + ) + .await; + assert_eq!(schedule_result(&actor, "ok").unwrap()["ok"], true); + for id in [ + "empty", + "long", + "far", + "dup", + "missing", + "text", + "bad-cancel", + ] { + assert_eq!( + schedule_result(&actor, id).unwrap()["error"], + "bad_args", + "{id}" + ); + } + let pended: Vec = journal + .entries() + .into_iter() + .filter_map(|entry| match entry { + JournalEntry::ScheduleSet { id, .. } => Some(id), + _ => None, + }) + .collect(); + assert_eq!(pended, ["kept"], "only the accepted request is journaled"); + } + + #[tokio::test] + async fn a_fire_the_program_refuses_stays_pending_in_the_journal() { + let (mut actor, clock, token, journal) = + scheduling_actor("sched-refuse", &["schedule.at"], true); + ask( + &mut actor, + &token, + serde_json::json!({"requests": [ + {"id": "s1", "cap": "schedule.at", "args": {"id": "stuck", "at": EPOCH_MS}}, + ]}), + ) + .await; + assert!(schedule_result(&actor, "s1").is_some()); + clock.advance(1); + actor.fire_schedules().await; + // The program is unavailable now, but the actor still holds the state. + assert!(!actor.program_healthy); + + let entries = journal.entries(); + assert!( + !entries + .iter() + .any(|entry| matches!(entry, JournalEntry::ScheduleFired { .. })), + "a refused fire is not consumed" + ); + let journaled_fire = entries.iter().any(|entry| match entry { + JournalEntry::System { event } => matches!( + &event.kind, + WorldEventKind::System { event } if event.contains("\"schedule\"") + ), + _ => false, + }); + assert!(!journaled_fire, "a refused fire is not journaled"); + let restored = WorldCore::restore("sched-refuse", WorldLimits::default(), entries).unwrap(); + assert!( + restored.core.schedules.contains_key("stuck"), + "the next run delivers it" + ); + } + + #[tokio::test] + async fn a_schedule_overdue_at_restart_fires_late_on_the_first_wakeup() { + let entries = vec![ + JournalEntry::Created { + world_id: "sched-late".to_owned(), + version: JOURNAL_VERSION, + }, + JournalEntry::ScheduleSet { + id: "overdue".to_owned(), + at_ms: EPOCH_MS - 5_000, + }, + ]; + let restored = WorldCore::restore("sched-late", WorldLimits::default(), entries).unwrap(); + let journal = Recorded::default(); + let clock: Arc = Arc::new(ManualClock::new(EPOCH_MS)); + let mut core = restored.core; + core.clock = clock.clone(); + let mut actor = WorldActor::for_test( + core, + Box::new(Scheduler::default()), + Some(Box::new(journal.clone())), + ); + actor.fire_schedules().await; + let fires = schedule_fires(&actor); + assert_eq!(fires.len(), 1, "{fires:?}"); + assert_eq!(fires[0]["id"], "overdue"); + assert_eq!(fires[0]["late"], true); + assert!( + journal.entries().iter().any( + |entry| matches!(entry, JournalEntry::ScheduleFired { id } if id == "overdue") + ) + ); + } + + #[tokio::test] + async fn a_pending_schedule_survives_a_restart_and_fires_on_time() { + let at_ms = EPOCH_MS + 700; + let entries = vec![ + JournalEntry::Created { + world_id: "sched-later".to_owned(), + version: JOURNAL_VERSION, + }, + JournalEntry::ScheduleSet { + id: "later".to_owned(), + at_ms, + }, + ]; + let restored = WorldCore::restore("sched-later", WorldLimits::default(), entries).unwrap(); + assert_eq!(restored.core.schedules.get("later"), Some(&at_ms)); + let clock: Arc = Arc::new(ManualClock::new(EPOCH_MS)); + let mut core = restored.core; + core.clock = clock.clone(); + let mut actor = WorldActor::for_test(core, Box::new(Scheduler::default()), None); + actor.fire_schedules().await; + assert!(schedule_fires(&actor).is_empty(), "not due yet"); + clock.advance(700); + actor.fire_schedules().await; + let fires = schedule_fires(&actor); + assert_eq!(fires[0]["id"], "later"); + assert!(fires[0].get("late").is_none(), "it was not overdue at open"); + } + + #[tokio::test] + async fn replay_reproduces_the_pending_and_fired_sets() { + let (mut actor, clock, token, journal) = + scheduling_actor("sched-replay", &["schedule.at", "schedule.cancel"], false); + ask( + &mut actor, + &token, + serde_json::json!({"requests": [ + {"id": "s1", "cap": "schedule.at", "args": {"id": "keep", "at": EPOCH_MS + 3_600_000}}, + {"id": "s2", "cap": "schedule.at", "args": {"id": "now", "at": EPOCH_MS}}, + {"id": "s3", "cap": "schedule.at", "args": {"id": "gone", "at": EPOCH_MS + 3_600_000}}, + {"id": "c3", "cap": "schedule.cancel", "args": {"id": "gone"}}, + ]}), + ) + .await; + clock.advance(1); + actor.fire_schedules().await; + let live_fired: Vec = schedule_fires(&actor) + .iter() + .filter_map(|fire| fire["id"].as_str().map(str::to_owned)) + .collect(); + + let restored = + WorldCore::restore("sched-replay", WorldLimits::default(), journal.entries()).unwrap(); + let pending: Vec = restored.core.schedules.keys().cloned().collect(); + assert_eq!(pending, ["keep"]); + let replayed_fired: Vec = restored + .replay + .iter() + .filter_map(|event| match &event.kind { + WorldEventKind::System { event } => { + serde_json::from_str::(event) + .ok() + .filter(|value| value["cap"] == "schedule") + .and_then(|value| value["id"].as_str().map(str::to_owned)) + } + _ => None, + }) + .collect(); + assert_eq!(live_fired, ["now"]); + assert_eq!(replayed_fired, live_fired); + } + + #[test] + fn a_checkpoint_keeps_pending_schedules_and_writes_their_entries() { + let now = unix_ms(); + let mut core = world(8); + core.active_module_hash = Some("h".to_owned()); + core.schedules.insert("a".to_owned(), now + 100); + core.schedules.insert("b".to_owned(), now + 200); + let entries = core.checkpoint_entries("state".to_owned()).unwrap(); + for (id, at_ms) in [("a", now + 100), ("b", now + 200)] { + let set = JournalEntry::ScheduleSet { + id: id.to_owned(), + at_ms, + }; + assert!( + entries.contains(&set), + "a compacted journal keeps the schedule {id}" + ); + } + let restored = WorldCore::restore("test-world", WorldLimits::default(), entries).unwrap(); + assert_eq!(restored.core.schedules, core.schedules); + } + + #[test] + fn a_checkpoint_that_disagrees_with_its_schedule_entries_is_refused() { + let header = || JournalEntry::Created { + world_id: "w".to_owned(), + version: JOURNAL_VERSION, + }; + let set = || JournalEntry::ScheduleSet { + id: "a".to_owned(), + at_ms: 5, + }; + let checkpoint = |schedules: Option>| JournalEntry::Checkpoint { + sequence: 0, + module_hash: "h".to_owned(), + seed: 1, + provenance: None, + execution_profile: None, + caps_ceiling: None, + schedules, + snapshot: "s".to_owned(), + events: Vec::new(), + }; + let agreed = [header(), set(), checkpoint(Some(vec![("a".to_owned(), 5)]))]; + assert!(WorldCore::restore("w", WorldLimits::default(), agreed).is_ok()); + let omitted = [header(), set(), checkpoint(None)]; + assert!(WorldCore::restore("w", WorldLimits::default(), omitted).is_err()); + let unwritten = [header(), checkpoint(Some(vec![("a".to_owned(), 5)]))]; + assert!(WorldCore::restore("w", WorldLimits::default(), unwritten).is_err()); + let duplicated = [ + header(), + set(), + checkpoint(Some(vec![("a".to_owned(), 5), ("a".to_owned(), 5)])), + ]; + assert!(WorldCore::restore("w", WorldLimits::default(), duplicated).is_err()); + } + + #[test] + fn a_schedule_entry_must_refer_to_a_pending_schedule() { + let header = || JournalEntry::Created { + world_id: "w".to_owned(), + version: JOURNAL_VERSION, + }; + let fired = [header(), JournalEntry::ScheduleFired { id: "x".to_owned() }]; + assert!(WorldCore::restore("w", WorldLimits::default(), fired).is_err()); + let cancelled = [ + header(), + JournalEntry::ScheduleCancelled { id: "x".to_owned() }, + ]; + assert!(WorldCore::restore("w", WorldLimits::default(), cancelled).is_err()); + let twice = [ + header(), + JournalEntry::ScheduleSet { + id: "x".to_owned(), + at_ms: 1, + }, + JournalEntry::ScheduleSet { + id: "x".to_owned(), + at_ms: 2, + }, + ]; + assert!(WorldCore::restore("w", WorldLimits::default(), twice).is_err()); + let malformed = [ + header(), + JournalEntry::ScheduleSet { + id: "a\nb".to_owned(), + at_ms: 1, + }, + ]; + assert!(WorldCore::restore("w", WorldLimits::default(), malformed).is_err()); + } + + #[test] + fn schedules_wake_the_loop_only_while_the_program_can_take_them() { + let mut schedules = BTreeMap::new(); + schedules.insert("a".to_owned(), 2_000u64); + let now = std::time::Instant::now(); + assert!(next_schedule_wake(&schedules, 1_000, now, true).is_some()); + assert!( + next_schedule_wake(&schedules, 3_000, now, true).is_some(), + "an overdue schedule wakes the loop now" + ); + assert!( + next_schedule_wake(&schedules, 3_000, now, false).is_none(), + "a program that refuses fires never wakes the loop for one" + ); + assert!(next_schedule_wake(&BTreeMap::new(), 1_000, now, true).is_none()); + } + + #[test] + fn schedule_entries_keep_their_journal_tags() { + let set = serde_json::to_value(JournalEntry::ScheduleSet { + id: "a".to_owned(), + at_ms: 7, + }) + .unwrap(); + assert_eq!( + set, + serde_json::json!({"entry": "schedule_set", "id": "a", "at_ms": 7}) + ); + let cancelled = + serde_json::to_value(JournalEntry::ScheduleCancelled { id: "a".to_owned() }).unwrap(); + assert_eq!(cancelled["entry"], "schedule_cancelled"); + let fired = + serde_json::to_value(JournalEntry::ScheduleFired { id: "a".to_owned() }).unwrap(); + assert_eq!(fired["entry"], "schedule_fired"); + } + + /// `schedule.at` returns the reason a schedule was refused, not a bare + /// `bad_args`: the program (and any operator reading the result) can see + /// why, on the wire. + #[tokio::test] + async fn a_refused_schedule_carries_its_reason_on_the_wire() { + let (mut actor, _clock, token, _journal) = + scheduling_actor("sched-reason", &["schedule.at"], false); + // First request is accepted; the second, reusing the id, is refused by + // `check_schedule` with a specific reason. + ask( + &mut actor, + &token, + serde_json::json!({"requests": [ + {"id": "ok", "cap": "schedule.at", "args": {"id": "nap", "at": EPOCH_MS + 60_000}}, + ]}), + ) + .await; + ask( + &mut actor, + &token, + serde_json::json!({"requests": [ + {"id": "dup", "cap": "schedule.at", "args": {"id": "nap", "at": EPOCH_MS + 120_000}}, + ]}), + ) + .await; + let result = schedule_result(&actor, "dup").unwrap(); + assert_eq!(result["error"], "bad_args"); + let reason = result["reason"] + .as_str() + .expect("a reason is carried on the wire"); + assert!( + reason.contains("already pending"), + "unexpected reason: {reason}" + ); + } +} + +/// Structural guard for the one client projection (F11.11, #543). +/// +/// Every path that hands a [`WorldEvent`] to a participant must go through +/// [`project_event_for`] (or the [`WorldHandle`] methods that wrap it), so a +/// future path cannot serialize a `WorldEvent` to a client around the +/// projection. This test pins the two serialization sites in the session and +/// the behavioural contract of the projection itself. +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod projection_guard_tests { + use crate::world::{WorldEvent, WorldEventKind, WorldScopes, project_event_for}; + + /// The live stream and the catch-up page are the only two places a + /// `WorldEvent` is serialized to a client, and both go through the + /// projection. If a new site appears, this fails and forces a decision + /// about whether it, too, projects. + #[test] + fn the_session_serializes_events_only_through_the_projection() { + let session = include_str!("../world_session/mod.rs"); + let sites = session.matches("ServerFrame::Event {").count(); + assert_eq!(sites, 2, "exactly two client event serialization sites"); + // The live stream projects before it sends. + assert!( + session.contains("world.project_event(token.clone(), event.clone())"), + "the live stream must project via WorldHandle::project_event" + ); + // The catch-up path is `events_after`, which projects internally. + assert!( + session.contains("events_after"), + "the catch-up page must come from events_after (projected)" + ); + // `snapshot` is the third client path and is projected too. + assert!( + session.contains("world.snapshot(token.clone())"), + "the snapshot must come from WorldHandle::snapshot (projected)" + ); + } + + /// The projection's contract: a join-only viewer neither reads chat nor + /// sees an install seed, and a program-install event keeps everything else. + #[test] + fn the_projection_redacts_chat_and_the_install_seed() { + let chat = WorldEvent { + sequence: 1, + participant_id: 1, + kind: WorldEventKind::Chat("hello".to_owned()), + }; + assert_eq!( + project_event_for(WorldScopes::JOIN, &chat), + None, + "a join-only viewer does not see chat" + ); + assert_eq!( + project_event_for(WorldScopes::CHAT, &chat), + Some(chat.clone()), + "a CHAT viewer sees chat" + ); + + let installed = WorldEvent { + sequence: 2, + participant_id: 0, + kind: WorldEventKind::ProgramInstalled { + module_hash: "hash".to_owned(), + seed: 424_242, + provenance: None, + }, + }; + let shown = project_event_for(WorldScopes::GUEST, &installed) + .expect("a program install is visible to every participant"); + assert_eq!(shown.sequence, 2); + match &shown.kind { + WorldEventKind::ProgramInstalled { + module_hash, seed, .. + } => { + assert_eq!(module_hash, "hash", "the module hash is kept"); + assert_eq!(*seed, 0, "the install seed is redacted"); + } + other => panic!("unexpected kind: {other:?}"), + } + } +} diff --git a/pkgs/id/src/world/util.rs b/pkgs/id/src/world/util.rs new file mode 100644 index 0000000000..04f2998501 --- /dev/null +++ b/pkgs/id/src/world/util.rs @@ -0,0 +1,84 @@ +use super::*; + +use std::sync::Arc; + +use sha2::{Digest, Sha256}; +use tokio::sync::watch; + +/// Incremental event page for an authorized participant. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct EventPage { + /// Latest committed sequence at response time. + pub current_sequence: u64, + /// Earliest retained sequence. + pub oldest_retained_sequence: u64, + /// The event cursor fell behind retention and a full snapshot is required. + pub needs_snapshot: bool, + /// Events newer than the requested cursor, if it is still retained. + pub events: Vec, +} + +pub(crate) fn token_digest(token: &str) -> [u8; 32] { + Sha256::digest(token.as_bytes()).into() +} + +pub(crate) fn constant_time_eq(left: &[u8; 32], right: &[u8; 32]) -> bool { + bool::from(left.ct_eq(right)) +} + +/// Lower-case hex encoding of a byte slice, two characters per byte. +pub fn hex_encode(bytes: &[u8]) -> String { + const HEX: &[u8; 16] = b"0123456789abcdef"; + let mut encoded = String::with_capacity(bytes.len() * 2); + for byte in bytes { + encoded.push(char::from(HEX[usize::from(byte >> 4)])); + encoded.push(char::from(HEX[usize::from(byte & 0x0f)])); + } + encoded +} + +/// Publish a new records snapshot through the watch channel when it differs. +pub fn publish_records( + sender: &watch::Sender<(u64, Arc)>, + sequence: u64, + records: Records, +) { + sender.send_if_modified(|current| { + if *current.1 == records { + false + } else { + *current = (sequence, Arc::new(records)); + true + } + }); +} + +pub(crate) fn hex_decode_32(encoded: &str) -> Option<[u8; 32]> { + let bytes = encoded.as_bytes(); + if bytes.len() != 64 { + return None; + } + let mut out = [0_u8; 32]; + for (slot, pair) in out.iter_mut().zip(bytes.chunks_exact(2)) { + let nibble = |b: u8| char::from(b).to_digit(16); + *slot = u8::try_from(nibble(pair[0])? << 4 | nibble(pair[1])?).ok()?; + } + Some(out) +} + +pub(crate) fn sanitize_display_name(name: &str) -> String { + name.chars() + .filter(|ch| !ch.is_control()) + .take(48) + .collect::() + .trim() + .to_owned() +} + +pub(crate) fn sanitize_chat(text: &str) -> String { + text.chars() + .filter(|ch| !ch.is_control() || *ch == '\n' || *ch == '\t') + .collect::() + .trim() + .to_owned() +} diff --git a/pkgs/id/src/world_caps.rs b/pkgs/id/src/world_caps.rs index a832ee68e1..bfa20f3cfe 100644 --- a/pkgs/id/src/world_caps.rs +++ b/pkgs/id/src/world_caps.rs @@ -23,6 +23,22 @@ //! capability names, and the grant policy with its usage accounting. The //! actor in [`crate::world`] executes providers because they need the world. //! +//! ## Refusal codes +//! +//! A refused request or subscription carries a stable wire `"error"` code and, +//! when the refusal has a specific cause, an advisory `"reason"`. Codes are +//! part of the wire contract and never change meaning; the DoS suite asserts +//! them. +//! +//! | Code | Meaning | +//! | ---------------- | ------------------------------------------------------------------- | +//! | `cap_denied` | The world has not granted the capability. | +//! | `unknown_cap` | The server has no such capability. | +//! | `bad_args` | The request's arguments were not acceptable. | +//! | `failed` | The provider failed. | +//! | `actor_denied` | The participant whose input caused the request lacks the scope. | +//! | `outside_ceiling`| The server or the world's capability ceiling excludes it. | +//! //! **Local, not signed.** The granted set, the policy and the usage counts //! ([`CapUsage`]) belong to the hosting node and are journaled there. None of //! them is signed or replicated. A usage count reports what happened and bounds @@ -296,7 +312,12 @@ pub fn result_event(id: &str, outcome: Result) -> S let event = match outcome { Ok(value) => serde_json::json!({"cap":"result","id":id,"ok":true,"value":value}), Err(error) => { - serde_json::json!({"cap":"result","id":id,"ok":false,"error":error.code()}) + let mut event = + serde_json::json!({"cap":"result","id":id,"ok":false,"error":error.code()}); + if let Some(reason) = error.reason() { + event["reason"] = serde_json::json!(reason); + } + event } }; let text = event.to_string(); @@ -310,13 +331,32 @@ pub fn result_event(id: &str, outcome: Result) -> S /// The event delivered when a subscription is refused. #[must_use] pub fn subscription_refused_event(spec: &str, error: CapError) -> String { - serde_json::json!({"cap":"subscription","spec":spec,"ok":false,"error":error.code()}) - .to_string() + let mut event = + serde_json::json!({"cap":"subscription","spec":spec,"ok":false,"error":error.code()}); + if let Some(reason) = error.reason() { + event["reason"] = serde_json::json!(reason); + } + event.to_string() } /// Why a request or subscription was refused. +/// +/// Every refusal carries a stable [`CapErrorCode`] and, where the refusal has +/// one, a human-readable reason. Codes are part of the wire contract and never +/// change meaning; reasons are advisory and describe the specific refusal. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CapError { + code: CapErrorCode, + reason: Option, +} + +/// The stable wire code of a refused request or subscription. +/// +/// These are documented in the capability guide and asserted by the DoS +/// suite; adding a code changes the wire contract, so new refusals reuse an +/// existing code before a new one is considered. #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum CapError { +pub enum CapErrorCode { /// The world has not granted the capability. Denied, /// The server has no such capability. @@ -332,18 +372,87 @@ pub enum CapError { } impl CapError { + /// The capability was not granted. + #[must_use] + pub const fn denied() -> Self { + Self { + code: CapErrorCode::Denied, + reason: None, + } + } + + /// The server has no such capability. + #[must_use] + pub const fn unknown() -> Self { + Self { + code: CapErrorCode::Unknown, + reason: None, + } + } + + /// The request's arguments were not acceptable. + #[must_use] + pub const fn bad_args() -> Self { + Self { + code: CapErrorCode::BadArgs, + reason: None, + } + } + + /// The request's arguments were not acceptable, and `reason` says why. + #[must_use] + pub fn bad_args_with(reason: impl Into) -> Self { + Self { + code: CapErrorCode::BadArgs, + reason: Some(reason.into()), + } + } + + /// The provider failed. + #[must_use] + pub const fn failed() -> Self { + Self { + code: CapErrorCode::Failed, + reason: None, + } + } + + /// The acting participant lacks the scope for the effect. + #[must_use] + pub const fn actor_denied() -> Self { + Self { + code: CapErrorCode::ActorDenied, + reason: None, + } + } + + /// A ceiling excludes the capability, even if granted. + #[must_use] + pub const fn outside_ceiling() -> Self { + Self { + code: CapErrorCode::OutsideCeiling, + reason: None, + } + } + /// The code a program sees. #[must_use] - pub const fn code(self) -> &'static str { - match self { - Self::Denied => "cap_denied", - Self::Unknown => "unknown_cap", - Self::BadArgs => "bad_args", - Self::Failed => "failed", - Self::ActorDenied => "actor_denied", - Self::OutsideCeiling => "outside_ceiling", + pub const fn code(&self) -> &'static str { + match self.code { + CapErrorCode::Denied => "cap_denied", + CapErrorCode::Unknown => "unknown_cap", + CapErrorCode::BadArgs => "bad_args", + CapErrorCode::Failed => "failed", + CapErrorCode::ActorDenied => "actor_denied", + CapErrorCode::OutsideCeiling => "outside_ceiling", } } + + /// The advisory reason, if the refusal has one. + #[must_use] + pub const fn reason(&self) -> Option<&String> { + self.reason.as_ref() + } } /// How a capability was used since the world opened. @@ -370,7 +479,7 @@ pub struct CapLedger { } /// The outcome of asking the ledger about one use. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq)] pub enum Decision { /// Allowed; the capability was already granted. Allow, @@ -423,17 +532,17 @@ impl CapLedger { let entry = self.usage.entry(cap.to_owned()).or_default(); if !is_known(cap) { entry.denied += 1; - return Decision::Deny(CapError::Unknown); + return Decision::Deny(CapError::unknown()); } // A ceiling is checked before anything else, so grant-on-use can // never add a name the server or the world excludes. if !self.allowed.contains(cap) { entry.denied += 1; - return Decision::Deny(CapError::OutsideCeiling); + return Decision::Deny(CapError::outside_ceiling()); } if !actor_permits { entry.denied += 1; - return Decision::Deny(CapError::ActorDenied); + return Decision::Deny(CapError::actor_denied()); } if self.granted.contains(cap) || self.granted.contains("*") { entry.allowed += 1; @@ -445,7 +554,7 @@ impl CapLedger { return Decision::AllowAndGrant; } entry.denied += 1; - Decision::Deny(CapError::Denied) + Decision::Deny(CapError::denied()) } /// The granted set. @@ -539,6 +648,11 @@ pub struct CapsReport { /// ceilings. #[serde(default)] pub effective: Vec, + /// Times a `view` or `layout` call trapped since the world opened + /// (F11.17). A trapping view degrades to an error screen instead of + /// poisoning the world, so this is the only trace of it. + #[serde(default)] + pub view_failures: u64, } #[cfg(test)] @@ -626,11 +740,17 @@ mod tests { #[test] fn the_ledger_denies_until_granted_and_counts_every_use() { let mut ledger = CapLedger::new(BTreeSet::new(), false); - assert_eq!(ledger.decide("time.now"), Decision::Deny(CapError::Denied)); - assert_eq!(ledger.decide("time.now"), Decision::Deny(CapError::Denied)); + assert_eq!( + ledger.decide("time.now"), + Decision::Deny(CapError::denied()) + ); + assert_eq!( + ledger.decide("time.now"), + Decision::Deny(CapError::denied()) + ); assert_eq!( ledger.decide("telepathy"), - Decision::Deny(CapError::Unknown) + Decision::Deny(CapError::unknown()) ); ledger.set_granted(BTreeSet::from(["time.now".to_owned()])); assert_eq!(ledger.decide("time.now"), Decision::Allow); @@ -650,7 +770,7 @@ mod tests { ); assert_eq!( ledger.decide("telepathy"), - Decision::Deny(CapError::Unknown) + Decision::Deny(CapError::unknown()) ); } @@ -661,7 +781,7 @@ mod tests { assert_eq!(ledger.decide("random.u64"), Decision::Allow); assert_eq!( ledger.decide("telepathy"), - Decision::Deny(CapError::Unknown) + Decision::Deny(CapError::unknown()) ); assert!(ledger.granted().contains("random.u64")); assert!(!ledger.granted().contains("telepathy")); @@ -672,7 +792,7 @@ mod tests { let mut ledger = CapLedger::new(BTreeSet::new(), true); assert_eq!( ledger.decide_for("chat.say", false), - Decision::Deny(CapError::ActorDenied) + Decision::Deny(CapError::actor_denied()) ); assert!(!ledger.granted().contains("chat.say")); assert_eq!( @@ -728,7 +848,7 @@ mod tests { assert_eq!(ok["ok"], true); assert_eq!(ok["value"]["n"], 1); let denied: serde_json::Value = - serde_json::from_str(&result_event("a", Err(CapError::Denied))).unwrap(); + serde_json::from_str(&result_event("a", Err(CapError::denied()))).unwrap(); assert_eq!( (denied["ok"].as_bool(), denied["error"].as_str()), (Some(false), Some("cap_denied")) @@ -750,7 +870,10 @@ mod tests { assert_eq!(ledger.allowed(), &catalog_names()); assert!(ledger.is_granted("time.now")); assert_eq!(ledger.decide("time.now"), Decision::Allow); - assert_eq!(ledger.decide("chat.say"), Decision::Deny(CapError::Denied)); + assert_eq!( + ledger.decide("chat.say"), + Decision::Deny(CapError::denied()) + ); ledger.set_granted(names(&["*"])); assert_eq!(ledger.effective(), catalog_names()); assert_eq!( @@ -768,12 +891,12 @@ mod tests { assert!(!ledger.is_granted("chat.say")); assert_eq!( ledger.decide_for("chat.say", true), - Decision::Deny(CapError::OutsideCeiling) + Decision::Deny(CapError::outside_ceiling()) ); ledger.set_granted(names(&["chat.say"])); assert_eq!( ledger.decide_for("chat.say", true), - Decision::Deny(CapError::OutsideCeiling), + Decision::Deny(CapError::outside_ceiling()), "an explicit grant does not reach past the ceiling" ); assert_eq!( @@ -796,7 +919,7 @@ mod tests { ledger.set_allowed(names(&["time.now"])); assert_eq!( ledger.decide("chat.say"), - Decision::Deny(CapError::OutsideCeiling) + Decision::Deny(CapError::outside_ceiling()) ); assert!(!ledger.granted().contains("chat.say")); assert_eq!(ledger.decide("time.now"), Decision::AllowAndGrant); @@ -809,7 +932,7 @@ mod tests { ledger.set_allowed(names(&["time.now", "telepathy"])); assert_eq!( ledger.decide("telepathy"), - Decision::Deny(CapError::Unknown), + Decision::Deny(CapError::unknown()), "a name the catalog lacks is never allowed, even if a ceiling lists it" ); assert_eq!(ledger.allowed(), &names(&["time.now"])); diff --git a/pkgs/id/src/world_line.rs b/pkgs/id/src/world_line.rs new file mode 100644 index 0000000000..7a12a9ce84 --- /dev/null +++ b/pkgs/id/src/world_line.rs @@ -0,0 +1,176 @@ +//! One line grammar for the world's three surfaces. +//! +//! The SSH command mode (`cmd:` login), the `id world join` stdin pump, and +//! the `id world` CLI subcommands all speak the same verbs: chat, records, +//! stats, logs, caps and quit. This module is the single parser that maps one +//! line to one [`WorldLine`] action, so a sentence works identically as an SSH +//! command, a piped script line, and a CLI one-off. + +/// What one input line asks the world for. +/// +/// Each surface maps a [`WorldLine`] to its own execution: SSH turns it into a +/// session frame, the pump into the same frame over stdin, and the CLI into a +/// `WorldCommand` subcommand. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum WorldLine { + /// A plain chat line. + Chat(String), + /// `/input `: an opaque participant input, hex-encoded. + Input(String), + /// `/records [prefix]`: read the world's structured records. + Records { prefix: Option }, + /// `/documents [prefix]`: list public documents. + Documents { prefix: Option }, + /// `/document `: read one public document. + Document(String), + /// `/stats`: the world's module, capability and profile state. + Stats, + /// `/logs [seconds]`: tail the world's events. + Logs { seconds: Option }, + /// `/caps`: the world's capability report. + Caps, + /// `/help`: list the commands. + Help, + /// `/quit`: end the session. + Quit, + /// A command that did not parse; the message is shown to the user. + Message(String), +} + +/// Parse one line (already trimmed) into a [`WorldLine`]. +/// +/// An empty line returns `None`. Any other line that does not start with `/` +/// is chat. Unknown `/` commands become [`WorldLine::Message`]. +#[must_use] +pub fn parse_line(line: &str) -> Option { + if line.is_empty() { + return None; + } + match line { + "/help" => return Some(WorldLine::Help), + "/quit" => return Some(WorldLine::Quit), + "/stats" => return Some(WorldLine::Stats), + "/caps" => return Some(WorldLine::Caps), + _ => {} + } + if line == "/records" || line.starts_with("/records ") { + let Some(prefix) = line.strip_prefix("/records") else { + return Some(WorldLine::Message("usage: /records [prefix]".to_owned())); + }; + let prefix = prefix.trim(); + return Some(WorldLine::Records { + prefix: (!prefix.is_empty()).then(|| prefix.to_owned()), + }); + } + if line == "/documents" || line.starts_with("/documents ") { + let Some(prefix) = line.strip_prefix("/documents") else { + return Some(WorldLine::Message("usage: /documents [prefix]".to_owned())); + }; + let prefix = prefix.trim(); + return Some(WorldLine::Documents { + prefix: (!prefix.is_empty()).then(|| prefix.to_owned()), + }); + } + if let Some(rest) = line.strip_prefix("/document ") { + let name = rest.trim(); + if !name.is_empty() && name == rest { + return Some(WorldLine::Document(name.to_owned())); + } + return Some(WorldLine::Message("usage: /document ".to_owned())); + } + if let Some(rest) = line.strip_prefix("/logs") { + let rest = rest.trim(); + if rest.is_empty() { + return Some(WorldLine::Logs { seconds: None }); + } + if let Ok(seconds) = rest.parse::() { + return Some(WorldLine::Logs { + seconds: Some(seconds), + }); + } + return Some(WorldLine::Message("usage: /logs [seconds]".to_owned())); + } + if let Some(hex) = line.strip_prefix("/input ") { + if !hex.is_empty() && hex.len() % 2 == 0 && hex.bytes().all(|b| b.is_ascii_hexdigit()) { + return Some(WorldLine::Input(hex.to_ascii_lowercase())); + } + return Some(WorldLine::Message("usage: /input ".to_owned())); + } + if line.starts_with('/') { + return Some(WorldLine::Message("unknown command; type /help".to_owned())); + } + Some(WorldLine::Chat(line.to_owned())) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + + #[test] + fn empty_and_plain_lines() { + assert_eq!(parse_line(""), None); + assert_eq!( + parse_line("hi there"), + Some(WorldLine::Chat("hi there".into())) + ); + assert_eq!( + parse_line(" padded "), + Some(WorldLine::Chat(" padded ".into())), + "the caller trims before parsing" + ); + } + + #[test] + fn the_shared_verbs_parse_identically() { + assert_eq!(parse_line("/help"), Some(WorldLine::Help)); + assert_eq!(parse_line("/quit"), Some(WorldLine::Quit)); + assert_eq!(parse_line("/stats"), Some(WorldLine::Stats)); + assert_eq!(parse_line("/caps"), Some(WorldLine::Caps)); + assert_eq!(parse_line("/logs"), Some(WorldLine::Logs { seconds: None })); + assert_eq!( + parse_line("/logs 5"), + Some(WorldLine::Logs { seconds: Some(5) }) + ); + assert_eq!( + parse_line("/records"), + Some(WorldLine::Records { prefix: None }) + ); + assert_eq!( + parse_line("/records abc"), + Some(WorldLine::Records { + prefix: Some("abc".into()) + }) + ); + assert_eq!( + parse_line("/documents notes"), + Some(WorldLine::Documents { + prefix: Some("notes".into()) + }) + ); + assert_eq!( + parse_line("/document notes.md"), + Some(WorldLine::Document("notes.md".into())) + ); + assert_eq!( + parse_line("/input 00aF"), + Some(WorldLine::Input("00af".into())) + ); + } + + #[test] + fn unknown_and_malformed_commands_become_messages() { + assert_eq!( + parse_line("/nonsense"), + Some(WorldLine::Message("unknown command; type /help".into())) + ); + assert_eq!( + parse_line("/input nope"), + Some(WorldLine::Message("usage: /input ".into())) + ); + assert_eq!( + parse_line("/logs soon"), + Some(WorldLine::Message("usage: /logs [seconds]".into())) + ); + } +} diff --git a/pkgs/id/src/world_session.rs b/pkgs/id/src/world_session.rs deleted file mode 100644 index bb700d5ae7..0000000000 --- a/pkgs/id/src/world_session.rs +++ /dev/null @@ -1,4180 +0,0 @@ -//! Transport-neutral world session driver. -//! -//! A *session* is one participant's connection to a [`WorldHandle`]. The -//! wire protocol is one JSON object per frame; this module owns that protocol -//! and nothing else. A transport (WebSocket, Iroh stream, an in-memory test -//! channel) only implements [`SessionIo`] to move whole text frames, so the -//! behavior cannot drift between transports. -//! -//! Client frames (`type` tag): `join {capability, after?}`, -//! `invite {admin_token, display_name}`, `attenuate {name, scopes}`, `chat {text}`, `input {data_hex}`. -//! The first frame must be `join` or `invite`. Server frames: `snapshot`, -//! `event`, `invite`, `error`. -//! -//! Authorization is the capability alone. A transport may know who the peer -//! is (an Iroh node ID); that never grants world authority. - -use std::sync::Arc; -use std::time::Duration; - -use anyhow::Context as _; -use iroh_blobs::{ - BlobFormat, Hash, - api::{Store, TempTag, blobs::AddBytesOptions}, -}; -use rand::RngExt as _; -use serde::{Deserialize, Serialize}; -use subtle::ConstantTimeEq as _; -use tokio::sync::{Mutex, OwnedSemaphorePermit, RwLock, Semaphore, broadcast}; - -use crate::directory_auth::Signed; -use crate::time::unix_ms; -use crate::world::{ - Authority, CapabilityBounds, FileScope, Isolation, JoinCapability, Participant, WorldEvent, - WorldHandle, WorldPolicy, WorldScopes, WorldSnapshot, -}; -use crate::world_compile::Compiler; -#[cfg(feature = "sandbox")] -use crate::world_compile::{COMPILE_TIMEOUT, CompileSpec}; -use crate::world_hub::{WorldHub, WorldInfo, WorldLease}; - -/// Re-exported so `crate::world_session::MAX_FRAME_BYTES` keeps working: the -/// limit now lives in [`crate::frames`] so the crate builds without the -/// `world` feature. -pub use crate::frames::MAX_FRAME_BYTES; - -/// Largest Wasm world module that may be installed (16 MiB). -pub const MAX_WORLD_MODULE_BYTES: usize = 16 * 1024 * 1024; - -/// Largest raw upload chunk; hex + JSON framing remains below [`MAX_FRAME_BYTES`]. -pub const MAX_WORLD_MODULE_CHUNK_BYTES: usize = 6 * 1024; - -/// Longest accepted capability string, in bytes. -const MAX_CAPABILITY_BYTES: usize = 256; - -/// Longest accepted admin secret, in bytes. -const MAX_ADMIN_TOKEN_BYTES: usize = 256; -/// Sent with a capability ceiling change: unlike a profile, it takes effect now. -const CAPS_CEILING_NOTICE: &str = - "ceiling saved; it applies immediately to new uses and active subscriptions"; - -/// Simultaneous bounded module uploads accepted by a world service. -const MAX_CONCURRENT_MODULE_UPLOADS: usize = 2; - -/// One inbound unit from a transport. -#[derive(Debug)] -pub enum Inbound { - /// A complete text frame no larger than [`MAX_FRAME_BYTES`]. - Text(String), - /// A frame larger than [`MAX_FRAME_BYTES`] (its contents are discarded). - Oversized, - /// A frame that is not UTF-8 text. - Unsupported, - /// The peer is gone or the stream failed; the session must end. - Closed, -} - -/// Moves whole text frames for one session. -/// -/// `recv` must be cancel-safe: the driver races it against world events and a -/// cancelled call must not lose or split a frame. -pub trait SessionIo: Send { - /// Next inbound frame. - fn recv(&mut self) -> impl Future + Send; - /// Send one frame. Returns `false` when the peer is gone. - fn send(&mut self, frame: String) -> impl Future + Send; -} - -/// Tunables for [`run_session_with`]. -#[derive(Clone, Copy, Debug)] -pub struct SessionConfig { - /// How long a peer may take to send its first frame. - pub join_timeout: Duration, -} - -impl Default for SessionConfig { - fn default() -> Self { - Self { - join_timeout: Duration::from_secs(10), - } - } -} - -// Install frames are only produced/consumed with the `sandbox` feature. -#[cfg_attr(not(feature = "sandbox"), allow(dead_code))] -#[derive(Debug, Deserialize)] -#[serde(tag = "type", rename_all = "snake_case")] -enum ClientFrame { - Join { - capability: String, - after: Option, - }, - Info { - capability: String, - }, - /// Page through the world's structured records. - Records { - capability: String, - /// Only keys starting with this prefix. - prefix: Option, - /// Continue after this key (exclusive). - after: Option, - }, - /// Ask for a read-only doc ticket to replicate the records peer-to-peer. - RecordsTicket { - capability: String, - }, - DownloadModule { - capability: String, - module_hash: String, - }, - Invite { - admin_token: String, - display_name: String, - /// Seconds until the invite stops working (default 7 days, at most 30). - expires_in_secs: Option, - /// Committed actions the invite may take; absent means no limit. - uses: Option, - /// Role preset (`spectator`, `observer`, `player`, `guest`, `delegator`); absent - /// means `guest`. - #[serde(default)] - role: Option, - }, - /// Admin: list the worlds this server hosts. - ListWorlds { - admin_token: String, - }, - /// Admin: create the world named by the frame's `world` field. - CreateWorld { - admin_token: String, - }, - /// Admin, or a signed request from a moderator: set the world's isolation. - /// A signed request covers method `PUT`, path `/world//isolation`, - /// and the isolation word as its body. - SetIsolation { - isolation: Isolation, - admin_token: Option, - signed: Option, - }, - /// Admin, or a signed request from a moderator: let other unisolated - /// worlds write here. A signed request covers `PUT - /// /world//cross-world-write` with the body `on` or `off`. - SetCrossWorldWrite { - enabled: bool, - admin_token: Option, - signed: Option, - }, - /// Admin: force cross-world writes on, overriding the world's own setting. - ForceCrossWorldWrite { - admin_token: String, - }, - /// Admin, or a signed request from a moderator: set the file scope. Only - /// the admin sets `write_override`. A signed request covers `PUT - /// /world//file-scope` with the scope word as its body. - SetFileScope { - scope: FileScope, - write_override: Option, - admin_token: Option, - signed: Option, - }, - /// Admin: compile Roc sources and install the result. - Compile { - admin_token: String, - files: Vec, - seed: Option, - #[serde(default)] - native: bool, - }, - /// Admin: grant or revoke capabilities for this world. - UpdateCaps { - admin_token: String, - grant: Vec, - revoke: Vec, - }, - /// Admin: replace this world's capability ceiling. It applies immediately; - /// grants are kept, and an empty list allows no capability. - SetCapsCeiling { - admin_token: String, - ceiling: Vec, - }, - /// Admin: persist requested per-world runtime bounds. They do not change - /// a running guest; they apply on its next install or process restart. - SetExecutionProfile { - admin_token: String, - profile: crate::world_limits::WorldExecutionProfile, - }, - /// Read the world's requested runtime bounds (needs either admin token or guest capability). - ExecutionProfileInfo { - admin_token: Option, - capability: Option, - }, - /// Show this world's capability grants, wants and usage. - Caps { - capability: String, - }, - Chat { - text: String, - }, - /// Joined: mint a capability with a subset of this session's scopes. A - /// delegation carries no use count. - Attenuate { - name: String, - scopes: Vec, - /// Unix milliseconds at which the delegated capability stops working. - expires_at: Option, - }, - /// Joined as an account: delegate a subset of its scopes to one of its friends. - DelegateToFriend { - friend: String, - name: String, - scopes: Vec, - expires_at: Option, - }, - Input { - data_hex: String, - }, - /// Ephemeral dimensions for this connection's presentation only. Never journaled. - Resize { - width: u16, - height: u16, - }, - /// Explicit bounded clipboard text, delivered as one durable input event. - Paste { - text: String, - }, - InstallBegin { - admin_token: String, - total_bytes: usize, - /// Expected BLAKE3 hash. Optional for browser uploads, whose `WebCrypto` - /// API does not provide BLAKE3; the host still computes and returns it. - module_hash: Option, - seed: u64, - }, - InstallChunk { - offset: usize, - data_hex: String, - }, - InstallEnd, -} - -// Install frames are only produced/consumed with the `sandbox` feature. -#[cfg_attr(not(feature = "sandbox"), allow(dead_code))] -#[derive(Debug, Serialize)] -#[serde(tag = "type", rename_all = "snake_case")] -enum ServerFrame<'a> { - Snapshot { - snapshot: &'a WorldSnapshot, - }, - Event { - event: &'a WorldEvent, - }, - /// Host-rendered presentation for the participant's adapter. - View { - sequence: u64, - data: &'a str, - /// Optional typed screen surface. Older clients can continue using `data`. - #[serde(skip_serializing_if = "Option::is_none")] - surface: Option<&'a crate::world_presentation::WorldSurface>, - }, - ModuleInfo { - world_id: String, - active_module_hash: Option, - #[serde(skip_serializing_if = "Option::is_none")] - active_module_provenance: Option, - current_sequence: u64, - }, - /// One page of structured records, with the sequence they were read at. - Records { - sequence: u64, - records: crate::world::Records, - /// Present when more keys follow; pass as `after` to continue. - next_after: Option, - }, - /// A read-only iroh-docs ticket for the records document. - RecordsTicket { - ticket: String, - }, - ModuleBegin { - module_hash: String, - total_bytes: usize, - }, - ModuleChunk { - offset: usize, - data_hex: String, - }, - ModuleEnd { - module_hash: String, - }, - Invite(&'a InviteResponse), - /// The worlds this server hosts. - Worlds { - default: &'a str, - worlds: Vec, - }, - WorldCreated { - world: &'a str, - created: bool, - }, - Isolation { - world: &'a str, - isolation: Isolation, - }, - /// The world's sharing and file settings after a change. - Policy { - world: &'a str, - policy: WorldPolicy, - }, - /// The world's capability report. - Caps { - report: crate::world_caps::CapsReport, - }, - /// The requested profile and an explicit deferred-application notice. - ExecutionProfile { - update: crate::world::ExecutionProfileUpdate, - message: &'static str, - }, - /// The capability report after a ceiling change, and a notice that the - /// change applied immediately. - CapsCeiling { - report: crate::world_caps::CapsReport, - message: &'static str, - }, - /// A compiled module was installed. - Compiled { - module_hash: String, - sequence: u64, - diagnostics: String, - }, - UploadReady { - chunk_bytes: usize, - }, - ModuleInstalled { - module_hash: &'a str, - sequence: u64, - }, - ProgramChanged { - module_hash: &'a str, - sequence: u64, - }, - Error { - message: &'a str, - }, -} - -/// A freshly minted guest capability. -#[derive(Debug, Serialize)] -pub struct InviteResponse { - /// Bearer capability; shown once, never logged. - pub capability: String, - /// The new participant's ID. - pub participant_id: u64, - /// The sanitized display name. - pub display_name: String, -} - -/// Why an invite was not issued. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum InviteError { - /// Invites are not enabled (no admin secret configured). - Disabled, - /// The supplied admin secret is missing or wrong. - Unauthorized, - /// The world refused another participant (full, or shut down). - Unavailable, - /// The requested lifetime or use limit is out of range. - InvalidBounds(&'static str), -} - -/// Lifetime of an invite when the admin names none. -pub const INVITE_DEFAULT_SECS: u64 = 7 * 24 * 60 * 60; -/// Longest lifetime an invite may be given. -pub const INVITE_MAX_SECS: u64 = 30 * 24 * 60 * 60; - -/// Check an invite's requested lifetime and use limit. The host applies it to -/// every invite, and `id world invite` applies it before dialing. -/// -/// # Errors -/// -/// Returns the refusal reason for a lifetime outside 1 second to 30 days, or a -/// use limit below one. -pub fn check_invite_bounds( - expires_in_secs: Option, - uses: Option, -) -> Result<(), &'static str> { - if expires_in_secs.is_some_and(|secs| secs == 0 || secs > INVITE_MAX_SECS) { - return Err("invite lifetime must be from 1 second to 30 days"); - } - if uses == Some(0) { - return Err("uses must be at least 1"); - } - Ok(()) -} - -fn invite_bounds( - expires_in_secs: Option, - uses: Option, - now_ms: u64, -) -> Result { - check_invite_bounds(expires_in_secs, uses)?; - let secs = expires_in_secs.unwrap_or(INVITE_DEFAULT_SECS); - Ok(CapabilityBounds { - expires_at: Some(now_ms.saturating_add(secs * 1000)), - uses, - }) -} - -/// Why an uploaded Wasm program was not installed. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum InstallError { - /// Module installation is unavailable in this service/build. - Disabled, - /// The supplied admin secret is missing or wrong. - Unauthorized, - /// Size or content hash validation failed. - InvalidUpload, - /// Raw artifacts are disabled by this world's source-only policy. - RawModuleDisabled, - /// Wasmtime rejected or could not instantiate the module. - InvalidModule, - /// The blob could not be pinned or the world actor refused activation. - Unavailable, -} - -/// One source file in a compile request. -#[derive(Debug, Deserialize)] -#[cfg_attr(not(feature = "sandbox"), allow(dead_code))] -pub(crate) struct CompileFile { - name: String, - content: String, -} - -/// A world plus the secret that may mint guest capabilities for it. -#[derive(Clone)] -pub struct WorldService { - world: WorldHandle, - admin_token: Option, - blobs: Option, - module_pin: Arc>>, - module_hash: Arc>>, - upload_slots: Arc, - module_dir: Option, - records: Option>, - compiler: Option>, - native: bool, - /// Raw artifact installs are refused; compiled source remains permitted. - source_only: bool, - runtime: crate::world_limits::RuntimeLimits, - mail: Option>, - outbox: Option>>, - profile_operation: Arc>, -} - -impl std::fmt::Debug for WorldService { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("WorldService") - .field( - "admin_token", - &self.admin_token.as_ref().map(|_| "[REDACTED]"), - ) - .finish_non_exhaustive() - } -} - -impl WorldService { - /// Accept native (ELF) module installs. Wasm stays the default tier. - #[must_use] - pub const fn with_native_enabled(mut self) -> Self { - self.native = true; - self - } - - /// Require new Wasm programs to be compiled from source by this server. - /// This disables raw artifact installation, but not the compiled output path. - #[must_use] - pub const fn with_source_only(mut self, enabled: bool) -> Self { - self.source_only = enabled; - self - } - - /// Whether raw Wasm/native uploads are disabled for this world. - #[must_use] - pub(crate) const fn source_only(&self) -> bool { - self.source_only - } - - /// Read or change this world's directory as the caller. - /// - /// # Errors - /// - /// Fails for an unknown credential or a refused change. - pub async fn directory( - &self, - caller: crate::directory_auth::Caller, - action: crate::directory_view::DirectoryAction, - ) -> anyhow::Result { - if action.sends_mail() && self.mail.is_none() { - return Err(crate::directory::Refusal::Forbidden( - "this server has no mail configured".to_owned(), - ) - .into()); - } - // The actor refuses an outbox-less server only when the change would queue for another server. - let mut outcome = self - .world - .directory(caller.clone(), action, self.outbox.is_some()) - .await?; - if let (Some(sink), Some(mail)) = (&self.mail, outcome.mail.take()) { - let sink = Arc::clone(sink); - tokio::task::spawn_blocking(move || sink.send(&mail)) - .await - .context("mail task stopped")??; - outcome.mailed = true; - } - if let Some(outbox) = &self.outbox { - let outbound = std::mem::take(&mut outcome.outbound); - match outcome.pending.take() { - Some(entry) => { - self.queue_then_apply(outbox, outbound, entry).await?; - outcome = self - .world - .directory(caller, crate::directory_view::DirectoryAction::View, true) - .await?; - } - None => { - enqueue_all(&mut *outbox.lock().await, outbound)?; - } - } - let queue = outbox.lock().await; - outcome.view.deliveries = - crate::directory_view::deliveries(&queue, &outcome.view.viewer); - } - Ok(outcome) - } - - /// Queue the outbound payloads, then apply the change. The outbox lock is - /// held across the apply so a flush cannot send anything before the change - /// is in. If the apply is refused, the payloads are withdrawn. - async fn queue_then_apply( - &self, - outbox: &Mutex, - outbound: Vec, - entry: crate::directory::DirectoryEntry, - ) -> anyhow::Result<()> { - let mut queue = outbox.lock().await; - let keys = enqueue_all(&mut queue, outbound)?; - if let Err(error) = self.world.apply_directory_entry(entry).await { - withdraw_all(&mut queue, &keys); - return Err(error); - } - Ok(()) - } - - /// Attempt every due outbox envelope once. Returns how many were attempted. - /// - /// # Errors - /// - /// Fails when the outbox file cannot be written. - pub async fn flush_outbox(&self, endpoint: &iroh::Endpoint, now: u64) -> anyhow::Result { - match &self.outbox { - Some(outbox) => crate::envelope_outbox::flush(outbox, endpoint, now).await, - None => Ok(0), - } - } - - /// Wrap a world. `admin_token: None` disables invites. - #[must_use] - pub fn new(world: WorldHandle, admin_token: Option) -> Self { - Self { - world, - admin_token, - blobs: None, - module_pin: Arc::new(Mutex::new(None)), - module_hash: Arc::new(RwLock::new(None)), - upload_slots: Arc::new(Semaphore::new(MAX_CONCURRENT_MODULE_UPLOADS)), - module_dir: None, - records: None, - compiler: None, - native: false, - source_only: false, - runtime: crate::world_limits::RuntimeLimits::default(), - mail: None, - outbox: None, - profile_operation: Arc::new(Mutex::new(())), - } - } - - /// Bound the programs this world runs by the admin's limits. - #[must_use] - pub const fn with_runtime_limits( - mut self, - runtime: crate::world_limits::RuntimeLimits, - ) -> Self { - self.runtime = runtime; - self - } - - /// Replace the world's capability ceiling, admin only. Unlike a profile, - /// the ceiling applies at once: the next use or subscription sees it. - /// - /// # Errors - /// - /// Fails with `admin denied` for a wrong token, and with the world's - /// message for an invalid or unstorable ceiling. - pub async fn set_caps_ceiling( - &self, - supplied_admin: Option<&str>, - ceiling: Vec, - ) -> anyhow::Result { - anyhow::ensure!(self.authorize_admin(supplied_admin).is_ok(), "admin denied"); - self.world.set_caps_ceiling(ceiling).await - } - - /// Persist a per-world resource profile. The running program keeps its - /// existing limits; the request applies on the next install or restart. - pub async fn set_execution_profile( - &self, - supplied_admin: Option<&str>, - profile: crate::world_limits::WorldExecutionProfile, - ) -> anyhow::Result { - self.authorize_admin(supplied_admin) - .map_err(|_| anyhow::anyhow!("admin denied"))?; - // Resolve now for validation and to ensure this request is valid under - // this process's hard ceilings. The stored request remains unclamped, - // so a later server with lower ceilings still wins at instantiation. - profile.resolve(self.runtime)?; - let _operation = self.profile_operation.lock().await; - self.world.set_execution_profile(profile).await - } - - /// Let admins compile Roc sources into this world on the fly. - #[must_use] - pub fn with_compiler(mut self, compiler: Compiler) -> Self { - self.compiler = Some(Arc::new(compiler)); - self - } - - /// Compile `spec` on the server and install the result exactly like an - /// admin upload (validated, pinned, journaled). Returns the module hash, - /// the install sequence and the compiler's diagnostics. - /// - /// # Errors - /// - /// A human-readable refusal: unauthorized, disabled, or the compiler's - /// own failure text (so an admin sees why their program did not build). - #[cfg(feature = "sandbox")] - pub async fn compile_and_install( - &self, - supplied_admin: Option<&str>, - spec: &CompileSpec, - ) -> Result<(String, u64, String), String> { - if self.authorize_admin(supplied_admin).is_err() { - return Err("compile denied".to_owned()); - } - let Some(compiler) = self.compiler.as_ref() else { - return Err("compilation is not enabled on this server".to_owned()); - }; - if spec.native && !self.native { - return Err("native modules are not enabled on this server".to_owned()); - } - // The effective list, not the raw grants: a platform module outside a - // server or world ceiling is refused at compile time too. - let granted = self - .world - .caps_report() - .await - .map_err(|error| format!("compile failed: {error:#}"))? - .effective; - let (wasm, diagnostics, provenance) = - crate::world_compile::compile(spec, compiler, &granted, COMPILE_TIMEOUT) - .await - .map_err(|error| { - tracing::warn!("world compile failed: {error:#}"); - format!("compile failed: {error:#}") - })?; - let hash = module_hash(&wasm); - let permit = self - .try_reserve_module_upload() - .map_err(|error| format!("install failed: {error:?}"))?; - let (_, sequence) = self - .install_wasm_reserved( - supplied_admin, - wasm, - spec.seed, - &hash, - permit, - true, - Some(provenance), - ) - .await - .map_err(|error| format!("install failed: {error:?}"))?; - Ok((hash, sequence, diagnostics)) - } - - /// Attach the world's records document and start mirroring program - /// records into it. - #[must_use] - pub fn with_records_store(mut self, records: crate::world_records::RecordsStore) -> Self { - let records = Arc::new(records); - records.spawn_publisher(&self.world); - self.records = Some(records); - self - } - - /// The world's records document, if it has one. - #[must_use] - pub const fn records_store(&self) -> Option<&Arc> { - self.records.as_ref() - } - - /// Persist installed modules here so a durable world can re-instantiate - /// its program after a restart. - #[must_use] - pub fn with_module_dir(mut self, modules: crate::world_store::ModuleDir) -> Self { - self.module_dir = Some(modules); - self - } - - /// Mark `wasm` as the active module after a restore: pin it in the blob - /// store (when attached) so peers can download it again. - /// - /// # Errors - /// - /// Fails if the blob store refuses the bytes. - pub async fn adopt_module(&self, wasm: Vec) -> anyhow::Result<()> { - let hash = module_hash(&wasm); - if let Some(blobs) = self.blobs.as_ref() { - let pin = blobs - .add_bytes_with_opts(AddBytesOptions { - data: wasm.into(), - format: BlobFormat::Raw, - }) - .temp_tag() - .await?; - *self.module_pin.lock().await = Some(pin); - } - *self.module_hash.write().await = Some(hash); - Ok(()) - } - - /// Attach this node's blob store so uploaded modules survive as pinned - /// Iroh content for the life of the running world. - #[must_use] - pub fn with_blob_store(mut self, blobs: Store) -> Self { - self.blobs = Some(blobs); - self - } - - /// Send confirmation and sign-in codes through this sink. Without one, - /// email actions are refused. - #[must_use] - pub fn with_mail(mut self, sink: Arc) -> Self { - self.mail = Some(sink); - self - } - - /// Queue envelopes for other servers in this outbox. Without one, remote - /// friend actions are refused. - #[must_use] - pub fn with_outbox(mut self, outbox: crate::envelope_outbox::Outbox) -> Self { - self.outbox = Some(Arc::new(Mutex::new(outbox))); - self - } - - /// Reserve one upload slot before accepting a potentially large body. - fn try_reserve_module_upload(&self) -> Result { - Arc::clone(&self.upload_slots) - .try_acquire_owned() - .map_err(|_| InstallError::Unavailable) - } - - /// The underlying world actor. - #[must_use] - pub const fn world(&self) -> &WorldHandle { - &self.world - } - - /// Mint a guest capability if `supplied` matches the admin secret. - /// - /// # Errors - /// - /// See [`InviteError`]. - pub async fn invite( - &self, - supplied: Option<&str>, - display_name: String, - expires_in_secs: Option, - uses: Option, - ) -> Result { - self.invite_scoped( - supplied, - display_name, - expires_in_secs, - uses, - WorldScopes::GUEST, - ) - .await - } - - /// Like [`Self::invite`], with the invited participant's scopes chosen by - /// the caller (see `WorldScopes::from_role`). - pub async fn invite_scoped( - &self, - supplied: Option<&str>, - display_name: String, - expires_in_secs: Option, - uses: Option, - scopes: WorldScopes, - ) -> Result { - self.authorize_admin(supplied)?; - let bounds = - invite_bounds(expires_in_secs, uses, unix_ms()).map_err(InviteError::InvalidBounds)?; - match self.world.issue_bounded(display_name, scopes, bounds).await { - Ok((participant, capability)) => Ok(InviteResponse { - capability: capability.expose().to_owned(), - participant_id: participant.id, - display_name: participant.display_name, - }), - Err(_) => Err(InviteError::Unavailable), - } - } - - /// The configured admin secret, for a hub that shares it process-wide. - pub(crate) fn admin_token(&self) -> Option<&str> { - self.admin_token.as_deref() - } - - /// Validate the separately configured world-administrator token. - pub fn authorize_admin(&self, supplied: Option<&str>) -> Result<(), InviteError> { - let Some(expected) = self.admin_token.as_deref().filter(|t| !t.is_empty()) else { - return Err(InviteError::Disabled); - }; - if !supplied.is_some_and(|s| { - s.len() <= MAX_ADMIN_TOKEN_BYTES && secret_eq(expected.as_bytes(), s.as_bytes()) - }) { - return Err(InviteError::Unauthorized); - } - Ok(()) - } - - /// Compile, instantiate and atomically install a Wasm program. The module - /// is first pinned in Iroh's blob store; only then does the actor activate - /// it. A failed compile or write leaves the running program unchanged. - #[cfg(feature = "sandbox")] - pub async fn install_wasm( - &self, - supplied_admin: Option<&str>, - wasm: Vec, - seed: u64, - claimed_hash: &str, - ) -> Result<(String, u64), InstallError> { - let permit = self.try_reserve_module_upload()?; - self.install_wasm_reserved( - supplied_admin, - wasm, - seed, - claimed_hash, - permit, - false, - None, - ) - .await - } - - #[cfg(feature = "sandbox")] - async fn install_wasm_reserved( - &self, - supplied_admin: Option<&str>, - wasm: Vec, - seed: u64, - claimed_hash: &str, - _permit: OwnedSemaphorePermit, - compiled_from_source: bool, - provenance: Option, - ) -> Result<(String, u64), InstallError> { - let _profile_operation = self.profile_operation.lock().await; - self.authorize_admin(supplied_admin) - .map_err(|error| match error { - InviteError::Disabled => InstallError::Disabled, - InviteError::Unauthorized => InstallError::Unauthorized, - InviteError::Unavailable => InstallError::Unavailable, - InviteError::InvalidBounds(_) => InstallError::InvalidUpload, - })?; - if self.source_only && !compiled_from_source { - return Err(InstallError::RawModuleDisabled); - } - if compiled_from_source && provenance.is_none() { - return Err(InstallError::InvalidModule); - } - 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); - } - let is_native = crate::world_native::is_native_module(&wasm); - if is_native && !self.native { - return Err(InstallError::InvalidModule); - } - let guest: Box = if is_native { - // A durable world must have the worker on disk before the journal - // references it; native modules spawn from their stored file. - let modules = self.module_dir.clone().ok_or(InstallError::Disabled)?; - 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 path = self - .module_dir - .as_ref() - .ok_or(InstallError::Disabled)? - .path_of(&module_hash) - .map_err(|_| InstallError::Unavailable)?; - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - tokio::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o700)) - .await - .map_err(|_| InstallError::Unavailable)?; - } - let runtime = self - .world - .execution_profile() - .await - .map_err(|_| InstallError::Unavailable)? - .resolve(self.runtime) - .map_err(|_| InstallError::InvalidModule)?; - let native_limits = runtime.native; - let program = tokio::task::spawn_blocking(move || { - crate::world_native::NativeProgram::new(&path, seed, native_limits, None) - }) - .await - .map_err(|e| { - tracing::error!("native install join failed: {e:#}"); - InstallError::InvalidModule - })? - .map_err(|e| { - tracing::error!("native install failed: {e:#}"); - InstallError::InvalidModule - })?; - Box::new(program) - } else { - 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)?; - Box::new(program) - }; - - // A durable world must be able to reload this module before the - // journal may reference it (native was saved above). - if !is_native && 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); - } - } - - // Native workers are never offered for peer download: only the Wasm - // tier gets pinned in the blob store. - let blobs = self.blobs.as_ref().ok_or(InstallError::Disabled)?.clone(); - let pin = (!is_native).then(|| { - blobs - .add_bytes_with_opts(AddBytesOptions { - data: wasm.into(), - format: BlobFormat::Raw, - }) - .temp_tag() - }); - let pin = match pin { - Some(pin) => { - let pin = pin.await.map_err(|_| InstallError::Unavailable)?; - if pin.hash() != hash { - return Err(InstallError::Unavailable); - } - Some(pin) - } - None => None, - }; - let installed = self - .world - .install_program_with_provenance( - module_hash.clone(), - seed, - Some(provenance.unwrap_or(crate::world::ModuleProvenance::Artifact)), - guest, - ) - .await - .map_err(|_| InstallError::Unavailable)?; - if !matches!( - installed.kind, - crate::world::WorldEventKind::ProgramInstalled { .. } - ) { - return Err(InstallError::Unavailable); - } - *self.module_pin.lock().await = 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. - pub async fn module_bytes(&self, expected_hash: &str) -> Result, InstallError> { - let blobs = self.blobs.as_ref().ok_or(InstallError::Disabled)?; - let pin = self.module_pin.lock().await; - let Some(pin) = pin.as_ref() else { - return Err(InstallError::Unavailable); - }; - if pin.hash().to_string() != expected_hash { - return Err(InstallError::InvalidUpload); - } - let bytes = blobs - .blobs() - .get_bytes(pin.hash()) - .await - .map_err(|_| InstallError::Unavailable)?; - if bytes.len() > MAX_WORLD_MODULE_BYTES || module_hash(&bytes) != expected_hash { - return Err(InstallError::Unavailable); - } - Ok(bytes.to_vec()) - } - - /// 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() - } -} - -/// Canonical content identifier expected in an install-begin frame. -#[must_use] -pub fn module_hash(wasm: &[u8]) -> String { - Hash::new(wasm).to_string() -} - -/// Constant-time (for equal lengths) secret comparison. -#[must_use] -pub fn secret_eq(expected: &[u8], supplied: &[u8]) -> bool { - expected.len() == supplied.len() && bool::from(expected.ct_eq(supplied)) -} - -/// Run one session to completion with default settings. -pub async fn run_session(hub: &WorldHub, io: &mut I) { - run_session_with(hub, io, SessionConfig::default()).await; -} - -/// The admin secret a first frame carries, if it is an administrative one. -/// A valid secret lets the frame create the world it names. -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), - ClientFrame::SetExecutionProfile { admin_token, .. } => Some(admin_token), - _ => None, - } -} - -/// Run one session to completion. -/// -/// The first frame names the world (`"world": ""`, default world if -/// absent), and the session holds a lease on it until it ends. -pub async fn run_session_with(hub: &WorldHub, io: &mut I, config: SessionConfig) { - let first = match tokio::time::timeout(config.join_timeout, io.recv()).await { - Ok(Inbound::Text(text)) => text, - Ok(Inbound::Oversized) => { - let _ = send_error(io, "world frame is too large").await; - return; - } - Ok(Inbound::Unsupported) => { - let _ = send_error(io, "frames must be UTF-8 text").await; - return; - } - Ok(Inbound::Closed) => return, - Err(_) => { - let _ = send_error(io, "timed out waiting for join").await; - return; - } - }; - let Ok(mut value) = serde_json::from_str::(&first) else { - let _ = send_error(io, "first frame must be a valid join or invite request").await; - return; - }; - // `world` is a routing field, not part of any frame. - let world = match value - .as_object_mut() - .and_then(|object| object.remove("world")) - { - None | Some(serde_json::Value::Null) => None, - Some(serde_json::Value::String(name)) => Some(name), - Some(_) => { - let _ = send_error(io, "world must be a string").await; - return; - } - }; - let Ok(frame) = serde_json::from_value::(value) else { - let _ = send_error(io, "first frame must be a valid join or invite request").await; - return; - }; - // Hub-level frames are about the server, not one world. - match &frame { - ClientFrame::ListWorlds { admin_token } => { - if admin_token.len() > MAX_ADMIN_TOKEN_BYTES || !hub.admin_ok(admin_token) { - let _ = send_error(io, "admin denied").await; - return; - } - let worlds = hub.list(); - let _ = send_json( - io, - &ServerFrame::Worlds { - default: hub.default_world(), - worlds, - }, - ) - .await; - return; - } - ClientFrame::CreateWorld { admin_token } => { - if admin_token.len() > MAX_ADMIN_TOKEN_BYTES || !hub.admin_ok(admin_token) { - let _ = send_error(io, "admin denied").await; - return; - } - let name = world.as_deref().unwrap_or_else(|| hub.default_world()); - match hub.create(name).await { - Ok(created) => { - let _ = send_json( - io, - &ServerFrame::WorldCreated { - world: name, - created, - }, - ) - .await; - } - Err(error) => { - let _ = send_error(io, error.message()).await; - } - } - return; - } - _ => {} - } - let admin = frame_admin_token(&frame).filter(|token| token.len() <= MAX_ADMIN_TOKEN_BYTES); - let lease = match hub.lease(world.as_deref(), admin).await { - Ok(lease) => lease, - Err(error) => { - let _ = send_error(io, error.message()).await; - return; - } - }; - if let ClientFrame::SetIsolation { - isolation, - admin_token, - signed, - } = &frame - { - match set_isolation_frame( - hub, - &lease, - *isolation, - admin_token.as_deref(), - signed.as_ref(), - ) - .await - { - Ok(isolation) => { - let _ = send_json( - io, - &ServerFrame::Isolation { - world: lease.name(), - isolation, - }, - ) - .await; - } - Err(error) => { - let _ = send_error(io, &format!("{error:#}")).await; - } - } - return; - } - if let Some(result) = policy_frame(hub, &lease, &frame).await { - match result { - Ok(policy) => { - let _ = send_json( - io, - &ServerFrame::Policy { - world: lease.name(), - policy, - }, - ) - .await; - } - Err(error) => { - let _ = send_error(io, &format!("{error:#}")).await; - } - } - return; - } - run_world_session(lease.service(), io, frame).await; -} - -/// Apply an isolation change for the admin token, or for a signed request -/// whose account moderates the world. -async fn set_isolation_frame( - hub: &WorldHub, - lease: &WorldLease, - isolation: Isolation, - admin_token: Option<&str>, - signed: Option<&Signed>, -) -> anyhow::Result { - let target = format!("/world/{}/isolation", lease.name()); - let authority = - moderation_authority(hub, lease, admin_token, signed, &target, isolation.as_str())?; - lease - .service() - .world() - .set_isolation(authority, isolation) - .await -} - -/// Handle a cross-world write or file scope frame; `None` for any other frame. -async fn policy_frame( - hub: &WorldHub, - lease: &WorldLease, - frame: &ClientFrame, -) -> Option> { - Some(match frame { - ClientFrame::SetCrossWorldWrite { - enabled, - admin_token, - signed, - } => { - set_cross_world_write_frame( - hub, - lease, - *enabled, - admin_token.as_deref(), - signed.as_ref(), - ) - .await - } - ClientFrame::ForceCrossWorldWrite { admin_token } => { - force_cross_world_write_frame(lease, admin_token).await - } - ClientFrame::SetFileScope { - scope, - write_override, - admin_token, - signed, - } => { - set_file_scope_frame( - hub, - lease, - *scope, - *write_override, - admin_token.as_deref(), - signed.as_ref(), - ) - .await - } - _ => return None, - }) -} - -async fn set_cross_world_write_frame( - hub: &WorldHub, - lease: &WorldLease, - enabled: bool, - admin_token: Option<&str>, - signed: Option<&Signed>, -) -> anyhow::Result { - let target = format!("/world/{}/cross-world-write", lease.name()); - let body = if enabled { "on" } else { "off" }; - let authority = moderation_authority(hub, lease, admin_token, signed, &target, body)?; - lease - .service() - .world() - .set_cross_world_write(authority, enabled) - .await -} - -async fn force_cross_world_write_frame( - lease: &WorldLease, - admin_token: &str, -) -> anyhow::Result { - anyhow::ensure!(is_admin(lease, Some(admin_token)), "admin denied"); - lease - .service() - .world() - .force_cross_world_write(Authority::Admin) - .await -} - -async fn set_file_scope_frame( - hub: &WorldHub, - lease: &WorldLease, - scope: FileScope, - write_override: Option, - admin_token: Option<&str>, - signed: Option<&Signed>, -) -> anyhow::Result { - let target = format!("/world/{}/file-scope", lease.name()); - let body = match scope { - FileScope::Confined => "confined", - FileScope::Unrestricted => "unrestricted", - }; - let authority = moderation_authority(hub, lease, admin_token, signed, &target, body)?; - lease - .service() - .world() - .set_file_scope(authority, scope, write_override) - .await -} - -fn is_admin(lease: &WorldLease, admin_token: Option<&str>) -> bool { - admin_token - .filter(|token| token.len() <= MAX_ADMIN_TOKEN_BYTES) - .is_some_and(|token| lease.service().authorize_admin(Some(token)).is_ok()) -} - -/// The admin when the token matches; otherwise a signed request's account, -/// which the world's moderator check then judges. -fn moderation_authority( - hub: &WorldHub, - lease: &WorldLease, - admin_token: Option<&str>, - signed: Option<&Signed>, - target: &str, - body: &str, -) -> anyhow::Result { - if is_admin(lease, admin_token) { - return Ok(Authority::Admin); - } - let Some(signed) = signed else { - anyhow::bail!("admin denied"); - }; - let key = hub.verify_signed(signed, "PUT", target, body.as_bytes())?; - Ok(Authority::Signed(key)) -} - -/// Serve one session against its resolved world, starting from its first frame. -async fn run_world_session(service: &WorldService, io: &mut I, frame: ClientFrame) { - match frame { - ClientFrame::Join { capability, after } => { - if capability.len() > MAX_CAPABILITY_BYTES { - let _ = send_error(io, "invalid join capability").await; - return; - } - joined(service, io, JoinCapability::from_wire(capability), after).await; - } - ClientFrame::Invite { - admin_token, - display_name, - expires_in_secs, - uses, - role, - } => match role.as_deref().map(WorldScopes::from_role) { - Some(None) => { - let _ = send_error( - io, - "unknown invite role; use spectator, observer, player, guest, or delegator", - ) - .await; - } - role_scopes => match service - .invite_scoped( - Some(&admin_token), - display_name, - expires_in_secs, - uses, - role_scopes.flatten().unwrap_or(WorldScopes::GUEST), - ) - .await - { - Ok(invite) => { - let _ = send_json(io, &ServerFrame::Invite(&invite)).await; - } - Err(InviteError::InvalidBounds(message)) => { - let _ = send_error(io, message).await; - } - Err(InviteError::Disabled) => { - let _ = send_error(io, "invites are not enabled").await; - } - Err(InviteError::Unauthorized) => { - let _ = send_error(io, "invite denied").await; - } - Err(InviteError::Unavailable) => { - let _ = send_error(io, "world cannot issue another invite").await; - } - }, - }, - // Query frames keep the session open for further queries: a client - // can page through records, and may still join later on. - ClientFrame::Info { .. } - | ClientFrame::Records { .. } - | ClientFrame::RecordsTicket { .. } - | ClientFrame::DownloadModule { .. } => { - query_session(service, io, frame).await; - } - ClientFrame::InstallBegin { - admin_token, - total_bytes, - module_hash, - seed, - } => { - if service.source_only() { - if service.authorize_admin(Some(&admin_token)).is_err() { - let _ = send_error(io, "module install denied").await; - return; - } - let _ = - send_error(io, "raw module uploads are disabled by source-only policy").await; - return; - } - if let Err(message) = install_module_session( - service, - io, - &admin_token, - total_bytes, - module_hash.as_deref(), - seed, - ) - .await - { - let _ = send_error(io, message).await; - } - } - ClientFrame::Caps { capability } => { - let token = JoinCapability::from_wire(capability); - if service.world().participant_id(token).await.is_err() { - let _ = send_error(io, "join denied").await; - } else { - match service.world().caps_report().await { - Ok(report) => { - let _ = send_json(io, &ServerFrame::Caps { report }).await; - } - Err(_) => { - let _ = send_error(io, "capability report unavailable").await; - } - } - } - } - ClientFrame::UpdateCaps { - admin_token, - grant, - revoke, - } => match service.authorize_admin(Some(&admin_token)) { - Ok(()) => match service.world().update_caps(grant, revoke).await { - Ok(report) => { - let _ = send_json(io, &ServerFrame::Caps { report }).await; - } - Err(error) => { - let _ = send_error(io, &format!("{error:#}")).await; - } - }, - Err(_) => { - let _ = send_error(io, "admin denied").await; - } - }, - ClientFrame::SetCapsCeiling { - admin_token, - ceiling, - } => match service.set_caps_ceiling(Some(&admin_token), ceiling).await { - Ok(report) => { - let _ = send_json( - io, - &ServerFrame::CapsCeiling { - report, - message: CAPS_CEILING_NOTICE, - }, - ) - .await; - } - Err(error) => { - let _ = send_error(io, &format!("{error:#}")).await; - } - }, - ClientFrame::SetExecutionProfile { - admin_token, - profile, - } => match service - .set_execution_profile(Some(&admin_token), profile) - .await - { - Ok(update) => { - let _ = send_json( - io, - &ServerFrame::ExecutionProfile { - update, - message: "profile saved; it applies on the next program install or process restart, not to the running instance", - }, - ) - .await; - } - Err(error) => { - let _ = send_error(io, &format!("{error:#}")).await; - } - }, - ClientFrame::ExecutionProfileInfo { - admin_token, - capability, - } => { - let auth_ok = if let Some(admin) = admin_token.as_deref() { - service.authorize_admin(Some(admin)).is_ok() - } else if let Some(cap) = capability.as_deref() { - let token = JoinCapability::from_wire(cap.to_string()); - service.world().participant_id(token).await.is_ok() - } else { - false - }; - if !auth_ok { - let _ = send_error(io, "access denied").await; - } else { - match service.world().execution_profile().await { - Ok(profile) => { - let _ = send_json( - io, - &ServerFrame::ExecutionProfile { - update: crate::world::ExecutionProfileUpdate { - requested: profile, - applies_on_next_program_install_or_process_restart: false, - }, - message: "current persisted execution profile", - }, - ) - .await; - } - Err(error) => { - let _ = send_error(io, &format!("{error:#}")).await; - } - } - } - } - #[cfg(feature = "sandbox")] - ClientFrame::Compile { - admin_token, - files, - seed, - native, - } => { - let seed = seed.unwrap_or_else(|| rand::rng().random::()); - let spec = CompileSpec { - files: files - .into_iter() - .map(|file| (file.name, file.content)) - .collect(), - seed, - native, - }; - match service.compile_and_install(Some(&admin_token), &spec).await { - Ok((module_hash, sequence, diagnostics)) => { - let _ = send_json( - io, - &ServerFrame::Compiled { - module_hash, - sequence, - diagnostics, - }, - ) - .await; - } - Err(message) => { - let _ = send_error(io, &message).await; - } - } - } - #[cfg(not(feature = "sandbox"))] - ClientFrame::Compile { .. } => { - let _ = send_error(io, "compilation is not enabled on this server").await; - } - ClientFrame::InstallChunk { .. } - | ClientFrame::InstallEnd - | ClientFrame::ListWorlds { .. } - | ClientFrame::CreateWorld { .. } - | ClientFrame::SetIsolation { .. } - | ClientFrame::SetCrossWorldWrite { .. } - | ClientFrame::ForceCrossWorldWrite { .. } - | ClientFrame::SetFileScope { .. } - | ClientFrame::Chat { .. } - | ClientFrame::Attenuate { .. } - | ClientFrame::DelegateToFriend { .. } - | ClientFrame::Input { .. } - | ClientFrame::Resize { .. } - | ClientFrame::Paste { .. } => { - let _ = send_error(io, "first frame must be join, invite or install_begin").await; - } - } -} - -/// Serve query frames (`info`, `records`, `records_ticket`, -/// `download_module`) until the peer closes, denies, or sends a frame that -/// ends the session. A `join` frame switches to the joined session. -async fn query_session(service: &WorldService, io: &mut I, first: ClientFrame) { - let mut next = Some(first); - loop { - let frame = match next.take() { - Some(frame) => frame, - None => match io.recv().await { - Inbound::Text(text) => { - if let Ok(frame) = serde_json::from_str::(&text) { - frame - } else { - let _ = send_error(io, "invalid world frame").await; - return; - } - } - Inbound::Oversized => { - let _ = send_error(io, "world frame is too large").await; - return; - } - Inbound::Unsupported => { - let _ = send_error(io, "frames must be UTF-8 text").await; - return; - } - Inbound::Closed => return, - }, - }; - match frame { - ClientFrame::Join { capability, after } => { - if capability.len() > MAX_CAPABILITY_BYTES { - let _ = send_error(io, "invalid join capability").await; - return; - } - joined(service, io, JoinCapability::from_wire(capability), after).await; - return; - } - ClientFrame::Info { capability } => { - let token = JoinCapability::from_wire(capability); - if let Ok(snapshot) = service.world().snapshot(token).await { - if !send_json( - io, - &ServerFrame::ModuleInfo { - world_id: snapshot.world_id, - active_module_hash: snapshot.active_module_hash, - active_module_provenance: snapshot.active_module_provenance, - current_sequence: snapshot.current_sequence, - }, - ) - .await - { - return; - } - } else { - let _ = send_error(io, "join denied").await; - return; - } - } - ClientFrame::Records { - capability, - prefix, - after, - } => { - let token = JoinCapability::from_wire(capability); - if let Err(message) = records_session( - service.world(), - io, - token, - prefix.as_deref(), - after.as_deref(), - ) - .await - { - let _ = send_error(io, message).await; - return; - } - } - ClientFrame::RecordsTicket { capability } => { - let token = JoinCapability::from_wire(capability); - if service.world().participant_id(token).await.is_err() { - let _ = send_error(io, "join denied").await; - return; - } - match records_ticket_session(service, io).await { - Ok(()) => {} - Err(message) => { - let _ = send_error(io, message).await; - return; - } - } - } - ClientFrame::DownloadModule { - capability, - module_hash, - } => { - let token = JoinCapability::from_wire(capability); - if service.world().snapshot(token).await.is_err() { - let _ = send_error(io, "join denied").await; - return; - } - if let Err(message) = download_module_session(service, io, &module_hash).await { - let _ = send_error(io, message).await; - return; - } - } - _ => { - let _ = send_error(io, "expected a query frame").await; - return; - } - } - } -} - -/// Answer a `records_ticket` query. -async fn records_ticket_session( - service: &WorldService, - io: &mut I, -) -> Result<(), &'static str> { - match service.records_store() { - Some(store) => match store.read_ticket().await { - Ok(ticket) => { - if send_json(io, &ServerFrame::RecordsTicket { ticket }).await { - Ok(()) - } else { - Err("connection closed") - } - } - Err(_) => Err("records ticket unavailable"), - }, - None => Err("world keeps no structured records"), - } -} - -/// Largest page of records returned in one frame, comfortably inside -/// [`MAX_FRAME_BYTES`] after JSON framing overhead. -pub(crate) const MAX_RECORDS_PAGE_BYTES: usize = 768 * 1024; - -async fn records_session( - world: &WorldHandle, - io: &mut I, - token: JoinCapability, - prefix: Option<&str>, - after: Option<&str>, -) -> Result<(), &'static str> { - if world.participant_id(token).await.is_err() { - return Err("join denied"); - } - let (sequence, records) = world.records(); - let mut page = crate::world::Records::new(); - let mut used = 0usize; - let mut last_included: Option = None; - let mut more = false; - for (key, value) in records.iter() { - if let Some(prefix) = prefix - && !key.starts_with(prefix) - { - continue; - } - if let Some(after) = after - && key.as_str() <= after - { - continue; - } - let size = key.len() + serde_json::to_vec(value).map_or(0, |v| v.len()) + 8; - if used + size > MAX_RECORDS_PAGE_BYTES { - // `next_after` is exclusive on the client, so it must be the - // last key *included* here; anything else would skip a record. - if page.is_empty() { - return Err("a record is too large to serve in one page"); - } - more = true; - break; - } - used += size; - last_included = Some(key.clone()); - page.insert(key.clone(), value.clone()); - } - let next_after = more.then_some(last_included).flatten(); - if !send_json( - io, - &ServerFrame::Records { - sequence, - records: page, - next_after, - }, - ) - .await - { - return Err("connection closed"); - } - Ok(()) -} - -async fn download_module_session( - service: &WorldService, - io: &mut I, - requested_hash: &str, -) -> Result<(), &'static str> { - let Some(active_hash) = service.active_module_hash().await else { - return Err("world has no installed module"); - }; - if requested_hash != active_hash { - return Err("requested module is not the active world module"); - } - let bytes = service - .module_bytes(&active_hash) - .await - .map_err(|_| "module bytes are unavailable")?; - if !send_json( - io, - &ServerFrame::ModuleBegin { - module_hash: active_hash.clone(), - total_bytes: bytes.len(), - }, - ) - .await - { - return Err("connection closed"); - } - for (index, chunk) in bytes.chunks(MAX_WORLD_MODULE_CHUNK_BYTES).enumerate() { - if !send_json( - io, - &ServerFrame::ModuleChunk { - offset: index * MAX_WORLD_MODULE_CHUNK_BYTES, - data_hex: encode_hex(chunk), - }, - ) - .await - { - return Err("connection closed"); - } - } - if !send_json( - io, - &ServerFrame::ModuleEnd { - module_hash: active_hash, - }, - ) - .await - { - return Err("connection closed"); - } - Ok(()) -} - -async fn install_module_session( - service: &WorldService, - io: &mut I, - admin_token: &str, - total_bytes: usize, - claimed_hash: Option<&str>, - seed: u64, -) -> Result<(), &'static str> { - if admin_token.len() > MAX_ADMIN_TOKEN_BYTES - || service.authorize_admin(Some(admin_token)).is_err() - { - return Err("module install denied"); - } - 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 Err("invalid module size or content hash"); - } - let upload_permit = service - .try_reserve_module_upload() - .map_err(|_| "world is busy installing another module")?; - #[cfg(not(feature = "sandbox"))] - { - let _ = (io, seed, upload_permit); - return Err("module installation requires the sandbox feature"); - } - - #[cfg(feature = "sandbox")] - { - if !send_json( - io, - &ServerFrame::UploadReady { - chunk_bytes: MAX_WORLD_MODULE_CHUNK_BYTES, - }, - ) - .await - { - 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 }) = - serde_json::from_str::(&text) - 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!(serde_json::from_str::(text), Ok(ClientFrame::InstallEnd))) - { - return Err("expected install_end frame"); - } - 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"); - } - let (module_hash, sequence) = service - .install_wasm_reserved( - Some(admin_token), - bytes, - seed, - &actual_hash, - upload_permit, - false, - None, - ) - .await - .map_err(|error| match error { - InstallError::Disabled => "module installation is not enabled on this host", - InstallError::Unauthorized => "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::Unavailable => "world could not activate the module", - })?; - if !send_json( - io, - &ServerFrame::ModuleInstalled { - module_hash: &module_hash, - sequence, - }, - ) - .await - { - return Err("connection closed"); - } - Ok(()) - } -} - -async fn joined( - service: &WorldService, - io: &mut I, - token: JoinCapability, - after: Option, -) { - let world = service.world(); - // Subscribe before taking the snapshot so no event can fall in the gap; - // events at or below the cursor are skipped when delivered. - let mut events = world.subscribe(); - let mut revocations = world.subscribe_revocations(); - let Ok(participant_id) = world.participant_id(token.clone()).await else { - let _ = send_error(io, "join denied").await; - return; - }; - let Ok(snapshot) = world.snapshot(token.clone()).await else { - let _ = send_error(io, "join denied").await; - return; - }; - let mut cursor = snapshot.current_sequence; - let mut viewport = None; - if let Some(after) = after { - match world.events_after(token.clone(), after).await { - Ok(page) if page.needs_snapshot => { - let Ok(fresh) = world.snapshot(token.clone()).await else { - return; - }; - cursor = fresh.current_sequence; - if !send_json(io, &ServerFrame::Snapshot { snapshot: &fresh }).await { - return; - } - } - Ok(page) => { - cursor = page.current_sequence; - for event in &page.events { - if !send_json(io, &ServerFrame::Event { event }).await { - return; - } - if !send_view(world, io, &token, event.sequence, viewport).await { - return; - } - } - } - Err(_) => { - let _ = send_error(io, "join denied").await; - return; - } - } - } else if !send_json( - io, - &ServerFrame::Snapshot { - snapshot: &snapshot, - }, - ) - .await - { - return; - } - if !send_view(world, io, &token, cursor, viewport).await { - return; - } - - // Presence starts here and ends whenever this session does. Views are - // re-sent whenever program state changes for another reason (host events - // are not broadcast as events). - world.presence(participant_id, true).await; - let _guard = PresenceGuard { - world: world.clone(), - participant: participant_id, - }; - let mut views = world.watch_views(); - - loop { - tokio::select! { - inbound = io.recv() => match inbound { - Inbound::Text(text) => { - if !handle_client_frame(service, io, &token, &text, &mut viewport, cursor).await { - break; - } - } - Inbound::Oversized => { - if !send_error(io, "world frame is too large").await { break; } - } - Inbound::Unsupported => { - if !send_error(io, "frames must be UTF-8 text").await { break; } - } - Inbound::Closed => break, - }, - event = events.recv() => match event { - Ok(event) => { - if let crate::world::WorldEventKind::ProgramInstalled { ref module_hash, .. } = event.kind { - if event.sequence > cursor { - let Ok(snapshot) = world.snapshot(token.clone()).await else { break }; - if !send_json(io, &ServerFrame::Snapshot { snapshot: &snapshot }).await { - break; - } - cursor = event.sequence; - if !send_json(io, &ServerFrame::ProgramChanged { - module_hash, - sequence: cursor, - }).await || !send_view(world, io, &token, cursor, viewport).await { - break; - } - } - continue; - } - if event.sequence <= cursor { - continue; - } - // Projecting the event re-validates the capability on every - // delivery, which is what disconnects a revoked - // participant, and applies what this viewer may see now. - let Ok(projected) = world.project_event(token.clone(), event.clone()).await else { - break; - }; - // A withheld event still moves the cursor past it. - cursor = event.sequence; - let Some(shown) = projected else { - continue; - }; - if !send_json(io, &ServerFrame::Event { event: &shown }).await { - break; - } - if !send_view(world, io, &token, cursor, viewport).await { - break; - } - } - Err(broadcast::error::RecvError::Lagged(_)) => { - let Ok(snapshot) = world.snapshot(token.clone()).await else { break }; - if !send_json(io, &ServerFrame::Snapshot { snapshot: &snapshot }).await { - break; - } - cursor = snapshot.current_sequence; - if !send_view(world, io, &token, cursor, viewport).await { - break; - } - } - Err(broadcast::error::RecvError::Closed) => break, - }, - changed = views.changed() => match changed { - Ok(()) => { - let sequence = *views.borrow_and_update(); - if !send_view(world, io, &token, sequence, viewport).await { - break; - } - } - Err(_) => break, - }, - revoked = revocations.recv() => match revoked { - Ok(revoked_id) if revoked_id == participant_id => { - let _ = send_error(io, "world capability revoked").await; - break; - } - Ok(_) | Err(broadcast::error::RecvError::Lagged(_)) => {}, - Err(broadcast::error::RecvError::Closed) => break, - } - } - } -} - -/// Returns the participant's presence when the session ends, however it ends. -struct PresenceGuard { - world: WorldHandle, - participant: u64, -} - -impl Drop for PresenceGuard { - fn drop(&mut self) { - let world = self.world.clone(); - let participant = self.participant; - tokio::spawn(async move { - world.presence(participant, false).await; - }); - } -} - -async fn send_view( - world: &WorldHandle, - io: &mut I, - token: &JoinCapability, - sequence: u64, - viewport: Option, -) -> bool { - let view = match viewport { - Some(viewport) => { - let width = u16::try_from(viewport.width).unwrap_or(u16::MAX); - let height = u16::try_from(viewport.height).unwrap_or(u16::MAX); - world.view_at(token.clone(), width, height).await - } - None => world.view(token.clone()).await, - }; - match view { - Ok(Some(data)) => { - if data.len() > MAX_FRAME_BYTES { - return send_error(io, "world presentation is too large").await; - } - let surface = match crate::world_presentation::parse_surface(&data) { - Ok(Some(crate::world_presentation::WorldSurface::Screen(screen))) => { - let screen = viewport.map_or(screen.clone(), |viewport| { - screen.fit(viewport.width, viewport.height) - }); - Some(crate::world_presentation::WorldSurface::Screen(screen)) - } - Ok(surface) => surface, - Err(_) => return send_error(io, "invalid world screen presentation").await, - }; - send_json( - io, - &ServerFrame::View { - sequence, - data: &data, - surface: surface.as_ref(), - }, - ) - .await - } - Ok(None) => true, - Err(_) => false, - } -} - -/// Connection-local terminal/browser dimensions. This value is intentionally -/// absent from world events and snapshots. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -struct Viewport { - width: usize, - height: usize, -} - -fn normalize_paste(text: &str) -> Result, &'static str> { - let normalized = text.replace("\r\n", "\n").replace('\r', "\n"); - if normalized.len() > 4096 - || normalized - .chars() - .any(|ch| ch.is_control() && ch != '\n' && ch != '\t') - { - return Err("paste must be at most 4096 UTF-8 bytes and contain no control characters"); - } - Ok(normalized.into_bytes()) -} - -const USES_REFUSED: &str = "a delegation may not carry `uses`: a delegated grant has no use count, and the host's limit still applies"; - -/// Whether a delegation frame names `uses` anywhere in it. The field was -/// removed from delegations, and serde would ignore it, minting an unbounded -/// grant from a client that still sends it. Any depth is refused, so no -/// position hides the field. -fn delegation_names_uses(value: &serde_json::Value) -> bool { - let delegating = matches!( - value.get("type").and_then(serde_json::Value::as_str), - Some("attenuate" | "delegate_to_friend") - ); - delegating && names_uses(value) -} - -fn names_uses(value: &serde_json::Value) -> bool { - match value { - serde_json::Value::Object(map) => map - .iter() - .any(|(key, inner)| key == "uses" || names_uses(inner)), - serde_json::Value::Array(items) => items.iter().any(names_uses), - _ => false, - } -} - -/// Handle one frame from a joined participant. Returns `false` to end the session. -async fn handle_client_frame( - service: &WorldService, - io: &mut I, - token: &JoinCapability, - text: &str, - viewport: &mut Option, - sequence: u64, -) -> bool { - let world = service.world(); - let Ok(value) = serde_json::from_str::(text) else { - return send_error(io, "invalid world frame").await; - }; - if delegation_names_uses(&value) { - return send_error(io, USES_REFUSED).await; - } - let Ok(frame) = serde_json::from_value::(value) else { - return send_error(io, "invalid world frame").await; - }; - let result = match frame { - ClientFrame::Attenuate { - name, - scopes, - expires_at, - } => { - let Some(scopes) = WorldScopes::from_names(scopes.iter().map(String::as_str)) else { - return send_error(io, "unknown scope").await; - }; - let bounds = CapabilityBounds { - expires_at, - uses: None, - }; - let result = world.attenuate(token.clone(), scopes, bounds, name).await; - return send_delegation(io, result).await; - } - ClientFrame::DelegateToFriend { - friend, - name, - scopes, - expires_at, - } => { - let Some(scopes) = WorldScopes::from_names(scopes.iter().map(String::as_str)) else { - return send_error(io, "unknown scope").await; - }; - let bounds = CapabilityBounds { - expires_at, - uses: None, - }; - let result = world - .delegate_to_friend(token.clone(), friend, scopes, bounds, name) - .await; - return send_delegation(io, result).await; - } - ClientFrame::Chat { text } => world.chat(token.clone(), text).await, - ClientFrame::Resize { width, height } => { - if width == 0 || height == 0 || width > 500 || height > 200 { - return send_error( - io, - "viewport dimensions must be width 1..=500 and height 1..=200", - ) - .await; - } - *viewport = Some(Viewport { - width: usize::from(width), - height: usize::from(height), - }); - return send_view(world, io, token, sequence, *viewport).await; - } - ClientFrame::Paste { text } => { - let Ok(bytes) = normalize_paste(&text) else { - return send_error( - io, - "paste must be at most 4096 UTF-8 bytes and contain no control characters", - ) - .await; - }; - world.input(token.clone(), bytes).await - } - ClientFrame::Input { data_hex } => match decode_hex(&data_hex) { - Some(data) => world.input(token.clone(), data).await, - None => return send_error(io, "input data must be hexadecimal").await, - }, - ClientFrame::Records { prefix, after, .. } => { - // Authorized by the session's own capability. - if let Err(message) = records_session( - world, - io, - token.clone(), - prefix.as_deref(), - after.as_deref(), - ) - .await - { - return send_error(io, message).await; - } - return true; - } - ClientFrame::SetExecutionProfile { - admin_token, - profile, - } => { - match service - .set_execution_profile(Some(&admin_token), profile) - .await - { - Ok(update) => { - let _ = send_json( - io, - &ServerFrame::ExecutionProfile { - update, - message: "profile saved; it applies on the next program install or process restart, not to the running instance", - }, - ) - .await; - } - Err(error) => return send_error(io, &format!("{error:#}")).await, - } - return true; - } - ClientFrame::ExecutionProfileInfo { .. } => { - match service.world().execution_profile().await { - Ok(profile) => { - let _ = send_json( - io, - &ServerFrame::ExecutionProfile { - update: crate::world::ExecutionProfileUpdate { - requested: profile, - applies_on_next_program_install_or_process_restart: false, - }, - message: "current persisted execution profile", - }, - ) - .await; - } - Err(error) => return send_error(io, &format!("{error:#}")).await, - } - return true; - } - ClientFrame::RecordsTicket { .. } => { - if let Err(message) = records_ticket_session(service, io).await { - return send_error(io, message).await; - } - return true; - } - ClientFrame::Caps { .. } => { - match service.world().caps_report().await { - Ok(report) => { - let _ = send_json(io, &ServerFrame::Caps { report }).await; - } - Err(_) => { - return send_error(io, "capability report unavailable").await; - } - } - return true; - } - ClientFrame::UpdateCaps { - admin_token, - grant, - revoke, - } => { - match service.authorize_admin(Some(&admin_token)) { - Ok(()) => match service.world().update_caps(grant, revoke).await { - Ok(report) => { - let _ = send_json(io, &ServerFrame::Caps { report }).await; - } - Err(error) => { - return send_error(io, &format!("{error:#}")).await; - } - }, - Err(_) => { - return send_error(io, "admin denied").await; - } - } - return true; - } - ClientFrame::SetCapsCeiling { - admin_token, - ceiling, - } => { - match service.set_caps_ceiling(Some(&admin_token), ceiling).await { - Ok(report) => { - let _ = send_json( - io, - &ServerFrame::CapsCeiling { - report, - message: CAPS_CEILING_NOTICE, - }, - ) - .await; - } - Err(error) => return send_error(io, &format!("{error:#}")).await, - } - return true; - } - ClientFrame::Join { .. } - | ClientFrame::Invite { .. } - | ClientFrame::Info { .. } - | ClientFrame::ListWorlds { .. } - | ClientFrame::CreateWorld { .. } - | ClientFrame::SetIsolation { .. } - | ClientFrame::SetCrossWorldWrite { .. } - | ClientFrame::ForceCrossWorldWrite { .. } - | ClientFrame::SetFileScope { .. } - | ClientFrame::Compile { .. } - | ClientFrame::DownloadModule { .. } - | ClientFrame::InstallBegin { .. } - | ClientFrame::InstallChunk { .. } - | ClientFrame::InstallEnd => { - return send_error(io, "already joined").await; - } - }; - // Accepted events reach everyone, including the sender, through the - // broadcast branch, so only rejections are answered directly. - result.is_ok() || send_error(io, "world event rejected").await -} - -async fn send_json(io: &mut I, frame: &impl Serialize) -> bool { - match serde_json::to_string(frame) { - Ok(encoded) if encoded.len() <= MAX_FRAME_BYTES => io.send(encoded).await, - _ => false, - } -} - -async fn send_error(io: &mut I, message: &str) -> bool { - send_json(io, &ServerFrame::Error { message }).await -} - -async fn send_delegation( - io: &mut I, - result: anyhow::Result<(Participant, JoinCapability)>, -) -> bool { - match result { - Ok((participant, capability)) => { - let delegated = InviteResponse { - capability: capability.expose().to_owned(), - participant_id: participant.id, - display_name: participant.display_name, - }; - send_json(io, &ServerFrame::Invite(&delegated)).await - } - Err(_) => send_error(io, "delegation denied").await, - } -} - -/// Decode a bounded hex string. -#[must_use] -pub fn decode_hex(encoded: &str) -> Option> { - if !encoded.len().is_multiple_of(2) || encoded.len() > MAX_FRAME_BYTES * 2 { - return None; - } - encoded - .as_bytes() - .chunks_exact(2) - .map(|pair| Some((hex_nibble(pair[0])? << 4) | hex_nibble(pair[1])?)) - .collect() -} - -pub(crate) fn encode_hex(bytes: &[u8]) -> String { - const HEX: &[u8; 16] = b"0123456789abcdef"; - let mut result = String::with_capacity(bytes.len() * 2); - for byte in bytes { - result.push(char::from(HEX[usize::from(byte >> 4)])); - result.push(char::from(HEX[usize::from(byte & 0x0f)])); - } - result -} - -const fn hex_nibble(byte: u8) -> Option { - match byte { - b'0'..=b'9' => Some(byte - b'0'), - b'a'..=b'f' => Some(byte - b'a' + 10), - b'A'..=b'F' => Some(byte - b'A' + 10), - _ => None, - } -} - -fn enqueue_all( - queue: &mut crate::envelope_outbox::Outbox, - outbound: Vec, -) -> anyhow::Result> { - use crate::envelope_outbox::Payload; - let mut keys = Vec::with_capacity(outbound.len()); - for crate::directory_view::Outbound { target, payload } in outbound { - let key = payload.key(&target); - let queued = match payload { - Payload::Envelope(envelope) => queue.enqueue(&target, envelope), - Payload::Artifact(artifact) => queue.enqueue_artifact(&target, artifact), - }; - if let Err(error) = queued { - withdraw_all(queue, &keys); - return Err(error); - } - keys.push(key); - } - Ok(keys) -} - -fn withdraw_all(queue: &mut crate::envelope_outbox::Outbox, keys: &[String]) { - for key in keys { - if let Err(withdrawn) = queue.withdraw(key) { - tracing::error!("{key} stays queued though its change was refused: {withdrawn:#}"); - } - } -} - -#[cfg(test)] -#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] -mod tests { - use tokio::sync::mpsc; - - use ed25519_dalek::SigningKey; - - use super::*; - use crate::directory::{Actor, Level, Member}; - use crate::directory_auth::sign_request; - use crate::world::{WorldCore, WorldLimits, WorldScopes, hex_encode, unix_ms}; - - /// In-memory transport: tests push frames in and read frames out. - struct ChannelIo { - inbound: mpsc::Receiver, - outbound: mpsc::Sender, - } - - impl SessionIo for ChannelIo { - async fn recv(&mut self) -> Inbound { - self.inbound.recv().await.unwrap_or(Inbound::Closed) - } - async fn send(&mut self, frame: String) -> bool { - self.outbound.send(frame).await.is_ok() - } - } - - struct Peer { - to_server: mpsc::Sender, - from_server: mpsc::Receiver, - task: tokio::task::JoinHandle<()>, - } - - impl Peer { - fn connect(service: WorldService, config: SessionConfig) -> Self { - Self::connect_hub(WorldHub::single(service), config) - } - - fn connect_hub(hub: WorldHub, config: SessionConfig) -> Self { - let (to_server, inbound) = mpsc::channel(16); - let (outbound, from_server) = mpsc::channel(64); - let task = tokio::spawn(async move { - let mut io = ChannelIo { inbound, outbound }; - run_session_with(&hub, &mut io, config).await; - }); - Self { - to_server, - from_server, - task, - } - } - - async fn say(&self, frame: serde_json::Value) { - self.to_server - .send(Inbound::Text(frame.to_string())) - .await - .unwrap(); - } - - /// Sends the frame text as given, so a test controls field order. - async fn say_text(&self, text: &str) { - self.to_server - .send(Inbound::Text(text.to_owned())) - .await - .unwrap(); - } - - async fn next(&mut self) -> Option { - // An upload takes several seconds in a debug build, so 5 s was too - // tight. The deadline still bounds a real hang. - let frame = tokio::time::timeout(Duration::from_mins(1), self.from_server.recv()) - .await - .expect("timed out waiting for a server frame")?; - Some(serde_json::from_str(&frame).unwrap()) - } - } - - /// A program that does nothing, for tests that only install one. - struct NoProgram; - - impl crate::world::WorldProgram for NoProgram {} - - /// Publishes 1024 records of about 1 KiB, so one query needs several - /// pages (the page budget is 768 KiB). - struct Bulky; - - impl crate::world::WorldProgram for Bulky { - fn records(&mut self) -> anyhow::Result> { - let payload = "x".repeat(1024); - let records: crate::world::Records = (0..1024) - .map(|i| { - ( - format!("key-{i:04}"), - serde_json::Value::from(payload.clone()), - ) - }) - .collect(); - Ok(Some(serde_json::to_string(&records)?)) - } - } - - fn service_with_records(admin: Option<&str>) -> WorldService { - WorldService::new( - WorldHandle::spawn_with_program( - WorldCore::new("lobby", WorldLimits::default()).unwrap(), - Box::new(Bulky), - ), - admin.map(str::to_owned), - ) - } - - fn service(admin: Option<&str>) -> WorldService { - WorldService::new( - WorldHandle::spawn(WorldCore::new("lobby", WorldLimits::default()).unwrap()), - admin.map(str::to_owned), - ) - } - - #[tokio::test] - async fn execution_profile_change_is_admin_only_and_does_not_replace_live_program() { - struct MarkerProgram; - impl crate::world::WorldProgram for MarkerProgram { - fn view(&mut self, _viewer: &Participant) -> anyhow::Result> { - Ok(Some("existing instance".to_owned())) - } - } - - let world = WorldHandle::spawn_with_program( - WorldCore::new("lobby", WorldLimits::default()).unwrap(), - Box::new(MarkerProgram), - ); - let service = WorldService::new(world.clone(), Some("admin".to_owned())); - let requested = crate::world_limits::WorldExecutionProfile { - wasm_fuel: Some(1000), - ..Default::default() - }; - assert!( - service - .set_execution_profile(Some("wrong"), requested) - .await - .is_err() - ); - assert_eq!( - world.execution_profile().await.unwrap(), - crate::world_limits::WorldExecutionProfile::default() - ); - - let update = service - .set_execution_profile(Some("admin"), requested) - .await - .unwrap(); - assert_eq!(update.requested, requested); - assert!(update.applies_on_next_program_install_or_process_restart); - let (_, token) = world.issue("guest", WorldScopes::GUEST).await.unwrap(); - assert_eq!( - world.view(token).await.unwrap().as_deref(), - Some("existing instance"), - "updating the profile must not replace or mutate the running program" - ); - } - - #[tokio::test] - async fn execution_profile_protocol_returns_the_deferred_application_notice() { - let service = service(Some("admin")); - let mut peer = Peer::connect(service, SessionConfig::default()); - peer.say(serde_json::json!({ - "type": "set_execution_profile", - "admin_token": "admin", - "profile": {"wasm_fuel": 1234}, - })) - .await; - let response = peer.next().await.unwrap(); - assert_eq!(response["type"], "execution_profile"); - assert_eq!(response["update"]["requested"]["wasm_fuel"], 1234); - assert_eq!( - response["update"]["applies_on_next_program_install_or_process_restart"], - true - ); - assert!( - response["message"] - .as_str() - .unwrap() - .contains("not to the running instance") - ); - } - - #[tokio::test] - async fn caps_ceiling_is_admin_only_and_applies_at_once() { - let world = WorldHandle::spawn(WorldCore::new("lobby", WorldLimits::default()).unwrap()); - let service = WorldService::new(world.clone(), Some("admin".to_owned())); - let full = world.caps_report().await.unwrap().ceiling; - assert!( - service - .set_caps_ceiling(Some("wrong"), vec!["time.now".to_owned()]) - .await - .is_err() - ); - assert!( - service - .set_caps_ceiling(None, vec!["time.now".to_owned()]) - .await - .is_err() - ); - assert_eq!( - world.caps_report().await.unwrap().ceiling, - full, - "a refused change changes nothing" - ); - - let report = service - .set_caps_ceiling(Some("admin"), vec!["time.now".to_owned()]) - .await - .unwrap(); - assert_eq!(report.ceiling, vec!["time.now".to_owned()]); - assert_eq!( - world.caps_report().await.unwrap().ceiling, - vec!["time.now".to_owned()] - ); - } - - #[tokio::test] - async fn caps_ceiling_protocol_round_trips_and_says_it_applies_now() { - let mut peer = Peer::connect(service(Some("admin")), SessionConfig::default()); - peer.say(serde_json::json!({ - "type": "set_caps_ceiling", - "admin_token": "admin", - "ceiling": ["time.now"], - })) - .await; - let response = peer.next().await.unwrap(); - assert_eq!(response["type"], "caps_ceiling"); - assert_eq!( - response["report"]["ceiling"], - serde_json::json!(["time.now"]) - ); - assert!( - response["message"] - .as_str() - .unwrap() - .contains("applies immediately") - ); - - let mut peer = Peer::connect(service(Some("admin")), SessionConfig::default()); - peer.say(serde_json::json!({ - "type": "set_caps_ceiling", - "admin_token": "wrong", - "ceiling": [], - })) - .await; - assert_eq!(peer.next().await.unwrap()["type"], "error"); - - let mut peer = Peer::connect(service(Some("admin")), SessionConfig::default()); - peer.say(serde_json::json!({ - "type": "set_caps_ceiling", - "admin_token": "admin", - "ceiling": ["*"], - })) - .await; - assert_eq!(peer.next().await.unwrap()["type"], "error"); - } - - #[cfg(feature = "sandbox")] - #[tokio::test] - async fn source_compile_sees_the_effective_list_not_the_raw_grants() { - let root = tempfile::tempdir().unwrap(); - std::fs::write(root.path().join("platform.roc"), "x").unwrap(); - std::fs::create_dir_all(root.path().join("targets/wasm32")).unwrap(); - std::fs::write(root.path().join("targets/wasm32/host.wasm"), b"\0asm").unwrap(); - std::fs::write(root.path().join("Key.roc"), "module []\n").unwrap(); - std::fs::write(root.path().join("Screen.roc"), "module []\n").unwrap(); - let compiler = - Compiler::new(root.path().to_path_buf(), "/nonexistent/roc".to_owned()).unwrap(); - let svc = service(Some("admin")).with_compiler(compiler); - svc.world() - .update_caps(vec!["*".to_owned()], Vec::new()) - .await - .unwrap(); - let spec = CompileSpec { - files: vec![( - "main.roc".to_owned(), - "import pf.Screen\napp [x] {}".to_owned(), - )], - seed: 1, - native: false, - }; - - svc.set_caps_ceiling(Some("admin"), vec!["Key".to_owned()]) - .await - .unwrap(); - let error = svc - .compile_and_install(Some("admin"), &spec) - .await - .unwrap_err(); - assert!(error.contains("main.roc imports Screen"), "{error}"); - - // Inside the ceiling the same import passes the gate and reaches the - // compiler, which is not installed here. - svc.set_caps_ceiling(Some("admin"), vec!["Key".to_owned(), "Screen".to_owned()]) - .await - .unwrap(); - let error = svc - .compile_and_install(Some("admin"), &spec) - .await - .unwrap_err(); - assert!(!error.contains("imports Screen"), "{error}"); - } - - struct FixedScreen; - - impl crate::world::WorldProgram for FixedScreen { - fn view(&mut self, _viewer: &Participant) -> anyhow::Result> { - Ok(Some( - r#"{"kind":"screen","version":1,"width":4,"height":2,"rows":["界ab","wxyz"]}"# - .to_owned(), - )) - } - } - - #[tokio::test] - async fn viewport_is_session_local_and_never_advances_the_world_sequence() { - let world = WorldHandle::spawn_with_program( - WorldCore::new("lobby", WorldLimits::default()).unwrap(), - Box::new(FixedScreen), - ); - let svc = WorldService::new(world.clone(), None); - let scopes = WorldScopes::from_names(["join", "input"]).unwrap(); - let (_, capability) = world.issue("player".to_owned(), scopes).await.unwrap(); - let mut peer = Peer::connect(svc, SessionConfig::default()); - peer.say(serde_json::json!({"type":"join","capability":capability.expose()})) - .await; - assert_eq!(peer.next().await.unwrap()["type"], "snapshot"); - assert_eq!(peer.next().await.unwrap()["type"], "view"); - let sequence = world - .snapshot(capability.clone()) - .await - .unwrap() - .current_sequence; - - peer.say(serde_json::json!({"type":"resize","width":1,"height":1})) - .await; - let view = peer.next().await.unwrap(); - assert_eq!(view["type"], "view"); - assert_eq!(view["surface"]["width"], 1); - assert_eq!(view["surface"]["height"], 1); - assert_eq!(view["surface"]["cells"][0]["symbol"], " "); - assert_eq!( - world.snapshot(capability).await.unwrap().current_sequence, - sequence - ); - } - - /// A server with Ann and Bo as friends and no outbox. When `bo_home_is_remote`, - /// Bo's artifacts are held on another server, so removing Bo must be sent. - async fn friends_without_outbox( - bo_home_is_remote: bool, - ) -> (WorldService, crate::directory_auth::Caller, String) { - let mut core = WorldCore::new("lobby", WorldLimits::default()).unwrap(); - let (ann_secret, _) = core.directory_mut().sign_up("Ann").unwrap(); - let (bo_secret, _) = core.directory_mut().sign_up("Bo").unwrap(); - let ann_id = core.directory().account_for(&ann_secret).unwrap(); - let bo_id = core.directory().account_for(&bo_secret).unwrap(); - if bo_home_is_remote { - let home = crate::artifact::HomeServer { - endpoint: iroh::SecretKey::from_bytes(&[5; 32]).public().to_string(), - world_id: "home".to_owned(), - }; - core.directory_mut() - .declare_home(&bo_secret, vec![home]) - .unwrap(); - } - let svc = WorldService::new(WorldHandle::spawn(core), None); - let ann = crate::directory_auth::Caller::from_secret(&ann_secret); - let bo = crate::directory_auth::Caller::from_secret(&bo_secret); - svc.directory( - ann.clone(), - crate::directory_view::DirectoryAction::RequestFriend { - to: bo_id.clone(), - remote: None, - }, - ) - .await - .unwrap(); - svc.directory( - bo, - crate::directory_view::DirectoryAction::AcceptFriend { - from: ann_id, - remote: None, - }, - ) - .await - .unwrap(); - (svc, ann, bo_id) - } - - async fn friends_of_ann( - svc: &WorldService, - ann: &crate::directory_auth::Caller, - ) -> Option> { - let view = svc - .directory(ann.clone(), crate::directory_view::DirectoryAction::View) - .await - .unwrap() - .view; - view.accounts - .iter() - .find(|a| a.name == "Ann") - .unwrap() - .friends - .clone() - } - - #[tokio::test] - async fn a_local_friend_removal_needs_no_outbox() { - let (svc, ann, bo) = friends_without_outbox(false).await; - svc.directory( - ann.clone(), - crate::directory_view::DirectoryAction::RemoveFriend { other: bo }, - ) - .await - .unwrap(); - assert_eq!(friends_of_ann(&svc, &ann).await, Some(Vec::new())); - } - - #[tokio::test] - async fn a_removal_of_a_friend_on_another_server_is_refused_without_an_outbox() { - let (svc, ann, bo) = friends_without_outbox(true).await; - let refused = svc - .directory( - ann.clone(), - crate::directory_view::DirectoryAction::RemoveFriend { other: bo.clone() }, - ) - .await - .unwrap_err(); - assert!( - format!("{refused:#}").contains("cannot send to other servers"), - "{refused:#}" - ); - assert_eq!(friends_of_ann(&svc, &ann).await, Some(vec![bo])); - } - - #[tokio::test] - async fn a_signed_moderator_sets_isolation_and_a_forged_request_does_not() { - let key = SigningKey::from_bytes(&[9; 32]); - let moderator = hex_encode(&key.verifying_key().to_bytes()); - let mut core = WorldCore::new("lobby", WorldLimits::default()).unwrap(); - core.directory_mut() - .sign_up_keyed(&moderator, "Mo") - .unwrap(); - let (credential, _) = core.directory_mut().sign_up("Founder").unwrap(); - let founder = core.directory().account_for(&credential).unwrap(); - let (group, _) = core - .directory_mut() - .create_group(&founder, "staff", "", WorldScopes::GUEST) - .unwrap(); - core.directory_mut() - .set_member( - Actor::Server, - group, - Member::Account { - id: moderator.clone(), - }, - Some(Level::Moderator), - ) - .unwrap(); - let hub = WorldHub::single(WorldService::new(WorldHandle::spawn(core), None)); - let lease = hub.lease(None, None).await.unwrap(); - let target = format!("/world/{}/isolation", lease.name()); - let now = unix_ms(); - - let mut forged = sign_request(&key, "PUT", &target, b"unisolated", now, "forged"); - let last = forged.signature.pop().unwrap(); - forged.signature.push(if last == '0' { '1' } else { '0' }); - let other_body = sign_request(&key, "PUT", &target, b"isolated", now, "other-body"); - for signed in [&forged, &other_body] { - assert!( - set_isolation_frame(&hub, &lease, Isolation::Unisolated, None, Some(signed)) - .await - .is_err() - ); - } - assert_eq!( - lease.service().world().isolation().await.unwrap(), - Isolation::Isolated - ); - - let signed = sign_request(&key, "PUT", &target, b"unisolated", now, "good"); - assert_eq!( - set_isolation_frame(&hub, &lease, Isolation::Unisolated, None, Some(&signed)) - .await - .unwrap(), - Isolation::Unisolated - ); - } - - #[tokio::test] - async fn a_bad_admin_token_is_refused_for_force_and_override() { - let world = WorldHandle::spawn(WorldCore::new("lobby", WorldLimits::default()).unwrap()); - world - .set_isolation(Authority::Admin, Isolation::Unisolated) - .await - .unwrap(); - let hub = WorldHub::single(WorldService::new(world, Some("secret".to_owned()))); - let lease = hub.lease(None, None).await.unwrap(); - let force_guess = ClientFrame::ForceCrossWorldWrite { - admin_token: "guess".to_owned(), - }; - let override_guess = ClientFrame::SetFileScope { - scope: FileScope::Unrestricted, - write_override: Some(true), - admin_token: Some("guess".to_owned()), - signed: None, - }; - assert!( - policy_frame(&hub, &lease, &force_guess) - .await - .unwrap() - .is_err() - ); - assert!( - policy_frame(&hub, &lease, &override_guess) - .await - .unwrap() - .is_err() - ); - let policy = lease.service().world().policy().await.unwrap(); - assert!(!policy.cross_world_forced && !policy.file_write_override); - - let force = ClientFrame::ForceCrossWorldWrite { - admin_token: "secret".to_owned(), - }; - let forced = policy_frame(&hub, &lease, &force).await.unwrap().unwrap(); - assert!(forced.cross_world_forced); - let override_on = ClientFrame::SetFileScope { - scope: FileScope::Unrestricted, - write_override: Some(true), - admin_token: Some("secret".to_owned()), - signed: None, - }; - let set = policy_frame(&hub, &lease, &override_on) - .await - .unwrap() - .unwrap(); - assert!(set.file_write_override); - } - - #[test] - fn hex_input_parser_is_bounded_and_strict() { - assert_eq!(decode_hex("00aBff"), Some(vec![0, 0xab, 0xff])); - assert_eq!(decode_hex(""), Some(vec![])); - assert_eq!(decode_hex("0"), None); - assert_eq!(decode_hex("zz"), None); - assert_eq!(decode_hex(&"0".repeat(MAX_FRAME_BYTES * 2 + 2)), None); - } - - #[test] - fn paste_is_normalized_bounded_and_rejects_controls() { - assert_eq!(normalize_paste("a\r\nb\rc\t"), Ok(b"a\nb\nc\t".to_vec())); - assert_eq!(normalize_paste(&"x".repeat(4096)).unwrap().len(), 4096); - assert!(normalize_paste(&"x".repeat(4097)).is_err()); - assert!(normalize_paste("a\u{1b}b").is_err()); - assert_eq!( - normalize_paste(&"界".repeat(1366)).unwrap_err(), - "paste must be at most 4096 UTF-8 bytes and contain no control characters" - ); - } - - #[test] - fn wire_event_and_view_shape_are_presentation_neutral() { - use crate::world::WorldEventKind; - let event = WorldEvent { - sequence: 3, - participant_id: 9, - kind: WorldEventKind::Chat("hello".to_owned()), - }; - let encoded = serde_json::to_string(&ServerFrame::Event { event: &event }).unwrap(); - assert!(encoded.contains("\"type\":\"event\"")); - assert!(encoded.contains("\"sequence\":3")); - assert!(encoded.contains("\"kind\":\"chat\"")); - assert!(encoded.contains("\"data\":\"hello\"")); - let view = serde_json::to_string(&ServerFrame::View { - sequence: 3, - data: "count=1", - surface: None, - }) - .unwrap(); - assert!(view.contains("\"type\":\"view\"")); - assert!(view.contains("\"data\":\"count=1\"")); - } - - #[test] - fn typed_screen_is_an_optional_view_surface_without_dropping_legacy_data() { - let data = - r#"{"kind":"screen","version":1,"width":2,"height":1,"rows":["ok"],"styles":[[]]}"#; - let surface = crate::world_presentation::parse_surface(data) - .unwrap() - .unwrap(); - let encoded = serde_json::to_string(&ServerFrame::View { - sequence: 8, - data, - surface: Some(&surface), - }) - .unwrap(); - assert!(encoded.contains("\"data\":\"{\\\"kind\\\":\\\"screen\\\"")); - assert!(encoded.contains("\"surface\":{\"kind\":\"screen\",\"version\":1")); - assert!(encoded.contains("\"symbol\":\"o\"")); - } - - #[test] - fn secret_comparison_requires_equal_bytes() { - assert!(secret_eq(b"abc", b"abc")); - assert!(!secret_eq(b"abc", b"abd")); - assert!(!secret_eq(b"abc", b"ab")); - } - - #[tokio::test] - async fn silent_peers_are_dropped_after_the_join_timeout() { - let mut peer = Peer::connect( - service(None), - SessionConfig { - join_timeout: Duration::from_millis(50), - }, - ); - let frame = peer.next().await.unwrap(); - assert_eq!(frame["type"], "error"); - assert!(frame["message"].as_str().unwrap().contains("timed out")); - assert!(peer.next().await.is_none()); - peer.task.await.unwrap(); - } - - #[tokio::test] - async fn first_frame_must_be_join_or_invite() { - let mut peer = Peer::connect(service(Some("a")), SessionConfig::default()); - peer.say(serde_json::json!({"type": "chat", "text": "hi"})) - .await; - assert_eq!(peer.next().await.unwrap()["type"], "error"); - assert!(peer.next().await.is_none()); - - let mut garbage = Peer::connect(service(None), SessionConfig::default()); - garbage - .to_server - .send(Inbound::Text("not json".to_owned())) - .await - .unwrap(); - assert_eq!(garbage.next().await.unwrap()["type"], "error"); - - let mut big = Peer::connect(service(None), SessionConfig::default()); - big.to_server.send(Inbound::Oversized).await.unwrap(); - assert_eq!(big.next().await.unwrap()["type"], "error"); - let mut bin = Peer::connect(service(None), SessionConfig::default()); - bin.to_server.send(Inbound::Unsupported).await.unwrap(); - assert_eq!(bin.next().await.unwrap()["type"], "error"); - } - - #[test] - fn invite_lifetimes_default_to_a_week_and_stop_at_thirty_days() { - let now = 1_000_000; - let default = invite_bounds(None, None, now).unwrap(); - assert_eq!(default.expires_at, Some(now + INVITE_DEFAULT_SECS * 1000)); - assert_eq!(default.uses, None); - let longest = invite_bounds(Some(INVITE_MAX_SECS), Some(3), now).unwrap(); - assert_eq!(longest.expires_at, Some(now + INVITE_MAX_SECS * 1000)); - assert_eq!(longest.uses, Some(3)); - assert!(invite_bounds(Some(0), None, now).is_err()); - assert!(invite_bounds(Some(INVITE_MAX_SECS + 1), None, now).is_err()); - assert!(invite_bounds(None, Some(0), now).is_err()); - } - - #[tokio::test] - async fn invite_frame_refuses_bounds_out_of_range() { - let svc = service(Some("admin")); - let mut long = Peer::connect(svc.clone(), SessionConfig::default()); - long.say(serde_json::json!({"type":"invite","admin_token":"admin","display_name":"ann","expires_in_secs":INVITE_MAX_SECS + 1})) - .await; - assert_eq!(long.next().await.unwrap()["type"], "error"); - let mut none = Peer::connect(svc, SessionConfig::default()); - none.say(serde_json::json!({"type":"invite","admin_token":"admin","display_name":"ann","uses":0})) - .await; - assert_eq!( - none.next().await.unwrap()["message"], - "uses must be at least 1" - ); - } - - #[tokio::test] - async fn delegate_to_friend_frame_needs_an_account_capability() { - let svc = service(Some("admin")); - let mut host = Peer::connect(svc.clone(), SessionConfig::default()); - host.say(serde_json::json!({"type":"invite","admin_token":"admin","display_name":"ann"})) - .await; - let capability = host.next().await.unwrap()["capability"] - .as_str() - .unwrap() - .to_owned(); - - let mut guest = Peer::connect(svc, SessionConfig::default()); - guest - .say(serde_json::json!({"type":"join","capability":capability})) - .await; - assert_eq!(guest.next().await.unwrap()["type"], "snapshot"); - guest - .say(serde_json::json!({"type":"delegate_to_friend","friend":"nobody","name":"bo","scopes":["join"]})) - .await; - assert_eq!(guest.next().await.unwrap()["message"], "delegation denied"); - guest - .say(serde_json::json!({"type":"delegate_to_friend","friend":"nobody","name":"bo","scopes":["root"]})) - .await; - assert_eq!(guest.next().await.unwrap()["message"], "unknown scope"); - } - - #[tokio::test] - async fn invite_frame_issues_a_capability_that_can_join() { - let svc = service(Some("admin")); - - let mut denied = Peer::connect(svc.clone(), SessionConfig::default()); - denied - .say(serde_json::json!({"type":"invite","admin_token":"nope","display_name":"x"})) - .await; - assert_eq!(denied.next().await.unwrap()["message"], "invite denied"); - - let mut host = Peer::connect(svc.clone(), SessionConfig::default()); - host.say(serde_json::json!({"type":"invite","admin_token":"admin","display_name":"ann"})) - .await; - let invite = host.next().await.unwrap(); - assert_eq!(invite["type"], "invite"); - let capability = invite["capability"].as_str().unwrap().to_owned(); - - let mut guest = Peer::connect(svc, SessionConfig::default()); - guest - .say(serde_json::json!({"type":"join","capability":capability})) - .await; - assert_eq!(guest.next().await.unwrap()["type"], "snapshot"); - } - - #[tokio::test] - async fn invite_roles_grant_and_withhold_the_expected_scopes() { - let svc = service(Some("admin")); - - // An unknown role is refused by name. - let mut bad = Peer::connect(svc.clone(), SessionConfig::default()); - bad.say(serde_json::json!({ - "type": "invite", - "admin_token": "admin", - "display_name": "spec", - "role": "builder", - })) - .await; - let message = bad.next().await.unwrap()["message"] - .as_str() - .unwrap() - .to_owned(); - assert!(message.contains("unknown invite role"), "{message}"); - - // A spectator may join and read, but not chat or submit input. - let mut host = Peer::connect(svc.clone(), SessionConfig::default()); - host.say(serde_json::json!({ - "type": "invite", - "admin_token": "admin", - "display_name": "spec", - "role": "spectator", - })) - .await; - let capability = host.next().await.unwrap()["capability"] - .as_str() - .unwrap() - .to_owned(); - let mut spectator = Peer::connect(svc.clone(), SessionConfig::default()); - spectator - .say(serde_json::json!({"type":"join","capability":capability})) - .await; - assert_eq!(spectator.next().await.unwrap()["type"], "snapshot"); - spectator - .say(serde_json::json!({"type":"chat","text":"hello"})) - .await; - let refusal = spectator.next().await.unwrap(); - assert_eq!(refusal["type"], "error", "{refusal}"); - spectator - .say(serde_json::json!({"type":"input","data_hex":"6c"})) - .await; - let refusal = spectator.next().await.unwrap(); - assert_eq!(refusal["type"], "error", "{refusal}"); - - // A player may submit input but not chat. - let mut host = Peer::connect(svc.clone(), SessionConfig::default()); - host.say(serde_json::json!({ - "type": "invite", - "admin_token": "admin", - "display_name": "player", - "role": "player", - })) - .await; - let capability = host.next().await.unwrap()["capability"] - .as_str() - .unwrap() - .to_owned(); - let mut player = Peer::connect(svc, SessionConfig::default()); - player - .say(serde_json::json!({"type":"join","capability":capability})) - .await; - assert_eq!(player.next().await.unwrap()["type"], "snapshot"); - player - .say(serde_json::json!({"type":"input","data_hex":"6c"})) - .await; - let event = player.next().await.unwrap(); - assert_eq!(event["type"], "event", "{event}"); - player - .say(serde_json::json!({"type":"chat","text":"hello"})) - .await; - let refusal = player.next().await.unwrap(); - assert_eq!(refusal["type"], "error", "{refusal}"); - } - - #[tokio::test] - async fn a_delegate_mints_narrower_capabilities_over_the_session() { - let svc = service(None); - let delegate = WorldScopes::from_names(["join", "chat", "input", "delegate"]).unwrap(); - let (_, owner) = svc.world().issue("ann".to_owned(), delegate).await.unwrap(); - - let mut owner_peer = Peer::connect(svc.clone(), SessionConfig::default()); - owner_peer - .say(serde_json::json!({"type":"join","capability":owner.expose()})) - .await; - assert_eq!(owner_peer.next().await.unwrap()["type"], "snapshot"); - owner_peer - .say(serde_json::json!({"type":"attenuate","name":"bo","scopes":["join"]})) - .await; - let delegated = owner_peer.next().await.unwrap(); - assert_eq!(delegated["type"], "invite"); - let child = delegated["capability"].as_str().unwrap().to_owned(); - - let mut child_peer = Peer::connect(svc, SessionConfig::default()); - child_peer - .say(serde_json::json!({"type":"join","capability":child})) - .await; - assert_eq!(child_peer.next().await.unwrap()["type"], "snapshot"); - child_peer - .say(serde_json::json!({"type":"attenuate","name":"cy","scopes":["join"]})) - .await; - assert_eq!(child_peer.next().await.unwrap()["type"], "error"); - child_peer - .say(serde_json::json!({"type":"attenuate","name":"cy","scopes":["telepathy"]})) - .await; - assert_eq!(child_peer.next().await.unwrap()["message"], "unknown scope"); - } - - /// A joined participant that may delegate `join`. - async fn delegator(svc: &WorldService) -> Peer { - let delegate = WorldScopes::from_names(["join", "chat", "input", "delegate"]).unwrap(); - let (_, owner) = svc.world().issue("ann".to_owned(), delegate).await.unwrap(); - let mut peer = Peer::connect(svc.clone(), SessionConfig::default()); - peer.say(serde_json::json!({"type":"join","capability":owner.expose()})) - .await; - assert_eq!(peer.next().await.unwrap()["type"], "snapshot"); - peer - } - - /// Delegation frames that name `uses`, in each position a client could put - /// it. Serde would ignore the field and mint an unbounded grant. - const FRAMES_NAMING_USES: [&str; 9] = [ - r#"{"type":"attenuate","uses":1,"name":"bo","scopes":["join"]}"#, - r#"{"type":"attenuate","name":"bo","uses":1,"scopes":["join"]}"#, - r#"{"type":"attenuate","name":"bo","scopes":["join"],"uses":1}"#, - r#"{"type":"attenuate","name":"bo","scopes":["join"],"expires_at":null,"uses":null}"#, - r#"{"type":"attenuate","name":"bo","scopes":["join"],"bounds":{"uses":1}}"#, - r#"{"type":"attenuate","name":"bo","scopes":[{"uses":1}]}"#, - r#"{"type":"delegate_to_friend","uses":1,"friend":"nobody","name":"bo","scopes":["join"]}"#, - r#"{"type":"delegate_to_friend","friend":"nobody","name":"bo","scopes":["join"],"uses":1}"#, - r#"{"type":"delegate_to_friend","friend":"nobody","name":"bo","scopes":["join"],"bounds":{"uses":1}}"#, - ]; - - #[tokio::test] - async fn a_delegation_frame_that_names_uses_is_refused_by_name() { - let svc = service(None); - let mut peer = delegator(&svc).await; - for text in FRAMES_NAMING_USES { - peer.say_text(text).await; - let reply = peer.next().await.unwrap(); - assert_eq!(reply["type"], "error", "{text}"); - assert!( - reply["message"] - .as_str() - .unwrap_or_default() - .contains("`uses`"), - "{text}: {reply}" - ); - } - } - - #[tokio::test] - async fn a_delegation_frame_without_uses_is_accepted() { - let svc = service(None); - let mut peer = delegator(&svc).await; - for text in [ - r#"{"type":"attenuate","name":"bo","scopes":["join"]}"#, - r#"{"type":"attenuate","scopes":["join"],"expires_at":null,"name":"cy"}"#, - ] { - peer.say_text(text).await; - assert_eq!(peer.next().await.unwrap()["type"], "invite", "{text}"); - } - // Past the uses check, this delegate has no account, so the friend - // delegation is denied for that reason alone. - peer.say_text( - r#"{"type":"delegate_to_friend","friend":"nobody","name":"di","scopes":["join"]}"#, - ) - .await; - assert_eq!(peer.next().await.unwrap()["message"], "delegation denied"); - } - - #[tokio::test] - async fn records_are_paged_prefixed_and_queryable_while_joined() { - let svc = service_with_records(None); - let (_, token) = svc - .world() - .issue("ann".to_owned(), WorldScopes::GUEST) - .await - .unwrap(); - - // A fresh session can page through records; pages must be bounded and - // terminate with `next_after: null`. - let mut peer = Peer::connect(svc.clone(), SessionConfig::default()); - let mut pages = 0; - let mut seen = crate::world::Records::new(); - let mut after: Option = None; - loop { - let mut frame = serde_json::json!({ - "type": "records", - "capability": token.expose(), - }); - if let Some(after) = &after { - frame["after"] = serde_json::Value::from(after.clone()); - } - peer.say(frame).await; - let reply = peer.next().await.unwrap(); - assert_eq!(reply["type"], "records"); - assert!(reply["sequence"].as_u64().is_some()); - let page: crate::world::Records = - serde_json::from_value(reply["records"].clone()).unwrap(); - assert!(!page.is_empty()); - assert!( - serde_json::to_vec(&page).unwrap().len() <= MAX_RECORDS_PAGE_BYTES, - "page exceeds the byte budget" - ); - pages += 1; - seen.extend(page); - match reply["next_after"].as_str() { - Some(next) => after = Some(next.to_owned()), - None => break, - } - } - assert_eq!(seen.len(), 1024, "every record arrives exactly once"); - assert!(pages > 1, "1 MiB of records cannot fit in one page"); - assert!(seen.contains_key("key-0000") && seen.contains_key("key-1023")); - - // Prefix filtering works on the same session. - peer.say(serde_json::json!({ - "type": "records", - "capability": token.expose(), - "prefix": "key-010", - })) - .await; - let reply = peer.next().await.unwrap(); - let page: crate::world::Records = serde_json::from_value(reply["records"].clone()).unwrap(); - assert_eq!(page.len(), 10, "key-0100..key-0109"); - - // A joined session can also request the records document ticket (the - // reply is an error here only because this service has no docs store). - let mut joined = Peer::connect(svc, SessionConfig::default()); - joined - .say(serde_json::json!({"type":"join","capability": token.expose()})) - .await; - assert_eq!(joined.next().await.unwrap()["type"], "snapshot"); - joined - .say(serde_json::json!({"type":"records","capability": token.expose()})) - .await; - let reply = joined.next().await.unwrap(); - assert_eq!(reply["type"], "records"); - let page: crate::world::Records = serde_json::from_value(reply["records"].clone()).unwrap(); - assert!(!page.is_empty() && page.len() < 1024, "one bounded page"); - assert!( - reply["next_after"].is_string(), - "the page advertises that more records follow" - ); - // Still joined afterwards. - joined - .say(serde_json::json!({"type":"chat","text":"hi"})) - .await; - let reply = joined.next().await.unwrap(); - assert_eq!(reply["type"], "event"); - } - - fn memory_hub( - limits: crate::world_hub::HubLimits, - ) -> (WorldHub, Arc) { - let opener = crate::world_hub::testing::MemoryOpener::new(false); - let dyn_opener: Arc = opener.clone(); - ( - WorldHub::new(dyn_opener, Some("admin".to_owned()), "lobby", limits), - opener, - ) - } - - /// Invite `name` into `world` (creating it) and return the capability. - async fn invite_into(hub: &WorldHub, world: &str, name: &str) -> String { - let mut peer = Peer::connect_hub(hub.clone(), SessionConfig::default()); - peer.say(serde_json::json!({ - "type": "invite", - "admin_token": "admin", - "display_name": name, - "world": world, - })) - .await; - let reply = peer.next().await.unwrap(); - assert_eq!(reply["type"], "invite", "{reply}"); - reply["capability"].as_str().unwrap().to_owned() - } - - #[tokio::test] - async fn the_world_field_routes_a_session_and_capabilities_do_not_cross_worlds() { - let (hub, _) = memory_hub(crate::world_hub::HubLimits::default()); - let in_arena = invite_into(&hub, "arena", "ann").await; - let in_bazaar = invite_into(&hub, "bazaar", "bob").await; - - // Joining the world the capability belongs to works... - let mut arena = Peer::connect_hub(hub.clone(), SessionConfig::default()); - arena - .say(serde_json::json!({"type":"join","capability": in_arena,"world":"arena"})) - .await; - let snapshot = arena.next().await.unwrap(); - assert_eq!(snapshot["type"], "snapshot"); - assert_eq!(snapshot["snapshot"]["world_id"], "arena"); - - // ...the same capability is refused in another world... - let mut wrong = Peer::connect_hub(hub.clone(), SessionConfig::default()); - wrong - .say(serde_json::json!({"type":"join","capability": in_arena,"world":"bazaar"})) - .await; - assert_eq!(wrong.next().await.unwrap()["message"], "join denied"); - - // ...and chat in one world is invisible in the other. - arena - .say(serde_json::json!({"type":"chat","text":"hello arena"})) - .await; - assert_eq!(arena.next().await.unwrap()["type"], "event"); - let mut bazaar = Peer::connect_hub(hub.clone(), SessionConfig::default()); - bazaar - .say(serde_json::json!({"type":"join","capability": in_bazaar,"world":"bazaar"})) - .await; - let snapshot = bazaar.next().await.unwrap(); - assert_eq!(snapshot["snapshot"]["world_id"], "bazaar"); - assert_eq!(snapshot["snapshot"]["events"].as_array().unwrap().len(), 0); - - // No `world` field means the default world, which nobody created. - let mut default = Peer::connect_hub(hub, SessionConfig::default()); - default - .say(serde_json::json!({"type":"join","capability": in_arena})) - .await; - assert_eq!(default.next().await.unwrap()["message"], "unknown world"); - } - - #[tokio::test] - async fn only_an_admin_creates_or_lists_worlds() { - let (hub, _) = memory_hub(crate::world_hub::HubLimits::default()); - let mut denied = Peer::connect_hub(hub.clone(), SessionConfig::default()); - denied - .say(serde_json::json!({"type":"create_world","admin_token":"nope","world":"arena"})) - .await; - assert_eq!(denied.next().await.unwrap()["message"], "admin denied"); - let mut denied = Peer::connect_hub(hub.clone(), SessionConfig::default()); - denied - .say(serde_json::json!({"type":"list_worlds","admin_token":"nope"})) - .await; - assert_eq!(denied.next().await.unwrap()["message"], "admin denied"); - - let mut admin = Peer::connect_hub(hub.clone(), SessionConfig::default()); - admin - .say(serde_json::json!({"type":"create_world","admin_token":"admin","world":"arena"})) - .await; - let created = admin.next().await.unwrap(); - assert_eq!( - (created["type"].as_str(), created["created"].as_bool()), - (Some("world_created"), Some(true)) - ); - let mut admin = Peer::connect_hub(hub.clone(), SessionConfig::default()); - admin - .say(serde_json::json!({"type":"create_world","admin_token":"admin","world":"arena"})) - .await; - assert_eq!(admin.next().await.unwrap()["created"], false); - let mut admin = Peer::connect_hub(hub.clone(), SessionConfig::default()); - admin - .say(serde_json::json!({"type":"create_world","admin_token":"admin","world":"../x"})) - .await; - assert_eq!(admin.next().await.unwrap()["message"], "invalid world name"); - - let mut admin = Peer::connect_hub(hub, SessionConfig::default()); - admin - .say(serde_json::json!({"type":"list_worlds","admin_token":"admin"})) - .await; - let listed = admin.next().await.unwrap(); - assert_eq!(listed["type"], "worlds"); - assert_eq!(listed["default"], "lobby"); - assert_eq!(listed["worlds"][0]["name"], "arena"); - } - - #[tokio::test] - async fn unauthenticated_frames_cannot_create_or_probe_worlds() { - let (hub, opener) = memory_hub(crate::world_hub::HubLimits::default()); - for frame in [ - serde_json::json!({"type":"join","capability":"1.abc","world":"arena"}), - serde_json::json!({"type":"info","capability":"1.abc","world":"arena"}), - serde_json::json!({"type":"invite","admin_token":"wrong","display_name":"x","world":"arena"}), - ] { - let mut peer = Peer::connect_hub(hub.clone(), SessionConfig::default()); - peer.say(frame).await; - assert_eq!(peer.next().await.unwrap()["message"], "unknown world"); - } - assert_eq!( - opener.opens.load(std::sync::atomic::Ordering::SeqCst), - 0, - "nothing was opened or created by outsiders" - ); - } - - #[tokio::test] - async fn many_sessions_across_many_worlds_stay_separate() { - let (hub, _) = memory_hub(crate::world_hub::HubLimits::default()); - let mut tasks = tokio::task::JoinSet::new(); - for world in 0..8 { - for player in 0..8 { - let hub = hub.clone(); - tasks.spawn(async move { - let name = format!("world-{world}"); - let capability = invite_into(&hub, &name, &format!("p{player}")).await; - let mut peer = Peer::connect_hub(hub, SessionConfig::default()); - peer.say(serde_json::json!({ - "type": "join", "capability": capability, "world": name - })) - .await; - let snapshot = peer.next().await.unwrap(); - assert_eq!(snapshot["snapshot"]["world_id"], name.as_str()); - peer.say(serde_json::json!({ - "type": "chat", "text": format!("{name}/{player}") - })) - .await; - // Every event this session sees was said in its own world. - let mut seen = 0; - while seen < 1 { - let frame = peer.next().await.unwrap(); - if frame["type"] == "event" { - let text = frame["event"]["kind"]["data"].as_str().unwrap_or_default(); - assert!(text.starts_with(&name), "{name} saw {text}"); - seen += 1; - } - } - }); - } - } - while let Some(result) = tasks.join_next().await { - result.unwrap(); - } - assert_eq!(hub.open_count(), 8); - } - - #[tokio::test] - async fn a_session_over_the_ceiling_is_refused_politely() { - let (hub, _) = memory_hub(crate::world_hub::HubLimits { - max_sessions: 1, - ..crate::world_hub::HubLimits::default() - }); - let capability = invite_into(&hub, "arena", "ann").await; - let mut first = Peer::connect_hub(hub.clone(), SessionConfig::default()); - first - .say(serde_json::json!({"type":"join","capability": capability,"world":"arena"})) - .await; - assert_eq!(first.next().await.unwrap()["type"], "snapshot"); - let mut second = Peer::connect_hub(hub, SessionConfig::default()); - second - .say(serde_json::json!({"type":"join","capability": capability,"world":"arena"})) - .await; - assert_eq!( - second.next().await.unwrap()["message"], - "server is busy; try again shortly" - ); - } - - #[tokio::test] - async fn records_queries_need_a_valid_capability() { - let svc = service_with_records(None); - let mut peer = Peer::connect(svc, SessionConfig::default()); - peer.say(serde_json::json!({ - "type": "records", - "capability": "0.00", - })) - .await; - assert_eq!(peer.next().await.unwrap()["message"], "join denied"); - } - - #[cfg(feature = "sandbox")] - #[tokio::test] - async fn admin_upload_pins_validates_and_activates_a_roc_program() { - use iroh_blobs::store::mem::MemStore; - - let world = WorldHandle::spawn(WorldCore::new("lobby", WorldLimits::default()).unwrap()); - let blobs: Store = MemStore::new().into(); - let svc = WorldService::new(world.clone(), Some("admin".to_owned())) - .with_blob_store(blobs.clone()); - let wasm = include_bytes!("../examples/roc-counter/counter.wasm"); - let hash = module_hash(wasm); - - let mut peer = Peer::connect(svc.clone(), SessionConfig::default()); - peer.say(serde_json::json!({ - "type": "install_begin", - "admin_token": "wrong", - "total_bytes": wasm.len(), - "module_hash": hash, - "seed": 12, - })) - .await; - assert_eq!( - peer.next().await.unwrap()["message"], - "module install denied" - ); - - let (_, guest) = world - .issue("ada".to_owned(), WorldScopes::GUEST) - .await - .unwrap(); - let mut peer = Peer::connect(svc, SessionConfig::default()); - peer.say(serde_json::json!({ - "type": "install_begin", - "admin_token": "admin", - "total_bytes": wasm.len(), - "module_hash": null, - "seed": 12, - })) - .await; - let ready = peer.next().await.unwrap(); - assert_eq!(ready["type"], "upload_ready"); - let chunk_bytes = usize::try_from(ready["chunk_bytes"].as_u64().unwrap()).unwrap(); - for (index, chunk) in wasm.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; - let ack = peer.next().await.unwrap(); - assert_eq!(ack["type"], "module_installed"); - assert_eq!(ack["module_hash"], hash); - - let hash: Hash = hash.parse().unwrap(); - assert!( - blobs.blobs().has(hash).await.unwrap(), - "uploaded module is pinned in the blob store" - ); - assert_eq!( - world.view(guest.clone()).await.unwrap().as_deref(), - Some("count=0") - ); - world.input(guest.clone(), b"inc".to_vec()).await.unwrap(); - assert_eq!(world.view(guest).await.unwrap().as_deref(), Some("count=1")); - } - - #[cfg(feature = "sandbox")] - #[tokio::test] - async fn admin_fuel_limit_applies_to_installed_programs() { - use iroh_blobs::store::mem::MemStore; - - let wasm = include_bytes!("../examples/roc-counter/counter.wasm").to_vec(); - let hash = module_hash(&wasm); - let starved = crate::world_limits::RuntimeLimits { - sandbox: crate::sandbox::SandboxLimits { - fuel: 1, - ..crate::sandbox::SandboxLimits::default() - }, - ..crate::world_limits::RuntimeLimits::default() - }; - let world = WorldHandle::spawn(WorldCore::new("lobby", WorldLimits::default()).unwrap()); - let svc = WorldService::new(world, Some("admin".to_owned())) - .with_blob_store(MemStore::new().into()) - .with_runtime_limits(starved); - assert!(matches!( - svc.install_wasm(Some("admin"), wasm.clone(), 12, &hash) - .await, - Err(InstallError::InvalidModule) - )); - - let world = WorldHandle::spawn(WorldCore::new("lobby", WorldLimits::default()).unwrap()); - let svc = WorldService::new(world, Some("admin".to_owned())) - .with_blob_store(MemStore::new().into()); - svc.set_execution_profile( - Some("admin"), - crate::world_limits::WorldExecutionProfile { - wasm_fuel: Some(1), - ..Default::default() - }, - ) - .await - .unwrap(); - assert!(matches!( - svc.install_wasm(Some("admin"), wasm.clone(), 12, &hash) - .await, - Err(InstallError::InvalidModule) - )); - - let world = WorldHandle::spawn(WorldCore::new("lobby", WorldLimits::default()).unwrap()); - let svc = WorldService::new(world, Some("admin".to_owned())) - .with_blob_store(MemStore::new().into()); - svc.install_wasm(Some("admin"), wasm, 12, &hash) - .await - .expect("default limits install"); - } - - #[cfg(feature = "sandbox")] - #[tokio::test] - async fn source_only_policy_rejects_raw_modules_but_preserves_normal_mode() { - use iroh_blobs::store::mem::MemStore; - - let wasm = include_bytes!("../examples/roc-counter/counter.wasm").to_vec(); - let hash = module_hash(&wasm); - let world = WorldHandle::spawn(WorldCore::new("lobby", WorldLimits::default()).unwrap()); - let service = WorldService::new(world.clone(), Some("admin".to_owned())) - .with_blob_store(MemStore::new().into()) - .with_source_only(true); - - assert!(service.source_only()); - assert!(matches!( - service - .install_wasm(Some("wrong"), wasm.clone(), 1, &hash) - .await, - Err(InstallError::Unauthorized) - )); - assert!(matches!( - service - .install_wasm(Some("admin"), wasm.clone(), 1, &hash) - .await, - Err(InstallError::RawModuleDisabled) - )); - assert_eq!(service.active_module_hash().await, None); - - let normal = WorldService::new( - WorldHandle::spawn(WorldCore::new("lobby", WorldLimits::default()).unwrap()), - Some("admin".to_owned()), - ) - .with_blob_store(MemStore::new().into()); - normal - .install_wasm(Some("admin"), wasm, 1, &hash) - .await - .expect("raw modules stay supported by default"); - } - - #[cfg(feature = "sandbox")] - #[tokio::test] - async fn source_only_policy_rejects_streaming_upload_before_accepting_chunks() { - let world = WorldHandle::spawn(WorldCore::new("lobby", WorldLimits::default()).unwrap()); - let service = WorldService::new(world, Some("admin".to_owned())).with_source_only(true); - let mut peer = Peer::connect(service, SessionConfig::default()); - peer.say(serde_json::json!({ - "type": "install_begin", - "admin_token": "admin", - "total_bytes": 32, - "module_hash": null, - "seed": 1, - })) - .await; - let error = peer.next().await.unwrap(); - assert_eq!(error["type"], "error"); - assert!(error["message"].as_str().unwrap().contains("source-only")); - } - - #[cfg(feature = "sandbox")] - #[tokio::test] - async fn bad_module_replacement_preserves_the_active_program() { - use iroh_blobs::store::mem::MemStore; - - let wasm = include_bytes!("../examples/roc-counter/counter.wasm"); - let sandbox = - crate::sandbox::Sandbox::compile(wasm, crate::sandbox::SandboxLimits::default()) - .unwrap(); - let world = WorldHandle::spawn_with_program( - WorldCore::new("counter", WorldLimits::default()).unwrap(), - Box::new(sandbox.instantiate(1).unwrap()), - ); - let blobs: Store = MemStore::new().into(); - let service = - WorldService::new(world.clone(), Some("admin".to_owned())).with_blob_store(blobs); - let (_, guest) = world.issue("guest", WorldScopes::GUEST).await.unwrap(); - assert_eq!( - world.view(guest.clone()).await.unwrap().as_deref(), - Some("count=0") - ); - - let bad = b"not wasm".to_vec(); - let hash = module_hash(&bad); - assert_eq!( - service - .install_wasm(Some("admin"), bad, 2, &hash) - .await - .unwrap_err(), - InstallError::InvalidModule - ); - assert_eq!( - world.view(guest.clone()).await.unwrap().as_deref(), - Some("count=0") - ); - world.input(guest.clone(), b"inc".to_vec()).await.unwrap(); - assert_eq!(world.view(guest).await.unwrap().as_deref(), Some("count=1")); - } - - #[tokio::test] - async fn invites_are_disabled_without_an_admin_secret() { - let mut peer = Peer::connect(service(None), SessionConfig::default()); - peer.say(serde_json::json!({"type":"invite","admin_token":"","display_name":"x"})) - .await; - assert_eq!( - peer.next().await.unwrap()["message"], - "invites are not enabled" - ); - } - - #[tokio::test] - async fn chat_is_broadcast_and_rejections_are_private() { - let svc = service(None); - let (_, alice) = svc - .world() - .issue("alice".to_owned(), WorldScopes::GUEST) - .await - .unwrap(); - let (_, watcher) = svc - .world() - .issue("watcher".to_owned(), WorldScopes::JOIN) - .await - .unwrap(); - let mut a = Peer::connect(svc.clone(), SessionConfig::default()); - let mut w = Peer::connect(svc, SessionConfig::default()); - a.say(serde_json::json!({"type":"join","capability":alice.expose()})) - .await; - w.say(serde_json::json!({"type":"join","capability":watcher.expose()})) - .await; - assert_eq!(a.next().await.unwrap()["type"], "snapshot"); - assert_eq!(w.next().await.unwrap()["type"], "snapshot"); - - // A join-only participant cannot speak; only they hear about it. - w.say(serde_json::json!({"type":"chat","text":"psst"})) - .await; - assert_eq!(w.next().await.unwrap()["message"], "world event rejected"); - - // Chat reaches the guest; the join-only watcher hears the next - // non-chat event instead, past a gap in sequence numbers. - a.say(serde_json::json!({"type":"chat","text":"hello"})) - .await; - let frame = a.next().await.unwrap(); - assert_eq!(frame["type"], "event"); - assert!(frame.to_string().contains("hello")); - a.say(serde_json::json!({"type":"input","data_hex":"00"})) - .await; - let frame = w.next().await.unwrap(); - assert_eq!(frame["type"], "event"); - assert_eq!(frame["event"]["sequence"], 2, "{frame}"); - assert!(!frame.to_string().contains("hello"), "{frame}"); - assert_eq!(a.next().await.unwrap()["event"]["sequence"], 2); - a.say(serde_json::json!({"type":"input","data_hex":"xyz"})) - .await; - assert_eq!( - a.next().await.unwrap()["message"], - "input data must be hexadecimal" - ); - a.say(serde_json::json!({"type":"join","capability":"x"})) - .await; - assert_eq!(a.next().await.unwrap()["message"], "already joined"); - } - - fn kinds(events: &serde_json::Value) -> Vec { - events - .as_array() - .unwrap() - .iter() - .map(|event| event["kind"]["kind"].as_str().unwrap().to_owned()) - .collect() - } - - #[tokio::test] - async fn chat_visibility_a_join_only_joiner_gets_a_snapshot_without_chat() { - let svc = service(None); - let world = svc.world(); - let (_, guest) = world - .issue("guest".to_owned(), WorldScopes::GUEST) - .await - .unwrap(); - let (_, join_only) = world - .issue("join".to_owned(), WorldScopes::JOIN) - .await - .unwrap(); - let (_, reader) = world - .issue( - "reader".to_owned(), - WorldScopes::from_names(["join", "history"]).unwrap(), - ) - .await - .unwrap(); - world - .chat(guest.clone(), "secret".to_owned()) - .await - .unwrap(); - world.input(guest.clone(), b"move".to_vec()).await.unwrap(); - - for (token, sees_chat) in [(&guest, true), (&reader, true), (&join_only, false)] { - let mut peer = Peer::connect(svc.clone(), SessionConfig::default()); - peer.say(serde_json::json!({"type":"join","capability":token.expose()})) - .await; - let frame = peer.next().await.unwrap(); - assert_eq!(frame["type"], "snapshot"); - let events = &frame["snapshot"]["events"]; - assert_eq!(frame["snapshot"]["current_sequence"], 2); - assert_eq!( - kinds(events), - if sees_chat { - vec!["chat", "input"] - } else { - vec!["input"] - }, - "{frame}" - ); - assert_eq!(frame.to_string().contains("secret"), sees_chat, "{frame}"); - } - - // A rejoin from a cursor goes through catch-up, which projects too. - let mut peer = Peer::connect(svc.clone(), SessionConfig::default()); - peer.say(serde_json::json!({"type":"join","capability":join_only.expose(),"after":0})) - .await; - let frame = peer.next().await.unwrap(); - assert_eq!(frame["type"], "event", "{frame}"); - assert_eq!(frame["event"]["sequence"], 2); - assert!(!frame.to_string().contains("secret")); - } - - #[tokio::test] - async fn chat_visibility_a_live_install_never_shows_a_session_the_seed() { - // The raw broadcast carries the real seed; the session sends a - // snapshot and a program-changed frame instead, and every frame it - // sends is built from the projection. - let svc = service(None); - let world = svc.world(); - let (_, guest) = world - .issue("guest".to_owned(), WorldScopes::GUEST) - .await - .unwrap(); - let mut peer = Peer::connect(svc.clone(), SessionConfig::default()); - peer.say(serde_json::json!({"type":"join","capability":guest.expose()})) - .await; - assert_eq!(peer.next().await.unwrap()["type"], "snapshot"); - world - .install_program("ab".repeat(32), 424_242, Box::new(NoProgram)) - .await - .unwrap(); - let mut frames = Vec::new(); - loop { - let frame = peer.next().await.unwrap(); - let done = frame["type"] == "program_changed"; - frames.push(frame); - if done { - break; - } - } - let text = serde_json::to_string(&frames).unwrap(); - assert!(!text.contains("424242"), "{text}"); - assert!(text.contains(&"ab".repeat(32)), "the module hash is kept"); - } - - #[tokio::test] - async fn chat_visibility_the_live_stream_follows_the_viewers_scopes() { - let svc = service(None); - let world = svc.world(); - let (_, guest) = world - .issue("guest".to_owned(), WorldScopes::GUEST) - .await - .unwrap(); - let (_, join_only) = world - .issue("join".to_owned(), WorldScopes::JOIN) - .await - .unwrap(); - let (_, reader) = world - .issue( - "reader".to_owned(), - WorldScopes::from_names(["join", "history"]).unwrap(), - ) - .await - .unwrap(); - let mut watcher = Peer::connect(svc.clone(), SessionConfig::default()); - let mut reading = Peer::connect(svc.clone(), SessionConfig::default()); - for (peer, token) in [(&mut watcher, &join_only), (&mut reading, &reader)] { - peer.say(serde_json::json!({"type":"join","capability":token.expose()})) - .await; - assert_eq!(peer.next().await.unwrap()["type"], "snapshot"); - } - - world - .chat(guest.clone(), "secret".to_owned()) - .await - .unwrap(); - world.input(guest.clone(), b"move".to_vec()).await.unwrap(); - - let frame = reading.next().await.unwrap(); - assert!(frame.to_string().contains("secret"), "{frame}"); - assert_eq!(reading.next().await.unwrap()["event"]["sequence"], 2); - // The join-only watcher's first event is the input, after the gap. - let frame = watcher.next().await.unwrap(); - assert_eq!(frame["type"], "event", "{frame}"); - assert_eq!(frame["event"]["sequence"], 2, "{frame}"); - assert!(!frame.to_string().contains("secret")); - - // A reader may not speak. - reading - .say(serde_json::json!({"type":"chat","text":"hi"})) - .await; - assert_eq!( - reading.next().await.unwrap()["message"], - "world event rejected" - ); - } -} diff --git a/pkgs/id/src/world_session/mod.rs b/pkgs/id/src/world_session/mod.rs new file mode 100644 index 0000000000..381b4ec868 --- /dev/null +++ b/pkgs/id/src/world_session/mod.rs @@ -0,0 +1,2136 @@ +//! Transport-neutral world session driver. +//! +//! A *session* is one participant's connection to a [`WorldHandle`]. The +//! wire protocol is one JSON object per frame; this module owns that protocol +//! and nothing else. A transport (WebSocket, Iroh stream, an in-memory test +//! channel) only implements [`SessionIo`] to move whole text frames, so the +//! behavior cannot drift between transports. +//! +//! Client frames (`type` tag): `join {capability, after?}`, +//! `invite {admin_token, display_name}`, `attenuate {name, scopes}`, `chat {text}`, `input {data_hex}`. +//! The first frame must be `join` or `invite`. Server frames: `snapshot`, +//! `event`, `invite`, `error`. +//! +//! Authorization is the capability alone. A transport may know who the peer +//! is (an Iroh node ID); that never grants world authority. + +use std::sync::Arc; +use std::time::Duration; + +use anyhow::Context as _; +use iroh_blobs::{ + BlobFormat, Hash, + api::{Store, blobs::AddBytesOptions}, +}; +use rand::RngExt as _; +use serde::Serialize; +use subtle::ConstantTimeEq as _; +use tokio::sync::{Mutex, OwnedSemaphorePermit, RwLock, Semaphore, broadcast}; + +use crate::directory_auth::Signed; +use crate::time::unix_ms; +use crate::world::{ + Authority, CapabilityBounds, FileScope, Isolation, JoinCapability, Participant, WorldHandle, + WorldPolicy, WorldScopes, +}; +use crate::world_compile::Compiler; +#[cfg(feature = "sandbox")] +use crate::world_compile::{COMPILE_TIMEOUT, CompileSpec}; +use crate::world_hub::{WorldHub, WorldLease}; + +/// Re-exported so `crate::world_session::MAX_FRAME_BYTES` keeps working: the +/// limit now lives in [`crate::frames`] so the crate builds without the +/// `world` feature. +pub use crate::frames::MAX_FRAME_BYTES; + +#[cfg(test)] +mod tests; +/// Largest Wasm world module that may be installed (16 MiB). +mod types; + +pub(crate) use types::{ + CAPS_CEILING_NOTICE, ClientFrame, CompileFile, MAX_ADMIN_TOKEN_BYTES, MAX_CAPABILITY_BYTES, + MAX_CONCURRENT_MODULE_UPLOADS, ServerFrame, invite_bounds, +}; +pub use types::{ + INVITE_DEFAULT_SECS, INVITE_MAX_SECS, Inbound, InstallError, InviteError, InviteResponse, + MAX_WORLD_MODULE_BYTES, MAX_WORLD_MODULE_CHUNK_BYTES, SessionConfig, SessionIo, WorldService, + check_invite_bounds, +}; + +impl WorldService { + /// Accept native (ELF) module installs. Wasm stays the default tier. + #[must_use] + pub const fn with_native_enabled(mut self) -> Self { + self.native = true; + self + } + + /// Require new Wasm programs to be compiled from source by this server. + /// This disables raw artifact installation, but not the compiled output path. + #[must_use] + pub const fn with_source_only(mut self, enabled: bool) -> Self { + self.source_only = enabled; + self + } + + /// Whether raw Wasm/native uploads are disabled for this world. + #[must_use] + pub(crate) const fn source_only(&self) -> bool { + self.source_only + } + + /// Read or change this world's directory as the caller. + /// + /// # Errors + /// + /// Fails for an unknown credential or a refused change. + pub async fn directory( + &self, + caller: crate::directory_auth::Caller, + action: crate::directory_view::DirectoryAction, + ) -> anyhow::Result { + if action.sends_mail() && self.mail.is_none() { + return Err(crate::directory::Refusal::Forbidden( + "this server has no mail configured".to_owned(), + ) + .into()); + } + // The actor refuses an outbox-less server only when the change would queue for another server. + let mut outcome = self + .world + .directory(caller.clone(), action, self.outbox.is_some()) + .await?; + if let (Some(sink), Some(mail)) = (&self.mail, outcome.mail.take()) { + let sink = Arc::clone(sink); + tokio::task::spawn_blocking(move || sink.send(&mail)) + .await + .context("mail task stopped")??; + outcome.mailed = true; + } + if let Some(outbox) = &self.outbox { + let outbound = std::mem::take(&mut outcome.outbound); + match outcome.pending.take() { + Some(entry) => { + self.queue_then_apply(outbox, outbound, entry).await?; + outcome = self + .world + .directory(caller, crate::directory_view::DirectoryAction::View, true) + .await?; + } + None => { + enqueue_all(&mut *outbox.lock().await, outbound)?; + } + } + let queue = outbox.lock().await; + outcome.view.deliveries = + crate::directory_view::deliveries(&queue, &outcome.view.viewer); + } + Ok(outcome) + } + + /// Queue the outbound payloads, then apply the change. The outbox lock is + /// held across the apply so a flush cannot send anything before the change + /// is in. If the apply is refused, the payloads are withdrawn. + async fn queue_then_apply( + &self, + outbox: &Mutex, + outbound: Vec, + entry: crate::directory::DirectoryEntry, + ) -> anyhow::Result<()> { + let mut queue = outbox.lock().await; + let keys = enqueue_all(&mut queue, outbound)?; + if let Err(error) = self.world.apply_directory_entry(entry).await { + withdraw_all(&mut queue, &keys); + return Err(error); + } + Ok(()) + } + + /// Attempt every due outbox envelope once. Returns how many were attempted. + /// + /// # Errors + /// + /// Fails when the outbox file cannot be written. + pub async fn flush_outbox(&self, endpoint: &iroh::Endpoint, now: u64) -> anyhow::Result { + match &self.outbox { + Some(outbox) => crate::envelope_outbox::flush(outbox, endpoint, now).await, + None => Ok(0), + } + } + + /// Wrap a world. `admin_token: None` disables invites. + #[must_use] + pub fn new(world: WorldHandle, admin_token: Option) -> Self { + Self { + world, + admin_token, + blobs: None, + module_pin: Arc::new(Mutex::new(None)), + module_hash: Arc::new(RwLock::new(None)), + upload_slots: Arc::new(Semaphore::new(MAX_CONCURRENT_MODULE_UPLOADS)), + module_dir: None, + records: None, + compiler: None, + native: false, + source_only: false, + runtime: crate::world_limits::RuntimeLimits::default(), + mail: None, + outbox: None, + profile_operation: Arc::new(Mutex::new(())), + } + } + + /// Bound the programs this world runs by the admin's limits. + #[must_use] + pub const fn with_runtime_limits( + mut self, + runtime: crate::world_limits::RuntimeLimits, + ) -> Self { + self.runtime = runtime; + self + } + + /// Replace the world's capability ceiling, admin only. Unlike a profile, + /// the ceiling applies at once: the next use or subscription sees it. + /// + /// # Errors + /// + /// Fails with `admin denied` for a wrong token, and with the world's + /// message for an invalid or unstorable ceiling. + pub async fn set_caps_ceiling( + &self, + supplied_admin: Option<&str>, + ceiling: Vec, + ) -> anyhow::Result { + anyhow::ensure!(self.authorize_admin(supplied_admin).is_ok(), "admin denied"); + self.world.set_caps_ceiling(ceiling).await + } + + /// Persist a per-world resource profile. The running program keeps its + /// existing limits; the request applies on the next install or restart. + pub async fn set_execution_profile( + &self, + supplied_admin: Option<&str>, + profile: crate::world_limits::WorldExecutionProfile, + ) -> anyhow::Result { + self.authorize_admin(supplied_admin) + .map_err(|_| anyhow::anyhow!("admin denied"))?; + // Resolve now for validation and to ensure this request is valid under + // this process's hard ceilings. The stored request remains unclamped, + // so a later server with lower ceilings still wins at instantiation. + profile.resolve(self.runtime)?; + let _operation = self.profile_operation.lock().await; + self.world.set_execution_profile(profile).await + } + + /// Let admins compile Roc sources into this world on the fly. + #[must_use] + pub fn with_compiler(mut self, compiler: Compiler) -> Self { + self.compiler = Some(Arc::new(compiler)); + self + } + + /// Compile `spec` on the server and install the result exactly like an + /// admin upload (validated, pinned, journaled). Returns the module hash, + /// the install sequence and the compiler's diagnostics. + /// + /// # Errors + /// + /// A human-readable refusal: unauthorized, disabled, or the compiler's + /// own failure text (so an admin sees why their program did not build). + #[cfg(feature = "sandbox")] + pub async fn compile_and_install( + &self, + supplied_admin: Option<&str>, + spec: &CompileSpec, + ) -> Result<(String, u64, String), String> { + if self.authorize_admin(supplied_admin).is_err() { + return Err("compile denied".to_owned()); + } + let Some(compiler) = self.compiler.as_ref() else { + return Err("compilation is not enabled on this server".to_owned()); + }; + if spec.native && !self.native { + return Err("native modules are not enabled on this server".to_owned()); + } + // The effective list, not the raw grants: a platform module outside a + // server or world ceiling is refused at compile time too. + let granted = self + .world + .caps_report() + .await + .map_err(|error| format!("compile failed: {error:#}"))? + .effective; + let (wasm, diagnostics, provenance) = + crate::world_compile::compile(spec, compiler, &granted, COMPILE_TIMEOUT) + .await + .map_err(|error| { + tracing::warn!("world compile failed: {error:#}"); + format!("compile failed: {error:#}") + })?; + let hash = module_hash(&wasm); + let permit = self + .try_reserve_module_upload() + .map_err(|error| format!("install failed: {error:?}"))?; + let (_, sequence) = self + .install_wasm_reserved( + supplied_admin, + wasm, + spec.seed, + &hash, + permit, + true, + Some(provenance), + ) + .await + .map_err(|error| format!("install failed: {error:?}"))?; + Ok((hash, sequence, diagnostics)) + } + + /// Attach the world's records document and start mirroring program + /// records into it. + #[must_use] + pub fn with_records_store(mut self, records: crate::world_records::RecordsStore) -> Self { + let records = Arc::new(records); + records.spawn_publisher(&self.world); + self.records = Some(records); + self + } + + /// The world's records document, if it has one. + #[must_use] + pub const fn records_store(&self) -> Option<&Arc> { + self.records.as_ref() + } + + /// Persist installed modules here so a durable world can re-instantiate + /// its program after a restart. + #[must_use] + pub fn with_module_dir(mut self, modules: crate::world_store::ModuleDir) -> Self { + self.module_dir = Some(modules); + self + } + + /// Mark `wasm` as the active module after a restore: pin it in the blob + /// store (when attached) so peers can download it again. + /// + /// # Errors + /// + /// Fails if the blob store refuses the bytes. + pub async fn adopt_module(&self, wasm: Vec) -> anyhow::Result<()> { + let hash = module_hash(&wasm); + if let Some(blobs) = self.blobs.as_ref() { + let pin = blobs + .add_bytes_with_opts(AddBytesOptions { + data: wasm.into(), + format: BlobFormat::Raw, + }) + .temp_tag() + .await?; + *self.module_pin.lock().await = Some(pin); + } + *self.module_hash.write().await = Some(hash); + Ok(()) + } + + /// Attach this node's blob store so uploaded modules survive as pinned + /// Iroh content for the life of the running world. + #[must_use] + pub fn with_blob_store(mut self, blobs: Store) -> Self { + self.blobs = Some(blobs); + self + } + + /// Send confirmation and sign-in codes through this sink. Without one, + /// email actions are refused. + #[must_use] + pub fn with_mail(mut self, sink: Arc) -> Self { + self.mail = Some(sink); + self + } + + /// Queue envelopes for other servers in this outbox. Without one, remote + /// friend actions are refused. + #[must_use] + pub fn with_outbox(mut self, outbox: crate::envelope_outbox::Outbox) -> Self { + self.outbox = Some(Arc::new(Mutex::new(outbox))); + self + } + + /// Reserve one upload slot before accepting a potentially large body. + fn try_reserve_module_upload(&self) -> Result { + Arc::clone(&self.upload_slots) + .try_acquire_owned() + .map_err(|_| InstallError::Unavailable) + } + + /// The underlying world actor. + #[must_use] + pub const fn world(&self) -> &WorldHandle { + &self.world + } + + /// Mint a guest capability if `supplied` matches the admin secret. + /// + /// # Errors + /// + /// See [`InviteError`]. + pub async fn invite( + &self, + supplied: Option<&str>, + display_name: String, + expires_in_secs: Option, + uses: Option, + ) -> Result { + self.invite_scoped( + supplied, + display_name, + expires_in_secs, + uses, + WorldScopes::GUEST, + ) + .await + } + + /// Like [`Self::invite`], with the invited participant's scopes chosen by + /// the caller (see `WorldScopes::from_role`). + pub async fn invite_scoped( + &self, + supplied: Option<&str>, + display_name: String, + expires_in_secs: Option, + uses: Option, + scopes: WorldScopes, + ) -> Result { + self.authorize_admin(supplied)?; + let bounds = + invite_bounds(expires_in_secs, uses, unix_ms()).map_err(InviteError::InvalidBounds)?; + match self.world.issue_bounded(display_name, scopes, bounds).await { + Ok((participant, capability)) => Ok(InviteResponse { + capability: capability.expose().to_owned(), + participant_id: participant.id, + display_name: participant.display_name, + }), + Err(_) => Err(InviteError::Unavailable), + } + } + + /// The configured admin secret, for a hub that shares it process-wide. + pub(crate) fn admin_token(&self) -> Option<&str> { + self.admin_token.as_deref() + } + + /// Validate the separately configured world-administrator token. + pub fn authorize_admin(&self, supplied: Option<&str>) -> Result<(), InviteError> { + let Some(expected) = self.admin_token.as_deref().filter(|t| !t.is_empty()) else { + return Err(InviteError::Disabled); + }; + if !supplied.is_some_and(|s| { + s.len() <= MAX_ADMIN_TOKEN_BYTES && secret_eq(expected.as_bytes(), s.as_bytes()) + }) { + return Err(InviteError::Unauthorized); + } + Ok(()) + } + + /// Compile, instantiate and atomically install a Wasm program. The module + /// is first pinned in Iroh's blob store; only then does the actor activate + /// it. A failed compile or write leaves the running program unchanged. + #[cfg(feature = "sandbox")] + pub async fn install_wasm( + &self, + supplied_admin: Option<&str>, + wasm: Vec, + seed: u64, + claimed_hash: &str, + ) -> Result<(String, u64), InstallError> { + let permit = self.try_reserve_module_upload()?; + self.install_wasm_reserved( + supplied_admin, + wasm, + seed, + claimed_hash, + permit, + false, + None, + ) + .await + } + + #[cfg(feature = "sandbox")] + async fn install_wasm_reserved( + &self, + supplied_admin: Option<&str>, + wasm: Vec, + seed: u64, + claimed_hash: &str, + _permit: OwnedSemaphorePermit, + compiled_from_source: bool, + provenance: Option, + ) -> Result<(String, u64), InstallError> { + let _profile_operation = self.profile_operation.lock().await; + self.authorize_admin(supplied_admin) + .map_err(|error| match error { + InviteError::Disabled => InstallError::Disabled, + InviteError::Unauthorized => InstallError::Unauthorized, + InviteError::Unavailable => InstallError::Unavailable, + InviteError::InvalidBounds(_) => InstallError::InvalidUpload, + })?; + if self.source_only && !compiled_from_source { + return Err(InstallError::RawModuleDisabled); + } + if compiled_from_source && provenance.is_none() { + return Err(InstallError::InvalidModule); + } + 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); + } + let is_native = crate::world_native::is_native_module(&wasm); + if is_native && !self.native { + return Err(InstallError::InvalidModule); + } + let guest: Box = if is_native { + // A durable world must have the worker on disk before the journal + // references it; native modules spawn from their stored file. + let modules = self.module_dir.clone().ok_or(InstallError::Disabled)?; + 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 path = self + .module_dir + .as_ref() + .ok_or(InstallError::Disabled)? + .path_of(&module_hash) + .map_err(|_| InstallError::Unavailable)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + tokio::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o700)) + .await + .map_err(|_| InstallError::Unavailable)?; + } + let runtime = self + .world + .execution_profile() + .await + .map_err(|_| InstallError::Unavailable)? + .resolve(self.runtime) + .map_err(|_| InstallError::InvalidModule)?; + let native_limits = runtime.native; + let program = tokio::task::spawn_blocking(move || { + crate::world_native::NativeProgram::new(&path, seed, native_limits, None) + }) + .await + .map_err(|e| { + tracing::error!("native install join failed: {e:#}"); + InstallError::InvalidModule + })? + .map_err(|e| { + tracing::error!("native install failed: {e:#}"); + InstallError::InvalidModule + })?; + Box::new(program) + } else { + 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)?; + Box::new(program) + }; + + // A durable world must be able to reload this module before the + // journal may reference it (native was saved above). + if !is_native && 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); + } + } + + // Native workers are never offered for peer download: only the Wasm + // tier gets pinned in the blob store. + let blobs = self.blobs.as_ref().ok_or(InstallError::Disabled)?.clone(); + let pin = (!is_native).then(|| { + blobs + .add_bytes_with_opts(AddBytesOptions { + data: wasm.into(), + format: BlobFormat::Raw, + }) + .temp_tag() + }); + let pin = match pin { + Some(pin) => { + let pin = pin.await.map_err(|_| InstallError::Unavailable)?; + if pin.hash() != hash { + return Err(InstallError::Unavailable); + } + Some(pin) + } + None => None, + }; + let installed = self + .world + .install_program_with_provenance( + module_hash.clone(), + seed, + Some(provenance.unwrap_or(crate::world::ModuleProvenance::Artifact)), + guest, + ) + .await + .map_err(|_| InstallError::Unavailable)?; + if !matches!( + installed.kind, + crate::world::WorldEventKind::ProgramInstalled { .. } + ) { + return Err(InstallError::Unavailable); + } + *self.module_pin.lock().await = 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. + pub async fn module_bytes(&self, expected_hash: &str) -> Result, InstallError> { + let blobs = self.blobs.as_ref().ok_or(InstallError::Disabled)?; + let pin = self.module_pin.lock().await; + let Some(pin) = pin.as_ref() else { + return Err(InstallError::Unavailable); + }; + if pin.hash().to_string() != expected_hash { + return Err(InstallError::InvalidUpload); + } + let bytes = blobs + .blobs() + .get_bytes(pin.hash()) + .await + .map_err(|_| InstallError::Unavailable)?; + if bytes.len() > MAX_WORLD_MODULE_BYTES || module_hash(&bytes) != expected_hash { + return Err(InstallError::Unavailable); + } + Ok(bytes.to_vec()) + } + + /// 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() + } +} + +/// Canonical content identifier expected in an install-begin frame. +#[must_use] +pub fn module_hash(wasm: &[u8]) -> String { + Hash::new(wasm).to_string() +} + +/// Constant-time (for equal lengths) secret comparison. +#[must_use] +pub fn secret_eq(expected: &[u8], supplied: &[u8]) -> bool { + expected.len() == supplied.len() && bool::from(expected.ct_eq(supplied)) +} + +/// Run one session to completion with default settings. +pub async fn run_session(hub: &WorldHub, io: &mut I) { + run_session_with(hub, io, SessionConfig::default()).await; +} + +/// The admin secret a first frame carries, if it is an administrative one. +/// A valid secret lets the frame create the world it names. +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), + ClientFrame::SetExecutionProfile { admin_token, .. } => Some(admin_token), + _ => None, + } +} + +/// Run one session to completion. +/// +/// The first frame names the world (`"world": ""`, default world if +/// absent), and the session holds a lease on it until it ends. +pub async fn run_session_with(hub: &WorldHub, io: &mut I, config: SessionConfig) { + let first = match tokio::time::timeout(config.join_timeout, io.recv()).await { + Ok(Inbound::Text(text)) => text, + Ok(Inbound::Oversized) => { + let _ = send_error(io, "world frame is too large").await; + return; + } + Ok(Inbound::Unsupported) => { + let _ = send_error(io, "frames must be UTF-8 text").await; + return; + } + Ok(Inbound::Closed) => return, + Err(_) => { + let _ = send_error(io, "timed out waiting for join").await; + return; + } + }; + let Ok(mut value) = serde_json::from_str::(&first) else { + let _ = send_error(io, "first frame must be a valid join or invite request").await; + return; + }; + // `world` is a routing field, not part of any frame. + let world = match value + .as_object_mut() + .and_then(|object| object.remove("world")) + { + None | Some(serde_json::Value::Null) => None, + Some(serde_json::Value::String(name)) => Some(name), + Some(_) => { + let _ = send_error(io, "world must be a string").await; + return; + } + }; + let Ok(frame) = serde_json::from_value::(value) else { + let _ = send_error(io, "first frame must be a valid join or invite request").await; + return; + }; + // Hub-level frames are about the server, not one world. + match &frame { + ClientFrame::ListWorlds { admin_token } => { + if admin_token.len() > MAX_ADMIN_TOKEN_BYTES || !hub.admin_ok(admin_token) { + let _ = send_error(io, "admin denied").await; + return; + } + let worlds = hub.list(); + let _ = send_json( + io, + &ServerFrame::Worlds { + default: hub.default_world(), + worlds, + }, + ) + .await; + return; + } + ClientFrame::CreateWorld { admin_token } => { + if admin_token.len() > MAX_ADMIN_TOKEN_BYTES || !hub.admin_ok(admin_token) { + let _ = send_error(io, "admin denied").await; + return; + } + let name = world.as_deref().unwrap_or_else(|| hub.default_world()); + match hub.create(name).await { + Ok(created) => { + let _ = send_json( + io, + &ServerFrame::WorldCreated { + world: name, + created, + }, + ) + .await; + } + Err(error) => { + let _ = send_error(io, error.message()).await; + } + } + return; + } + _ => {} + } + let admin = frame_admin_token(&frame).filter(|token| token.len() <= MAX_ADMIN_TOKEN_BYTES); + let lease = match hub.lease(world.as_deref(), admin).await { + Ok(lease) => lease, + Err(error) => { + let _ = send_error(io, error.message()).await; + return; + } + }; + if let ClientFrame::SetIsolation { + isolation, + admin_token, + signed, + } = &frame + { + match set_isolation_frame( + hub, + &lease, + *isolation, + admin_token.as_deref(), + signed.as_ref(), + ) + .await + { + Ok(isolation) => { + let _ = send_json( + io, + &ServerFrame::Isolation { + world: lease.name(), + isolation, + }, + ) + .await; + } + Err(error) => { + let _ = send_error(io, &format!("{error:#}")).await; + } + } + return; + } + if let Some(result) = policy_frame(hub, &lease, &frame).await { + match result { + Ok(policy) => { + let _ = send_json( + io, + &ServerFrame::Policy { + world: lease.name(), + policy, + }, + ) + .await; + } + Err(error) => { + let _ = send_error(io, &format!("{error:#}")).await; + } + } + return; + } + run_world_session(lease.service(), io, frame).await; +} + +/// Apply an isolation change for the admin token, or for a signed request +/// whose account moderates the world. +pub(crate) async fn set_isolation_frame( + hub: &WorldHub, + lease: &WorldLease, + isolation: Isolation, + admin_token: Option<&str>, + signed: Option<&Signed>, +) -> anyhow::Result { + let target = format!("/world/{}/isolation", lease.name()); + let authority = + moderation_authority(hub, lease, admin_token, signed, &target, isolation.as_str())?; + lease + .service() + .world() + .set_isolation(authority, isolation) + .await +} + +/// Handle a cross-world write or file scope frame; `None` for any other frame. +pub(crate) async fn policy_frame( + hub: &WorldHub, + lease: &WorldLease, + frame: &ClientFrame, +) -> Option> { + Some(match frame { + ClientFrame::SetCrossWorldWrite { + enabled, + admin_token, + signed, + } => { + set_cross_world_write_frame( + hub, + lease, + *enabled, + admin_token.as_deref(), + signed.as_ref(), + ) + .await + } + ClientFrame::ForceCrossWorldWrite { admin_token } => { + force_cross_world_write_frame(lease, admin_token).await + } + ClientFrame::SetFileScope { + scope, + write_override, + admin_token, + signed, + } => { + set_file_scope_frame( + hub, + lease, + *scope, + *write_override, + admin_token.as_deref(), + signed.as_ref(), + ) + .await + } + _ => return None, + }) +} + +pub(crate) async fn set_cross_world_write_frame( + hub: &WorldHub, + lease: &WorldLease, + enabled: bool, + admin_token: Option<&str>, + signed: Option<&Signed>, +) -> anyhow::Result { + let target = format!("/world/{}/cross-world-write", lease.name()); + let body = if enabled { "on" } else { "off" }; + let authority = moderation_authority(hub, lease, admin_token, signed, &target, body)?; + lease + .service() + .world() + .set_cross_world_write(authority, enabled) + .await +} + +pub(crate) async fn force_cross_world_write_frame( + lease: &WorldLease, + admin_token: &str, +) -> anyhow::Result { + anyhow::ensure!(is_admin(lease, Some(admin_token)), "admin denied"); + lease + .service() + .world() + .force_cross_world_write(Authority::Admin) + .await +} + +pub(crate) async fn set_file_scope_frame( + hub: &WorldHub, + lease: &WorldLease, + scope: FileScope, + write_override: Option, + admin_token: Option<&str>, + signed: Option<&Signed>, +) -> anyhow::Result { + let target = format!("/world/{}/file-scope", lease.name()); + let body = match scope { + FileScope::Confined => "confined", + FileScope::Unrestricted => "unrestricted", + }; + let authority = moderation_authority(hub, lease, admin_token, signed, &target, body)?; + lease + .service() + .world() + .set_file_scope(authority, scope, write_override) + .await +} + +pub(crate) fn is_admin(lease: &WorldLease, admin_token: Option<&str>) -> bool { + admin_token + .filter(|token| token.len() <= MAX_ADMIN_TOKEN_BYTES) + .is_some_and(|token| lease.service().authorize_admin(Some(token)).is_ok()) +} + +/// The admin when the token matches; otherwise a signed request's account, +/// which the world's moderator check then judges. +pub(crate) fn moderation_authority( + hub: &WorldHub, + lease: &WorldLease, + admin_token: Option<&str>, + signed: Option<&Signed>, + target: &str, + body: &str, +) -> anyhow::Result { + if is_admin(lease, admin_token) { + return Ok(Authority::Admin); + } + let Some(signed) = signed else { + anyhow::bail!("admin denied"); + }; + let key = hub.verify_signed(signed, "PUT", target, body.as_bytes())?; + Ok(Authority::Signed(key)) +} + +/// Serve one session against its resolved world, starting from its first frame. +async fn run_world_session(service: &WorldService, io: &mut I, frame: ClientFrame) { + match frame { + ClientFrame::Join { capability, after } => { + if capability.len() > MAX_CAPABILITY_BYTES { + let _ = send_error(io, "invalid join capability").await; + return; + } + joined(service, io, JoinCapability::from_wire(capability), after).await; + } + ClientFrame::Invite { + admin_token, + display_name, + expires_in_secs, + uses, + role, + } => match role.as_deref().map(WorldScopes::from_role) { + Some(None) => { + let _ = send_error( + io, + "unknown invite role; use spectator, observer, player, guest, or delegator", + ) + .await; + } + role_scopes => match service + .invite_scoped( + Some(&admin_token), + display_name, + expires_in_secs, + uses, + role_scopes.flatten().unwrap_or(WorldScopes::GUEST), + ) + .await + { + Ok(invite) => { + let _ = send_json(io, &ServerFrame::Invite(&invite)).await; + } + Err(InviteError::InvalidBounds(message)) => { + let _ = send_error(io, message).await; + } + Err(InviteError::Disabled) => { + let _ = send_error(io, "invites are not enabled").await; + } + Err(InviteError::Unauthorized) => { + let _ = send_error(io, "invite denied").await; + } + Err(InviteError::Unavailable) => { + let _ = send_error(io, "world cannot issue another invite").await; + } + }, + }, + // Query frames keep the session open for further queries: a client + // can page through records, and may still join later on. + ClientFrame::Info { .. } + | ClientFrame::Records { .. } + | ClientFrame::RecordsTicket { .. } + | ClientFrame::DownloadModule { .. } => { + query_session(service, io, frame).await; + } + ClientFrame::InstallBegin { + admin_token, + total_bytes, + module_hash, + seed, + } => { + if service.source_only() { + if service.authorize_admin(Some(&admin_token)).is_err() { + let _ = send_error(io, "module install denied").await; + return; + } + let _ = + send_error(io, "raw module uploads are disabled by source-only policy").await; + return; + } + if let Err(message) = install_module_session( + service, + io, + &admin_token, + total_bytes, + module_hash.as_deref(), + seed, + ) + .await + { + let _ = send_error(io, message).await; + } + } + ClientFrame::Caps { capability } => { + let token = JoinCapability::from_wire(capability); + if service.world().participant_id(token).await.is_err() { + let _ = send_error(io, "join denied").await; + } else { + match service.world().caps_report().await { + Ok(report) => { + let _ = send_json(io, &ServerFrame::Caps { report }).await; + } + Err(_) => { + let _ = send_error(io, "capability report unavailable").await; + } + } + } + } + ClientFrame::UpdateCaps { + admin_token, + grant, + revoke, + } => match service.authorize_admin(Some(&admin_token)) { + Ok(()) => match service.world().update_caps(grant, revoke).await { + Ok(report) => { + let _ = send_json(io, &ServerFrame::Caps { report }).await; + } + Err(error) => { + let _ = send_error(io, &format!("{error:#}")).await; + } + }, + Err(_) => { + let _ = send_error(io, "admin denied").await; + } + }, + ClientFrame::SetCapsCeiling { + admin_token, + ceiling, + } => match service.set_caps_ceiling(Some(&admin_token), ceiling).await { + Ok(report) => { + let _ = send_json( + io, + &ServerFrame::CapsCeiling { + report, + message: CAPS_CEILING_NOTICE, + }, + ) + .await; + } + Err(error) => { + let _ = send_error(io, &format!("{error:#}")).await; + } + }, + ClientFrame::SetExecutionProfile { + admin_token, + profile, + } => match service + .set_execution_profile(Some(&admin_token), profile) + .await + { + Ok(update) => { + let _ = send_json( + io, + &ServerFrame::ExecutionProfile { + update, + message: "profile saved; it applies on the next program install or process restart, not to the running instance", + }, + ) + .await; + } + Err(error) => { + let _ = send_error(io, &format!("{error:#}")).await; + } + }, + ClientFrame::ExecutionProfileInfo { + admin_token, + capability, + } => { + let auth_ok = if let Some(admin) = admin_token.as_deref() { + service.authorize_admin(Some(admin)).is_ok() + } else if let Some(cap) = capability.as_deref() { + let token = JoinCapability::from_wire(cap.to_string()); + service.world().participant_id(token).await.is_ok() + } else { + false + }; + if !auth_ok { + let _ = send_error(io, "access denied").await; + } else { + match service.world().execution_profile().await { + Ok(profile) => { + let _ = send_json( + io, + &ServerFrame::ExecutionProfile { + update: crate::world::ExecutionProfileUpdate { + requested: profile, + applies_on_next_program_install_or_process_restart: false, + }, + message: "current persisted execution profile", + }, + ) + .await; + } + Err(error) => { + let _ = send_error(io, &format!("{error:#}")).await; + } + } + } + } + #[cfg(feature = "sandbox")] + ClientFrame::Compile { + admin_token, + files, + seed, + native, + } => { + let seed = seed.unwrap_or_else(|| rand::rng().random::()); + let spec = CompileSpec { + files: files + .into_iter() + .map(|file| (file.name, file.content)) + .collect(), + seed, + native, + }; + match service.compile_and_install(Some(&admin_token), &spec).await { + Ok((module_hash, sequence, diagnostics)) => { + let _ = send_json( + io, + &ServerFrame::Compiled { + module_hash, + sequence, + diagnostics, + }, + ) + .await; + } + Err(message) => { + let _ = send_error(io, &message).await; + } + } + } + #[cfg(not(feature = "sandbox"))] + ClientFrame::Compile { .. } => { + let _ = send_error(io, "compilation is not enabled on this server").await; + } + ClientFrame::InstallChunk { .. } + | ClientFrame::InstallEnd + | ClientFrame::ListWorlds { .. } + | ClientFrame::CreateWorld { .. } + | ClientFrame::SetIsolation { .. } + | ClientFrame::SetCrossWorldWrite { .. } + | ClientFrame::ForceCrossWorldWrite { .. } + | ClientFrame::SetFileScope { .. } + | ClientFrame::Chat { .. } + | ClientFrame::Attenuate { .. } + | ClientFrame::DelegateToFriend { .. } + | ClientFrame::Input { .. } + | ClientFrame::Resize { .. } + | ClientFrame::Paste { .. } => { + let _ = send_error(io, "first frame must be join, invite or install_begin").await; + } + } +} + +/// Serve query frames (`info`, `records`, `records_ticket`, +/// `download_module`) until the peer closes, denies, or sends a frame that +/// ends the session. A `join` frame switches to the joined session. +async fn query_session(service: &WorldService, io: &mut I, first: ClientFrame) { + let mut next = Some(first); + loop { + let frame = match next.take() { + Some(frame) => frame, + None => match io.recv().await { + Inbound::Text(text) => { + if let Ok(frame) = serde_json::from_str::(&text) { + frame + } else { + let _ = send_error(io, "invalid world frame").await; + return; + } + } + Inbound::Oversized => { + let _ = send_error(io, "world frame is too large").await; + return; + } + Inbound::Unsupported => { + let _ = send_error(io, "frames must be UTF-8 text").await; + return; + } + Inbound::Closed => return, + }, + }; + match frame { + ClientFrame::Join { capability, after } => { + if capability.len() > MAX_CAPABILITY_BYTES { + let _ = send_error(io, "invalid join capability").await; + return; + } + joined(service, io, JoinCapability::from_wire(capability), after).await; + return; + } + ClientFrame::Info { capability } => { + let token = JoinCapability::from_wire(capability); + if let Ok(snapshot) = service.world().snapshot(token).await { + if !send_json( + io, + &ServerFrame::ModuleInfo { + world_id: snapshot.world_id, + active_module_hash: snapshot.active_module_hash, + active_module_provenance: snapshot.active_module_provenance, + current_sequence: snapshot.current_sequence, + }, + ) + .await + { + return; + } + } else { + let _ = send_error(io, "join denied").await; + return; + } + } + ClientFrame::Records { + capability, + prefix, + after, + } => { + let token = JoinCapability::from_wire(capability); + if let Err(message) = records_session( + service.world(), + io, + token, + prefix.as_deref(), + after.as_deref(), + ) + .await + { + let _ = send_error(io, message).await; + return; + } + } + ClientFrame::RecordsTicket { capability } => { + let token = JoinCapability::from_wire(capability); + if service.world().participant_id(token).await.is_err() { + let _ = send_error(io, "join denied").await; + return; + } + match records_ticket_session(service, io).await { + Ok(()) => {} + Err(message) => { + let _ = send_error(io, message).await; + return; + } + } + } + ClientFrame::DownloadModule { + capability, + module_hash, + } => { + let token = JoinCapability::from_wire(capability); + if service.world().snapshot(token).await.is_err() { + let _ = send_error(io, "join denied").await; + return; + } + if let Err(message) = download_module_session(service, io, &module_hash).await { + let _ = send_error(io, message).await; + return; + } + } + _ => { + let _ = send_error(io, "expected a query frame").await; + return; + } + } + } +} + +/// Answer a `records_ticket` query. +async fn records_ticket_session( + service: &WorldService, + io: &mut I, +) -> Result<(), &'static str> { + match service.records_store() { + Some(store) => match store.read_ticket().await { + Ok(ticket) => { + if send_json(io, &ServerFrame::RecordsTicket { ticket }).await { + Ok(()) + } else { + Err("connection closed") + } + } + Err(_) => Err("records ticket unavailable"), + }, + None => Err("world keeps no structured records"), + } +} + +/// Largest page of records returned in one frame, comfortably inside +/// [`MAX_FRAME_BYTES`] after JSON framing overhead. +pub(crate) const MAX_RECORDS_PAGE_BYTES: usize = 768 * 1024; + +async fn records_session( + world: &WorldHandle, + io: &mut I, + token: JoinCapability, + prefix: Option<&str>, + after: Option<&str>, +) -> Result<(), &'static str> { + if world.participant_id(token).await.is_err() { + return Err("join denied"); + } + let (sequence, records) = world.records(); + let mut page = crate::world::Records::new(); + let mut used = 0usize; + let mut last_included: Option = None; + let mut more = false; + for (key, value) in records.iter() { + if let Some(prefix) = prefix + && !key.starts_with(prefix) + { + continue; + } + if let Some(after) = after + && key.as_str() <= after + { + continue; + } + let size = key.len() + serde_json::to_vec(value).map_or(0, |v| v.len()) + 8; + if used + size > MAX_RECORDS_PAGE_BYTES { + // `next_after` is exclusive on the client, so it must be the + // last key *included* here; anything else would skip a record. + if page.is_empty() { + return Err("a record is too large to serve in one page"); + } + more = true; + break; + } + used += size; + last_included = Some(key.clone()); + page.insert(key.clone(), value.clone()); + } + let next_after = more.then_some(last_included).flatten(); + if !send_json( + io, + &ServerFrame::Records { + sequence, + records: page, + next_after, + }, + ) + .await + { + return Err("connection closed"); + } + Ok(()) +} + +async fn download_module_session( + service: &WorldService, + io: &mut I, + requested_hash: &str, +) -> Result<(), &'static str> { + let Some(active_hash) = service.active_module_hash().await else { + return Err("world has no installed module"); + }; + if requested_hash != active_hash { + return Err("requested module is not the active world module"); + } + let bytes = service + .module_bytes(&active_hash) + .await + .map_err(|_| "module bytes are unavailable")?; + if !send_json( + io, + &ServerFrame::ModuleBegin { + module_hash: active_hash.clone(), + total_bytes: bytes.len(), + }, + ) + .await + { + return Err("connection closed"); + } + for (index, chunk) in bytes.chunks(MAX_WORLD_MODULE_CHUNK_BYTES).enumerate() { + if !send_json( + io, + &ServerFrame::ModuleChunk { + offset: index * MAX_WORLD_MODULE_CHUNK_BYTES, + data_hex: encode_hex(chunk), + }, + ) + .await + { + return Err("connection closed"); + } + } + if !send_json( + io, + &ServerFrame::ModuleEnd { + module_hash: active_hash, + }, + ) + .await + { + return Err("connection closed"); + } + Ok(()) +} + +async fn install_module_session( + service: &WorldService, + io: &mut I, + admin_token: &str, + total_bytes: usize, + claimed_hash: Option<&str>, + seed: u64, +) -> Result<(), &'static str> { + if admin_token.len() > MAX_ADMIN_TOKEN_BYTES + || service.authorize_admin(Some(admin_token)).is_err() + { + return Err("module install denied"); + } + 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 Err("invalid module size or content hash"); + } + let upload_permit = service + .try_reserve_module_upload() + .map_err(|_| "world is busy installing another module")?; + #[cfg(not(feature = "sandbox"))] + { + let _ = (io, seed, upload_permit); + return Err("module installation requires the sandbox feature"); + } + + #[cfg(feature = "sandbox")] + { + if !send_json( + io, + &ServerFrame::UploadReady { + chunk_bytes: MAX_WORLD_MODULE_CHUNK_BYTES, + }, + ) + .await + { + 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 }) = + serde_json::from_str::(&text) + 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!(serde_json::from_str::(text), Ok(ClientFrame::InstallEnd))) + { + return Err("expected install_end frame"); + } + 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"); + } + let (module_hash, sequence) = service + .install_wasm_reserved( + Some(admin_token), + bytes, + seed, + &actual_hash, + upload_permit, + false, + None, + ) + .await + .map_err(|error| match error { + InstallError::Disabled => "module installation is not enabled on this host", + InstallError::Unauthorized => "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::Unavailable => "world could not activate the module", + })?; + if !send_json( + io, + &ServerFrame::ModuleInstalled { + module_hash: &module_hash, + sequence, + }, + ) + .await + { + return Err("connection closed"); + } + Ok(()) + } +} + +async fn joined( + service: &WorldService, + io: &mut I, + token: JoinCapability, + after: Option, +) { + let world = service.world(); + // Subscribe before taking the snapshot so no event can fall in the gap; + // events at or below the cursor are skipped when delivered. + let mut events = world.subscribe(); + let mut revocations = world.subscribe_revocations(); + let Ok(participant_id) = world.participant_id(token.clone()).await else { + let _ = send_error(io, "join denied").await; + return; + }; + let Ok(snapshot) = world.snapshot(token.clone()).await else { + let _ = send_error(io, "join denied").await; + return; + }; + let mut cursor = snapshot.current_sequence; + let mut viewport = None; + if let Some(after) = after { + match world.events_after(token.clone(), after).await { + Ok(page) if page.needs_snapshot => { + let Ok(fresh) = world.snapshot(token.clone()).await else { + return; + }; + cursor = fresh.current_sequence; + if !send_json(io, &ServerFrame::Snapshot { snapshot: &fresh }).await { + return; + } + } + Ok(page) => { + cursor = page.current_sequence; + for event in &page.events { + if !send_json(io, &ServerFrame::Event { event }).await { + return; + } + if !send_view(world, io, &token, event.sequence, viewport).await { + return; + } + } + } + Err(_) => { + let _ = send_error(io, "join denied").await; + return; + } + } + } else if !send_json( + io, + &ServerFrame::Snapshot { + snapshot: &snapshot, + }, + ) + .await + { + return; + } + if !send_view(world, io, &token, cursor, viewport).await { + return; + } + + // Presence starts here and ends whenever this session does. Views are + // re-sent whenever program state changes for another reason (host events + // are not broadcast as events). + world.presence(participant_id, true).await; + let _guard = PresenceGuard { + world: world.clone(), + participant: participant_id, + }; + let mut views = world.watch_views(); + + loop { + tokio::select! { + inbound = io.recv() => match inbound { + Inbound::Text(text) => { + if !handle_client_frame(service, io, &token, &text, &mut viewport, cursor).await { + break; + } + } + Inbound::Oversized => { + if !send_error(io, "world frame is too large").await { break; } + } + Inbound::Unsupported => { + if !send_error(io, "frames must be UTF-8 text").await { break; } + } + Inbound::Closed => break, + }, + event = events.recv() => match event { + Ok(event) => { + if let crate::world::WorldEventKind::ProgramInstalled { ref module_hash, .. } = event.kind { + if event.sequence > cursor { + let Ok(snapshot) = world.snapshot(token.clone()).await else { break }; + if !send_json(io, &ServerFrame::Snapshot { snapshot: &snapshot }).await { + break; + } + cursor = event.sequence; + if !send_json(io, &ServerFrame::ProgramChanged { + module_hash, + sequence: cursor, + }).await || !send_view(world, io, &token, cursor, viewport).await { + break; + } + } + continue; + } + if event.sequence <= cursor { + continue; + } + // Projecting the event re-validates the capability on every + // delivery, which is what disconnects a revoked + // participant, and applies what this viewer may see now. + let Ok(projected) = world.project_event(token.clone(), event.clone()).await else { + break; + }; + // A withheld event still moves the cursor past it. + cursor = event.sequence; + let Some(shown) = projected else { + continue; + }; + if !send_json(io, &ServerFrame::Event { event: &shown }).await { + break; + } + if !send_view(world, io, &token, cursor, viewport).await { + break; + } + } + Err(broadcast::error::RecvError::Lagged(_)) => { + let Ok(snapshot) = world.snapshot(token.clone()).await else { break }; + if !send_json(io, &ServerFrame::Snapshot { snapshot: &snapshot }).await { + break; + } + cursor = snapshot.current_sequence; + if !send_view(world, io, &token, cursor, viewport).await { + break; + } + } + Err(broadcast::error::RecvError::Closed) => break, + }, + changed = views.changed() => match changed { + Ok(()) => { + let sequence = *views.borrow_and_update(); + if !send_view(world, io, &token, sequence, viewport).await { + break; + } + } + Err(_) => break, + }, + revoked = revocations.recv() => match revoked { + Ok(revoked_id) if revoked_id == participant_id => { + let _ = send_error(io, "world capability revoked").await; + break; + } + Ok(_) | Err(broadcast::error::RecvError::Lagged(_)) => {}, + Err(broadcast::error::RecvError::Closed) => break, + } + } + } +} + +/// Returns the participant's presence when the session ends, however it ends. +pub(crate) struct PresenceGuard { + world: WorldHandle, + participant: u64, +} + +impl Drop for PresenceGuard { + fn drop(&mut self) { + let world = self.world.clone(); + let participant = self.participant; + tokio::spawn(async move { + world.presence(participant, false).await; + }); + } +} + +async fn send_view( + world: &WorldHandle, + io: &mut I, + token: &JoinCapability, + sequence: u64, + viewport: Option, +) -> bool { + let view = match viewport { + Some(viewport) => { + let width = u16::try_from(viewport.width).unwrap_or(u16::MAX); + let height = u16::try_from(viewport.height).unwrap_or(u16::MAX); + world.view_at(token.clone(), width, height).await + } + None => world.view(token.clone()).await, + }; + match view { + Ok(Some(data)) => { + if data.len() > MAX_FRAME_BYTES { + return send_error(io, "world presentation is too large").await; + } + let surface = match crate::world_presentation::parse_surface(&data) { + Ok(Some(crate::world_presentation::WorldSurface::Screen(screen))) => { + let screen = viewport.map_or(screen.clone(), |viewport| { + screen.fit(viewport.width, viewport.height) + }); + Some(crate::world_presentation::WorldSurface::Screen(screen)) + } + Ok(surface) => surface, + Err(_) => return send_error(io, "invalid world screen presentation").await, + }; + send_json( + io, + &ServerFrame::View { + sequence, + data: &data, + surface: surface.as_ref(), + }, + ) + .await + } + Ok(None) => true, + Err(_) => false, + } +} + +/// Connection-local terminal/browser dimensions. This value is intentionally +/// absent from world events and snapshots. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Viewport { + width: usize, + height: usize, +} + +pub(crate) fn normalize_paste(text: &str) -> Result, &'static str> { + let normalized = text.replace("\r\n", "\n").replace('\r', "\n"); + if normalized.len() > 4096 + || normalized + .chars() + .any(|ch| ch.is_control() && ch != '\n' && ch != '\t') + { + return Err("paste must be at most 4096 UTF-8 bytes and contain no control characters"); + } + Ok(normalized.into_bytes()) +} + +const USES_REFUSED: &str = "a delegation may not carry `uses`: a delegated grant has no use count, and the host's limit still applies"; + +/// Whether a delegation frame names `uses` anywhere in it. The field was +/// removed from delegations, and serde would ignore it, minting an unbounded +/// grant from a client that still sends it. Any depth is refused, so no +/// position hides the field. +pub(crate) fn delegation_names_uses(value: &serde_json::Value) -> bool { + let delegating = matches!( + value.get("type").and_then(serde_json::Value::as_str), + Some("attenuate" | "delegate_to_friend") + ); + delegating && names_uses(value) +} + +pub(crate) fn names_uses(value: &serde_json::Value) -> bool { + match value { + serde_json::Value::Object(map) => map + .iter() + .any(|(key, inner)| key == "uses" || names_uses(inner)), + serde_json::Value::Array(items) => items.iter().any(names_uses), + _ => false, + } +} + +/// Handle one frame from a joined participant. Returns `false` to end the session. +async fn handle_client_frame( + service: &WorldService, + io: &mut I, + token: &JoinCapability, + text: &str, + viewport: &mut Option, + sequence: u64, +) -> bool { + let world = service.world(); + let Ok(value) = serde_json::from_str::(text) else { + return send_error(io, "invalid world frame").await; + }; + if delegation_names_uses(&value) { + return send_error(io, USES_REFUSED).await; + } + let Ok(frame) = serde_json::from_value::(value) else { + return send_error(io, "invalid world frame").await; + }; + let result = match frame { + ClientFrame::Attenuate { + name, + scopes, + expires_at, + } => { + let Some(scopes) = WorldScopes::from_names(scopes.iter().map(String::as_str)) else { + return send_error(io, "unknown scope").await; + }; + let bounds = CapabilityBounds { + expires_at, + uses: None, + }; + let result = world.attenuate(token.clone(), scopes, bounds, name).await; + return send_delegation(io, result).await; + } + ClientFrame::DelegateToFriend { + friend, + name, + scopes, + expires_at, + } => { + let Some(scopes) = WorldScopes::from_names(scopes.iter().map(String::as_str)) else { + return send_error(io, "unknown scope").await; + }; + let bounds = CapabilityBounds { + expires_at, + uses: None, + }; + let result = world + .delegate_to_friend(token.clone(), friend, scopes, bounds, name) + .await; + return send_delegation(io, result).await; + } + ClientFrame::Chat { text } => world.chat(token.clone(), text).await, + ClientFrame::Resize { width, height } => { + if width == 0 || height == 0 || width > 500 || height > 200 { + return send_error( + io, + "viewport dimensions must be width 1..=500 and height 1..=200", + ) + .await; + } + *viewport = Some(Viewport { + width: usize::from(width), + height: usize::from(height), + }); + return send_view(world, io, token, sequence, *viewport).await; + } + ClientFrame::Paste { text } => { + let Ok(bytes) = normalize_paste(&text) else { + return send_error( + io, + "paste must be at most 4096 UTF-8 bytes and contain no control characters", + ) + .await; + }; + world.input(token.clone(), bytes).await + } + ClientFrame::Input { data_hex } => match decode_hex(&data_hex) { + Some(data) => world.input(token.clone(), data).await, + None => return send_error(io, "input data must be hexadecimal").await, + }, + ClientFrame::Records { prefix, after, .. } => { + // Authorized by the session's own capability. + if let Err(message) = records_session( + world, + io, + token.clone(), + prefix.as_deref(), + after.as_deref(), + ) + .await + { + return send_error(io, message).await; + } + return true; + } + ClientFrame::SetExecutionProfile { + admin_token, + profile, + } => { + match service + .set_execution_profile(Some(&admin_token), profile) + .await + { + Ok(update) => { + let _ = send_json( + io, + &ServerFrame::ExecutionProfile { + update, + message: "profile saved; it applies on the next program install or process restart, not to the running instance", + }, + ) + .await; + } + Err(error) => return send_error(io, &format!("{error:#}")).await, + } + return true; + } + ClientFrame::ExecutionProfileInfo { .. } => { + match service.world().execution_profile().await { + Ok(profile) => { + let _ = send_json( + io, + &ServerFrame::ExecutionProfile { + update: crate::world::ExecutionProfileUpdate { + requested: profile, + applies_on_next_program_install_or_process_restart: false, + }, + message: "current persisted execution profile", + }, + ) + .await; + } + Err(error) => return send_error(io, &format!("{error:#}")).await, + } + return true; + } + ClientFrame::RecordsTicket { .. } => { + if let Err(message) = records_ticket_session(service, io).await { + return send_error(io, message).await; + } + return true; + } + ClientFrame::Caps { .. } => { + match service.world().caps_report().await { + Ok(report) => { + let _ = send_json(io, &ServerFrame::Caps { report }).await; + } + Err(_) => { + return send_error(io, "capability report unavailable").await; + } + } + return true; + } + ClientFrame::UpdateCaps { + admin_token, + grant, + revoke, + } => { + match service.authorize_admin(Some(&admin_token)) { + Ok(()) => match service.world().update_caps(grant, revoke).await { + Ok(report) => { + let _ = send_json(io, &ServerFrame::Caps { report }).await; + } + Err(error) => { + return send_error(io, &format!("{error:#}")).await; + } + }, + Err(_) => { + return send_error(io, "admin denied").await; + } + } + return true; + } + ClientFrame::SetCapsCeiling { + admin_token, + ceiling, + } => { + match service.set_caps_ceiling(Some(&admin_token), ceiling).await { + Ok(report) => { + let _ = send_json( + io, + &ServerFrame::CapsCeiling { + report, + message: CAPS_CEILING_NOTICE, + }, + ) + .await; + } + Err(error) => return send_error(io, &format!("{error:#}")).await, + } + return true; + } + ClientFrame::Join { .. } + | ClientFrame::Invite { .. } + | ClientFrame::Info { .. } + | ClientFrame::ListWorlds { .. } + | ClientFrame::CreateWorld { .. } + | ClientFrame::SetIsolation { .. } + | ClientFrame::SetCrossWorldWrite { .. } + | ClientFrame::ForceCrossWorldWrite { .. } + | ClientFrame::SetFileScope { .. } + | ClientFrame::Compile { .. } + | ClientFrame::DownloadModule { .. } + | ClientFrame::InstallBegin { .. } + | ClientFrame::InstallChunk { .. } + | ClientFrame::InstallEnd => { + return send_error(io, "already joined").await; + } + }; + // Accepted events reach everyone, including the sender, through the + // broadcast branch, so only rejections are answered directly. + result.is_ok() || send_error(io, "world event rejected").await +} + +async fn send_json(io: &mut I, frame: &impl Serialize) -> bool { + match serde_json::to_string(frame) { + Ok(encoded) if encoded.len() <= MAX_FRAME_BYTES => io.send(encoded).await, + _ => false, + } +} + +async fn send_error(io: &mut I, message: &str) -> bool { + send_json(io, &ServerFrame::Error { message }).await +} + +async fn send_delegation( + io: &mut I, + result: anyhow::Result<(Participant, JoinCapability)>, +) -> bool { + match result { + Ok((participant, capability)) => { + let delegated = InviteResponse { + capability: capability.expose().to_owned(), + participant_id: participant.id, + display_name: participant.display_name, + }; + send_json(io, &ServerFrame::Invite(&delegated)).await + } + Err(_) => send_error(io, "delegation denied").await, + } +} + +/// Decode a bounded hex string. +#[must_use] +pub fn decode_hex(encoded: &str) -> Option> { + if !encoded.len().is_multiple_of(2) || encoded.len() > MAX_FRAME_BYTES * 2 { + return None; + } + encoded + .as_bytes() + .chunks_exact(2) + .map(|pair| Some((hex_nibble(pair[0])? << 4) | hex_nibble(pair[1])?)) + .collect() +} + +pub(crate) fn encode_hex(bytes: &[u8]) -> String { + const HEX: &[u8; 16] = b"0123456789abcdef"; + let mut result = String::with_capacity(bytes.len() * 2); + for byte in bytes { + result.push(char::from(HEX[usize::from(byte >> 4)])); + result.push(char::from(HEX[usize::from(byte & 0x0f)])); + } + result +} + +const fn hex_nibble(byte: u8) -> Option { + match byte { + b'0'..=b'9' => Some(byte - b'0'), + b'a'..=b'f' => Some(byte - b'a' + 10), + b'A'..=b'F' => Some(byte - b'A' + 10), + _ => None, + } +} + +pub(crate) fn enqueue_all( + queue: &mut crate::envelope_outbox::Outbox, + outbound: Vec, +) -> anyhow::Result> { + use crate::envelope_outbox::Payload; + let mut keys = Vec::with_capacity(outbound.len()); + for crate::directory_view::Outbound { target, payload } in outbound { + let key = payload.key(&target); + let queued = match payload { + Payload::Envelope(envelope) => queue.enqueue(&target, envelope), + Payload::Artifact(artifact) => queue.enqueue_artifact(&target, artifact), + }; + if let Err(error) = queued { + withdraw_all(queue, &keys); + return Err(error); + } + keys.push(key); + } + Ok(keys) +} + +pub(crate) fn withdraw_all(queue: &mut crate::envelope_outbox::Outbox, keys: &[String]) { + for key in keys { + if let Err(withdrawn) = queue.withdraw(key) { + tracing::error!("{key} stays queued though its change was refused: {withdrawn:#}"); + } + } +} diff --git a/pkgs/id/src/world_session/tests.rs b/pkgs/id/src/world_session/tests.rs new file mode 100644 index 0000000000..6cb1b9fea5 --- /dev/null +++ b/pkgs/id/src/world_session/tests.rs @@ -0,0 +1,1626 @@ +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod tests { + use tokio::sync::mpsc; + + use ed25519_dalek::SigningKey; + + use super::*; + use crate::directory::{Actor, Level, Member}; + use crate::directory_auth::sign_request; + use crate::world::{ + Participant, WorldCore, WorldEvent, WorldHandle, WorldLimits, WorldScopes, hex_encode, + unix_ms, + }; + use crate::world_hub::WorldHub; + use crate::world_session::*; + use std::time::Duration; + + /// In-memory transport: tests push frames in and read frames out. + struct ChannelIo { + inbound: mpsc::Receiver, + outbound: mpsc::Sender, + } + + impl SessionIo for ChannelIo { + async fn recv(&mut self) -> Inbound { + self.inbound.recv().await.unwrap_or(Inbound::Closed) + } + async fn send(&mut self, frame: String) -> bool { + self.outbound.send(frame).await.is_ok() + } + } + + struct Peer { + to_server: mpsc::Sender, + from_server: mpsc::Receiver, + task: tokio::task::JoinHandle<()>, + } + + impl Peer { + fn connect(service: WorldService, config: SessionConfig) -> Self { + Self::connect_hub(WorldHub::single(service), config) + } + + fn connect_hub(hub: WorldHub, config: SessionConfig) -> Self { + let (to_server, inbound) = mpsc::channel(16); + let (outbound, from_server) = mpsc::channel(64); + let task = tokio::spawn(async move { + let mut io = ChannelIo { inbound, outbound }; + run_session_with(&hub, &mut io, config).await; + }); + Self { + to_server, + from_server, + task, + } + } + + async fn say(&self, frame: serde_json::Value) { + self.to_server + .send(Inbound::Text(frame.to_string())) + .await + .unwrap(); + } + + /// Sends the frame text as given, so a test controls field order. + async fn say_text(&self, text: &str) { + self.to_server + .send(Inbound::Text(text.to_owned())) + .await + .unwrap(); + } + + async fn next(&mut self) -> Option { + // An upload takes several seconds in a debug build, so 5 s was too + // tight. The deadline still bounds a real hang. + let frame = tokio::time::timeout(Duration::from_mins(1), self.from_server.recv()) + .await + .expect("timed out waiting for a server frame")?; + Some(serde_json::from_str(&frame).unwrap()) + } + } + + /// A program that does nothing, for tests that only install one. + struct NoProgram; + + impl crate::world::WorldProgram for NoProgram {} + + /// Publishes 1024 records of about 1 KiB, so one query needs several + /// pages (the page budget is 768 KiB). + struct Bulky; + + impl crate::world::WorldProgram for Bulky { + fn records(&mut self) -> anyhow::Result> { + let payload = "x".repeat(1024); + let records: crate::world::Records = (0..1024) + .map(|i| { + ( + format!("key-{i:04}"), + serde_json::Value::from(payload.clone()), + ) + }) + .collect(); + Ok(Some(serde_json::to_string(&records)?)) + } + } + + fn service_with_records(admin: Option<&str>) -> WorldService { + WorldService::new( + WorldHandle::spawn_with_program( + WorldCore::new("lobby", WorldLimits::default()).unwrap(), + Box::new(Bulky), + ), + admin.map(str::to_owned), + ) + } + + fn service(admin: Option<&str>) -> WorldService { + WorldService::new( + WorldHandle::spawn(WorldCore::new("lobby", WorldLimits::default()).unwrap()), + admin.map(str::to_owned), + ) + } + + #[tokio::test] + async fn execution_profile_change_is_admin_only_and_does_not_replace_live_program() { + struct MarkerProgram; + impl crate::world::WorldProgram for MarkerProgram { + fn view(&mut self, _viewer: &Participant) -> anyhow::Result> { + Ok(Some("existing instance".to_owned())) + } + } + + let world = WorldHandle::spawn_with_program( + WorldCore::new("lobby", WorldLimits::default()).unwrap(), + Box::new(MarkerProgram), + ); + let service = WorldService::new(world.clone(), Some("admin".to_owned())); + let requested = crate::world_limits::WorldExecutionProfile { + wasm_fuel: Some(1000), + ..Default::default() + }; + assert!( + service + .set_execution_profile(Some("wrong"), requested) + .await + .is_err() + ); + assert_eq!( + world.execution_profile().await.unwrap(), + crate::world_limits::WorldExecutionProfile::default() + ); + + let update = service + .set_execution_profile(Some("admin"), requested) + .await + .unwrap(); + assert_eq!(update.requested, requested); + assert!(update.applies_on_next_program_install_or_process_restart); + let (_, token) = world.issue("guest", WorldScopes::GUEST).await.unwrap(); + assert_eq!( + world.view(token).await.unwrap().as_deref(), + Some("existing instance"), + "updating the profile must not replace or mutate the running program" + ); + } + + #[tokio::test] + async fn execution_profile_protocol_returns_the_deferred_application_notice() { + let service = service(Some("admin")); + let mut peer = Peer::connect(service, SessionConfig::default()); + peer.say(serde_json::json!({ + "type": "set_execution_profile", + "admin_token": "admin", + "profile": {"wasm_fuel": 1234}, + })) + .await; + let response = peer.next().await.unwrap(); + assert_eq!(response["type"], "execution_profile"); + assert_eq!(response["update"]["requested"]["wasm_fuel"], 1234); + assert_eq!( + response["update"]["applies_on_next_program_install_or_process_restart"], + true + ); + assert!( + response["message"] + .as_str() + .unwrap() + .contains("not to the running instance") + ); + } + + #[tokio::test] + async fn caps_ceiling_is_admin_only_and_applies_at_once() { + let world = WorldHandle::spawn(WorldCore::new("lobby", WorldLimits::default()).unwrap()); + let service = WorldService::new(world.clone(), Some("admin".to_owned())); + let full = world.caps_report().await.unwrap().ceiling; + assert!( + service + .set_caps_ceiling(Some("wrong"), vec!["time.now".to_owned()]) + .await + .is_err() + ); + assert!( + service + .set_caps_ceiling(None, vec!["time.now".to_owned()]) + .await + .is_err() + ); + assert_eq!( + world.caps_report().await.unwrap().ceiling, + full, + "a refused change changes nothing" + ); + + let report = service + .set_caps_ceiling(Some("admin"), vec!["time.now".to_owned()]) + .await + .unwrap(); + assert_eq!(report.ceiling, vec!["time.now".to_owned()]); + assert_eq!( + world.caps_report().await.unwrap().ceiling, + vec!["time.now".to_owned()] + ); + } + + #[tokio::test] + async fn caps_ceiling_protocol_round_trips_and_says_it_applies_now() { + let mut peer = Peer::connect(service(Some("admin")), SessionConfig::default()); + peer.say(serde_json::json!({ + "type": "set_caps_ceiling", + "admin_token": "admin", + "ceiling": ["time.now"], + })) + .await; + let response = peer.next().await.unwrap(); + assert_eq!(response["type"], "caps_ceiling"); + assert_eq!( + response["report"]["ceiling"], + serde_json::json!(["time.now"]) + ); + assert!( + response["message"] + .as_str() + .unwrap() + .contains("applies immediately") + ); + + let mut peer = Peer::connect(service(Some("admin")), SessionConfig::default()); + peer.say(serde_json::json!({ + "type": "set_caps_ceiling", + "admin_token": "wrong", + "ceiling": [], + })) + .await; + assert_eq!(peer.next().await.unwrap()["type"], "error"); + + let mut peer = Peer::connect(service(Some("admin")), SessionConfig::default()); + peer.say(serde_json::json!({ + "type": "set_caps_ceiling", + "admin_token": "admin", + "ceiling": ["*"], + })) + .await; + assert_eq!(peer.next().await.unwrap()["type"], "error"); + } + + #[cfg(feature = "sandbox")] + #[tokio::test] + async fn source_compile_sees_the_effective_list_not_the_raw_grants() { + let root = tempfile::tempdir().unwrap(); + std::fs::write(root.path().join("platform.roc"), "x").unwrap(); + std::fs::create_dir_all(root.path().join("targets/wasm32")).unwrap(); + std::fs::write(root.path().join("targets/wasm32/host.wasm"), b"\0asm").unwrap(); + std::fs::write(root.path().join("Key.roc"), "module []\n").unwrap(); + std::fs::write(root.path().join("Screen.roc"), "module []\n").unwrap(); + let compiler = + Compiler::new(root.path().to_path_buf(), "/nonexistent/roc".to_owned()).unwrap(); + let svc = service(Some("admin")).with_compiler(compiler); + svc.world() + .update_caps(vec!["*".to_owned()], Vec::new()) + .await + .unwrap(); + let spec = CompileSpec { + files: vec![( + "main.roc".to_owned(), + "import pf.Screen\napp [x] {}".to_owned(), + )], + seed: 1, + native: false, + }; + + svc.set_caps_ceiling(Some("admin"), vec!["Key".to_owned()]) + .await + .unwrap(); + let error = svc + .compile_and_install(Some("admin"), &spec) + .await + .unwrap_err(); + assert!(error.contains("main.roc imports Screen"), "{error}"); + + // Inside the ceiling the same import passes the gate and reaches the + // compiler, which is not installed here. + svc.set_caps_ceiling(Some("admin"), vec!["Key".to_owned(), "Screen".to_owned()]) + .await + .unwrap(); + let error = svc + .compile_and_install(Some("admin"), &spec) + .await + .unwrap_err(); + assert!(!error.contains("imports Screen"), "{error}"); + } + + struct FixedScreen; + + impl crate::world::WorldProgram for FixedScreen { + fn view(&mut self, _viewer: &Participant) -> anyhow::Result> { + Ok(Some( + r#"{"kind":"screen","version":1,"width":4,"height":2,"rows":["界ab","wxyz"]}"# + .to_owned(), + )) + } + } + + #[tokio::test] + async fn viewport_is_session_local_and_never_advances_the_world_sequence() { + let world = WorldHandle::spawn_with_program( + WorldCore::new("lobby", WorldLimits::default()).unwrap(), + Box::new(FixedScreen), + ); + let svc = WorldService::new(world.clone(), None); + let scopes = WorldScopes::from_names(["join", "input"]).unwrap(); + let (_, capability) = world.issue("player".to_owned(), scopes).await.unwrap(); + let mut peer = Peer::connect(svc, SessionConfig::default()); + peer.say(serde_json::json!({"type":"join","capability":capability.expose()})) + .await; + assert_eq!(peer.next().await.unwrap()["type"], "snapshot"); + assert_eq!(peer.next().await.unwrap()["type"], "view"); + let sequence = world + .snapshot(capability.clone()) + .await + .unwrap() + .current_sequence; + + peer.say(serde_json::json!({"type":"resize","width":1,"height":1})) + .await; + let view = peer.next().await.unwrap(); + assert_eq!(view["type"], "view"); + assert_eq!(view["surface"]["width"], 1); + assert_eq!(view["surface"]["height"], 1); + assert_eq!(view["surface"]["cells"][0]["symbol"], " "); + assert_eq!( + world.snapshot(capability).await.unwrap().current_sequence, + sequence + ); + } + + /// A server with Ann and Bo as friends and no outbox. When `bo_home_is_remote`, + /// Bo's artifacts are held on another server, so removing Bo must be sent. + async fn friends_without_outbox( + bo_home_is_remote: bool, + ) -> (WorldService, crate::directory_auth::Caller, String) { + let mut core = WorldCore::new("lobby", WorldLimits::default()).unwrap(); + let (ann_secret, _) = core.directory_mut().sign_up("Ann").unwrap(); + let (bo_secret, _) = core.directory_mut().sign_up("Bo").unwrap(); + let ann_id = core.directory().account_for(&ann_secret).unwrap(); + let bo_id = core.directory().account_for(&bo_secret).unwrap(); + if bo_home_is_remote { + let home = crate::artifact::HomeServer { + endpoint: iroh::SecretKey::from_bytes(&[5; 32]).public().to_string(), + world_id: "home".to_owned(), + }; + core.directory_mut() + .declare_home(&bo_secret, vec![home]) + .unwrap(); + } + let svc = WorldService::new(WorldHandle::spawn(core), None); + let ann = crate::directory_auth::Caller::from_secret(&ann_secret); + let bo = crate::directory_auth::Caller::from_secret(&bo_secret); + svc.directory( + ann.clone(), + crate::directory_view::DirectoryAction::RequestFriend { + to: bo_id.clone(), + remote: None, + }, + ) + .await + .unwrap(); + svc.directory( + bo, + crate::directory_view::DirectoryAction::AcceptFriend { + from: ann_id, + remote: None, + }, + ) + .await + .unwrap(); + (svc, ann, bo_id) + } + + async fn friends_of_ann( + svc: &WorldService, + ann: &crate::directory_auth::Caller, + ) -> Option> { + let view = svc + .directory(ann.clone(), crate::directory_view::DirectoryAction::View) + .await + .unwrap() + .view; + view.accounts + .iter() + .find(|a| a.name == "Ann") + .unwrap() + .friends + .clone() + } + + #[tokio::test] + async fn a_local_friend_removal_needs_no_outbox() { + let (svc, ann, bo) = friends_without_outbox(false).await; + svc.directory( + ann.clone(), + crate::directory_view::DirectoryAction::RemoveFriend { other: bo }, + ) + .await + .unwrap(); + assert_eq!(friends_of_ann(&svc, &ann).await, Some(Vec::new())); + } + + #[tokio::test] + async fn a_removal_of_a_friend_on_another_server_is_refused_without_an_outbox() { + let (svc, ann, bo) = friends_without_outbox(true).await; + let refused = svc + .directory( + ann.clone(), + crate::directory_view::DirectoryAction::RemoveFriend { other: bo.clone() }, + ) + .await + .unwrap_err(); + assert!( + format!("{refused:#}").contains("cannot send to other servers"), + "{refused:#}" + ); + assert_eq!(friends_of_ann(&svc, &ann).await, Some(vec![bo])); + } + + #[tokio::test] + async fn a_signed_moderator_sets_isolation_and_a_forged_request_does_not() { + let key = SigningKey::from_bytes(&[9; 32]); + let moderator = hex_encode(&key.verifying_key().to_bytes()); + let mut core = WorldCore::new("lobby", WorldLimits::default()).unwrap(); + core.directory_mut() + .sign_up_keyed(&moderator, "Mo") + .unwrap(); + let (credential, _) = core.directory_mut().sign_up("Founder").unwrap(); + let founder = core.directory().account_for(&credential).unwrap(); + let (group, _) = core + .directory_mut() + .create_group(&founder, "staff", "", WorldScopes::GUEST) + .unwrap(); + core.directory_mut() + .set_member( + Actor::Server, + group, + Member::Account { + id: moderator.clone(), + }, + Some(Level::Moderator), + ) + .unwrap(); + let hub = WorldHub::single(WorldService::new(WorldHandle::spawn(core), None)); + let lease = hub.lease(None, None).await.unwrap(); + let target = format!("/world/{}/isolation", lease.name()); + let now = unix_ms(); + + let mut forged = sign_request(&key, "PUT", &target, b"unisolated", now, "forged"); + let last = forged.signature.pop().unwrap(); + forged.signature.push(if last == '0' { '1' } else { '0' }); + let other_body = sign_request(&key, "PUT", &target, b"isolated", now, "other-body"); + for signed in [&forged, &other_body] { + assert!( + set_isolation_frame(&hub, &lease, Isolation::Unisolated, None, Some(signed)) + .await + .is_err() + ); + } + assert_eq!( + lease.service().world().isolation().await.unwrap(), + Isolation::Isolated + ); + + let signed = sign_request(&key, "PUT", &target, b"unisolated", now, "good"); + assert_eq!( + set_isolation_frame(&hub, &lease, Isolation::Unisolated, None, Some(&signed)) + .await + .unwrap(), + Isolation::Unisolated + ); + } + + #[tokio::test] + async fn a_bad_admin_token_is_refused_for_force_and_override() { + let world = WorldHandle::spawn(WorldCore::new("lobby", WorldLimits::default()).unwrap()); + world + .set_isolation(Authority::Admin, Isolation::Unisolated) + .await + .unwrap(); + let hub = WorldHub::single(WorldService::new(world, Some("secret".to_owned()))); + let lease = hub.lease(None, None).await.unwrap(); + let force_guess = ClientFrame::ForceCrossWorldWrite { + admin_token: "guess".to_owned(), + }; + let override_guess = ClientFrame::SetFileScope { + scope: FileScope::Unrestricted, + write_override: Some(true), + admin_token: Some("guess".to_owned()), + signed: None, + }; + assert!( + policy_frame(&hub, &lease, &force_guess) + .await + .unwrap() + .is_err() + ); + assert!( + policy_frame(&hub, &lease, &override_guess) + .await + .unwrap() + .is_err() + ); + let policy = lease.service().world().policy().await.unwrap(); + assert!(!policy.cross_world_forced && !policy.file_write_override); + + let force = ClientFrame::ForceCrossWorldWrite { + admin_token: "secret".to_owned(), + }; + let forced = policy_frame(&hub, &lease, &force).await.unwrap().unwrap(); + assert!(forced.cross_world_forced); + let override_on = ClientFrame::SetFileScope { + scope: FileScope::Unrestricted, + write_override: Some(true), + admin_token: Some("secret".to_owned()), + signed: None, + }; + let set = policy_frame(&hub, &lease, &override_on) + .await + .unwrap() + .unwrap(); + assert!(set.file_write_override); + } + + #[test] + fn hex_input_parser_is_bounded_and_strict() { + assert_eq!(decode_hex("00aBff"), Some(vec![0, 0xab, 0xff])); + assert_eq!(decode_hex(""), Some(vec![])); + assert_eq!(decode_hex("0"), None); + assert_eq!(decode_hex("zz"), None); + assert_eq!(decode_hex(&"0".repeat(MAX_FRAME_BYTES * 2 + 2)), None); + } + + #[test] + fn paste_is_normalized_bounded_and_rejects_controls() { + assert_eq!(normalize_paste("a\r\nb\rc\t"), Ok(b"a\nb\nc\t".to_vec())); + assert_eq!(normalize_paste(&"x".repeat(4096)).unwrap().len(), 4096); + assert!(normalize_paste(&"x".repeat(4097)).is_err()); + assert!(normalize_paste("a\u{1b}b").is_err()); + assert_eq!( + normalize_paste(&"界".repeat(1366)).unwrap_err(), + "paste must be at most 4096 UTF-8 bytes and contain no control characters" + ); + } + + #[test] + fn wire_event_and_view_shape_are_presentation_neutral() { + use crate::world::WorldEventKind; + let event = WorldEvent { + sequence: 3, + participant_id: 9, + kind: WorldEventKind::Chat("hello".to_owned()), + }; + let encoded = serde_json::to_string(&ServerFrame::Event { event: &event }).unwrap(); + assert!(encoded.contains("\"type\":\"event\"")); + assert!(encoded.contains("\"sequence\":3")); + assert!(encoded.contains("\"kind\":\"chat\"")); + assert!(encoded.contains("\"data\":\"hello\"")); + let view = serde_json::to_string(&ServerFrame::View { + sequence: 3, + data: "count=1", + surface: None, + }) + .unwrap(); + assert!(view.contains("\"type\":\"view\"")); + assert!(view.contains("\"data\":\"count=1\"")); + } + + #[test] + fn typed_screen_is_an_optional_view_surface_without_dropping_legacy_data() { + let data = + r#"{"kind":"screen","version":1,"width":2,"height":1,"rows":["ok"],"styles":[[]]}"#; + let surface = crate::world_presentation::parse_surface(data) + .unwrap() + .unwrap(); + let encoded = serde_json::to_string(&ServerFrame::View { + sequence: 8, + data, + surface: Some(&surface), + }) + .unwrap(); + assert!(encoded.contains("\"data\":\"{\\\"kind\\\":\\\"screen\\\"")); + assert!(encoded.contains("\"surface\":{\"kind\":\"screen\",\"version\":1")); + assert!(encoded.contains("\"symbol\":\"o\"")); + } + + #[test] + fn secret_comparison_requires_equal_bytes() { + assert!(secret_eq(b"abc", b"abc")); + assert!(!secret_eq(b"abc", b"abd")); + assert!(!secret_eq(b"abc", b"ab")); + } + + #[tokio::test] + async fn silent_peers_are_dropped_after_the_join_timeout() { + let mut peer = Peer::connect( + service(None), + SessionConfig { + join_timeout: Duration::from_millis(50), + }, + ); + let frame = peer.next().await.unwrap(); + assert_eq!(frame["type"], "error"); + assert!(frame["message"].as_str().unwrap().contains("timed out")); + assert!(peer.next().await.is_none()); + peer.task.await.unwrap(); + } + + #[tokio::test] + async fn first_frame_must_be_join_or_invite() { + let mut peer = Peer::connect(service(Some("a")), SessionConfig::default()); + peer.say(serde_json::json!({"type": "chat", "text": "hi"})) + .await; + assert_eq!(peer.next().await.unwrap()["type"], "error"); + assert!(peer.next().await.is_none()); + + let mut garbage = Peer::connect(service(None), SessionConfig::default()); + garbage + .to_server + .send(Inbound::Text("not json".to_owned())) + .await + .unwrap(); + assert_eq!(garbage.next().await.unwrap()["type"], "error"); + + let mut big = Peer::connect(service(None), SessionConfig::default()); + big.to_server.send(Inbound::Oversized).await.unwrap(); + assert_eq!(big.next().await.unwrap()["type"], "error"); + let mut bin = Peer::connect(service(None), SessionConfig::default()); + bin.to_server.send(Inbound::Unsupported).await.unwrap(); + assert_eq!(bin.next().await.unwrap()["type"], "error"); + } + + #[test] + fn invite_lifetimes_default_to_a_week_and_stop_at_thirty_days() { + let now = 1_000_000; + let default = invite_bounds(None, None, now).unwrap(); + assert_eq!(default.expires_at, Some(now + INVITE_DEFAULT_SECS * 1000)); + assert_eq!(default.uses, None); + let longest = invite_bounds(Some(INVITE_MAX_SECS), Some(3), now).unwrap(); + assert_eq!(longest.expires_at, Some(now + INVITE_MAX_SECS * 1000)); + assert_eq!(longest.uses, Some(3)); + assert!(invite_bounds(Some(0), None, now).is_err()); + assert!(invite_bounds(Some(INVITE_MAX_SECS + 1), None, now).is_err()); + assert!(invite_bounds(None, Some(0), now).is_err()); + } + + #[tokio::test] + async fn invite_frame_refuses_bounds_out_of_range() { + let svc = service(Some("admin")); + let mut long = Peer::connect(svc.clone(), SessionConfig::default()); + long.say(serde_json::json!({"type":"invite","admin_token":"admin","display_name":"ann","expires_in_secs":INVITE_MAX_SECS + 1})) + .await; + assert_eq!(long.next().await.unwrap()["type"], "error"); + let mut none = Peer::connect(svc, SessionConfig::default()); + none.say(serde_json::json!({"type":"invite","admin_token":"admin","display_name":"ann","uses":0})) + .await; + assert_eq!( + none.next().await.unwrap()["message"], + "uses must be at least 1" + ); + } + + #[tokio::test] + async fn delegate_to_friend_frame_needs_an_account_capability() { + let svc = service(Some("admin")); + let mut host = Peer::connect(svc.clone(), SessionConfig::default()); + host.say(serde_json::json!({"type":"invite","admin_token":"admin","display_name":"ann"})) + .await; + let capability = host.next().await.unwrap()["capability"] + .as_str() + .unwrap() + .to_owned(); + + let mut guest = Peer::connect(svc, SessionConfig::default()); + guest + .say(serde_json::json!({"type":"join","capability":capability})) + .await; + assert_eq!(guest.next().await.unwrap()["type"], "snapshot"); + guest + .say(serde_json::json!({"type":"delegate_to_friend","friend":"nobody","name":"bo","scopes":["join"]})) + .await; + assert_eq!(guest.next().await.unwrap()["message"], "delegation denied"); + guest + .say(serde_json::json!({"type":"delegate_to_friend","friend":"nobody","name":"bo","scopes":["root"]})) + .await; + assert_eq!(guest.next().await.unwrap()["message"], "unknown scope"); + } + + #[tokio::test] + async fn invite_frame_issues_a_capability_that_can_join() { + let svc = service(Some("admin")); + + let mut denied = Peer::connect(svc.clone(), SessionConfig::default()); + denied + .say(serde_json::json!({"type":"invite","admin_token":"nope","display_name":"x"})) + .await; + assert_eq!(denied.next().await.unwrap()["message"], "invite denied"); + + let mut host = Peer::connect(svc.clone(), SessionConfig::default()); + host.say(serde_json::json!({"type":"invite","admin_token":"admin","display_name":"ann"})) + .await; + let invite = host.next().await.unwrap(); + assert_eq!(invite["type"], "invite"); + let capability = invite["capability"].as_str().unwrap().to_owned(); + + let mut guest = Peer::connect(svc, SessionConfig::default()); + guest + .say(serde_json::json!({"type":"join","capability":capability})) + .await; + assert_eq!(guest.next().await.unwrap()["type"], "snapshot"); + } + + #[tokio::test] + async fn invite_roles_grant_and_withhold_the_expected_scopes() { + let svc = service(Some("admin")); + + // An unknown role is refused by name. + let mut bad = Peer::connect(svc.clone(), SessionConfig::default()); + bad.say(serde_json::json!({ + "type": "invite", + "admin_token": "admin", + "display_name": "spec", + "role": "builder", + })) + .await; + let message = bad.next().await.unwrap()["message"] + .as_str() + .unwrap() + .to_owned(); + assert!(message.contains("unknown invite role"), "{message}"); + + // A spectator may join and read, but not chat or submit input. + let mut host = Peer::connect(svc.clone(), SessionConfig::default()); + host.say(serde_json::json!({ + "type": "invite", + "admin_token": "admin", + "display_name": "spec", + "role": "spectator", + })) + .await; + let capability = host.next().await.unwrap()["capability"] + .as_str() + .unwrap() + .to_owned(); + let mut spectator = Peer::connect(svc.clone(), SessionConfig::default()); + spectator + .say(serde_json::json!({"type":"join","capability":capability})) + .await; + assert_eq!(spectator.next().await.unwrap()["type"], "snapshot"); + spectator + .say(serde_json::json!({"type":"chat","text":"hello"})) + .await; + let refusal = spectator.next().await.unwrap(); + assert_eq!(refusal["type"], "error", "{refusal}"); + spectator + .say(serde_json::json!({"type":"input","data_hex":"6c"})) + .await; + let refusal = spectator.next().await.unwrap(); + assert_eq!(refusal["type"], "error", "{refusal}"); + + // A player may submit input but not chat. + let mut host = Peer::connect(svc.clone(), SessionConfig::default()); + host.say(serde_json::json!({ + "type": "invite", + "admin_token": "admin", + "display_name": "player", + "role": "player", + })) + .await; + let capability = host.next().await.unwrap()["capability"] + .as_str() + .unwrap() + .to_owned(); + let mut player = Peer::connect(svc, SessionConfig::default()); + player + .say(serde_json::json!({"type":"join","capability":capability})) + .await; + assert_eq!(player.next().await.unwrap()["type"], "snapshot"); + player + .say(serde_json::json!({"type":"input","data_hex":"6c"})) + .await; + let event = player.next().await.unwrap(); + assert_eq!(event["type"], "event", "{event}"); + player + .say(serde_json::json!({"type":"chat","text":"hello"})) + .await; + let refusal = player.next().await.unwrap(); + assert_eq!(refusal["type"], "error", "{refusal}"); + } + + #[tokio::test] + async fn a_delegate_mints_narrower_capabilities_over_the_session() { + let svc = service(None); + let delegate = WorldScopes::from_names(["join", "chat", "input", "delegate"]).unwrap(); + let (_, owner) = svc.world().issue("ann".to_owned(), delegate).await.unwrap(); + + let mut owner_peer = Peer::connect(svc.clone(), SessionConfig::default()); + owner_peer + .say(serde_json::json!({"type":"join","capability":owner.expose()})) + .await; + assert_eq!(owner_peer.next().await.unwrap()["type"], "snapshot"); + owner_peer + .say(serde_json::json!({"type":"attenuate","name":"bo","scopes":["join"]})) + .await; + let delegated = owner_peer.next().await.unwrap(); + assert_eq!(delegated["type"], "invite"); + let child = delegated["capability"].as_str().unwrap().to_owned(); + + let mut child_peer = Peer::connect(svc, SessionConfig::default()); + child_peer + .say(serde_json::json!({"type":"join","capability":child})) + .await; + assert_eq!(child_peer.next().await.unwrap()["type"], "snapshot"); + child_peer + .say(serde_json::json!({"type":"attenuate","name":"cy","scopes":["join"]})) + .await; + assert_eq!(child_peer.next().await.unwrap()["type"], "error"); + child_peer + .say(serde_json::json!({"type":"attenuate","name":"cy","scopes":["telepathy"]})) + .await; + assert_eq!(child_peer.next().await.unwrap()["message"], "unknown scope"); + } + + /// A joined participant that may delegate `join`. + async fn delegator(svc: &WorldService) -> Peer { + let delegate = WorldScopes::from_names(["join", "chat", "input", "delegate"]).unwrap(); + let (_, owner) = svc.world().issue("ann".to_owned(), delegate).await.unwrap(); + let mut peer = Peer::connect(svc.clone(), SessionConfig::default()); + peer.say(serde_json::json!({"type":"join","capability":owner.expose()})) + .await; + assert_eq!(peer.next().await.unwrap()["type"], "snapshot"); + peer + } + + /// Delegation frames that name `uses`, in each position a client could put + /// it. Serde would ignore the field and mint an unbounded grant. + const FRAMES_NAMING_USES: [&str; 9] = [ + r#"{"type":"attenuate","uses":1,"name":"bo","scopes":["join"]}"#, + r#"{"type":"attenuate","name":"bo","uses":1,"scopes":["join"]}"#, + r#"{"type":"attenuate","name":"bo","scopes":["join"],"uses":1}"#, + r#"{"type":"attenuate","name":"bo","scopes":["join"],"expires_at":null,"uses":null}"#, + r#"{"type":"attenuate","name":"bo","scopes":["join"],"bounds":{"uses":1}}"#, + r#"{"type":"attenuate","name":"bo","scopes":[{"uses":1}]}"#, + r#"{"type":"delegate_to_friend","uses":1,"friend":"nobody","name":"bo","scopes":["join"]}"#, + r#"{"type":"delegate_to_friend","friend":"nobody","name":"bo","scopes":["join"],"uses":1}"#, + r#"{"type":"delegate_to_friend","friend":"nobody","name":"bo","scopes":["join"],"bounds":{"uses":1}}"#, + ]; + + #[tokio::test] + async fn a_delegation_frame_that_names_uses_is_refused_by_name() { + let svc = service(None); + let mut peer = delegator(&svc).await; + for text in FRAMES_NAMING_USES { + peer.say_text(text).await; + let reply = peer.next().await.unwrap(); + assert_eq!(reply["type"], "error", "{text}"); + assert!( + reply["message"] + .as_str() + .unwrap_or_default() + .contains("`uses`"), + "{text}: {reply}" + ); + } + } + + #[tokio::test] + async fn a_delegation_frame_without_uses_is_accepted() { + let svc = service(None); + let mut peer = delegator(&svc).await; + for text in [ + r#"{"type":"attenuate","name":"bo","scopes":["join"]}"#, + r#"{"type":"attenuate","scopes":["join"],"expires_at":null,"name":"cy"}"#, + ] { + peer.say_text(text).await; + assert_eq!(peer.next().await.unwrap()["type"], "invite", "{text}"); + } + // Past the uses check, this delegate has no account, so the friend + // delegation is denied for that reason alone. + peer.say_text( + r#"{"type":"delegate_to_friend","friend":"nobody","name":"di","scopes":["join"]}"#, + ) + .await; + assert_eq!(peer.next().await.unwrap()["message"], "delegation denied"); + } + + #[tokio::test] + async fn records_are_paged_prefixed_and_queryable_while_joined() { + let svc = service_with_records(None); + let (_, token) = svc + .world() + .issue("ann".to_owned(), WorldScopes::GUEST) + .await + .unwrap(); + + // A fresh session can page through records; pages must be bounded and + // terminate with `next_after: null`. + let mut peer = Peer::connect(svc.clone(), SessionConfig::default()); + let mut pages = 0; + let mut seen = crate::world::Records::new(); + let mut after: Option = None; + loop { + let mut frame = serde_json::json!({ + "type": "records", + "capability": token.expose(), + }); + if let Some(after) = &after { + frame["after"] = serde_json::Value::from(after.clone()); + } + peer.say(frame).await; + let reply = peer.next().await.unwrap(); + assert_eq!(reply["type"], "records"); + assert!(reply["sequence"].as_u64().is_some()); + let page: crate::world::Records = + serde_json::from_value(reply["records"].clone()).unwrap(); + assert!(!page.is_empty()); + assert!( + serde_json::to_vec(&page).unwrap().len() <= MAX_RECORDS_PAGE_BYTES, + "page exceeds the byte budget" + ); + pages += 1; + seen.extend(page); + match reply["next_after"].as_str() { + Some(next) => after = Some(next.to_owned()), + None => break, + } + } + assert_eq!(seen.len(), 1024, "every record arrives exactly once"); + assert!(pages > 1, "1 MiB of records cannot fit in one page"); + assert!(seen.contains_key("key-0000") && seen.contains_key("key-1023")); + + // Prefix filtering works on the same session. + peer.say(serde_json::json!({ + "type": "records", + "capability": token.expose(), + "prefix": "key-010", + })) + .await; + let reply = peer.next().await.unwrap(); + let page: crate::world::Records = serde_json::from_value(reply["records"].clone()).unwrap(); + assert_eq!(page.len(), 10, "key-0100..key-0109"); + + // A joined session can also request the records document ticket (the + // reply is an error here only because this service has no docs store). + let mut joined = Peer::connect(svc, SessionConfig::default()); + joined + .say(serde_json::json!({"type":"join","capability": token.expose()})) + .await; + assert_eq!(joined.next().await.unwrap()["type"], "snapshot"); + joined + .say(serde_json::json!({"type":"records","capability": token.expose()})) + .await; + let reply = joined.next().await.unwrap(); + assert_eq!(reply["type"], "records"); + let page: crate::world::Records = serde_json::from_value(reply["records"].clone()).unwrap(); + assert!(!page.is_empty() && page.len() < 1024, "one bounded page"); + assert!( + reply["next_after"].is_string(), + "the page advertises that more records follow" + ); + // Still joined afterwards. + joined + .say(serde_json::json!({"type":"chat","text":"hi"})) + .await; + let reply = joined.next().await.unwrap(); + assert_eq!(reply["type"], "event"); + } + + fn memory_hub( + limits: crate::world_hub::HubLimits, + ) -> (WorldHub, Arc) { + let opener = crate::world_hub::testing::MemoryOpener::new(false); + let dyn_opener: Arc = opener.clone(); + ( + WorldHub::new(dyn_opener, Some("admin".to_owned()), "lobby", limits), + opener, + ) + } + + /// Invite `name` into `world` (creating it) and return the capability. + async fn invite_into(hub: &WorldHub, world: &str, name: &str) -> String { + let mut peer = Peer::connect_hub(hub.clone(), SessionConfig::default()); + peer.say(serde_json::json!({ + "type": "invite", + "admin_token": "admin", + "display_name": name, + "world": world, + })) + .await; + let reply = peer.next().await.unwrap(); + assert_eq!(reply["type"], "invite", "{reply}"); + reply["capability"].as_str().unwrap().to_owned() + } + + #[tokio::test] + async fn the_world_field_routes_a_session_and_capabilities_do_not_cross_worlds() { + let (hub, _) = memory_hub(crate::world_hub::HubLimits::default()); + let in_arena = invite_into(&hub, "arena", "ann").await; + let in_bazaar = invite_into(&hub, "bazaar", "bob").await; + + // Joining the world the capability belongs to works... + let mut arena = Peer::connect_hub(hub.clone(), SessionConfig::default()); + arena + .say(serde_json::json!({"type":"join","capability": in_arena,"world":"arena"})) + .await; + let snapshot = arena.next().await.unwrap(); + assert_eq!(snapshot["type"], "snapshot"); + assert_eq!(snapshot["snapshot"]["world_id"], "arena"); + + // ...the same capability is refused in another world... + let mut wrong = Peer::connect_hub(hub.clone(), SessionConfig::default()); + wrong + .say(serde_json::json!({"type":"join","capability": in_arena,"world":"bazaar"})) + .await; + assert_eq!(wrong.next().await.unwrap()["message"], "join denied"); + + // ...and chat in one world is invisible in the other. + arena + .say(serde_json::json!({"type":"chat","text":"hello arena"})) + .await; + assert_eq!(arena.next().await.unwrap()["type"], "event"); + let mut bazaar = Peer::connect_hub(hub.clone(), SessionConfig::default()); + bazaar + .say(serde_json::json!({"type":"join","capability": in_bazaar,"world":"bazaar"})) + .await; + let snapshot = bazaar.next().await.unwrap(); + assert_eq!(snapshot["snapshot"]["world_id"], "bazaar"); + assert_eq!(snapshot["snapshot"]["events"].as_array().unwrap().len(), 0); + + // No `world` field means the default world, which nobody created. + let mut default = Peer::connect_hub(hub, SessionConfig::default()); + default + .say(serde_json::json!({"type":"join","capability": in_arena})) + .await; + assert_eq!(default.next().await.unwrap()["message"], "unknown world"); + } + + #[tokio::test] + async fn only_an_admin_creates_or_lists_worlds() { + let (hub, _) = memory_hub(crate::world_hub::HubLimits::default()); + let mut denied = Peer::connect_hub(hub.clone(), SessionConfig::default()); + denied + .say(serde_json::json!({"type":"create_world","admin_token":"nope","world":"arena"})) + .await; + assert_eq!(denied.next().await.unwrap()["message"], "admin denied"); + let mut denied = Peer::connect_hub(hub.clone(), SessionConfig::default()); + denied + .say(serde_json::json!({"type":"list_worlds","admin_token":"nope"})) + .await; + assert_eq!(denied.next().await.unwrap()["message"], "admin denied"); + + let mut admin = Peer::connect_hub(hub.clone(), SessionConfig::default()); + admin + .say(serde_json::json!({"type":"create_world","admin_token":"admin","world":"arena"})) + .await; + let created = admin.next().await.unwrap(); + assert_eq!( + (created["type"].as_str(), created["created"].as_bool()), + (Some("world_created"), Some(true)) + ); + let mut admin = Peer::connect_hub(hub.clone(), SessionConfig::default()); + admin + .say(serde_json::json!({"type":"create_world","admin_token":"admin","world":"arena"})) + .await; + assert_eq!(admin.next().await.unwrap()["created"], false); + let mut admin = Peer::connect_hub(hub.clone(), SessionConfig::default()); + admin + .say(serde_json::json!({"type":"create_world","admin_token":"admin","world":"../x"})) + .await; + assert_eq!(admin.next().await.unwrap()["message"], "invalid world name"); + + let mut admin = Peer::connect_hub(hub, SessionConfig::default()); + admin + .say(serde_json::json!({"type":"list_worlds","admin_token":"admin"})) + .await; + let listed = admin.next().await.unwrap(); + assert_eq!(listed["type"], "worlds"); + assert_eq!(listed["default"], "lobby"); + assert_eq!(listed["worlds"][0]["name"], "arena"); + } + + #[tokio::test] + async fn unauthenticated_frames_cannot_create_or_probe_worlds() { + let (hub, opener) = memory_hub(crate::world_hub::HubLimits::default()); + for frame in [ + serde_json::json!({"type":"join","capability":"1.abc","world":"arena"}), + serde_json::json!({"type":"info","capability":"1.abc","world":"arena"}), + serde_json::json!({"type":"invite","admin_token":"wrong","display_name":"x","world":"arena"}), + ] { + let mut peer = Peer::connect_hub(hub.clone(), SessionConfig::default()); + peer.say(frame).await; + assert_eq!(peer.next().await.unwrap()["message"], "unknown world"); + } + assert_eq!( + opener.opens.load(std::sync::atomic::Ordering::SeqCst), + 0, + "nothing was opened or created by outsiders" + ); + } + + #[tokio::test] + async fn many_sessions_across_many_worlds_stay_separate() { + let (hub, _) = memory_hub(crate::world_hub::HubLimits::default()); + let mut tasks = tokio::task::JoinSet::new(); + for world in 0..8 { + for player in 0..8 { + let hub = hub.clone(); + tasks.spawn(async move { + let name = format!("world-{world}"); + let capability = invite_into(&hub, &name, &format!("p{player}")).await; + let mut peer = Peer::connect_hub(hub, SessionConfig::default()); + peer.say(serde_json::json!({ + "type": "join", "capability": capability, "world": name + })) + .await; + let snapshot = peer.next().await.unwrap(); + assert_eq!(snapshot["snapshot"]["world_id"], name.as_str()); + peer.say(serde_json::json!({ + "type": "chat", "text": format!("{name}/{player}") + })) + .await; + // Every event this session sees was said in its own world. + let mut seen = 0; + while seen < 1 { + let frame = peer.next().await.unwrap(); + if frame["type"] == "event" { + let text = frame["event"]["kind"]["data"].as_str().unwrap_or_default(); + assert!(text.starts_with(&name), "{name} saw {text}"); + seen += 1; + } + } + }); + } + } + while let Some(result) = tasks.join_next().await { + result.unwrap(); + } + assert_eq!(hub.open_count(), 8); + } + + #[tokio::test] + async fn a_session_over_the_ceiling_is_refused_politely() { + let (hub, _) = memory_hub(crate::world_hub::HubLimits { + max_sessions: 1, + ..crate::world_hub::HubLimits::default() + }); + let capability = invite_into(&hub, "arena", "ann").await; + let mut first = Peer::connect_hub(hub.clone(), SessionConfig::default()); + first + .say(serde_json::json!({"type":"join","capability": capability,"world":"arena"})) + .await; + assert_eq!(first.next().await.unwrap()["type"], "snapshot"); + let mut second = Peer::connect_hub(hub, SessionConfig::default()); + second + .say(serde_json::json!({"type":"join","capability": capability,"world":"arena"})) + .await; + assert_eq!( + second.next().await.unwrap()["message"], + "server is busy; try again shortly" + ); + } + + #[tokio::test] + async fn records_queries_need_a_valid_capability() { + let svc = service_with_records(None); + let mut peer = Peer::connect(svc, SessionConfig::default()); + peer.say(serde_json::json!({ + "type": "records", + "capability": "0.00", + })) + .await; + assert_eq!(peer.next().await.unwrap()["message"], "join denied"); + } + + #[cfg(feature = "sandbox")] + #[tokio::test] + async fn admin_upload_pins_validates_and_activates_a_roc_program() { + use iroh_blobs::store::mem::MemStore; + + let world = WorldHandle::spawn(WorldCore::new("lobby", WorldLimits::default()).unwrap()); + let blobs: Store = MemStore::new().into(); + let svc = WorldService::new(world.clone(), Some("admin".to_owned())) + .with_blob_store(blobs.clone()); + let wasm = include_bytes!("../../examples/roc-counter/counter.wasm"); + let hash = module_hash(wasm); + + let mut peer = Peer::connect(svc.clone(), SessionConfig::default()); + peer.say(serde_json::json!({ + "type": "install_begin", + "admin_token": "wrong", + "total_bytes": wasm.len(), + "module_hash": hash, + "seed": 12, + })) + .await; + assert_eq!( + peer.next().await.unwrap()["message"], + "module install denied" + ); + + let (_, guest) = world + .issue("ada".to_owned(), WorldScopes::GUEST) + .await + .unwrap(); + let mut peer = Peer::connect(svc, SessionConfig::default()); + peer.say(serde_json::json!({ + "type": "install_begin", + "admin_token": "admin", + "total_bytes": wasm.len(), + "module_hash": null, + "seed": 12, + })) + .await; + let ready = peer.next().await.unwrap(); + assert_eq!(ready["type"], "upload_ready"); + let chunk_bytes = usize::try_from(ready["chunk_bytes"].as_u64().unwrap()).unwrap(); + for (index, chunk) in wasm.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; + let ack = peer.next().await.unwrap(); + assert_eq!(ack["type"], "module_installed"); + assert_eq!(ack["module_hash"], hash); + + let hash: Hash = hash.parse().unwrap(); + assert!( + blobs.blobs().has(hash).await.unwrap(), + "uploaded module is pinned in the blob store" + ); + assert_eq!( + world.view(guest.clone()).await.unwrap().as_deref(), + Some("count=0") + ); + world.input(guest.clone(), b"inc".to_vec()).await.unwrap(); + assert_eq!(world.view(guest).await.unwrap().as_deref(), Some("count=1")); + } + + #[cfg(feature = "sandbox")] + #[tokio::test] + async fn admin_fuel_limit_applies_to_installed_programs() { + use iroh_blobs::store::mem::MemStore; + + let wasm = include_bytes!("../../examples/roc-counter/counter.wasm").to_vec(); + let hash = module_hash(&wasm); + let starved = crate::world_limits::RuntimeLimits { + sandbox: crate::sandbox::SandboxLimits { + fuel: 1, + ..crate::sandbox::SandboxLimits::default() + }, + ..crate::world_limits::RuntimeLimits::default() + }; + let world = WorldHandle::spawn(WorldCore::new("lobby", WorldLimits::default()).unwrap()); + let svc = WorldService::new(world, Some("admin".to_owned())) + .with_blob_store(MemStore::new().into()) + .with_runtime_limits(starved); + assert!(matches!( + svc.install_wasm(Some("admin"), wasm.clone(), 12, &hash) + .await, + Err(InstallError::InvalidModule) + )); + + let world = WorldHandle::spawn(WorldCore::new("lobby", WorldLimits::default()).unwrap()); + let svc = WorldService::new(world, Some("admin".to_owned())) + .with_blob_store(MemStore::new().into()); + svc.set_execution_profile( + Some("admin"), + crate::world_limits::WorldExecutionProfile { + wasm_fuel: Some(1), + ..Default::default() + }, + ) + .await + .unwrap(); + assert!(matches!( + svc.install_wasm(Some("admin"), wasm.clone(), 12, &hash) + .await, + Err(InstallError::InvalidModule) + )); + + let world = WorldHandle::spawn(WorldCore::new("lobby", WorldLimits::default()).unwrap()); + let svc = WorldService::new(world, Some("admin".to_owned())) + .with_blob_store(MemStore::new().into()); + svc.install_wasm(Some("admin"), wasm, 12, &hash) + .await + .expect("default limits install"); + } + + #[cfg(feature = "sandbox")] + #[tokio::test] + async fn source_only_policy_rejects_raw_modules_but_preserves_normal_mode() { + use iroh_blobs::store::mem::MemStore; + + let wasm = include_bytes!("../../examples/roc-counter/counter.wasm").to_vec(); + let hash = module_hash(&wasm); + let world = WorldHandle::spawn(WorldCore::new("lobby", WorldLimits::default()).unwrap()); + let service = WorldService::new(world.clone(), Some("admin".to_owned())) + .with_blob_store(MemStore::new().into()) + .with_source_only(true); + + assert!(service.source_only()); + assert!(matches!( + service + .install_wasm(Some("wrong"), wasm.clone(), 1, &hash) + .await, + Err(InstallError::Unauthorized) + )); + assert!(matches!( + service + .install_wasm(Some("admin"), wasm.clone(), 1, &hash) + .await, + Err(InstallError::RawModuleDisabled) + )); + assert_eq!(service.active_module_hash().await, None); + + let normal = WorldService::new( + WorldHandle::spawn(WorldCore::new("lobby", WorldLimits::default()).unwrap()), + Some("admin".to_owned()), + ) + .with_blob_store(MemStore::new().into()); + normal + .install_wasm(Some("admin"), wasm, 1, &hash) + .await + .expect("raw modules stay supported by default"); + } + + #[cfg(feature = "sandbox")] + #[tokio::test] + async fn source_only_policy_rejects_streaming_upload_before_accepting_chunks() { + let world = WorldHandle::spawn(WorldCore::new("lobby", WorldLimits::default()).unwrap()); + let service = WorldService::new(world, Some("admin".to_owned())).with_source_only(true); + let mut peer = Peer::connect(service, SessionConfig::default()); + peer.say(serde_json::json!({ + "type": "install_begin", + "admin_token": "admin", + "total_bytes": 32, + "module_hash": null, + "seed": 1, + })) + .await; + let error = peer.next().await.unwrap(); + assert_eq!(error["type"], "error"); + assert!(error["message"].as_str().unwrap().contains("source-only")); + } + + #[cfg(feature = "sandbox")] + #[tokio::test] + async fn bad_module_replacement_preserves_the_active_program() { + use iroh_blobs::store::mem::MemStore; + + let wasm = include_bytes!("../../examples/roc-counter/counter.wasm"); + let sandbox = + crate::sandbox::Sandbox::compile(wasm, crate::sandbox::SandboxLimits::default()) + .unwrap(); + let world = WorldHandle::spawn_with_program( + WorldCore::new("counter", WorldLimits::default()).unwrap(), + Box::new(sandbox.instantiate(1).unwrap()), + ); + let blobs: Store = MemStore::new().into(); + let service = + WorldService::new(world.clone(), Some("admin".to_owned())).with_blob_store(blobs); + let (_, guest) = world.issue("guest", WorldScopes::GUEST).await.unwrap(); + assert_eq!( + world.view(guest.clone()).await.unwrap().as_deref(), + Some("count=0") + ); + + let bad = b"not wasm".to_vec(); + let hash = module_hash(&bad); + assert_eq!( + service + .install_wasm(Some("admin"), bad, 2, &hash) + .await + .unwrap_err(), + InstallError::InvalidModule + ); + assert_eq!( + world.view(guest.clone()).await.unwrap().as_deref(), + Some("count=0") + ); + world.input(guest.clone(), b"inc".to_vec()).await.unwrap(); + assert_eq!(world.view(guest).await.unwrap().as_deref(), Some("count=1")); + } + + #[tokio::test] + async fn invites_are_disabled_without_an_admin_secret() { + let mut peer = Peer::connect(service(None), SessionConfig::default()); + peer.say(serde_json::json!({"type":"invite","admin_token":"","display_name":"x"})) + .await; + assert_eq!( + peer.next().await.unwrap()["message"], + "invites are not enabled" + ); + } + + #[tokio::test] + async fn chat_is_broadcast_and_rejections_are_private() { + let svc = service(None); + let (_, alice) = svc + .world() + .issue("alice".to_owned(), WorldScopes::GUEST) + .await + .unwrap(); + let (_, watcher) = svc + .world() + .issue("watcher".to_owned(), WorldScopes::JOIN) + .await + .unwrap(); + let mut a = Peer::connect(svc.clone(), SessionConfig::default()); + let mut w = Peer::connect(svc, SessionConfig::default()); + a.say(serde_json::json!({"type":"join","capability":alice.expose()})) + .await; + w.say(serde_json::json!({"type":"join","capability":watcher.expose()})) + .await; + assert_eq!(a.next().await.unwrap()["type"], "snapshot"); + assert_eq!(w.next().await.unwrap()["type"], "snapshot"); + + // A join-only participant cannot speak; only they hear about it. + w.say(serde_json::json!({"type":"chat","text":"psst"})) + .await; + assert_eq!(w.next().await.unwrap()["message"], "world event rejected"); + + // Chat reaches the guest; the join-only watcher hears the next + // non-chat event instead, past a gap in sequence numbers. + a.say(serde_json::json!({"type":"chat","text":"hello"})) + .await; + let frame = a.next().await.unwrap(); + assert_eq!(frame["type"], "event"); + assert!(frame.to_string().contains("hello")); + a.say(serde_json::json!({"type":"input","data_hex":"00"})) + .await; + let frame = w.next().await.unwrap(); + assert_eq!(frame["type"], "event"); + assert_eq!(frame["event"]["sequence"], 2, "{frame}"); + assert!(!frame.to_string().contains("hello"), "{frame}"); + assert_eq!(a.next().await.unwrap()["event"]["sequence"], 2); + a.say(serde_json::json!({"type":"input","data_hex":"xyz"})) + .await; + assert_eq!( + a.next().await.unwrap()["message"], + "input data must be hexadecimal" + ); + a.say(serde_json::json!({"type":"join","capability":"x"})) + .await; + assert_eq!(a.next().await.unwrap()["message"], "already joined"); + } + + fn kinds(events: &serde_json::Value) -> Vec { + events + .as_array() + .unwrap() + .iter() + .map(|event| event["kind"]["kind"].as_str().unwrap().to_owned()) + .collect() + } + + #[tokio::test] + async fn chat_visibility_a_join_only_joiner_gets_a_snapshot_without_chat() { + let svc = service(None); + let world = svc.world(); + let (_, guest) = world + .issue("guest".to_owned(), WorldScopes::GUEST) + .await + .unwrap(); + let (_, join_only) = world + .issue("join".to_owned(), WorldScopes::JOIN) + .await + .unwrap(); + let (_, reader) = world + .issue( + "reader".to_owned(), + WorldScopes::from_names(["join", "history"]).unwrap(), + ) + .await + .unwrap(); + world + .chat(guest.clone(), "secret".to_owned()) + .await + .unwrap(); + world.input(guest.clone(), b"move".to_vec()).await.unwrap(); + + for (token, sees_chat) in [(&guest, true), (&reader, true), (&join_only, false)] { + let mut peer = Peer::connect(svc.clone(), SessionConfig::default()); + peer.say(serde_json::json!({"type":"join","capability":token.expose()})) + .await; + let frame = peer.next().await.unwrap(); + assert_eq!(frame["type"], "snapshot"); + let events = &frame["snapshot"]["events"]; + assert_eq!(frame["snapshot"]["current_sequence"], 2); + assert_eq!( + kinds(events), + if sees_chat { + vec!["chat", "input"] + } else { + vec!["input"] + }, + "{frame}" + ); + assert_eq!(frame.to_string().contains("secret"), sees_chat, "{frame}"); + } + + // A rejoin from a cursor goes through catch-up, which projects too. + let mut peer = Peer::connect(svc.clone(), SessionConfig::default()); + peer.say(serde_json::json!({"type":"join","capability":join_only.expose(),"after":0})) + .await; + let frame = peer.next().await.unwrap(); + assert_eq!(frame["type"], "event", "{frame}"); + assert_eq!(frame["event"]["sequence"], 2); + assert!(!frame.to_string().contains("secret")); + } + + #[tokio::test] + async fn chat_visibility_a_live_install_never_shows_a_session_the_seed() { + // The raw broadcast carries the real seed; the session sends a + // snapshot and a program-changed frame instead, and every frame it + // sends is built from the projection. + let svc = service(None); + let world = svc.world(); + let (_, guest) = world + .issue("guest".to_owned(), WorldScopes::GUEST) + .await + .unwrap(); + let mut peer = Peer::connect(svc.clone(), SessionConfig::default()); + peer.say(serde_json::json!({"type":"join","capability":guest.expose()})) + .await; + assert_eq!(peer.next().await.unwrap()["type"], "snapshot"); + world + .install_program("ab".repeat(32), 424_242, Box::new(NoProgram)) + .await + .unwrap(); + let mut frames = Vec::new(); + loop { + let frame = peer.next().await.unwrap(); + let done = frame["type"] == "program_changed"; + frames.push(frame); + if done { + break; + } + } + let text = serde_json::to_string(&frames).unwrap(); + assert!(!text.contains("424242"), "{text}"); + assert!(text.contains(&"ab".repeat(32)), "the module hash is kept"); + } + + #[tokio::test] + async fn chat_visibility_the_live_stream_follows_the_viewers_scopes() { + let svc = service(None); + let world = svc.world(); + let (_, guest) = world + .issue("guest".to_owned(), WorldScopes::GUEST) + .await + .unwrap(); + let (_, join_only) = world + .issue("join".to_owned(), WorldScopes::JOIN) + .await + .unwrap(); + let (_, reader) = world + .issue( + "reader".to_owned(), + WorldScopes::from_names(["join", "history"]).unwrap(), + ) + .await + .unwrap(); + let mut watcher = Peer::connect(svc.clone(), SessionConfig::default()); + let mut reading = Peer::connect(svc.clone(), SessionConfig::default()); + for (peer, token) in [(&mut watcher, &join_only), (&mut reading, &reader)] { + peer.say(serde_json::json!({"type":"join","capability":token.expose()})) + .await; + assert_eq!(peer.next().await.unwrap()["type"], "snapshot"); + } + + world + .chat(guest.clone(), "secret".to_owned()) + .await + .unwrap(); + world.input(guest.clone(), b"move".to_vec()).await.unwrap(); + + let frame = reading.next().await.unwrap(); + assert!(frame.to_string().contains("secret"), "{frame}"); + assert_eq!(reading.next().await.unwrap()["event"]["sequence"], 2); + // The join-only watcher's first event is the input, after the gap. + let frame = watcher.next().await.unwrap(); + assert_eq!(frame["type"], "event", "{frame}"); + assert_eq!(frame["event"]["sequence"], 2, "{frame}"); + assert!(!frame.to_string().contains("secret")); + + // A reader may not speak. + reading + .say(serde_json::json!({"type":"chat","text":"hi"})) + .await; + assert_eq!( + reading.next().await.unwrap()["message"], + "world event rejected" + ); + } +} diff --git a/pkgs/id/src/world_session/types.rs b/pkgs/id/src/world_session/types.rs new file mode 100644 index 0000000000..39be3d9201 --- /dev/null +++ b/pkgs/id/src/world_session/types.rs @@ -0,0 +1,450 @@ +use std::sync::Arc; +use std::time::Duration; + +use iroh_blobs::api::{Store, TempTag}; +use serde::{Deserialize, Serialize}; +use tokio::sync::{Mutex, RwLock, Semaphore}; + +use crate::directory_auth::Signed; +use crate::world::{ + CapabilityBounds, FileScope, Isolation, WorldEvent, WorldHandle, WorldPolicy, WorldSnapshot, +}; +use crate::world_compile::Compiler; +use crate::world_hub::WorldInfo; + +/// Largest Wasm world module that may be installed (16 MiB). +pub const MAX_WORLD_MODULE_BYTES: usize = 16 * 1024 * 1024; + +/// Largest raw upload chunk; hex + JSON framing remains below [`MAX_FRAME_BYTES`]. +pub const MAX_WORLD_MODULE_CHUNK_BYTES: usize = 6 * 1024; + +/// Longest accepted capability string, in bytes. +pub(crate) const MAX_CAPABILITY_BYTES: usize = 256; + +/// Longest accepted admin secret, in bytes. +pub(crate) const MAX_ADMIN_TOKEN_BYTES: usize = 256; +/// Sent with a capability ceiling change: unlike a profile, it takes effect now. +pub(crate) const CAPS_CEILING_NOTICE: &str = + "ceiling saved; it applies immediately to new uses and active subscriptions"; + +/// Simultaneous bounded module uploads accepted by a world service. +pub(crate) const MAX_CONCURRENT_MODULE_UPLOADS: usize = 2; + +/// One inbound unit from a transport. +#[derive(Debug)] +pub enum Inbound { + /// A complete text frame no larger than [`MAX_FRAME_BYTES`]. + Text(String), + /// A frame larger than [`MAX_FRAME_BYTES`] (its contents are discarded). + Oversized, + /// A frame that is not UTF-8 text. + Unsupported, + /// The peer is gone or the stream failed; the session must end. + Closed, +} + +/// Moves whole text frames for one session. +/// +/// `recv` must be cancel-safe: the driver races it against world events and a +/// cancelled call must not lose or split a frame. +pub trait SessionIo: Send { + /// Next inbound frame. + fn recv(&mut self) -> impl Future + Send; + /// Send one frame. Returns `false` when the peer is gone. + fn send(&mut self, frame: String) -> impl Future + Send; +} + +/// Tunables for [`run_session_with`]. +#[derive(Clone, Copy, Debug)] +pub struct SessionConfig { + /// How long a peer may take to send its first frame. + pub join_timeout: Duration, +} + +impl Default for SessionConfig { + fn default() -> Self { + Self { + join_timeout: Duration::from_secs(10), + } + } +} + +// Install frames are only produced/consumed with the `sandbox` feature. +#[cfg_attr(not(feature = "sandbox"), allow(dead_code))] +#[derive(Debug, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub(crate) enum ClientFrame { + Join { + capability: String, + after: Option, + }, + Info { + capability: String, + }, + /// Page through the world's structured records. + Records { + capability: String, + /// Only keys starting with this prefix. + prefix: Option, + /// Continue after this key (exclusive). + after: Option, + }, + /// Ask for a read-only doc ticket to replicate the records peer-to-peer. + RecordsTicket { + capability: String, + }, + DownloadModule { + capability: String, + module_hash: String, + }, + Invite { + admin_token: String, + display_name: String, + /// Seconds until the invite stops working (default 7 days, at most 30). + expires_in_secs: Option, + /// Committed actions the invite may take; absent means no limit. + uses: Option, + /// Role preset (`spectator`, `observer`, `player`, `guest`, `delegator`); absent + /// means `guest`. + #[serde(default)] + role: Option, + }, + /// Admin: list the worlds this server hosts. + ListWorlds { + admin_token: String, + }, + /// Admin: create the world named by the frame's `world` field. + CreateWorld { + admin_token: String, + }, + /// Admin, or a signed request from a moderator: set the world's isolation. + /// A signed request covers method `PUT`, path `/world//isolation`, + /// and the isolation word as its body. + SetIsolation { + isolation: Isolation, + admin_token: Option, + signed: Option, + }, + /// Admin, or a signed request from a moderator: let other unisolated + /// worlds write here. A signed request covers `PUT + /// /world//cross-world-write` with the body `on` or `off`. + SetCrossWorldWrite { + enabled: bool, + admin_token: Option, + signed: Option, + }, + /// Admin: force cross-world writes on, overriding the world's own setting. + ForceCrossWorldWrite { + admin_token: String, + }, + /// Admin, or a signed request from a moderator: set the file scope. Only + /// the admin sets `write_override`. A signed request covers `PUT + /// /world//file-scope` with the scope word as its body. + SetFileScope { + scope: FileScope, + write_override: Option, + admin_token: Option, + signed: Option, + }, + /// Admin: compile Roc sources and install the result. + Compile { + admin_token: String, + files: Vec, + seed: Option, + #[serde(default)] + native: bool, + }, + /// Admin: grant or revoke capabilities for this world. + UpdateCaps { + admin_token: String, + grant: Vec, + revoke: Vec, + }, + /// Admin: replace this world's capability ceiling. It applies immediately; + /// grants are kept, and an empty list allows no capability. + SetCapsCeiling { + admin_token: String, + ceiling: Vec, + }, + /// Admin: persist requested per-world runtime bounds. They do not change + /// a running guest; they apply on its next install or process restart. + SetExecutionProfile { + admin_token: String, + profile: crate::world_limits::WorldExecutionProfile, + }, + /// Read the world's requested runtime bounds (needs either admin token or guest capability). + ExecutionProfileInfo { + admin_token: Option, + capability: Option, + }, + /// Show this world's capability grants, wants and usage. + Caps { + capability: String, + }, + Chat { + text: String, + }, + /// Joined: mint a capability with a subset of this session's scopes. A + /// delegation carries no use count. + Attenuate { + name: String, + scopes: Vec, + /// Unix milliseconds at which the delegated capability stops working. + expires_at: Option, + }, + /// Joined as an account: delegate a subset of its scopes to one of its friends. + DelegateToFriend { + friend: String, + name: String, + scopes: Vec, + expires_at: Option, + }, + Input { + data_hex: String, + }, + /// Ephemeral dimensions for this connection's presentation only. Never journaled. + Resize { + width: u16, + height: u16, + }, + /// Explicit bounded clipboard text, delivered as one durable input event. + Paste { + text: String, + }, + InstallBegin { + admin_token: String, + total_bytes: usize, + /// Expected BLAKE3 hash. Optional for browser uploads, whose `WebCrypto` + /// API does not provide BLAKE3; the host still computes and returns it. + module_hash: Option, + seed: u64, + }, + InstallChunk { + offset: usize, + data_hex: String, + }, + InstallEnd, +} + +// Install frames are only produced/consumed with the `sandbox` feature. +#[cfg_attr(not(feature = "sandbox"), allow(dead_code))] +#[derive(Debug, Serialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub(crate) enum ServerFrame<'a> { + Snapshot { + snapshot: &'a WorldSnapshot, + }, + Event { + event: &'a WorldEvent, + }, + /// Host-rendered presentation for the participant's adapter. + View { + sequence: u64, + data: &'a str, + /// Optional typed screen surface. Older clients can continue using `data`. + #[serde(skip_serializing_if = "Option::is_none")] + surface: Option<&'a crate::world_presentation::WorldSurface>, + }, + ModuleInfo { + world_id: String, + active_module_hash: Option, + #[serde(skip_serializing_if = "Option::is_none")] + active_module_provenance: Option, + current_sequence: u64, + }, + /// One page of structured records, with the sequence they were read at. + Records { + sequence: u64, + records: crate::world::Records, + /// Present when more keys follow; pass as `after` to continue. + next_after: Option, + }, + /// A read-only iroh-docs ticket for the records document. + RecordsTicket { + ticket: String, + }, + ModuleBegin { + module_hash: String, + total_bytes: usize, + }, + ModuleChunk { + offset: usize, + data_hex: String, + }, + ModuleEnd { + module_hash: String, + }, + Invite(&'a InviteResponse), + /// The worlds this server hosts. + Worlds { + default: &'a str, + worlds: Vec, + }, + WorldCreated { + world: &'a str, + created: bool, + }, + Isolation { + world: &'a str, + isolation: Isolation, + }, + /// The world's sharing and file settings after a change. + Policy { + world: &'a str, + policy: WorldPolicy, + }, + /// The world's capability report. + Caps { + report: crate::world_caps::CapsReport, + }, + /// The requested profile and an explicit deferred-application notice. + ExecutionProfile { + update: crate::world::ExecutionProfileUpdate, + message: &'static str, + }, + /// The capability report after a ceiling change, and a notice that the + /// change applied immediately. + CapsCeiling { + report: crate::world_caps::CapsReport, + message: &'static str, + }, + /// A compiled module was installed. + Compiled { + module_hash: String, + sequence: u64, + diagnostics: String, + }, + UploadReady { + chunk_bytes: usize, + }, + ModuleInstalled { + module_hash: &'a str, + sequence: u64, + }, + ProgramChanged { + module_hash: &'a str, + sequence: u64, + }, + Error { + message: &'a str, + }, +} + +/// A freshly minted guest capability. +#[derive(Debug, Serialize)] +pub struct InviteResponse { + /// Bearer capability; shown once, never logged. + pub capability: String, + /// The new participant's ID. + pub participant_id: u64, + /// The sanitized display name. + pub display_name: String, +} + +/// Why an invite was not issued. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum InviteError { + /// Invites are not enabled (no admin secret configured). + Disabled, + /// The supplied admin secret is missing or wrong. + Unauthorized, + /// The world refused another participant (full, or shut down). + Unavailable, + /// The requested lifetime or use limit is out of range. + InvalidBounds(&'static str), +} + +/// Lifetime of an invite when the admin names none. +pub const INVITE_DEFAULT_SECS: u64 = 7 * 24 * 60 * 60; +/// Longest lifetime an invite may be given. +pub const INVITE_MAX_SECS: u64 = 30 * 24 * 60 * 60; + +/// Check an invite's requested lifetime and use limit. The host applies it to +/// every invite, and `id world invite` applies it before dialing. +/// +/// # Errors +/// +/// Returns the refusal reason for a lifetime outside 1 second to 30 days, or a +/// use limit below one. +pub fn check_invite_bounds( + expires_in_secs: Option, + uses: Option, +) -> Result<(), &'static str> { + if expires_in_secs.is_some_and(|secs| secs == 0 || secs > INVITE_MAX_SECS) { + return Err("invite lifetime must be from 1 second to 30 days"); + } + if uses == Some(0) { + return Err("uses must be at least 1"); + } + Ok(()) +} + +pub(crate) fn invite_bounds( + expires_in_secs: Option, + uses: Option, + now_ms: u64, +) -> Result { + check_invite_bounds(expires_in_secs, uses)?; + let secs = expires_in_secs.unwrap_or(INVITE_DEFAULT_SECS); + Ok(CapabilityBounds { + expires_at: Some(now_ms.saturating_add(secs * 1000)), + uses, + }) +} + +/// Why an uploaded Wasm program was not installed. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum InstallError { + /// Module installation is unavailable in this service/build. + Disabled, + /// The supplied admin secret is missing or wrong. + Unauthorized, + /// Size or content hash validation failed. + InvalidUpload, + /// Raw artifacts are disabled by this world's source-only policy. + RawModuleDisabled, + /// Wasmtime rejected or could not instantiate the module. + InvalidModule, + /// The blob could not be pinned or the world actor refused activation. + Unavailable, +} + +/// One source file in a compile request. +#[derive(Debug, Deserialize)] +#[cfg_attr(not(feature = "sandbox"), allow(dead_code))] +pub(crate) struct CompileFile { + pub(crate) name: String, + pub(crate) content: String, +} + +/// A world plus the secret that may mint guest capabilities for it. +#[derive(Clone)] +pub struct WorldService { + pub(crate) world: WorldHandle, + pub(crate) admin_token: Option, + pub(crate) blobs: Option, + pub(crate) module_pin: Arc>>, + pub(crate) module_hash: Arc>>, + pub(crate) upload_slots: Arc, + pub(crate) module_dir: Option, + pub(crate) records: Option>, + pub(crate) compiler: Option>, + pub(crate) native: bool, + /// Raw artifact installs are refused; compiled source remains permitted. + pub(crate) source_only: bool, + pub(crate) runtime: crate::world_limits::RuntimeLimits, + pub(crate) mail: Option>, + pub(crate) outbox: Option>>, + pub(crate) profile_operation: Arc>, +} + +impl std::fmt::Debug for WorldService { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("WorldService") + .field( + "admin_token", + &self.admin_token.as_ref().map(|_| "[REDACTED]"), + ) + .finish_non_exhaustive() + } +} diff --git a/pkgs/id/src/world_ssh.rs b/pkgs/id/src/world_ssh.rs index 6b42241129..40ef1fd0ec 100644 --- a/pkgs/id/src/world_ssh.rs +++ b/pkgs/id/src/world_ssh.rs @@ -4,6 +4,16 @@ //! password is the join capability. Keystrokes become `input` frames and each //! `view` frame repaints the terminal, so an ordinary `ssh` client can play any //! world that presents a view. +//! +//! ## Input modes +//! +//! Raw keystrokes are the default. Prefixing the username with `cmd:` enters +//! command (line) mode, where each line is parsed as a command instead of +//! forwarded as an input keystroke: `/help`, `/quit`, `/input `, +//! `/records [prefix]`, `/documents [prefix]` and `/document ` (see +//! [`world_command`]). Prefixing the username with `explore:` enters a +//! read-only explore session, the only mode that supports public-key login. +//! See the SSH input-modes decision record. use std::{ collections::VecDeque, @@ -360,6 +370,7 @@ impl Handler for SshClient { lines: WorldLineBuffer::default(), commands: VecDeque::new(), records_prefix: None, + records_drained: 0, errored: false, }; let hub = self.hub.clone(); @@ -459,6 +470,9 @@ struct SshIo { commands: VecDeque, /// `Some(prefix)` while draining records pages from a `/records` command. records_prefix: Option>, + /// Cumulative bytes already rendered for the current `/records` drain, so a + /// large world's records are bounded across pages, not just per page. + records_drained: usize, errored: bool, } @@ -571,6 +585,7 @@ impl SessionIo for SshIo { } WorldCommand::Records { prefix } => { self.records_prefix = Some(prefix.clone()); + self.records_drained = 0; return Inbound::Text( json!({ "type": "records", "capability": self.capability, @@ -621,11 +636,34 @@ impl SessionIo for SshIo { ); } WorldCommand::Help => { - let help = "World chat: type a line to chat. Commands: /input , /records [prefix], /documents [prefix], /document , /help, /quit\r\nworld> "; + let help = "World chat: type a line to chat. Commands: /input , /records [prefix], /stats, /logs, /caps, /documents [prefix], /document , /help, /quit\r\nworld> "; if self.handle.data(self.channel, help).await.is_err() { return Inbound::Closed; } } + WorldCommand::Stats => { + return Inbound::Text( + json!({ "type": "info", "capability": self.capability }) + .to_string(), + ); + } + WorldCommand::Caps => { + return Inbound::Text( + json!({ "type": "caps", "capability": self.capability }) + .to_string(), + ); + } + WorldCommand::Logs => { + let text = "event tailing is not available in command mode; join in raw mode (no `cmd:` prefix) to see events live, or use `id world logs`\r\nworld> "; + if self + .handle + .data(self.channel, terminal_text(text)) + .await + .is_err() + { + return Inbound::Closed; + } + } WorldCommand::Message(message) => { let text = format!("{message}\r\nworld> "); if self.handle.data(self.channel, text).await.is_err() { @@ -717,13 +755,46 @@ impl SessionIo for SshIo { let sequence = value["sequence"].as_u64().unwrap_or_default(); let after = value["next_after"].as_str().map(str::to_owned); let text = render_records_value(records, sequence, after.as_deref()); - if let (Some(prefix), Some(after)) = (self.records_prefix.clone(), after) { + // Bound the whole drain, not just each page: a world with many + // records would otherwise keep fetching pages without limit. + self.records_drained = self.records_drained.saturating_add(text.len()); + let next = match (&self.records_prefix, &after) { + (Some(prefix), Some(after)) + if self.records_drained < MAX_RECORDS_TOTAL_BYTES => + { + Some((prefix.clone(), after.clone())) + } + _ => None, + }; + let truncated = after.is_some() && self.records_drained >= MAX_RECORDS_TOTAL_BYTES; + if let Some((prefix, after)) = next { self.commands .push_back(WorldCommand::RecordsContinue { prefix, after }); } else { self.records_prefix = None; } - format!("\r\n{}", terminal_text(&text)) + if truncated { + format!( + "\r\n{}\r\n{}", + terminal_text(&text), + terminal_text("[records truncated: too much output]\n") + ) + } else { + format!("\r\n{}", terminal_text(&text)) + } + } + Some("caps") => { + let report = value + .get("report") + .map(serde_json::to_string_pretty) + .transpose() + .unwrap_or_default() + .unwrap_or_else(|| "caps report unavailable".to_owned()); + format!("\r\n{report}\r\nworld> ") + } + Some("module_info") => { + let info = serde_json::to_string_pretty(&value).unwrap_or_default(); + format!("\r\n{info}\r\nworld> ") } _ => return true, }; @@ -733,6 +804,9 @@ impl SessionIo for SshIo { const MAX_WORLD_TERMINAL_LINE: usize = 1024; const MAX_RECORDS_TERMINAL_BYTES: usize = 384 * 1024; +/// Total rendered bytes a single `/records` drain may produce across all its +/// pages. Each page is additionally bounded by [`MAX_RECORDS_TERMINAL_BYTES`]. +const MAX_RECORDS_TOTAL_BYTES: usize = 1024 * 1024; const MAX_DOCUMENT_BYTES: usize = 64 * 1024; const MAX_DOCUMENT_LIST_BYTES: usize = 32 * 1024; const MAX_DOCUMENT_LIST_ITEMS: usize = 512; @@ -752,59 +826,29 @@ enum WorldCommand { prefix: Option, }, Document(String), + Stats, + Logs, + Caps, Help, Message(String), Quit, } fn world_command(line: &str) -> Option { - if line.is_empty() { - return None; - } - if line == "/help" { - return Some(WorldCommand::Help); - } - if line == "/quit" { - return Some(WorldCommand::Quit); - } - if line == "/records" || line.starts_with("/records ") { - let Some(prefix) = line.strip_prefix("/records") else { - return Some(WorldCommand::Message("usage: /records [prefix]".to_owned())); - }; - let prefix = prefix.trim(); - return Some(WorldCommand::Records { - prefix: (!prefix.is_empty()).then(|| prefix.to_owned()), - }); - } - if line == "/documents" || line.starts_with("/documents ") { - let Some(prefix) = line.strip_prefix("/documents") else { - return Some(WorldCommand::Message( - "usage: /documents [prefix]".to_owned(), - )); - }; - let prefix = prefix.trim(); - return Some(WorldCommand::Documents { - prefix: (!prefix.is_empty()).then(|| prefix.to_owned()), - }); - } - if let Some(name) = line.strip_prefix("/document ") { - if !name.is_empty() && name == name.trim() { - return Some(WorldCommand::Document(name.to_owned())); - } - return Some(WorldCommand::Message("usage: /document ".to_owned())); - } - if let Some(hex) = line.strip_prefix("/input ") { - if !hex.is_empty() && hex.len() % 2 == 0 && hex.bytes().all(|b| b.is_ascii_hexdigit()) { - return Some(WorldCommand::Input(hex.to_ascii_lowercase())); - } - return Some(WorldCommand::Message("usage: /input ".to_owned())); - } - if line.starts_with('/') { - return Some(WorldCommand::Message( - "unknown command; type /help".to_owned(), - )); - } - Some(WorldCommand::Chat(line.to_owned())) + use crate::world_line::{WorldLine, parse_line}; + Some(match parse_line(line)? { + WorldLine::Chat(text) => WorldCommand::Chat(text), + WorldLine::Input(hex) => WorldCommand::Input(hex), + WorldLine::Records { prefix } => WorldCommand::Records { prefix }, + WorldLine::Documents { prefix } => WorldCommand::Documents { prefix }, + WorldLine::Document(name) => WorldCommand::Document(name), + WorldLine::Stats => WorldCommand::Stats, + WorldLine::Logs { .. } => WorldCommand::Logs, + WorldLine::Caps => WorldCommand::Caps, + WorldLine::Help => WorldCommand::Help, + WorldLine::Quit => WorldCommand::Quit, + WorldLine::Message(message) => WorldCommand::Message(message), + }) } #[derive(Default)] @@ -2020,6 +2064,10 @@ mod tests { ); assert_eq!(world_command("/help"), Some(WorldCommand::Help)); assert_eq!(world_command("/quit"), Some(WorldCommand::Quit)); + assert_eq!(world_command("/stats"), Some(WorldCommand::Stats)); + assert_eq!(world_command("/caps"), Some(WorldCommand::Caps)); + assert_eq!(world_command("/logs"), Some(WorldCommand::Logs)); + assert_eq!(world_command("/logs 5"), Some(WorldCommand::Logs)); assert_eq!( world_command("/input nope"), Some(WorldCommand::Message("usage: /input ".into())) @@ -2058,6 +2106,38 @@ mod tests { assert!(text.len() <= MAX_RECORDS_TERMINAL_BYTES); } + /// The `/records` drain is bounded in total, not just per page: the per-page + /// cap is [`MAX_RECORDS_TERMINAL_BYTES`], but a world with many records must + /// also stop after [`MAX_RECORDS_TOTAL_BYTES`] across pages. + #[test] + fn the_records_drain_is_bounded_in_total_as_well_as_per_page() { + // A single page is truncated at the per-page cap, so a page never + // exceeds it... + let one_page = render_records(&records_of(4096), 1, None); + assert!( + one_page.len() <= MAX_RECORDS_TERMINAL_BYTES + 64, + "one page stays under the per-page cap: {}", + one_page.len() + ); + // ...and the whole drain has a larger, but still finite, total cap, so + // a many-page world stops instead of streaming without bound. + assert!( + MAX_RECORDS_TOTAL_BYTES > MAX_RECORDS_TERMINAL_BYTES, + "the total cap must exceed the per-page cap" + ); + assert!( + MAX_RECORDS_TOTAL_BYTES < usize::MAX / 4, + "the total cap must be finite" + ); + } + + #[cfg(test)] + fn records_of(count: usize) -> crate::world::Records { + (0..count) + .map(|i| (format!("key-{i:04}"), serde_json::json!({"n": i}))) + .collect() + } + async fn put_document(store: &iroh_blobs::api::Store, name: &str, bytes: Vec) { let outcome = store.blobs().add_bytes(bytes).await.unwrap(); store.tags().set(name, outcome.hash).await.unwrap();