Skip to main content

sim_platform_bootstrap/
bootstrap.rs

1use sha2::{Digest, Sha256};
2use sim_kernel::{Cx, Lib, LibLoader};
3use sim_platform_core::{
4    BundleManifest, CapsuleManifest, parse_bundle, parse_capsule, validate_bundle,
5};
6use std::{
7    collections::BTreeSet,
8    ffi::OsString,
9    fmt, fs,
10    path::{Path, PathBuf},
11};
12
13/// Exact descriptor name admitted beside the caller-supplied executable.
14pub const BUNDLE_DESCRIPTOR_NAME: &str = "sim.platform-bundle.toml";
15/// Hard ceiling for the complete descriptor.
16pub const MAX_DESCRIPTOR_BYTES: u64 = 16 * 1024;
17/// Hard ceiling for the capsule card.
18pub const MAX_CAPSULE_CARD_BYTES: u64 = 16 * 1024;
19/// Hard ceiling for the one native artifact.
20pub const MAX_ARTIFACT_BYTES: u64 = 512 * 1024 * 1024;
21/// Hard ceiling for arguments and preopened roots.
22pub const MAX_ENVELOPE_ITEMS: usize = 256;
23/// Hard ceiling for any individual argument or path.
24pub const MAX_ENVELOPE_ITEM_BYTES: usize = 16 * 1024;
25
26/// Owned stdio data. The host surface may replace output buffers after boot.
27#[derive(Clone, Debug, Default, Eq, PartialEq)]
28pub struct BootstrapStdio {
29    /// Complete supplied standard input.
30    pub stdin: Vec<u8>,
31    /// Initial standard-output frame, normally empty.
32    pub stdout: Vec<u8>,
33    /// Initial standard-error frame, normally empty.
34    pub stderr: Vec<u8>,
35}
36
37/// Configuration roots resolved and supplied by the embedding host.
38#[derive(Clone, Debug, Default, Eq, PartialEq)]
39pub struct BootstrapConfigRoots {
40    /// Central user configuration root, when the host supplies one.
41    pub home: Option<PathBuf>,
42    /// Working configuration root.
43    pub work: PathBuf,
44}
45
46/// All data crossing from the tiny host rind into the bootloader.
47#[derive(Clone, Debug, Eq, PartialEq)]
48pub struct BootstrapEnvelope {
49    /// Owned process argument frames.
50    pub argv: Vec<OsString>,
51    /// Owned stdio frames.
52    pub stdio: BootstrapStdio,
53    /// Content identity from the admitted bundle descriptor.
54    pub bundle_identity: String,
55    /// The admitted capsule's shaped card.
56    pub capsule_card: CapsuleManifest,
57    /// Roots explicitly preopened by the host, with no implicit current root.
58    pub preopened_roots: Vec<PathBuf>,
59    /// Configuration roots explicitly resolved by the host.
60    pub config_roots: BootstrapConfigRoots,
61    /// Caller-owned deterministic kernel handle seed.
62    pub kernel_seed: u64,
63}
64
65impl BootstrapEnvelope {
66    /// Validates the bounded, owned transport shape.
67    ///
68    /// # Errors
69    /// Refuses oversized collections, frames, arguments, paths, or identity.
70    pub fn validate(&self) -> Result<(), BootstrapError> {
71        if self.argv.len() > MAX_ENVELOPE_ITEMS || self.preopened_roots.len() > MAX_ENVELOPE_ITEMS {
72            return Err(BootstrapError::EnvelopeBound(
73                "too many argv or preopened-root items",
74            ));
75        }
76        if self.bundle_identity.is_empty() || self.bundle_identity.len() > MAX_ENVELOPE_ITEM_BYTES {
77            return Err(BootstrapError::EnvelopeBound("invalid bundle identity"));
78        }
79        for arg in &self.argv {
80            if arg.as_encoded_bytes().len() > MAX_ENVELOPE_ITEM_BYTES {
81                return Err(BootstrapError::EnvelopeBound("argument is too large"));
82            }
83        }
84        for root in self
85            .preopened_roots
86            .iter()
87            .chain(self.config_roots.home.iter())
88            .chain(std::iter::once(&self.config_roots.work))
89        {
90            if root.as_os_str().as_encoded_bytes().len() > MAX_ENVELOPE_ITEM_BYTES {
91                return Err(BootstrapError::EnvelopeBound("preopened root is too large"));
92            }
93        }
94        for frame in [&self.stdio.stdin, &self.stdio.stdout, &self.stdio.stderr] {
95            if u64::try_from(frame.len()).unwrap_or(u64::MAX) > MAX_ARTIFACT_BYTES {
96                return Err(BootstrapError::EnvelopeBound("stdio frame is too large"));
97            }
98        }
99        Ok(())
100    }
101}
102
103/// Successful admission: one owned envelope and one already-instantiated lib.
104pub struct BootstrappedCapsule {
105    /// Pure input handed onward to the bootloader.
106    pub envelope: BootstrapEnvelope,
107    /// Capsule loaded through the existing native ABI loader.
108    pub capsule: Box<dyn Lib>,
109}
110
111/// Policy supplied by the embedding host; there are no ambient defaults.
112#[derive(Clone, Debug, Eq, PartialEq)]
113pub struct BootstrapPolicy {
114    /// Exact services the first capsule may claim.
115    pub allowed_services: BTreeSet<String>,
116}
117
118/// Fail-closed bootstrap errors.
119#[derive(Debug)]
120pub enum BootstrapError {
121    /// An exact required adjacent file is absent or unreadable.
122    Read {
123        /// Exact attempted path.
124        path: PathBuf,
125        /// Host error detail.
126        detail: String,
127    },
128    /// A bounded input exceeded its declared ceiling.
129    EnvelopeBound(&'static str),
130    /// A descriptor named anything except one adjacent plain filename.
131    InvalidAdjacentName(String),
132    /// Parsed platform metadata was invalid.
133    InvalidManifest(String),
134    /// Artifact content did not match the descriptor identity.
135    ContentMismatch {
136        /// Descriptor claim.
137        expected: String,
138        /// Computed content identity.
139        actual: String,
140    },
141    /// The capsule requested authority outside the supplied policy.
142    OverCapable(String),
143    /// Existing native ABI loading rejected the exact artifact.
144    Native(String),
145}
146
147impl fmt::Display for BootstrapError {
148    fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result {
149        write!(out, "{self:?}")
150    }
151}
152impl std::error::Error for BootstrapError {}
153
154/// Admit exactly one adjacent descriptor, capsule card, and native artifact.
155///
156/// `executable` is data supplied by the caller; this function deliberately
157/// never discovers it. `loader` is normally the existing native dylib loader,
158/// preserving the one `sim_native_abi_v1` implementation.
159///
160/// # Errors
161/// Refuses missing, changed, malformed, wrong-ABI, duplicate, or over-capable
162/// input and never tries an alternate location or loader.
163pub fn bootstrap<L: LibLoader>(
164    executable: &Path,
165    mut envelope: BootstrapEnvelope,
166    policy: &BootstrapPolicy,
167    cx: &mut Cx,
168    loader: &L,
169) -> Result<BootstrappedCapsule, BootstrapError> {
170    envelope.validate()?;
171    let adjacent = executable
172        .parent()
173        .ok_or_else(|| BootstrapError::InvalidAdjacentName(executable.display().to_string()))?;
174    let bundle_path = adjacent.join(BUNDLE_DESCRIPTOR_NAME);
175    let bundle_text = read_bounded(&bundle_path, MAX_DESCRIPTOR_BYTES)?;
176    let bundle: BundleManifest = parse_bundle(
177        std::str::from_utf8(&bundle_text)
178            .map_err(|error| BootstrapError::InvalidManifest(error.to_string()))?,
179    )
180    .map_err(|error| BootstrapError::InvalidManifest(error.to_string()))?;
181    require_plain_name(&bundle.capsule)?;
182    require_plain_name(&bundle.artifact)?;
183    let capsule_path = adjacent.join(&bundle.capsule);
184    let capsule_text = read_bounded(&capsule_path, MAX_CAPSULE_CARD_BYTES)?;
185    let capsule = parse_capsule(
186        std::str::from_utf8(&capsule_text)
187            .map_err(|error| BootstrapError::InvalidManifest(error.to_string()))?,
188    )
189    .map_err(|error| BootstrapError::InvalidManifest(error.to_string()))?;
190    validate_bundle(&bundle, &capsule)
191        .map_err(|error| BootstrapError::InvalidManifest(error.to_string()))?;
192    let providers: BTreeSet<_> = std::iter::once(&capsule.provider).collect();
193    if providers.len() != 1 {
194        return Err(BootstrapError::InvalidManifest(
195            "duplicate capsule provider".into(),
196        ));
197    }
198    if let Some(service) = capsule
199        .services
200        .iter()
201        .find(|service| !policy.allowed_services.contains(*service))
202    {
203        return Err(BootstrapError::OverCapable(service.clone()));
204    }
205    let artifact_path = adjacent.join(&bundle.artifact);
206    let artifact = read_bounded(&artifact_path, MAX_ARTIFACT_BYTES)?;
207    let actual = format!("sha256:{:x}", Sha256::digest(&artifact));
208    if actual != bundle.artifact_content {
209        return Err(BootstrapError::ContentMismatch {
210            expected: bundle.artifact_content,
211            actual,
212        });
213    }
214    envelope.bundle_identity = actual;
215    envelope.capsule_card = capsule;
216    let source = sim_run_loaders::path_source(artifact_path);
217    if !loader.can_load(&source) {
218        return Err(BootstrapError::Native(
219            "exact artifact is not accepted by the native loader".into(),
220        ));
221    }
222    let capsule = loader
223        .load(cx, source)
224        .map_err(|error| BootstrapError::Native(error.to_string()))?;
225    Ok(BootstrappedCapsule { envelope, capsule })
226}
227
228fn require_plain_name(name: &str) -> Result<(), BootstrapError> {
229    let path = Path::new(name);
230    if name.is_empty() || path.is_absolute() || path.components().count() != 1 {
231        return Err(BootstrapError::InvalidAdjacentName(name.to_owned()));
232    }
233    Ok(())
234}
235
236fn read_bounded(path: &Path, limit: u64) -> Result<Vec<u8>, BootstrapError> {
237    let metadata = fs::metadata(path).map_err(|error| BootstrapError::Read {
238        path: path.to_owned(),
239        detail: error.to_string(),
240    })?;
241    if !metadata.is_file() || metadata.len() > limit {
242        return Err(BootstrapError::EnvelopeBound(
243            "adjacent input is not a bounded regular file",
244        ));
245    }
246    fs::read(path).map_err(|error| BootstrapError::Read {
247        path: path.to_owned(),
248        detail: error.to_string(),
249    })
250}
251
252#[cfg(test)]
253#[path = "tests.rs"]
254mod tests;