|
| 1 | +// SPDX-License-Identifier: MPL-2.0 |
| 2 | +// Copyright (c) 2026 Jonathan D.A. Jewell <j.d.a.jewell@open.ac.uk> |
| 3 | +// |
| 4 | +//! Load-time enforcement gate — the Phase 3 slice (runtime-side |
| 5 | +//! enforcement, issue #51). |
| 6 | +//! |
| 7 | +//! Build-time verification (`tw build` self-verify, `tw link`) trusts |
| 8 | +//! whoever ran the build. This crate moves the trust boundary to the |
| 9 | +//! LOADER: a [`VerifiedModule`] is a witness type whose only |
| 10 | +//! constructors are [`gate_module`] / [`gate_link_graph`], which run |
| 11 | +//! the full typed-wasm verifier stack over the raw bytes — structural |
| 12 | +//! validation, L7/L10 ownership/linearity, L2 carrier bounds + access |
| 13 | +//! typing, L13 region-import consistency, and (for graphs) cross-module |
| 14 | +//! `SchemaSub` certification. Instantiation adapters accept only |
| 15 | +//! `&VerifiedModule`, so an unverified or violating module cannot reach |
| 16 | +//! a runtime through this crate's API at all. |
| 17 | +//! |
| 18 | +//! The gate is runtime-agnostic: it consumes bytes and returns a |
| 19 | +//! witness + [`GateReport`]. The `wasmi-runtime` feature provides an |
| 20 | +//! in-process adapter (pure Rust, CI-testable); a wasmtime adapter is |
| 21 | +//! the documented follow-up and needs nothing from the gate beyond |
| 22 | +//! what `wasmi::instantiate_verified` already uses. |
| 23 | +
|
| 24 | +use thiserror::Error; |
| 25 | +use typed_wasm_verify::{ |
| 26 | + verify_access_sites_from_module, verify_access_typing_from_module, verify_from_module, |
| 27 | + verify_link_graph, verify_region_imports_from_module, AccessSiteError, CompatCertificate, |
| 28 | + RegionImportsError, VerifyError, |
| 29 | +}; |
| 30 | + |
| 31 | +/// Why the gate refused a module (first failing layer reported). |
| 32 | +#[derive(Debug, Error)] |
| 33 | +pub enum GateError { |
| 34 | + /// Not decodable as wasm at all, or an L7/L10/L13-negative |
| 35 | + /// ownership violation (see the inner error). |
| 36 | + #[error("ownership/linearity verification failed: {0}")] |
| 37 | + Ownership(#[from] VerifyError), |
| 38 | + |
| 39 | + /// L2 carrier bounds violations (`typedwasm.regions` / |
| 40 | + /// `typedwasm.access-sites` internal consistency). |
| 41 | + #[error("L2 access-site bounds violations: {0:?}")] |
| 42 | + AccessSites(Vec<AccessSiteError>), |
| 43 | + |
| 44 | + /// L2 access-typing violations: a pinned instruction is not the |
| 45 | + /// right memory op at the right offset for its claimed field. |
| 46 | + #[error("L2 access-typing violations: {0:?}")] |
| 47 | + AccessTyping(Vec<String>), |
| 48 | + |
| 49 | + /// L13 region-import violations — module-local inconsistency, or |
| 50 | + /// (in a link graph) unresolved producers / schema disagreement. |
| 51 | + #[error("L13 region-import violations: {0:?}")] |
| 52 | + RegionImports(Vec<RegionImportsError>), |
| 53 | +} |
| 54 | + |
| 55 | +/// What the gate established about a module it passed. |
| 56 | +#[derive(Debug, Clone, Default)] |
| 57 | +pub struct GateReport { |
| 58 | + /// Pinned access sites whose instruction-level typing was checked. |
| 59 | + pub typed_sites_checked: u32, |
| 60 | + /// Declared-only (unpinned) access sites — counted, not checked. |
| 61 | + pub declared_only_sites: u32, |
| 62 | + /// Cross-module certificates this module participates in as the |
| 63 | + /// consumer (link-graph gate only; empty for single-module gates). |
| 64 | + pub certificates: Vec<CompatCertificate>, |
| 65 | +} |
| 66 | + |
| 67 | +/// Witness that `bytes` passed the gate. The field is private and the |
| 68 | +/// only constructors run the verifier stack — possession of a |
| 69 | +/// `VerifiedModule` IS the proof of verification. |
| 70 | +#[derive(Debug, Clone)] |
| 71 | +pub struct VerifiedModule { |
| 72 | + bytes: Vec<u8>, |
| 73 | + report: GateReport, |
| 74 | +} |
| 75 | + |
| 76 | +impl VerifiedModule { |
| 77 | + pub fn bytes(&self) -> &[u8] { |
| 78 | + &self.bytes |
| 79 | + } |
| 80 | + pub fn report(&self) -> &GateReport { |
| 81 | + &self.report |
| 82 | + } |
| 83 | +} |
| 84 | + |
| 85 | +/// Run the single-module verifier stack; a `VerifiedModule` comes back |
| 86 | +/// only if every layer passes. |
| 87 | +pub fn gate_module(bytes: &[u8]) -> Result<VerifiedModule, GateError> { |
| 88 | + // L7 / L10 / L13-negative (also rejects undecodable bytes). |
| 89 | + verify_from_module(bytes)?; |
| 90 | + |
| 91 | + // L2 carrier bounds. |
| 92 | + let bounds = verify_access_sites_from_module(bytes)?; |
| 93 | + if !bounds.is_empty() { |
| 94 | + return Err(GateError::AccessSites(bounds)); |
| 95 | + } |
| 96 | + |
| 97 | + // L2 access typing on pinned sites. |
| 98 | + let typing = verify_access_typing_from_module(bytes)?; |
| 99 | + if !typing.errors.is_empty() { |
| 100 | + return Err(GateError::AccessTyping( |
| 101 | + typing.errors.iter().map(|e| e.to_string()).collect(), |
| 102 | + )); |
| 103 | + } |
| 104 | + |
| 105 | + // L13 module-local import-table consistency. |
| 106 | + let import_errs = verify_region_imports_from_module(bytes)?; |
| 107 | + if !import_errs.is_empty() { |
| 108 | + return Err(GateError::RegionImports(import_errs)); |
| 109 | + } |
| 110 | + |
| 111 | + Ok(VerifiedModule { |
| 112 | + bytes: bytes.to_vec(), |
| 113 | + report: GateReport { |
| 114 | + typed_sites_checked: typing.type_verified, |
| 115 | + declared_only_sites: typing.declared_only, |
| 116 | + certificates: Vec::new(), |
| 117 | + }, |
| 118 | + }) |
| 119 | +} |
| 120 | + |
| 121 | +/// Gate a whole link graph: every module passes the single-module gate |
| 122 | +/// AND cross-module schema agreement holds (`verify_link_graph`, |
| 123 | +/// ADR-0007). Returns the witnesses in input order, each consumer's |
| 124 | +/// certificates attached to its report. |
| 125 | +pub fn gate_link_graph( |
| 126 | + named: &[(&str, &[u8])], |
| 127 | +) -> Result<Vec<(String, VerifiedModule)>, GateError> { |
| 128 | + let mut gated: Vec<(String, VerifiedModule)> = Vec::new(); |
| 129 | + for (name, bytes) in named { |
| 130 | + gated.push((name.to_string(), gate_module(bytes)?)); |
| 131 | + } |
| 132 | + let report = verify_link_graph(named)?; |
| 133 | + if !report.errors.is_empty() { |
| 134 | + return Err(GateError::RegionImports(report.errors)); |
| 135 | + } |
| 136 | + for cert in report.certificates { |
| 137 | + if let Some((_, module)) = gated.iter_mut().find(|(n, _)| *n == cert.consumer) { |
| 138 | + module.report.certificates.push(cert); |
| 139 | + } |
| 140 | + } |
| 141 | + Ok(gated) |
| 142 | +} |
| 143 | + |
| 144 | +/// In-process instantiation adapter backed by wasmi. Accepts only the |
| 145 | +/// gate's witness type — this is the enforcement point. |
| 146 | +#[cfg(feature = "wasmi-runtime")] |
| 147 | +pub mod wasmi_runtime { |
| 148 | + use super::VerifiedModule; |
| 149 | + |
| 150 | + /// Load + instantiate a verified module in a wasmi store. All |
| 151 | + /// wasmi-level errors pass through untouched; what this adapter |
| 152 | + /// adds is the TYPE-LEVEL guarantee that `module` went through the |
| 153 | + /// gate. |
| 154 | + pub fn instantiate_verified( |
| 155 | + engine: &wasmi::Engine, |
| 156 | + store: &mut wasmi::Store<()>, |
| 157 | + linker: &wasmi::Linker<()>, |
| 158 | + module: &VerifiedModule, |
| 159 | + ) -> Result<wasmi::Instance, wasmi::Error> { |
| 160 | + let compiled = wasmi::Module::new(engine, module.bytes())?; |
| 161 | + linker.instantiate_and_start(store, &compiled) |
| 162 | + } |
| 163 | +} |
0 commit comments