Skip to main content

rusty_agent_runtime/
capsule.rs

1//! The capsule manifest contract (R0.9 Rusty Capsules, wave 1): the
2//! content-addressed declaration of what untrusted code may reach, and the
3//! journaled payloads that make its enforcement attributable.
4//!
5//! The design doc is `docs/capsules-design.md`. Its capsule rule governs
6//! everything here: **no code the runtime does not trust may reach the
7//! filesystem, the network, a secret, the clock, a model, or another tool
8//! unless its manifest declared that reach — and every capability use and
9//! every denied attempt is journaled, budgeted, and attributable to the
10//! exact manifest grant that allowed or refused it.** This module is the
11//! declaration half; the capability host (`capsule_host`, feature `wasm`)
12//! is the enforcement half; the registry (`rusty-agent-server`) is the
13//! resolution half.
14//!
15//! - [`CapsuleManifest`] — the serde-versioned, golden-pinned declaration:
16//!   identity, version, build digest, declared interface (a WIT world
17//!   reference), the closed [`Effect`] classes the capsule may produce,
18//!   the [`CapabilityGrant`] set (the whole reach), and the
19//!   [`ResourceBudget`]. Identity is integrity: [`derive_capsule_id`] is
20//!   `sha256` over the canonical content (the one hashing primitive shared
21//!   with artifact references, journal heads, and candidate ids), so two
22//!   builds of the same declaration converge on one [`CapsuleId`] and a
23//!   tampered manifest fails its own address.
24//! - [`CapabilityGrant`] — the closed set of grants. The host maps grants
25//!   onto which of the declared world's imports it links: an ungranted
26//!   capability is an import that does not exist (structural denial, not a
27//!   runtime check), and a grant narrower than the world is enforced
28//!   inside the host's import implementation. A manifest with an empty
29//!   `capabilities` set — the default — describes a pure-compute guest,
30//!   which is precisely what `wasm_node`'s ABI v0 already executes.
31//! - [`CapsuleResolution`] / [`CapsuleUse`] / [`CapsuleDenial`] — the
32//!   journaled payloads. Resolutions carry the registry's answer to a
33//!   `RunManifest` capsule pin; uses carry a granted operation's summaries;
34//!   denials name **the manifest grant that was absent**, so a refusal is
35//!   attributable to a declaration, not to a stack trace. They journal
36//!   through the additive [`RunEventKind`](crate::record::RunEventKind)
37//!   variants `CapsuleResolved` / `CapsuleCall` / `CapsuleDenied` — the
38//!   same evolution rule every variant since R0.6's `EffectReceipt`
39//!   followed; old journals keep deserializing.
40//! - [`CapsuleOverlay`] / [`intersect_grants`] / [`grants_beyond`] (R0.9
41//!   wave 2) — the tenant-overlay contract: a grant ceiling whose
42//!   application is structural intersection (no code path computes
43//!   union), plus the advisory widening signal the server's Cedar
44//!   overlay decision consumes. Wave 2 also extended the journaled
45//!   payloads additively: resolutions pin the deciding policy version,
46//!   the applied overlays, the effective grants, and the clamped budget;
47//!   denials pin the policy version whose verdict refused the attempt.
48//!
49//! Golden-file tests under `tests/golden/` pin every wire shape in this
50//! module; any accidental contract drift fails CI.
51
52use std::collections::BTreeSet;
53
54use serde::{Deserialize, Serialize};
55use serde_json::Value;
56
57use crate::error::{Result, RustyError};
58use crate::record::{canonicalize_value, sha256_hex, CapsuleVersion, Effect};
59
60fn invalid(message: impl Into<String>) -> RustyError {
61    // Manifest validation is a contract check at a state boundary; the
62    // invalid-update class covers it rather than growing the error
63    // taxonomy for one module (the memory/learn convention).
64    RustyError::InvalidUpdate(message.into())
65}
66
67/// The one WIT world R0.9 wave 1 instantiates against:
68/// `rusty:capsule/world@0.1.0`. Worlds evolve additively — a later world
69/// version may add imports or tighten types; old world versions keep
70/// instantiating — so this constant joins a list rather than being
71/// replaced when a second world lands.
72pub const WORLD_V1: &str = "rusty:capsule/world@0.1.0";
73
74/// The world versions the host admits, oldest first. Wave 1 ships exactly
75/// one (the design's open question 6 owns the evolution rule for the
76/// second).
77pub const SUPPORTED_WORLDS: &[&str] = &[WORLD_V1];
78
79/// A content-addressed capsule identity: lowercase hex SHA-256 over the
80/// manifest's canonical content ([`derive_capsule_id`]).
81///
82/// Transparent newtype so the type system — not convention — keeps
83/// capsule ids distinct from memory addresses, candidate ids, and other
84/// digest strings (the [`CandidateId`](crate::learn::CandidateId)
85/// precedent).
86#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
87#[serde(transparent)]
88pub struct CapsuleId(String);
89
90impl CapsuleId {
91    /// The hex digest.
92    pub fn as_str(&self) -> &str {
93        &self.0
94    }
95}
96
97impl std::fmt::Display for CapsuleId {
98    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99        f.write_str(&self.0)
100    }
101}
102
103impl From<String> for CapsuleId {
104    /// Wrap a digest the caller already trusts — rehydration from storage,
105    /// a resolution's answer. Minting ids from content is
106    /// [`derive_capsule_id`]'s job alone; nothing here re-verifies.
107    fn from(digest: String) -> Self {
108        Self(digest)
109    }
110}
111
112/// The capsule's name plus human-facing metadata. Not the address — the
113/// address is derived from the whole declaration, never minted from the
114/// name.
115#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
116pub struct CapsuleIdentity {
117    /// The capsule's name — the key `RunManifest::capsules` pins versions
118    /// under, and half of the registry's `(identity, version)` mapping.
119    pub name: String,
120
121    /// Human-facing description. Metadata, not identity: it travels inside
122    /// the content address but is read by no enforcement point.
123    #[serde(default, skip_serializing_if = "Option::is_none")]
124    pub description: Option<String>,
125}
126
127/// The declared graph/node interface: the WIT world the component was
128/// built against, plus the typed input/output the world exports.
129#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
130pub struct CapsuleInterface {
131    /// The WIT world reference (`rusty:capsule/world@x.y.z`). Admission
132    /// accepts exactly the versions in [`SUPPORTED_WORLDS`] — an unknown
133    /// world is a capsule from another interface era, refused rather than
134    /// guessed at.
135    pub world: String,
136
137    /// JSON Schema (draft 2020-12, the dialect
138    /// [`crate::durable::ArtifactContract::schema`] pinned in R0.7)
139    /// describing the guest's input. Wave 1 pins the shape — the
140    /// declaration is part of the content address, so schema drift is
141    /// visible to every consumer — and the host enforces the structural
142    /// half (the canonical ABI itself types the export); full draft-2020-12
143    /// validation lands with the wave that adopts a validator, the same
144    /// staging `ArtifactContract::schema` documented.
145    #[serde(default, skip_serializing_if = "Option::is_none")]
146    pub input_schema: Option<Value>,
147
148    /// JSON Schema describing the guest's output, same staging as
149    /// [`CapsuleInterface::input_schema`]. The host's output gate enforces
150    /// well-formed JSON and `max_output_bytes` in wave 1.
151    #[serde(default, skip_serializing_if = "Option::is_none")]
152    pub output_schema: Option<Value>,
153}
154
155/// Filesystem access mode of a [`CapabilityGrant::Filesystem`] grant.
156#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
157#[serde(rename_all = "snake_case")]
158pub enum FilesystemMode {
159    /// Read-only access under the granted prefixes.
160    Read,
161    /// Read and write access under the granted prefixes.
162    ReadWrite,
163}
164
165/// One capability grant: the closed set of things a capsule may reach.
166/// Serialized with internal tagging (`{"kind": "network", …}`) so the
167/// grant's kind is part of the manifest's content address — a filesystem
168/// grant and a network grant that happened to carry alike lists must
169/// never converge (the [`crate::learn::CandidateContent`] rule).
170///
171/// The set is the whole reach. Grants narrower than the world (a
172/// `network` grant naming one hostname) are enforced inside the host's
173/// import implementation: the import exists, but the host matches the
174/// grant's scope before anything executes, and a mismatch is a journaled
175/// [`CapsuleDenial`].
176#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
177#[serde(tag = "kind", rename_all = "snake_case")]
178pub enum CapabilityGrant {
179    /// WASI-style preopened directories scoped to the granted path
180    /// prefixes; nothing else on the filesystem exists for the guest.
181    Filesystem {
182        /// Absolute path prefixes the guest may touch.
183        paths: Vec<String>,
184        /// Read-only or read-write.
185        mode: FilesystemMode,
186    },
187
188    /// Outbound calls through the host-side connector, matched on
189    /// host + protocol + method before any socket opens (Deno's scoping).
190    Network {
191        /// Hostnames the guest may call.
192        hosts: Vec<String>,
193        /// Protocols the guest may speak (`https`, `http`, `wss`, …).
194        protocols: Vec<String>,
195        /// HTTP methods the guest may use (`GET`, `POST`, …).
196        methods: Vec<String>,
197    },
198
199    /// Secret *handles* — names in the server's secret store. The guest
200    /// receives opaque tokens; the host resolves them at use and the bytes
201    /// never enter guest linear memory.
202    Secret {
203        /// The handles the guest may name.
204        handles: Vec<String>,
205    },
206
207    /// Tools in the run's `ToolRegistry`. The guest's tool-call import is
208    /// linked, dispatching through the host's tool executor — so the
209    /// effect kernel's admission path applies unchanged.
210    Tool {
211        /// The tool names the guest may call.
212        tools: Vec<String>,
213    },
214
215    /// Models the deployment serves. Usage accrues to the capsule's
216    /// budget.
217    Model {
218        /// The model names the guest may call.
219        models: Vec<String>,
220    },
221
222    /// Read the wall/monotonic clock through the host's clock import. A
223    /// grant rather than ambient authority because the clock is a
224    /// determinism boundary: a guest that can read wall time can branch on
225    /// evidence the journal does not hold.
226    Clock,
227}
228
229/// The capability class a [`CapabilityGrant`] (or an import of the
230/// declared world) belongs to. Closed enum — the host maps world imports
231/// onto kinds exhaustively, and an import naming no known kind fails
232/// closed at instantiation.
233#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
234#[serde(rename_all = "snake_case")]
235pub enum CapabilityKind {
236    /// The filesystem.
237    Filesystem,
238    /// The network.
239    Network,
240    /// The secret store.
241    Secret,
242    /// Another tool.
243    Tool,
244    /// A model.
245    Model,
246    /// The clock.
247    Clock,
248}
249
250impl CapabilityGrant {
251    /// The capability class of this grant.
252    pub fn capability_kind(&self) -> CapabilityKind {
253        match self {
254            CapabilityGrant::Filesystem { .. } => CapabilityKind::Filesystem,
255            CapabilityGrant::Network { .. } => CapabilityKind::Network,
256            CapabilityGrant::Secret { .. } => CapabilityKind::Secret,
257            CapabilityGrant::Tool { .. } => CapabilityKind::Tool,
258            CapabilityGrant::Model { .. } => CapabilityKind::Model,
259            CapabilityGrant::Clock => CapabilityKind::Clock,
260        }
261    }
262
263    /// The minimum [`Effect`] severity exercising this grant implies. The
264    /// manifest's declared `effects` must top out at or above it — a
265    /// capsule whose declared classes reach only `ReadOnly` is refused at
266    /// admission when its grants imply writes (the declaration and the
267    /// grants must agree; the host enforces the stricter of the two).
268    ///
269    /// The conservative readings are deliberate: a filesystem write is not
270    /// idempotency-keyed, a tool call defaults to the class the runtime
271    /// cannot prove otherwise, and a model call is `NonIdempotent`
272    /// everywhere else in the taxonomy.
273    pub fn implied_effect(&self) -> Effect {
274        match self {
275            CapabilityGrant::Filesystem { mode, .. } => match mode {
276                FilesystemMode::Read => Effect::ReadOnly,
277                FilesystemMode::ReadWrite => Effect::NonIdempotent,
278            },
279            CapabilityGrant::Network { methods, .. } => {
280                if methods.iter().all(|m| is_read_only_method(m)) {
281                    Effect::ReadOnly
282                } else {
283                    Effect::NonIdempotent
284                }
285            }
286            CapabilityGrant::Secret { .. } => Effect::ReadOnly,
287            CapabilityGrant::Tool { .. } => Effect::NonIdempotent,
288            CapabilityGrant::Model { .. } => Effect::NonIdempotent,
289            CapabilityGrant::Clock => Effect::ReadOnly,
290        }
291    }
292}
293
294/// `true` when `method` is a read-only HTTP method (no write semantics).
295/// Shared by the grant's implied-effect computation and the host's
296/// per-call effect classification of a granted fetch.
297pub fn is_read_only_method(method: &str) -> bool {
298    matches!(method, "GET" | "HEAD" | "OPTIONS")
299}
300
301/// `true` when any `network` grant in `grants` covers this exact call —
302/// union semantics across grants (a grant set is the whole reach, so any
303/// single covering grant permits). Called by the host's connector before
304/// anything executes; a `false` answer is a journaled denial, never a
305/// silent refusal.
306pub fn network_grant_covers<'a>(
307    grants: impl IntoIterator<Item = &'a CapabilityGrant>,
308    protocol: &str,
309    host: &str,
310    method: &str,
311) -> bool {
312    grants.into_iter().any(|grant| match grant {
313        CapabilityGrant::Network {
314            hosts,
315            protocols,
316            methods,
317        } => {
318            hosts.iter().any(|h| h == host)
319                && protocols.iter().any(|p| p == protocol)
320                && methods.iter().any(|m| m == method)
321        }
322        _ => false,
323    })
324}
325
326/// `true` when any grant in `grants` belongs to `kind` — the structural
327/// question (should the import exist at all), distinct from the scoped
328/// question [`network_grant_covers`] answers.
329pub fn any_grant_of_kind<'a>(
330    grants: impl IntoIterator<Item = &'a CapabilityGrant>,
331    kind: CapabilityKind,
332) -> bool {
333    grants
334        .into_iter()
335        .any(|grant| grant.capability_kind() == kind)
336}
337
338// --------------------------------------------------------------------- //
339// Tenant overlays (R0.9 wave 2)
340// --------------------------------------------------------------------- //
341
342/// A tenant overlay (R0.9 wave 2): the grant ceiling an operator attaches
343/// to a tenant, further restricting what capsules in that tenant may do.
344/// The contract half of the overlay plane lives here (golden-pinned, like
345/// every wire shape); the authorization half — *who may author* an
346/// overlay, against which capsules — is the server's Cedar decision
347/// (`rusty-server/src/capsule_policy.rs`, feature `capsules`).
348///
349/// The narrowing rule is enforced twice, and the structural half comes
350/// first: applying an overlay is [`intersect_grants`], a set intersection
351/// that mechanically cannot add a grant; Cedar then decides the overlay's
352/// legality. Policy decides legality; arithmetic decides narrowing.
353#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
354pub struct CapsuleOverlay {
355    /// The overlay's name — its registry key within the tenant.
356    pub name: String,
357
358    /// The capsule identity names the overlay applies to. `None` (the
359    /// sparse wire shape) means every capsule in the tenant; an empty list
360    /// is refused at validation for the same reason an empty grant scope
361    /// is — an overlay applying to nothing carries no meaning worth
362    /// storing.
363    #[serde(default, skip_serializing_if = "Option::is_none")]
364    pub targets: Option<Vec<String>>,
365
366    /// The grant ceiling. The effective capability set of a manifest
367    /// under this overlay is `intersect_grants(manifest, ceiling)` —
368    /// never the manifest's grants alone and never the ceiling's alone.
369    pub capabilities: BTreeSet<CapabilityGrant>,
370
371    /// Human-facing context (why the ceiling exists). Metadata, read by
372    /// no enforcement point.
373    #[serde(default, skip_serializing_if = "Option::is_none")]
374    pub note: Option<String>,
375}
376
377impl CapsuleOverlay {
378    /// Contract validation, run at every attach boundary: the name and
379    /// any targets are in the identifier grammar, and every ceiling grant
380    /// passes the manifest's per-grant rule.
381    pub fn validate(&self) -> Result<()> {
382        validate_token("overlay name", &self.name)?;
383        if let Some(targets) = &self.targets {
384            if targets.is_empty() {
385                return Err(invalid(
386                    "overlay targets: the list is empty — an overlay applying to no capsule \
387                     carries no meaning (omit the field to target every capsule)",
388                ));
389            }
390            for target in targets {
391                validate_token("overlay target", target)?;
392            }
393        }
394        for grant in &self.capabilities {
395            validate_grant(grant)?;
396        }
397        Ok(())
398    }
399
400    /// `true` when this overlay governs the capsule named `capsule_name`
401    /// (its identity name, the `RunManifest` pin key).
402    pub fn applies_to(&self, capsule_name: &str) -> bool {
403        self.targets
404            .as_ref()
405            .is_none_or(|targets| targets.iter().any(|target| target == capsule_name))
406    }
407
408    /// The effective grant set of `manifest_grants` under this overlay —
409    /// [`intersect_grants`], the only composition this wave defines.
410    pub fn effective_grants(
411        &self,
412        manifest_grants: &BTreeSet<CapabilityGrant>,
413    ) -> BTreeSet<CapabilityGrant> {
414        intersect_grants(manifest_grants, &self.capabilities)
415    }
416}
417
418/// The overlay narrowing rule, reduced to one function (R0.9 wave 2):
419/// the effective capability set of a manifest under an overlay is the
420/// **intersection** of the two grant sets — every grant in the result is
421/// a narrowing of one grant from *each* side, computed field-wise per
422/// capability kind.
423///
424/// This is the only composition of two grant sets anywhere in the wave,
425/// and it is deliberately written so union is unrepresentable: a reviewer
426/// verifying "overlays cannot widen" reads this function and nothing
427/// else. Grants of different kinds never meet (a network grant and a
428/// clock grant share no member), and a same-kind pair whose scopes share
429/// nothing contributes nothing — an overlay naming only hosts the
430/// manifest never granted *removes* the capability rather than adding
431/// the hosts. A grant whose intersection empties one scope list drops
432/// out entirely: a `network` grant with no common hosts permits no call,
433/// so carrying it would be the empty-scope lie manifests refuse at
434/// validation.
435pub fn intersect_grants(
436    manifest_grants: &BTreeSet<CapabilityGrant>,
437    overlay_grants: &BTreeSet<CapabilityGrant>,
438) -> BTreeSet<CapabilityGrant> {
439    /// The shared scope items of two lists, sorted and deduplicated — the
440    /// canonical form the manifest contract already pins.
441    fn common(a: &[String], b: &[String]) -> Vec<String> {
442        let mut out: Vec<String> = a.iter().filter(|item| b.contains(item)).cloned().collect();
443        out.sort();
444        out.dedup();
445        out
446    }
447    let mut out = BTreeSet::new();
448    for manifest_grant in manifest_grants {
449        for overlay_grant in overlay_grants {
450            let shared = match (manifest_grant, overlay_grant) {
451                (
452                    CapabilityGrant::Filesystem {
453                        paths: manifest_paths,
454                        mode: manifest_mode,
455                    },
456                    CapabilityGrant::Filesystem {
457                        paths: overlay_paths,
458                        mode: overlay_mode,
459                    },
460                ) => {
461                    let paths = common(manifest_paths, overlay_paths);
462                    // Read is the narrower mode (declaration order), so
463                    // `min` can only keep or tighten access.
464                    (!paths.is_empty()).then(|| CapabilityGrant::Filesystem {
465                        paths,
466                        mode: (*manifest_mode).min(*overlay_mode),
467                    })
468                }
469                (
470                    CapabilityGrant::Network {
471                        hosts: manifest_hosts,
472                        protocols: manifest_protocols,
473                        methods: manifest_methods,
474                    },
475                    CapabilityGrant::Network {
476                        hosts: overlay_hosts,
477                        protocols: overlay_protocols,
478                        methods: overlay_methods,
479                    },
480                ) => {
481                    let hosts = common(manifest_hosts, overlay_hosts);
482                    let protocols = common(manifest_protocols, overlay_protocols);
483                    let methods = common(manifest_methods, overlay_methods);
484                    (!hosts.is_empty() && !protocols.is_empty() && !methods.is_empty()).then_some(
485                        CapabilityGrant::Network {
486                            hosts,
487                            protocols,
488                            methods,
489                        },
490                    )
491                }
492                (
493                    CapabilityGrant::Secret {
494                        handles: manifest_handles,
495                    },
496                    CapabilityGrant::Secret {
497                        handles: overlay_handles,
498                    },
499                ) => {
500                    let handles = common(manifest_handles, overlay_handles);
501                    (!handles.is_empty()).then_some(CapabilityGrant::Secret { handles })
502                }
503                (
504                    CapabilityGrant::Tool {
505                        tools: manifest_tools,
506                    },
507                    CapabilityGrant::Tool {
508                        tools: overlay_tools,
509                    },
510                ) => {
511                    let tools = common(manifest_tools, overlay_tools);
512                    (!tools.is_empty()).then_some(CapabilityGrant::Tool { tools })
513                }
514                (
515                    CapabilityGrant::Model {
516                        models: manifest_models,
517                    },
518                    CapabilityGrant::Model {
519                        models: overlay_models,
520                    },
521                ) => {
522                    let models = common(manifest_models, overlay_models);
523                    (!models.is_empty()).then_some(CapabilityGrant::Model { models })
524                }
525                (CapabilityGrant::Clock, CapabilityGrant::Clock) => Some(CapabilityGrant::Clock),
526                _ => None,
527            };
528            if let Some(grant) = shared {
529                out.insert(grant);
530            }
531        }
532    }
533    out
534}
535
536/// The overlay grants asking for reach no manifest grant declares (R0.9
537/// wave 2) — the advisory widening signal the server's Cedar overlay
538/// decision consumes. Coverage is decided per capability kind against
539/// the union of the manifest's scope items of that kind: a manifest
540/// granting host A in one grant and host B in another covers an overlay
541/// grant naming both, and a kind the manifest never granted leaves every
542/// overlay grant of that kind beyond.
543///
544/// This is a *signal*, never an enforcement — it exists so an operator's
545/// Cedar policy can refuse overlays that ask for more than a manifest
546/// declared. The enforcement is [`intersect_grants`], exact and pairwise,
547/// and it needs no signal: hand-crafting an overlay past the policy
548/// plane still cannot widen the effective set.
549pub fn grants_beyond(
550    overlay_grants: &BTreeSet<CapabilityGrant>,
551    manifest_grants: &BTreeSet<CapabilityGrant>,
552) -> BTreeSet<CapabilityGrant> {
553    /// `true` when every item of `needed` appears in some same-kind
554    /// manifest grant's corresponding scope list.
555    fn covered<'a>(
556        needed: &[String],
557        offered: impl Iterator<Item = &'a Vec<String>> + Clone,
558    ) -> bool {
559        needed
560            .iter()
561            .all(|item| offered.clone().any(|list| list.contains(item)))
562    }
563    overlay_grants
564        .iter()
565        .filter(|overlay_grant| {
566            let same_kind = manifest_grants
567                .iter()
568                .filter(|m| m.capability_kind() == overlay_grant.capability_kind());
569            let covered = match overlay_grant {
570                CapabilityGrant::Filesystem { paths, mode } => {
571                    let mode_covered = same_kind.clone().any(|m| match m {
572                        CapabilityGrant::Filesystem {
573                            mode: manifest_mode,
574                            ..
575                        } => manifest_mode >= mode,
576                        _ => false,
577                    });
578                    mode_covered
579                        && covered(
580                            paths,
581                            same_kind.filter_map(|m| match m {
582                                CapabilityGrant::Filesystem { paths, .. } => Some(paths),
583                                _ => None,
584                            }),
585                        )
586                }
587                CapabilityGrant::Network {
588                    hosts,
589                    protocols,
590                    methods,
591                } => {
592                    let networks = same_kind.filter_map(|m| match m {
593                        CapabilityGrant::Network {
594                            hosts,
595                            protocols,
596                            methods,
597                        } => Some((hosts, protocols, methods)),
598                        _ => None,
599                    });
600                    covered(hosts, networks.clone().map(|(h, _, _)| h))
601                        && covered(protocols, networks.clone().map(|(_, p, _)| p))
602                        && covered(methods, networks.map(|(_, _, m)| m))
603                }
604                CapabilityGrant::Secret { handles } => covered(
605                    handles,
606                    same_kind.filter_map(|m| match m {
607                        CapabilityGrant::Secret { handles } => Some(handles),
608                        _ => None,
609                    }),
610                ),
611                CapabilityGrant::Tool { tools } => covered(
612                    tools,
613                    same_kind.filter_map(|m| match m {
614                        CapabilityGrant::Tool { tools } => Some(tools),
615                        _ => None,
616                    }),
617                ),
618                CapabilityGrant::Model { models } => covered(
619                    models,
620                    same_kind.filter_map(|m| match m {
621                        CapabilityGrant::Model { models } => Some(models),
622                        _ => None,
623                    }),
624                ),
625                CapabilityGrant::Clock => same_kind.count() > 0,
626            };
627            !covered
628        })
629        .cloned()
630        .collect()
631}
632
633/// The resource budget a capsule invocation may consume. Every field is
634/// optional on the wire; `None` means the enclosing run's own budget
635/// bounds apply — never an invented default, per the `AgentBudget`
636/// convention.
637#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
638pub struct ResourceBudget {
639    /// CPU budget in Wasmtime fuel units (deterministic, replay-stable).
640    #[serde(default, skip_serializing_if = "Option::is_none")]
641    pub fuel: Option<u64>,
642
643    /// Linear-memory cap in bytes.
644    #[serde(default, skip_serializing_if = "Option::is_none")]
645    pub max_memory_bytes: Option<u64>,
646
647    /// Wall-time bound in milliseconds, enforced by epoch interruption.
648    #[serde(default, skip_serializing_if = "Option::is_none")]
649    pub wall_time_ms: Option<u64>,
650
651    /// Token budget for model usage (evidence-grade, matching
652    /// `AgentBudget`).
653    #[serde(default, skip_serializing_if = "Option::is_none")]
654    pub max_tokens: Option<u64>,
655
656    /// Cost budget in USD for model usage (evidence-grade `f64`, matching
657    /// `AgentBudget`).
658    #[serde(default, skip_serializing_if = "Option::is_none")]
659    pub max_cost_usd: Option<f64>,
660
661    /// Upper bound on the guest's result payload in bytes, checked before
662    /// the host accepts the output.
663    #[serde(default, skip_serializing_if = "Option::is_none")]
664    pub max_output_bytes: Option<u64>,
665}
666
667impl ResourceBudget {
668    /// Field-wise minimum against an enclosing scope's ceiling: the
669    /// effective budget is never wider than what either layer declared.
670    /// `None` in one layer means that layer imposes no bound, so the other
671    /// layer's bound (if any) applies. This is the admission clamp the
672    /// design names — capsule budget ≤ the run's budgets ≤ tenant quotas
673    /// — reduced to its wave-1 pair; the quota layers compose the same
674    /// way when they arrive.
675    pub fn clamp(&self, ceiling: &ResourceBudget) -> ResourceBudget {
676        fn min_opt<T: Ord + Copy>(a: Option<T>, b: Option<T>) -> Option<T> {
677            match (a, b) {
678                (Some(x), Some(y)) => Some(x.min(y)),
679                (a, b) => a.or(b),
680            }
681        }
682        ResourceBudget {
683            fuel: min_opt(self.fuel, ceiling.fuel),
684            max_memory_bytes: min_opt(self.max_memory_bytes, ceiling.max_memory_bytes),
685            wall_time_ms: min_opt(self.wall_time_ms, ceiling.wall_time_ms),
686            max_tokens: min_opt(self.max_tokens, ceiling.max_tokens),
687            max_cost_usd: match (self.max_cost_usd, ceiling.max_cost_usd) {
688                (Some(a), Some(b)) => Some(a.min(b)),
689                (a, b) => a.or(b),
690            },
691            max_output_bytes: min_opt(self.max_output_bytes, ceiling.max_output_bytes),
692        }
693    }
694
695    fn validate(&self) -> Result<()> {
696        if let Some(cost) = self.max_cost_usd {
697            if !cost.is_finite() || cost < 0.0 {
698                return Err(invalid(format!(
699                    "resource budget: max_cost_usd must be finite and non-negative, got {cost}"
700                )));
701            }
702        }
703        Ok(())
704    }
705}
706
707/// The capsule manifest: one serde-versioned struct, additive-evolution
708/// only, golden pinned — the same discipline as `MemoryRecord` and
709/// `Candidate`.
710///
711/// The address ([`derive_capsule_id`]) covers the **canonical** content:
712/// every grant's scope lists are sorted and deduplicated, and the grant
713/// set itself has set semantics (`BTreeSet`), so two declarations that
714/// agree on substance converge on one id regardless of the order their
715/// authors happened to write lists in. Every other field exists because a
716/// downstream enforcement point needs it (see the field docs).
717#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
718pub struct CapsuleManifest {
719    /// Capsule name plus human-facing metadata. Not the address.
720    pub identity: CapsuleIdentity,
721
722    /// The exact version string — the value the R0.7 [`CapsuleVersion`]
723    /// pin already records in `RunManifest::capsules`. The registry
724    /// resolves `(identity, version)` → [`CapsuleId`] at admission, so the
725    /// version string stays the wire pin (additive, no migration) while
726    /// the journaled resolution reaches the content address.
727    pub version: String,
728
729    /// SHA-256 (lowercase hex) of the guest artifact — the `.wasm`
730    /// component bytes. Admission recomputes it; a manifest naming bytes
731    /// it was not built from does not load. The digest, not the version
732    /// string, is what the host caches compiled components under.
733    pub build_digest: String,
734
735    /// The declared interface: the WIT world reference plus the typed
736    /// input/output the world exports.
737    pub interface: CapsuleInterface,
738
739    /// The closed [`Effect`] classes the capsule may produce. Must agree
740    /// with the capability grants (see [`CapsuleManifest::validate`]):
741    /// declaring less than the grants imply is refused; declaring more is
742    /// harmless — the host grants nothing the capabilities do not name.
743    pub effects: BTreeSet<Effect>,
744
745    /// The capability grants. The set is the whole reach; the empty set
746    /// (the default) is the pure-compute guest.
747    pub capabilities: BTreeSet<CapabilityGrant>,
748
749    /// The declared resource budget. Clamped at admission against the
750    /// enclosing run's bounds ([`ResourceBudget::clamp`]); the host
751    /// enforces the result.
752    #[serde(default, skip_serializing_if = "ResourceBudget::is_empty")]
753    pub budget: ResourceBudget,
754}
755
756impl ResourceBudget {
757    /// `true` when no bound is declared (the sparse wire shape).
758    pub fn is_empty(&self) -> bool {
759        self.fuel.is_none()
760            && self.max_memory_bytes.is_none()
761            && self.wall_time_ms.is_none()
762            && self.max_tokens.is_none()
763            && self.max_cost_usd.is_none()
764            && self.max_output_bytes.is_none()
765    }
766}
767
768/// The content address of a capsule manifest: `sha256` over the canonical
769/// serialization of its content — the one hashing primitive shared with
770/// artifact references, journal heads, and candidate ids, over the
771/// canonical `serde_json` serialization
772/// [`crate::record::PayloadRef::content_hash`] also relies on (payload maps
773/// are key-sorted before hashing; see `canonicalize_value`).
774pub fn derive_capsule_id(manifest: &CapsuleManifest) -> Result<CapsuleId> {
775    let canonical = manifest.canonicalized();
776    Ok(CapsuleId(sha256_hex(&serde_json::to_vec(&canonical)?)))
777}
778
779impl CapsuleManifest {
780    /// The manifest's content address.
781    pub fn capsule_id(&self) -> Result<CapsuleId> {
782        derive_capsule_id(self)
783    }
784
785    /// The canonical form the content address covers: every scope list
786    /// sorted and deduplicated, so list order carries no identity, and the
787    /// interface schemas key-sorted ([`canonicalize_value`]), so the map
788    /// backend a build ends up with carries no identity either.
789    fn canonicalized(&self) -> CapsuleManifest {
790        fn sorted(mut list: Vec<String>) -> Vec<String> {
791            list.sort();
792            list.dedup();
793            list
794        }
795        let interface = CapsuleInterface {
796            world: self.interface.world.clone(),
797            input_schema: self.interface.input_schema.as_ref().map(canonicalize_value),
798            output_schema: self
799                .interface
800                .output_schema
801                .as_ref()
802                .map(canonicalize_value),
803        };
804        let capabilities = self
805            .capabilities
806            .iter()
807            .map(|grant| match grant {
808                CapabilityGrant::Filesystem { paths, mode } => CapabilityGrant::Filesystem {
809                    paths: sorted(paths.clone()),
810                    mode: *mode,
811                },
812                CapabilityGrant::Network {
813                    hosts,
814                    protocols,
815                    methods,
816                } => CapabilityGrant::Network {
817                    hosts: sorted(hosts.clone()),
818                    protocols: sorted(protocols.clone()),
819                    methods: sorted(methods.clone()),
820                },
821                CapabilityGrant::Secret { handles } => CapabilityGrant::Secret {
822                    handles: sorted(handles.clone()),
823                },
824                CapabilityGrant::Tool { tools } => CapabilityGrant::Tool {
825                    tools: sorted(tools.clone()),
826                },
827                CapabilityGrant::Model { models } => CapabilityGrant::Model {
828                    models: sorted(models.clone()),
829                },
830                CapabilityGrant::Clock => CapabilityGrant::Clock,
831            })
832            .collect();
833        CapsuleManifest {
834            identity: self.identity.clone(),
835            version: self.version.clone(),
836            build_digest: self.build_digest.clone(),
837            interface,
838            effects: self.effects.clone(),
839            capabilities,
840            budget: self.budget.clone(),
841        }
842    }
843
844    /// Contract validation, run at every admission boundary (host
845    /// construction, registry write, resolution).
846    ///
847    /// Refuses: an unknown world version; a malformed build digest;
848    /// grant scope lists that are empty or carry out-of-grammar tokens; a
849    /// declared effect set that tops out below what the grants imply; a
850    /// non-finite or negative cost budget. What passes here is a
851    /// declaration the host can enforce without further interpretation.
852    pub fn validate(&self) -> Result<()> {
853        validate_token("capsule name", &self.identity.name)?;
854        validate_token("capsule version", &self.version)?;
855        if !SUPPORTED_WORLDS.contains(&self.interface.world.as_str()) {
856            return Err(invalid(format!(
857                "unsupported WIT world `{}` (this release instantiates: {})",
858                self.interface.world,
859                SUPPORTED_WORLDS.join(", ")
860            )));
861        }
862        let digest_ok = self.build_digest.len() == 64
863            && self
864                .build_digest
865                .chars()
866                .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase());
867        if !digest_ok {
868            return Err(invalid(format!(
869                "build digest `{}` is not a lowercase hex SHA-256",
870                self.build_digest
871            )));
872        }
873        if self.effects.is_empty() {
874            return Err(invalid(
875                "declared effects are empty — even a pure-compute capsule declares `pure`",
876            ));
877        }
878        for grant in &self.capabilities {
879            validate_grant(grant)?;
880        }
881        let declared_max = self.effects.iter().max().copied().unwrap_or(Effect::Pure);
882        let implied_max = self
883            .capabilities
884            .iter()
885            .map(CapabilityGrant::implied_effect)
886            .max()
887            .unwrap_or(Effect::Pure);
888        if declared_max < implied_max {
889            return Err(invalid(format!(
890                "declared effects top out at {declared_max:?} but the capability grants imply \
891                 {implied_max:?} — the declaration and the grants must agree"
892            )));
893        }
894        self.budget.validate()?;
895        Ok(())
896    }
897}
898
899/// Identifier grammar for names that become registry keys, pin names, and
900/// path segments: `[A-Za-z0-9._-]`, 1..=128 chars (the policy registry's
901/// version rule).
902fn validate_token(what: &str, value: &str) -> Result<()> {
903    let valid = !value.is_empty()
904        && value.len() <= 128
905        && value
906            .chars()
907            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.'));
908    if !valid {
909        return Err(invalid(format!(
910            "invalid {what} `{value}` (allowed: [A-Za-z0-9._-], 1..=128 chars)"
911        )));
912    }
913    Ok(())
914}
915
916/// Scope-list validation per grant variant: every list non-empty (an
917/// empty scope is a grant that permits nothing — refuse it at the
918/// boundary rather than carrying a meaningless grant), every token in
919/// grammar.
920fn validate_grant(grant: &CapabilityGrant) -> Result<()> {
921    fn non_empty<'a>(what: &str, list: &'a [String]) -> Result<&'a [String]> {
922        if list.is_empty() {
923            return Err(invalid(format!("{what}: the scope list is empty")));
924        }
925        Ok(list)
926    }
927    match grant {
928        CapabilityGrant::Filesystem { paths, .. } => {
929            for path in non_empty("filesystem grant", paths)? {
930                if !path.starts_with('/') || path.split('/').any(|seg| seg == "..") {
931                    return Err(invalid(format!(
932                        "filesystem grant path `{path}` must be absolute and free of `..`"
933                    )));
934                }
935            }
936        }
937        CapabilityGrant::Network {
938            hosts,
939            protocols,
940            methods,
941        } => {
942            for host in non_empty("network grant hosts", hosts)? {
943                let valid = !host.is_empty()
944                    && host.len() <= 253
945                    && host
946                        .chars()
947                        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-'));
948                if !valid {
949                    return Err(invalid(format!(
950                        "network grant host `{host}` (allowed: [A-Za-z0-9.-], 1..=253 chars)"
951                    )));
952                }
953            }
954            for protocol in non_empty("network grant protocols", protocols)? {
955                let valid =
956                    !protocol.is_empty() && protocol.chars().all(|c| c.is_ascii_lowercase());
957                if !valid {
958                    return Err(invalid(format!(
959                        "network grant protocol `{protocol}` (lowercase ASCII, e.g. `https`)"
960                    )));
961                }
962            }
963            for method in non_empty("network grant methods", methods)? {
964                let valid = !method.is_empty() && method.chars().all(|c| c.is_ascii_uppercase());
965                if !valid {
966                    return Err(invalid(format!(
967                        "network grant method `{method}` (uppercase ASCII, e.g. `GET`)"
968                    )));
969                }
970            }
971        }
972        CapabilityGrant::Secret { handles } => {
973            for handle in non_empty("secret grant", handles)? {
974                validate_token("secret handle", handle)?;
975            }
976        }
977        CapabilityGrant::Tool { tools } => {
978            for tool in non_empty("tool grant", tools)? {
979                validate_token("tool name", tool)?;
980            }
981        }
982        CapabilityGrant::Model { models } => {
983            for model in non_empty("model grant", models)? {
984                validate_token("model name", model)?;
985            }
986        }
987        CapabilityGrant::Clock => {}
988    }
989    Ok(())
990}
991
992/// A journaled registry resolution (R0.9 wave 1): the answer to one
993/// `RunManifest` capsule pin, recorded as the output of a
994/// [`RunEventKind::CapsuleResolved`](crate::record::RunEventKind::CapsuleResolved)
995/// event at admission. This is the link that lets a checkpoint's version
996/// *string* pin reach the content *address*: header pin → journaled
997/// resolution → receipt.
998///
999/// Wave 2 (Cedar, overlays, budget composition) extended the payload
1000/// additively: the four optional fields are absent — on the wire and in
1001/// old journals — whenever the admission ran without the policy plane
1002/// (a build without the feature, a tenant with no active policy, no
1003/// overlays, no budget bounds), which is exactly the wave-1 shape.
1004#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1005pub struct CapsuleResolution {
1006    /// The pin's name (the `RunManifest::capsules` key — the capsule's
1007    /// identity name).
1008    pub name: String,
1009
1010    /// The pinned version string.
1011    pub version: CapsuleVersion,
1012
1013    /// The content address the registry resolved the pin to.
1014    pub capsule_id: CapsuleId,
1015
1016    /// The build digest the resolved manifest declares — what the host
1017    /// will recompute against the artifact bytes before instantiating.
1018    pub build_digest: String,
1019
1020    /// The Cedar policy version this admission was decided under (R0.9
1021    /// wave 2): the tenant's active policy version at resolve time,
1022    /// pinned so a later audit can answer "which policy permitted this"
1023    /// without reconstructing history. `None` when no policy was active.
1024    #[serde(default, skip_serializing_if = "Option::is_none")]
1025    pub policy_version: Option<String>,
1026
1027    /// The tenant overlays applied at admission (R0.9 wave 2), sorted by
1028    /// name. `None` when none applied.
1029    #[serde(default, skip_serializing_if = "Option::is_none")]
1030    pub overlays: Option<Vec<String>>,
1031
1032    /// The effective grant set after overlay intersection (R0.9 wave 2)
1033    /// — what the host may actually link, always a subset of the
1034    /// manifest's declared grants ([`intersect_grants`]). Present exactly
1035    /// when an overlay applied.
1036    #[serde(default, skip_serializing_if = "Option::is_none")]
1037    pub effective_grants: Option<BTreeSet<CapabilityGrant>>,
1038
1039    /// The budget after clamping against the enclosing run's bounds and
1040    /// the deployment's tenant ceiling (R0.9 wave 2), present exactly
1041    /// when the clamp changed the declared budget — the journaled
1042    /// evidence of the wave's budget composition.
1043    #[serde(default, skip_serializing_if = "Option::is_none")]
1044    pub clamped_budget: Option<ResourceBudget>,
1045}
1046
1047/// A journaled capability use (R0.9 wave 1): one granted import call,
1048/// recorded as the output of a
1049/// [`RunEventKind::CapsuleCall`](crate::record::RunEventKind::CapsuleCall)
1050/// event. Summaries, not transcripts: the request carries the matched
1051/// scope (protocol, host, method, path) and the response the status and
1052/// body — the body is the guest's own data, and the journal's inline/artifact
1053/// split applies when it is large.
1054#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1055pub struct CapsuleUse {
1056    /// The capsule that exercised the capability.
1057    pub capsule_id: CapsuleId,
1058
1059    /// The capability class of the import that was called.
1060    pub capability: CapabilityKind,
1061
1062    /// The operation within the capability (`fetch`, `now_millis`).
1063    pub operation: String,
1064
1065    /// The request summary — for `fetch`: `{protocol, host, method, path}`
1066    /// (never the body: request bodies are the capsule's business, and
1067    /// keeping them out of the use record keeps evidence lean).
1068    pub request: Value,
1069
1070    /// The response summary — for `fetch`: `{status, body}`; for
1071    /// `now_millis`: `{millis}`.
1072    pub response: Value,
1073}
1074
1075/// A journaled capability denial (R0.9 wave 1): one refused attempt,
1076/// recorded as the output of a
1077/// [`RunEventKind::CapsuleDenied`](crate::record::RunEventKind::CapsuleDenied)
1078/// event.
1079///
1080/// The payload exists so the denial is **attributable**: it names the
1081/// capsule, the capability class, and the exact grant that was absent —
1082/// the grant that would have permitted the attempt. Two shapes:
1083///
1084/// - **Structural** ([`CapsuleDenial::unscoped`]): the guest probed an
1085///   import its manifest grants never linked. The absent grant's scope
1086///   lists are empty — no grant at any scope existed, so none can be
1087///   named. (Empty scopes are refused in manifests by
1088///   [`CapsuleManifest::validate`]; in a denial they carry the "no scope
1089///   at all" meaning.)
1090/// - **Scoped** ([`CapsuleDenial::scoped`]): the guest called a linked
1091///   import outside its scope. The absent grant names the scope that was
1092///   missing — granted host A, attempted host B, so the absent grant is
1093///   `network` scoped to host B.
1094#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1095pub struct CapsuleDenial {
1096    /// The capsule whose attempt was refused.
1097    pub capsule_id: CapsuleId,
1098
1099    /// The capability class that was absent.
1100    pub capability: CapabilityKind,
1101
1102    /// The grant that would have permitted the attempt.
1103    pub absent_grant: CapabilityGrant,
1104
1105    /// Human-facing context: what was attempted, against which granted
1106    /// scope.
1107    pub detail: String,
1108
1109    /// The Cedar policy version whose verdict refused this attempt (R0.9
1110    /// wave 2). Present on authorization refusals — an admission refused
1111    /// by policy and a revoked grant denied at its next use (the
1112    /// revocation edge: the denial is journaled against the *new* policy
1113    /// version, not the version the capsule was admitted under). Absent
1114    /// on wave-1 scope denials, which are the manifest's own verdict and
1115    /// carry no policy context.
1116    #[serde(default, skip_serializing_if = "Option::is_none")]
1117    pub policy_version: Option<String>,
1118}
1119
1120impl CapsuleDenial {
1121    /// The structural denial: the capability class is absent entirely (the
1122    /// import does not exist in the guest's instantiated world).
1123    pub fn unscoped(
1124        capsule_id: CapsuleId,
1125        capability: CapabilityKind,
1126        detail: impl Into<String>,
1127    ) -> Self {
1128        let absent_grant = match capability {
1129            CapabilityKind::Filesystem => CapabilityGrant::Filesystem {
1130                paths: Vec::new(),
1131                mode: FilesystemMode::Read,
1132            },
1133            CapabilityKind::Network => CapabilityGrant::Network {
1134                hosts: Vec::new(),
1135                protocols: Vec::new(),
1136                methods: Vec::new(),
1137            },
1138            CapabilityKind::Secret => CapabilityGrant::Secret {
1139                handles: Vec::new(),
1140            },
1141            CapabilityKind::Tool => CapabilityGrant::Tool { tools: Vec::new() },
1142            CapabilityKind::Model => CapabilityGrant::Model { models: Vec::new() },
1143            CapabilityKind::Clock => CapabilityGrant::Clock,
1144        };
1145        Self {
1146            capsule_id,
1147            capability,
1148            absent_grant,
1149            detail: detail.into(),
1150            policy_version: None,
1151        }
1152    }
1153
1154    /// The scoped denial: the import exists, but the attempt fell outside
1155    /// every grant's scope. `absent_grant` names the scope that was
1156    /// missing.
1157    pub fn scoped(
1158        capsule_id: CapsuleId,
1159        absent_grant: CapabilityGrant,
1160        detail: impl Into<String>,
1161    ) -> Self {
1162        Self {
1163            capsule_id,
1164            capability: absent_grant.capability_kind(),
1165            absent_grant,
1166            detail: detail.into(),
1167            policy_version: None,
1168        }
1169    }
1170
1171    /// Pin the Cedar policy version whose verdict produced this denial
1172    /// (R0.9 wave 2 — see the field docs).
1173    pub fn with_policy_version(mut self, version: impl Into<String>) -> Self {
1174        self.policy_version = Some(version.into());
1175        self
1176    }
1177}
1178
1179#[cfg(test)]
1180mod tests {
1181    use super::*;
1182    use serde_json::json;
1183
1184    fn manifest() -> CapsuleManifest {
1185        CapsuleManifest {
1186            identity: CapsuleIdentity {
1187                name: "researcher".into(),
1188                description: None,
1189            },
1190            version: "1.4.0".into(),
1191            build_digest: sha256_hex(b"component-bytes"),
1192            interface: CapsuleInterface {
1193                world: WORLD_V1.into(),
1194                input_schema: None,
1195                output_schema: None,
1196            },
1197            effects: BTreeSet::from([Effect::ReadOnly]),
1198            capabilities: BTreeSet::new(),
1199            budget: ResourceBudget::default(),
1200        }
1201    }
1202
1203    #[test]
1204    fn content_address_converges_and_detects_tampering() {
1205        let id_a = derive_capsule_id(&manifest()).unwrap();
1206        // Scope-list order carries no identity.
1207        let mut reordered = manifest();
1208        reordered.capabilities.insert(CapabilityGrant::Network {
1209            hosts: vec!["b.example".into(), "a.example".into()],
1210            protocols: vec!["https".into()],
1211            methods: vec!["GET".into()],
1212        });
1213        reordered.effects.insert(Effect::NonIdempotent);
1214        let mut same = reordered.clone();
1215        same.capabilities.insert(CapabilityGrant::Network {
1216            hosts: vec!["a.example".into(), "b.example".into(), "a.example".into()],
1217            protocols: vec!["https".into()],
1218            methods: vec!["GET".into()],
1219        });
1220        assert_eq!(
1221            derive_capsule_id(&reordered).unwrap(),
1222            derive_capsule_id(&same).unwrap()
1223        );
1224        // A tampered manifest fails its own address.
1225        let mut tampered = manifest();
1226        tampered.version = "9.9.9".into();
1227        assert_ne!(derive_capsule_id(&tampered).unwrap(), id_a);
1228    }
1229
1230    #[test]
1231    fn validation_rejects_grants_above_declared_effects() {
1232        let mut m = manifest();
1233        m.capabilities.insert(CapabilityGrant::Tool {
1234            tools: vec!["search".into()],
1235        });
1236        // Declared effects top out at ReadOnly; a tool grant implies
1237        // NonIdempotent.
1238        let err = m.validate().unwrap_err();
1239        assert!(err.to_string().contains("must agree"), "got: {err}");
1240        m.effects.insert(Effect::NonIdempotent);
1241        m.validate().unwrap();
1242    }
1243
1244    #[test]
1245    fn validation_rejects_empty_effects_and_bad_worlds() {
1246        let mut m = manifest();
1247        m.effects.clear();
1248        assert!(m.validate().is_err());
1249        let mut m = manifest();
1250        m.interface.world = "rusty:capsule/world@9.9.9".into();
1251        assert!(m.validate().is_err());
1252        let mut m = manifest();
1253        m.build_digest = "DEADBEEF".into();
1254        assert!(m.validate().is_err());
1255    }
1256
1257    #[test]
1258    fn network_matching_is_exact_and_scoped() {
1259        let grants = [CapabilityGrant::Network {
1260            hosts: vec!["api.example".into()],
1261            protocols: vec!["https".into()],
1262            methods: vec!["GET".into()],
1263        }];
1264        assert!(network_grant_covers(&grants, "https", "api.example", "GET"));
1265        assert!(!network_grant_covers(
1266            &grants,
1267            "https",
1268            "evil.example",
1269            "GET"
1270        ));
1271        assert!(!network_grant_covers(&grants, "http", "api.example", "GET"));
1272        assert!(!network_grant_covers(
1273            &grants,
1274            "https",
1275            "api.example",
1276            "POST"
1277        ));
1278        assert!(any_grant_of_kind(&grants, CapabilityKind::Network));
1279        assert!(!any_grant_of_kind(&grants, CapabilityKind::Clock));
1280    }
1281
1282    #[test]
1283    fn budget_clamp_takes_the_field_wise_minimum() {
1284        let declared = ResourceBudget {
1285            fuel: Some(100),
1286            wall_time_ms: Some(5000),
1287            ..Default::default()
1288        };
1289        let ceiling = ResourceBudget {
1290            fuel: Some(50),
1291            max_output_bytes: Some(1024),
1292            ..Default::default()
1293        };
1294        let clamped = declared.clamp(&ceiling);
1295        assert_eq!(clamped.fuel, Some(50));
1296        assert_eq!(clamped.wall_time_ms, Some(5000));
1297        assert_eq!(clamped.max_output_bytes, Some(1024));
1298        assert!(clamped.max_memory_bytes.is_none());
1299    }
1300
1301    #[test]
1302    fn denial_payloads_name_the_absent_grant() {
1303        let id = CapsuleId::from("ab".repeat(32));
1304        let structural = CapsuleDenial::unscoped(id.clone(), CapabilityKind::Network, "probe");
1305        assert_eq!(structural.capability, CapabilityKind::Network);
1306        match &structural.absent_grant {
1307            CapabilityGrant::Network { hosts, .. } => assert!(hosts.is_empty()),
1308            other => panic!("expected network grant, got {other:?}"),
1309        }
1310        let scoped = CapsuleDenial::scoped(
1311            id,
1312            CapabilityGrant::Network {
1313                hosts: vec!["evil.example".into()],
1314                protocols: vec!["https".into()],
1315                methods: vec!["GET".into()],
1316            },
1317            "granted api.example, attempted evil.example",
1318        );
1319        assert_eq!(scoped.capability, CapabilityKind::Network);
1320        let value = serde_json::to_value(&scoped).unwrap();
1321        assert_eq!(value["absent_grant"]["hosts"], json!(["evil.example"]));
1322        // Wave-1 scope denials carry no policy context; the field is
1323        // absent from the wire (additive wave-2 evolution).
1324        assert!(value.get("policy_version").is_none());
1325        let pinned = scoped.with_policy_version("cedar-0123456789ab");
1326        let value = serde_json::to_value(&pinned).unwrap();
1327        assert_eq!(
1328            value["policy_version"],
1329            json!("cedar-0123456789ab"),
1330            "authorization refusals pin the deciding policy version"
1331        );
1332    }
1333
1334    #[test]
1335    fn intersection_is_pairwise_and_cannot_widen() {
1336        let net = |hosts: &[&str]| CapabilityGrant::Network {
1337            hosts: hosts.iter().map(|h| h.to_string()).collect(),
1338            protocols: vec!["https".into()],
1339            methods: vec!["GET".into()],
1340        };
1341        let manifest = BTreeSet::from([net(&["a.example", "b.example"]), CapabilityGrant::Clock]);
1342        // An overlay hand-crafted to *widen*: it names a host the
1343        // manifest never granted and drops the clock.
1344        let overlay = BTreeSet::from([net(&["b.example", "evil.example"])]);
1345        let effective = intersect_grants(&manifest, &overlay);
1346        // The only survivor is the shared host; the ungranted host adds
1347        // nothing and the uncovered clock grant vanishes.
1348        assert_eq!(effective, BTreeSet::from([net(&["b.example"])]));
1349        // Every returned grant is a narrowing of a grant on each side —
1350        // the property the whole wave rests on, stated as an assertion.
1351        for grant in &effective {
1352            match grant {
1353                CapabilityGrant::Network {
1354                    hosts,
1355                    protocols,
1356                    methods,
1357                } => {
1358                    assert!(hosts.iter().all(|h| ["b.example"].contains(&h.as_str())));
1359                    assert_eq!(protocols, &vec!["https".to_string()]);
1360                    assert_eq!(methods, &vec!["GET".to_string()]);
1361                }
1362                other => panic!("unexpected grant survived: {other:?}"),
1363            }
1364        }
1365        // Disjoint scopes remove the capability entirely rather than
1366        // carrying an empty-scope grant.
1367        let disjoint = BTreeSet::from([net(&["c.example"])]);
1368        assert!(intersect_grants(&manifest, &disjoint).is_empty());
1369        // Kinds never mix: a clock ceiling does not revive an ungranted
1370        // network capability, and vice versa.
1371        assert!(intersect_grants(
1372            &BTreeSet::from([CapabilityGrant::Clock]),
1373            &BTreeSet::from([net(&["a.example"])]),
1374        )
1375        .is_empty());
1376    }
1377
1378    #[test]
1379    fn intersection_combines_scope_fields_and_modes() {
1380        // Filesystem modes narrow to the stricter of the two; scope lists
1381        // intersect item-wise.
1382        let manifest = BTreeSet::from([CapabilityGrant::Filesystem {
1383            paths: vec!["/data".into(), "/tmp".into()],
1384            mode: FilesystemMode::ReadWrite,
1385        }]);
1386        let overlay = BTreeSet::from([CapabilityGrant::Filesystem {
1387            paths: vec!["/data".into()],
1388            mode: FilesystemMode::Read,
1389        }]);
1390        let effective = intersect_grants(&manifest, &overlay);
1391        assert_eq!(
1392            effective,
1393            BTreeSet::from([CapabilityGrant::Filesystem {
1394                paths: vec!["/data".into()],
1395                mode: FilesystemMode::Read,
1396            }])
1397        );
1398        // Network scoping is conjunctive across fields: sharing hosts but
1399        // not methods yields no grant.
1400        let manifest = BTreeSet::from([CapabilityGrant::Network {
1401            hosts: vec!["a.example".into()],
1402            protocols: vec!["https".into()],
1403            methods: vec!["POST".into()],
1404        }]);
1405        let overlay = BTreeSet::from([CapabilityGrant::Network {
1406            hosts: vec!["a.example".into()],
1407            protocols: vec!["https".into()],
1408            methods: vec!["GET".into()],
1409        }]);
1410        assert!(intersect_grants(&manifest, &overlay).is_empty());
1411    }
1412
1413    #[test]
1414    fn grants_beyond_flags_only_uncovered_reach() {
1415        let net = |hosts: &[&str], methods: &[&str]| CapabilityGrant::Network {
1416            hosts: hosts.iter().map(|h| h.to_string()).collect(),
1417            protocols: vec!["https".into()],
1418            methods: methods.iter().map(|m| m.to_string()).collect(),
1419        };
1420        let manifest = BTreeSet::from([net(&["a.example"], &["GET"]), CapabilityGrant::Clock]);
1421        // Coverage is the union of same-kind scope items: two manifest
1422        // grants together cover an overlay naming both hosts.
1423        let manifest = manifest
1424            .into_iter()
1425            .chain([net(&["b.example"], &["GET"])])
1426            .collect();
1427        let within = BTreeSet::from([net(&["a.example", "b.example"], &["GET"])]);
1428        assert!(grants_beyond(&within, &manifest).is_empty());
1429        // A new host, a new method, and a kind the manifest never granted
1430        // are all beyond.
1431        let beyond = BTreeSet::from([
1432            net(&["a.example", "evil.example"], &["GET"]),
1433            net(&["a.example"], &["POST"]),
1434            CapabilityGrant::Secret {
1435                handles: vec!["api-key".into()],
1436            },
1437        ]);
1438        let flagged = grants_beyond(&beyond, &manifest);
1439        assert_eq!(flagged.len(), 3);
1440        // But the clock and the in-scope network grant are covered.
1441        let covered = BTreeSet::from([CapabilityGrant::Clock, net(&["a.example"], &["GET"])]);
1442        assert!(grants_beyond(&covered, &manifest).is_empty());
1443    }
1444
1445    #[test]
1446    fn overlay_validation_and_targeting() {
1447        let overlay = CapsuleOverlay {
1448            name: "narrow-research".into(),
1449            targets: Some(vec!["researcher".into()]),
1450            capabilities: BTreeSet::from([CapabilityGrant::Clock]),
1451            note: None,
1452        };
1453        overlay.validate().unwrap();
1454        assert!(overlay.applies_to("researcher"));
1455        assert!(!overlay.applies_to("planner"));
1456        let tenant_wide = CapsuleOverlay {
1457            name: "tenant-wide".into(),
1458            targets: None,
1459            capabilities: BTreeSet::from([CapabilityGrant::Clock]),
1460            note: None,
1461        };
1462        tenant_wide.validate().unwrap();
1463        assert!(tenant_wide.applies_to("anything"));
1464        // An empty target list is refused (meaningless), as is an empty
1465        // grant scope.
1466        let mut bad = tenant_wide.clone();
1467        bad.targets = Some(Vec::new());
1468        assert!(bad.validate().is_err());
1469        let mut bad = tenant_wide.clone();
1470        bad.capabilities = BTreeSet::from([CapabilityGrant::Secret {
1471            handles: Vec::new(),
1472        }]);
1473        assert!(bad.validate().is_err());
1474        let mut bad = tenant_wide;
1475        bad.name = "has/slash".into();
1476        assert!(bad.validate().is_err());
1477    }
1478}