1#[derive(Clone, Debug, Eq, PartialEq)]
3pub struct PrivateLauncher {
4 executable: Option<std::path::PathBuf>,
5 #[cfg(target_os = "macos")]
6 identity: Option<(u64, u64)>,
7}
8static LAUNCHER: std::sync::OnceLock<PrivateLauncher> = std::sync::OnceLock::new();
9
10pub fn initialize_or_dispatch_private_launcher() -> PrivateLauncher {
13 #[cfg(any(target_os = "macos", target_os = "linux"))]
14 execution::dispatch_private_launcher();
15 LAUNCHER
16 .get_or_init(|| {
17 let executable = std::env::current_exe()
18 .ok()
19 .and_then(|p| std::fs::canonicalize(p).ok());
20 #[cfg(target_os = "macos")]
21 let identity = executable
22 .as_ref()
23 .and_then(|p| std::fs::metadata(p).ok())
24 .map(|m| {
25 use std::os::unix::fs::MetadataExt;
26 (m.dev(), m.ino())
27 });
28 PrivateLauncher {
29 executable,
30 #[cfg(target_os = "macos")]
31 identity,
32 }
33 })
34 .clone()
35}
36
37#[cfg(all(test, target_os = "macos"))]
39#[used]
40#[unsafe(link_section = "__DATA,__mod_init_func")]
41static TEST_LAUNCHER_INIT: extern "C" fn() = {
42 extern "C" fn init() {
43 initialize_or_dispatch_private_launcher();
44 }
45 init
46};
47
48#[cfg(all(test, target_os = "linux"))]
49#[used]
50#[unsafe(link_section = ".init_array")]
51static TEST_LAUNCHER_INIT_LINUX: extern "C" fn() = {
52 extern "C" fn init() {
53 initialize_or_dispatch_private_launcher();
54 }
55 init
56};
57
58pub mod config;
59pub mod execution;
60
61pub use config::{
62 AssuranceLevel, ConfigError, ConfigErrorCategory, ExecutionLimits, FilesystemPolicy,
63 MAX_CONFIG_BYTES, MAX_ENVIRONMENT_COUNT, MAX_GRANT_COUNT, MAX_PROFILE_COUNT, MAX_STRING_BYTES,
64 RunConfig, SandboxMode, SandboxPolicy,
65};
66pub use execution::{
67 BackendIdentity, CleanupConfidence, CompletionEvidence, ContainmentSupport, DimensionEvidence,
68 EnforcementDimension, EnforcementDimensions, EnforcementReceipt, EnforcementScope,
69 ExecutionError, ExecutionErrorCategory, ExecutionOutcome, ExecutionRequest,
70 ExecutionRequestBuilder, FilesystemAccess, FilesystemBindingMode, FilesystemGrantKind,
71 FilesystemGrantSource, MAX_ARGUMENT_COUNT, MAX_ARGUMENT_UNITS, MAX_ARGV_UNITS,
72 MAX_BACKEND_IDENTITY_BYTES, MAX_ENVIRONMENT_BLOCK_UNITS, MAX_ENVIRONMENT_VALUE_UNITS,
73 MAX_EXECUTABLE_SEARCH_PATH_COUNT, MAX_EXECUTABLE_SEARCH_PATH_UNITS,
74 MAX_EXECUTABLE_SEARCH_PATHS_UNITS, MAX_PROGRAM_UNITS, MAX_PROJECT_ROOT_UNITS,
75 ResolvedFilesystemGrant, ResolvedFilesystemGrants, Termination, execute,
76};
77
78use sha2::{Digest, Sha256};
79use std::fmt;
80use tapid_policy::{Decision, Evidence, PolicyDecision, ReasonCode};
81
82#[derive(Clone, Debug, Eq, Hash, PartialEq)]
83pub struct ScriptHash(String);
84impl ScriptHash {
85 pub fn as_str(&self) -> &str {
86 &self.0
87 }
88}
89impl fmt::Display for ScriptHash {
90 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91 f.write_str(&self.0)
92 }
93}
94
95pub fn normalize_script(script: &str) -> String {
96 script
97 .replace("\r\n", "\n")
98 .replace('\r', "\n")
99 .trim()
100 .to_owned()
101}
102pub fn normalized_script_hash(script: &str) -> ScriptHash {
103 let digest = Sha256::digest(normalize_script(script).as_bytes());
104 ScriptHash(format!("sha256-{}", hex_lower(&digest)))
105}
106fn hex_lower(bytes: &[u8]) -> String {
107 bytes.iter().map(|b| format!("{b:02x}")).collect()
108}
109
110#[derive(Clone, Debug, Eq, PartialEq)]
111pub struct RunnerRequest {
112 pub artifact_digest: String,
113 pub script: String,
114 pub unattended: bool,
115 pub os: String,
116}
117impl RunnerRequest {
118 pub fn script_hash(&self) -> ScriptHash {
119 normalized_script_hash(&self.script)
120 }
121}
122
123#[derive(Clone, Debug, Eq, PartialEq)]
124pub struct Approval {
125 pub artifact_digest: String,
126 pub script_hash: ScriptHash,
127}
128impl Approval {
129 pub fn for_request(request: &RunnerRequest) -> Self {
130 Self {
131 artifact_digest: request.artifact_digest.clone(),
132 script_hash: request.script_hash(),
133 }
134 }
135}
136
137#[derive(Clone, Debug, Eq, PartialEq)]
138pub enum ValidationError {
139 ArtifactDigestMismatch,
140 ScriptHashMismatch,
141 MissingApproval,
142 UnsupportedOs,
143 PolicyDenied,
144 RequestMismatch,
145}
146
147#[derive(Clone, Debug, Eq, PartialEq)]
148pub struct RunnerPlan {
149 policy: PolicyDecision,
150 approval_required: bool,
151 containment_available: bool,
152 request: RunnerRequest,
153}
154impl RunnerPlan {
155 pub fn policy(&self) -> &PolicyDecision {
156 &self.policy
157 }
158 pub fn approval_required(&self) -> bool {
159 self.approval_required
160 }
161 pub fn containment_available(&self) -> bool {
162 self.containment_available
163 }
164}
165impl RunnerPlan {
166 pub fn validate_approval(
167 &self,
168 request: &RunnerRequest,
169 approval: Option<&Approval>,
170 ) -> Result<(), ValidationError> {
171 if request.artifact_digest != self.request.artifact_digest {
172 return Err(ValidationError::ArtifactDigestMismatch);
173 }
174 if request.script_hash() != self.request.script_hash() {
175 return Err(ValidationError::ScriptHashMismatch);
176 }
177 if request.unattended != self.request.unattended || request.os != self.request.os {
178 return Err(ValidationError::RequestMismatch);
179 }
180 if self.policy.decision() == Decision::Deny {
181 return Err(ValidationError::PolicyDenied);
182 }
183 let Some(approval) = approval else {
184 return if self.approval_required {
185 Err(ValidationError::MissingApproval)
186 } else {
187 Ok(())
188 };
189 };
190 if approval.artifact_digest != request.artifact_digest {
191 return Err(ValidationError::ArtifactDigestMismatch);
192 }
193 if approval.script_hash != request.script_hash() {
194 return Err(ValidationError::ScriptHashMismatch);
195 }
196 Ok(())
197 }
198}
199
200pub fn plan(request: &RunnerRequest, evidence: Vec<Evidence>) -> RunnerPlan {
201 let mut policy = PolicyDecision::from_evidence(evidence, request.unattended);
202 if !matches!(request.os.as_str(), "linux" | "macos" | "windows") {
203 policy = PolicyDecision::new(
204 Decision::Deny,
205 vec![ReasonCode::UnsupportedOs],
206 policy.evidence().to_vec(),
207 );
208 }
209 let approval_required = !matches!(policy.decision(), Decision::Allow);
210 RunnerPlan {
211 policy,
212 approval_required,
213 containment_available: false,
214 request: request.clone(),
215 }
216}
217
218#[cfg(test)]
219mod tests {
220 use super::*;
221 use tapid_policy::{Capability, Evidence};
222 fn request() -> RunnerRequest {
223 RunnerRequest {
224 artifact_digest: "sha256-aaaa".into(),
225 script: " echo hi\r\n".into(),
226 unattended: false,
227 os: "linux".into(),
228 }
229 }
230 #[test]
231 fn approval_binds_exact_artifact_and_normalized_script() {
232 let r = request();
233 let p = plan(&r, vec![]);
234 assert!(
235 p.validate_approval(&r, Some(&Approval::for_request(&r)))
236 .is_ok()
237 );
238 let mut changed = r.clone();
239 changed.artifact_digest = "sha256-bbbb".into();
240 assert_eq!(
241 p.validate_approval(&changed, Some(&Approval::for_request(&r))),
242 Err(ValidationError::ArtifactDigestMismatch)
243 );
244 }
245 #[test]
246 fn changed_script_cannot_reuse_approval() {
247 let r = request();
248 let p = plan(&r, vec![]);
249 let approval = Approval::for_request(&r);
250 let mut changed = r.clone();
251 changed.script.push_str(" && whoami");
252 assert_eq!(
253 p.validate_approval(&changed, Some(&approval)),
254 Err(ValidationError::ScriptHashMismatch)
255 );
256 }
257 #[test]
258 fn unattended_promptable_evidence_fails_closed() {
259 let r = RunnerRequest {
260 unattended: true,
261 ..request()
262 };
263 let p = plan(
264 &r,
265 vec![Evidence::inferred(Capability::Network, "heuristic")],
266 );
267 assert_eq!(p.policy().decision(), Decision::Deny);
268 assert!(p.approval_required());
269 }
270 #[test]
271 fn approval_cannot_override_policy_denial() {
272 let cases = [
273 (
274 RunnerRequest {
275 unattended: true,
276 ..request()
277 },
278 vec![Evidence::inferred(Capability::Network, "heuristic")],
279 ),
280 (
281 request(),
282 vec![Evidence::ambiguous(Capability::Network, "unclear")],
283 ),
284 (
285 RunnerRequest {
286 os: "plan9".into(),
287 ..request()
288 },
289 vec![],
290 ),
291 ];
292 for (r, evidence) in cases {
293 let p = plan(&r, evidence);
294 assert_eq!(p.policy().decision(), Decision::Deny);
295 assert_eq!(
296 p.validate_approval(&r, Some(&Approval::for_request(&r))),
297 Err(ValidationError::PolicyDenied)
298 );
299 }
300 }
301
302 #[test]
303 fn existing_public_api_remains_source_compatible() {
304 let request = RunnerRequest {
305 artifact_digest: "sha256-aaaa".into(),
306 script: "echo compatible".into(),
307 unattended: false,
308 os: "linux".into(),
309 };
310 let hash: ScriptHash = normalized_script_hash(&request.script);
311 let approval: Approval = Approval::for_request(&request);
312 let plan: RunnerPlan = plan(&request, vec![]);
313
314 assert_eq!(hash, request.script_hash());
315 assert_eq!(approval.script_hash, hash);
316 assert!(plan.policy().evidence().is_empty());
317 }
318
319 #[test]
320 fn unsupported_os_is_explicit_and_not_containment() {
321 let r = RunnerRequest {
322 os: "plan9".into(),
323 ..request()
324 };
325 let p = plan(&r, vec![]);
326 assert_eq!(p.policy().decision(), Decision::Deny);
327 assert!(p.policy().reasons().contains(&ReasonCode::UnsupportedOs));
328 assert!(!p.containment_available());
329 }
330}