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
13pub const BUNDLE_DESCRIPTOR_NAME: &str = "sim.platform-bundle.toml";
15pub const MAX_DESCRIPTOR_BYTES: u64 = 16 * 1024;
17pub const MAX_CAPSULE_CARD_BYTES: u64 = 16 * 1024;
19pub const MAX_ARTIFACT_BYTES: u64 = 512 * 1024 * 1024;
21pub const MAX_ENVELOPE_ITEMS: usize = 256;
23pub const MAX_ENVELOPE_ITEM_BYTES: usize = 16 * 1024;
25
26#[derive(Clone, Debug, Default, Eq, PartialEq)]
28pub struct BootstrapStdio {
29 pub stdin: Vec<u8>,
31 pub stdout: Vec<u8>,
33 pub stderr: Vec<u8>,
35}
36
37#[derive(Clone, Debug, Default, Eq, PartialEq)]
39pub struct BootstrapConfigRoots {
40 pub home: Option<PathBuf>,
42 pub work: PathBuf,
44}
45
46#[derive(Clone, Debug, Eq, PartialEq)]
48pub struct BootstrapEnvelope {
49 pub argv: Vec<OsString>,
51 pub stdio: BootstrapStdio,
53 pub bundle_identity: String,
55 pub capsule_card: CapsuleManifest,
57 pub preopened_roots: Vec<PathBuf>,
59 pub config_roots: BootstrapConfigRoots,
61 pub kernel_seed: u64,
63}
64
65impl BootstrapEnvelope {
66 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
103pub struct BootstrappedCapsule {
105 pub envelope: BootstrapEnvelope,
107 pub capsule: Box<dyn Lib>,
109}
110
111#[derive(Clone, Debug, Eq, PartialEq)]
113pub struct BootstrapPolicy {
114 pub allowed_services: BTreeSet<String>,
116}
117
118#[derive(Debug)]
120pub enum BootstrapError {
121 Read {
123 path: PathBuf,
125 detail: String,
127 },
128 EnvelopeBound(&'static str),
130 InvalidAdjacentName(String),
132 InvalidManifest(String),
134 ContentMismatch {
136 expected: String,
138 actual: String,
140 },
141 OverCapable(String),
143 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
154pub 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;