use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
use serde::Serialize;
use serde_json::{json, Value};
use wasmtime::component::{Component, Linker};
use wasmtime::{Config, Engine, ResourceLimiter, Store};
use crate::capsule::{
any_grant_of_kind, is_read_only_method, network_grant_covers, CapabilityGrant, CapabilityKind,
CapsuleDenial, CapsuleId, CapsuleManifest, CapsuleUse, ResourceBudget,
};
use crate::error::{Result, RustyError};
use crate::journal::{EventDraft, Journal};
use crate::record::{sha256_hex, Effect, EventStatus, RunEventKind};
const NET_INSTANCE: &str = "rusty:capsule/net@0.1.0";
const CLOCK_INSTANCE: &str = "rusty:capsule/clock@0.1.0";
const EPOCH_TICK_MS: u64 = 5;
fn capability_for_import(name: &str) -> Option<CapabilityKind> {
match name {
NET_INSTANCE => Some(CapabilityKind::Network),
CLOCK_INSTANCE => Some(CapabilityKind::Clock),
_ => None,
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FetchRequest {
pub protocol: String,
pub host: String,
pub method: String,
pub path: String,
pub body: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FetchResponse {
pub status: u16,
pub body: String,
}
pub trait NetworkConnector: std::fmt::Debug + Send + Sync {
fn fetch(&self, request: &FetchRequest) -> std::result::Result<FetchResponse, String>;
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RecheckDenial {
pub policy_version: String,
pub detail: String,
}
pub trait GrantRecheck: std::fmt::Debug + Send + Sync {
fn recheck(&self, capsule_id: &CapsuleId, grant: &CapabilityGrant) -> Option<RecheckDenial>;
}
struct StoreLimits {
max_memory_bytes: Option<usize>,
}
impl ResourceLimiter for StoreLimits {
fn memory_growing(
&mut self,
_current: usize,
desired: usize,
_maximum: Option<usize>,
) -> std::result::Result<bool, wasmtime::Error> {
Ok(match self.max_memory_bytes {
Some(cap) => desired <= cap,
None => true,
})
}
fn table_growing(
&mut self,
_current: usize,
desired: usize,
_maximum: Option<usize>,
) -> std::result::Result<bool, wasmtime::Error> {
Ok(desired <= 100_000)
}
}
struct StoreData {
limiter: StoreLimits,
grants: Vec<CapabilityGrant>,
capsule_id: CapsuleId,
connector: Option<Arc<dyn NetworkConnector>>,
clock: Arc<dyn Fn() -> u64 + Send + Sync>,
recheck: Option<Arc<dyn GrantRecheck>>,
journal: Option<Journal>,
parent: Option<String>,
uses: Vec<CapsuleUse>,
denials: Vec<CapsuleDenial>,
}
impl StoreData {
fn journal_event(
&mut self,
kind: RunEventKind,
effect: Effect,
output: Value,
status: EventStatus,
) {
if let Some(journal) = &self.journal {
let mut draft = EventDraft::new(kind, effect).output(output).status(status);
if let Some(parent) = &self.parent {
draft = draft.parent(parent.clone());
}
self.parent = Some(journal.record(draft));
}
}
fn policy_recheck(&mut self, grant: CapabilityGrant) -> std::result::Result<(), String> {
let Some(recheck) = &self.recheck else {
return Ok(());
};
let Some(revocation) = recheck.recheck(&self.capsule_id, &grant) else {
return Ok(());
};
let denial = CapsuleDenial::scoped(
self.capsule_id.clone(),
grant,
format!(
"the grant was admitted but policy version `{}` no longer permits it — \
revocation takes effect at the next capability use: {}",
revocation.policy_version, revocation.detail
),
)
.with_policy_version(revocation.policy_version);
self.denials.push(denial.clone());
let detail = denial.detail.clone();
if let Ok(output) = serde_json::to_value(&denial) {
self.journal_event(
RunEventKind::CapsuleDenied,
Effect::Pure,
output,
EventStatus::Ok,
);
}
Err(format!("denied: {detail}"))
}
}
#[derive(Debug, Clone)]
pub struct CapsuleInvocation {
pub input: Value,
pub journal: Option<Journal>,
pub parent: Option<String>,
pub budget: ResourceBudget,
}
impl CapsuleInvocation {
pub fn new(input: Value) -> Self {
Self {
input,
journal: None,
parent: None,
budget: ResourceBudget::default(),
}
}
pub fn with_journal(mut self, journal: Journal, parent: Option<String>) -> Self {
self.journal = Some(journal);
self.parent = parent;
self
}
pub fn with_budget(mut self, budget: ResourceBudget) -> Self {
self.budget = budget;
self
}
}
#[derive(Debug)]
pub struct CapsuleOutcome {
pub output: Value,
pub fuel_consumed: u64,
pub uses: Vec<CapsuleUse>,
pub denials: Vec<CapsuleDenial>,
}
struct HostInner {
engine: Engine,
component: Component,
manifest: CapsuleManifest,
capsule_id: CapsuleId,
connector: Option<Arc<dyn NetworkConnector>>,
clock: Arc<dyn Fn() -> u64 + Send + Sync>,
recheck: Option<Arc<dyn GrantRecheck>>,
ticker_alive: Arc<AtomicBool>,
ticker_started: AtomicBool,
}
impl Drop for HostInner {
fn drop(&mut self) {
self.ticker_alive.store(false, Ordering::Relaxed);
}
}
#[derive(Clone)]
pub struct CapsuleHost {
inner: Arc<HostInner>,
}
impl std::fmt::Debug for CapsuleHost {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CapsuleHost")
.field("capsule", &self.inner.manifest.identity.name)
.field("capsule_id", &self.inner.capsule_id)
.finish()
}
}
impl CapsuleHost {
pub fn from_bytes(manifest: CapsuleManifest, bytes: impl AsRef<[u8]>) -> Result<Self> {
let bytes = bytes.as_ref();
let name = manifest.identity.name.clone();
let host_err = |msg: String| RustyError::Node(format!("capsule host '{name}': {msg}"));
manifest.validate()?;
let actual = sha256_hex(bytes);
if actual != manifest.build_digest {
return Err(host_err(format!(
"build digest mismatch: the manifest names {} but the artifact hashes to \
{actual} — a manifest is admitted against the bytes it was built from",
manifest.build_digest
)));
}
let mut config = Config::new();
config.consume_fuel(true);
config.epoch_interruption(true);
let engine =
Engine::new(&config).map_err(|e| host_err(format!("failed to create engine: {e}")))?;
let component = Component::new(&engine, bytes)
.map_err(|e| host_err(format!("failed to compile component: {e:#}")))?;
let exports_run = matches!(
component
.component_type()
.get_export(&engine, "run")
.map(|export| export.ty),
Some(wasmtime::component::types::ComponentItem::ComponentFunc(_))
);
if !exports_run {
return Err(host_err(
"the component does not export `run` — the declared world requires \
`run: func(input: string) -> result<string, string>`"
.into(),
));
}
let capsule_id = manifest.capsule_id()?;
Ok(Self {
inner: Arc::new(HostInner {
engine,
component,
manifest,
capsule_id,
connector: None,
clock: Arc::new(default_clock),
recheck: None,
ticker_alive: Arc::new(AtomicBool::new(true)),
ticker_started: AtomicBool::new(false),
}),
})
}
pub fn with_connector(mut self, connector: Arc<dyn NetworkConnector>) -> Self {
Arc::get_mut(&mut self.inner)
.expect("with_connector before the host is shared")
.connector = Some(connector);
self
}
pub fn with_grant_recheck(mut self, recheck: Arc<dyn GrantRecheck>) -> Self {
Arc::get_mut(&mut self.inner)
.expect("with_grant_recheck before the host is shared")
.recheck = Some(recheck);
self
}
pub fn with_clock(mut self, clock: impl Fn() -> u64 + Send + Sync + 'static) -> Self {
Arc::get_mut(&mut self.inner)
.expect("with_clock before the host is shared")
.clock = Arc::new(clock);
self
}
pub fn manifest(&self) -> &CapsuleManifest {
&self.inner.manifest
}
pub fn capsule_id(&self) -> &CapsuleId {
&self.inner.capsule_id
}
pub async fn invoke(&self, invocation: CapsuleInvocation) -> Result<CapsuleOutcome> {
let inner = Arc::clone(&self.inner);
let name = inner.manifest.identity.name.clone();
tokio::task::spawn_blocking(move || run_invocation(&inner, invocation))
.await
.map_err(|e| {
RustyError::Node(format!("capsule host '{name}': task join failed: {e}"))
})?
}
}
fn default_clock() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0)
}
fn run_invocation(inner: &HostInner, invocation: CapsuleInvocation) -> Result<CapsuleOutcome> {
let manifest = &inner.manifest;
let name = &manifest.identity.name;
let host_err = |msg: String| RustyError::Node(format!("capsule host '{name}': {msg}"));
let budget = manifest.budget.clamp(&invocation.budget);
let mut journal = invocation.journal;
let mut parent = invocation.parent;
for (import, _extern) in inner.component.component_type().imports(&inner.engine) {
match capability_for_import(import) {
Some(kind) if any_grant_of_kind(&manifest.capabilities, kind) => {}
Some(kind) => {
let denial = CapsuleDenial::unscoped(
inner.capsule_id.clone(),
kind,
format!(
"the component imports `{import}` but the manifest grants no \
`{kind:?}` capability — the import does not exist for this guest"
),
);
journal_capability_event(
&mut journal,
&mut parent,
RunEventKind::CapsuleDenied,
Effect::Pure,
&denial,
EventStatus::Ok,
);
return Err(host_err(format!("structural denial: {}", denial.detail)));
}
None => {
return Err(host_err(format!(
"the component imports `{import}`, which no supported world declares — \
fail closed rather than guess"
)));
}
}
}
let grants: Vec<CapabilityGrant> = manifest.capabilities.iter().cloned().collect();
let wants_network = any_grant_of_kind(&grants, CapabilityKind::Network);
if wants_network && inner.connector.is_none() {
return Err(host_err(
"the manifest grants `network` but the host was built without a connector — \
a granted egress path is explicit, never ambient"
.into(),
));
}
let mut store = Store::new(
&inner.engine,
StoreData {
limiter: StoreLimits {
max_memory_bytes: budget
.max_memory_bytes
.map(|bytes| bytes.try_into().unwrap_or(usize::MAX)),
},
grants: grants.clone(),
capsule_id: inner.capsule_id.clone(),
connector: inner.connector.clone(),
clock: Arc::clone(&inner.clock),
recheck: inner.recheck.clone(),
journal: journal.clone(),
parent: parent.clone(),
uses: Vec::new(),
denials: Vec::new(),
},
);
store.limiter(|s| &mut s.limiter);
let fuel_set = budget.fuel.unwrap_or(u64::MAX);
store.set_fuel(fuel_set).map_err(|e| {
host_err(format!(
"failed to set fuel (engine needs consume_fuel): {e}"
))
})?;
let deadline_ticks = match budget.wall_time_ms {
Some(ms) => {
ensure_ticker(inner);
(ms / EPOCH_TICK_MS).max(1)
}
None => u64::MAX,
};
store.set_epoch_deadline(deadline_ticks);
let mut linker = Linker::new(&inner.engine);
if wants_network {
linker
.instance(NET_INSTANCE)
.map_err(|e| host_err(format!("failed to define `{NET_INSTANCE}`: {e}")))?
.func_wrap(
"fetch",
|mut ctx: wasmtime::StoreContextMut<'_, StoreData>,
(protocol, host, method, path, body): (
String,
String,
String,
String,
Option<String>,
)| {
Ok((fetch_impl(&mut ctx, protocol, host, method, path, body),))
},
)
.map_err(|e| host_err(format!("failed to link `fetch`: {e}")))?;
}
if any_grant_of_kind(&grants, CapabilityKind::Clock) {
linker
.instance(CLOCK_INSTANCE)
.map_err(|e| host_err(format!("failed to define `{CLOCK_INSTANCE}`: {e}")))?
.func_wrap(
"now-millis",
|mut ctx: wasmtime::StoreContextMut<'_, StoreData>,
(): ()|
-> std::result::Result<(u64,), wasmtime::Error> {
Ok((now_millis_impl(&mut ctx).map_err(wasmtime::Error::msg)?,))
},
)
.map_err(|e| host_err(format!("failed to link `now-millis`: {e}")))?;
}
let input = serde_json::to_string(&invocation.input)?;
let started = Instant::now();
let invocation_effect = manifest
.effects
.iter()
.max()
.copied()
.unwrap_or(Effect::Pure);
let outcome = (|| -> std::result::Result<(Value, u64), String> {
let instance = linker
.instantiate(&mut store, &inner.component)
.map_err(|e| format!("instantiation failed: {e}"))?;
let run = instance
.get_typed_func::<(String,), (std::result::Result<String, String>,)>(&mut store, "run")
.map_err(|e| {
format!(
"bad `run` export (the world declares `run: func(input: string) -> \
result<string, string>`): {e}"
)
})?;
let (result,) = run
.call(&mut store, (input,))
.map_err(|e| format!("guest run trapped: {e}"))?;
let fuel_consumed = fuel_set.saturating_sub(store.get_fuel().unwrap_or(0));
let output =
result.map_err(|guest_err| format!("the guest returned an error: {guest_err}"))?;
if let Some(cap) = budget.max_output_bytes {
if output.len() as u64 > cap {
return Err(format!(
"guest output is {} bytes, over the {}-byte max_output_bytes budget",
output.len(),
cap
));
}
}
let parsed: Value = serde_json::from_str(&output)
.map_err(|e| format!("guest output is not valid JSON: {e}"))?;
Ok((parsed, fuel_consumed))
})();
let remaining_fuel = store.get_fuel().ok();
let data = store.into_data();
match outcome {
Ok((output, fuel_consumed)) => {
if let Some(journal) = &journal {
let mut draft = EventDraft::new(RunEventKind::WasmCall, invocation_effect)
.input(json!({
"capsule_id": inner.capsule_id,
"input": invocation.input,
}))
.output(json!({
"capsule_id": inner.capsule_id,
"output": output,
"fuel_consumed": fuel_consumed,
}));
if let Some(parent) = &parent {
draft = draft.parent(parent.clone());
}
journal.record(draft);
}
Ok(CapsuleOutcome {
output,
fuel_consumed,
uses: data.uses,
denials: data.denials,
})
}
Err(message) => {
let breach = if budget.fuel.is_some() && remaining_fuel == Some(0) {
Some("fuel")
} else if budget
.wall_time_ms
.is_some_and(|ms| started.elapsed() >= Duration::from_millis(ms))
{
Some("wall_time")
} else {
None
};
if let Some(journal) = &journal {
let mut output = json!({
"capsule_id": inner.capsule_id,
"error": message,
});
if let Some(breach) = breach {
output["budget_breach"] = json!(breach);
}
let mut draft = EventDraft::new(RunEventKind::WasmCall, invocation_effect)
.input(json!({
"capsule_id": inner.capsule_id,
"input": invocation.input,
}))
.output(output)
.status(EventStatus::Error);
if let Some(parent) = &parent {
draft = draft.parent(parent.clone());
}
journal.record(draft);
}
Err(host_err(message))
}
}
}
fn ensure_ticker(inner: &HostInner) {
if inner
.ticker_started
.compare_exchange(false, true, Ordering::Relaxed, Ordering::Relaxed)
.is_err()
{
return;
}
let engine = inner.engine.clone();
let alive = Arc::downgrade(&inner.ticker_alive);
std::thread::spawn(move || {
while let Some(alive) = alive.upgrade() {
std::thread::sleep(Duration::from_millis(EPOCH_TICK_MS));
if !alive.load(Ordering::Relaxed) {
break;
}
engine.increment_epoch();
}
});
}
fn fetch_impl(
ctx: &mut wasmtime::StoreContextMut<'_, StoreData>,
protocol: String,
host: String,
method: String,
path: String,
body: Option<String>,
) -> std::result::Result<String, String> {
let data = ctx.data_mut();
if !network_grant_covers(&data.grants, &protocol, &host, &method) {
let denial = CapsuleDenial::scoped(
data.capsule_id.clone(),
CapabilityGrant::Network {
hosts: vec![host.clone()],
protocols: vec![protocol.clone()],
methods: vec![method.clone()],
},
format!(
"fetch {method} {protocol}://{host}{path} names no granted network scope — \
the absent grant is `network` covering {method} {protocol}://{host}"
),
);
data.denials.push(denial.clone());
let detail = denial.detail.clone();
if let Ok(output) = serde_json::to_value(&denial) {
data.journal_event(
RunEventKind::CapsuleDenied,
Effect::Pure,
output,
EventStatus::Ok,
);
}
return Err(format!("denied: {detail}"));
}
data.policy_recheck(CapabilityGrant::Network {
hosts: vec![host.clone()],
protocols: vec![protocol.clone()],
methods: vec![method.clone()],
})?;
let request = FetchRequest {
protocol: protocol.clone(),
host: host.clone(),
method: method.clone(),
path: path.clone(),
body,
};
let connector = data
.connector
.clone()
.expect("the structural gate refuses network grants without a connector");
let outcome = connector.fetch(&request);
let effect = if is_read_only_method(&method) {
Effect::ReadOnly
} else {
Effect::NonIdempotent
};
let (response, status, guest_result) = match &outcome {
Ok(resp) => (
json!({ "status": resp.status, "body": resp.body }),
EventStatus::Ok,
Ok(resp.body.clone()),
),
Err(message) => (
json!({ "error": message }),
EventStatus::Error,
Err(format!("connector failed: {message}")),
),
};
let data = ctx.data_mut();
let use_record = CapsuleUse {
capsule_id: data.capsule_id.clone(),
capability: CapabilityKind::Network,
operation: "fetch".into(),
request: json!({
"protocol": protocol,
"host": host,
"method": method,
"path": path,
}),
response,
};
data.uses.push(use_record.clone());
if let Ok(output) = serde_json::to_value(&use_record) {
data.journal_event(RunEventKind::CapsuleCall, effect, output, status);
}
guest_result
}
fn now_millis_impl(
ctx: &mut wasmtime::StoreContextMut<'_, StoreData>,
) -> std::result::Result<u64, String> {
let data = ctx.data_mut();
data.policy_recheck(CapabilityGrant::Clock)?;
let millis = (data.clock)();
let use_record = CapsuleUse {
capsule_id: data.capsule_id.clone(),
capability: CapabilityKind::Clock,
operation: "now_millis".into(),
request: json!({}),
response: json!({ "millis": millis }),
};
data.uses.push(use_record.clone());
if let Ok(output) = serde_json::to_value(&use_record) {
data.journal_event(
RunEventKind::CapsuleCall,
Effect::ReadOnly,
output,
EventStatus::Ok,
);
}
Ok(millis)
}
fn journal_capability_event<T: Serialize>(
journal: &mut Option<Journal>,
parent: &mut Option<String>,
kind: RunEventKind,
effect: Effect,
payload: &T,
status: EventStatus,
) {
let Some(journal) = journal.as_ref() else {
return;
};
let Ok(output) = serde_json::to_value(payload) else {
return;
};
let mut draft = EventDraft::new(kind, effect).output(output).status(status);
if let Some(parent) = &parent {
draft = draft.parent(parent.clone());
}
*parent = Some(journal.record(draft));
}