Skip to main content

tapid_runner/
lib.rs

1/// Proof that this executable installed private launcher dispatch before application work.
2#[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
10/// Call as the first operation in main. Private invocations dispatch and never return.
11/// Subsequent requests retain this opaque token; missing integration fails before spawn.
12pub 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// The library test executable needs the same early dispatch as a consumer main.
38#[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;
59mod lifecycle;
60pub use execution::dependency_toolchain_identity;
61pub use lifecycle::{DependencyLifecycleApproval, DependencyLifecyclePolicy, LifecycleTool};
62pub mod execution;
63
64pub use config::{
65    AssuranceLevel, ConfigError, ConfigErrorCategory, ExecutionLimits, FilesystemPolicy,
66    MAX_CONFIG_BYTES, MAX_ENVIRONMENT_COUNT, MAX_GRANT_COUNT, MAX_PROFILE_COUNT, MAX_STRING_BYTES,
67    RunConfig, SandboxMode, SandboxPolicy,
68};
69pub use execution::{
70    BackendIdentity, CleanupConfidence, CompletionEvidence, ContainmentSupport, DimensionEvidence,
71    EnforcementDimension, EnforcementDimensions, EnforcementReceipt, EnforcementScope,
72    ExecutionError, ExecutionErrorCategory, ExecutionOutcome, ExecutionRequest,
73    ExecutionRequestBuilder, FilesystemAccess, FilesystemBindingMode, FilesystemGrantKind,
74    FilesystemGrantSource, MAX_ARGUMENT_COUNT, MAX_ARGUMENT_UNITS, MAX_ARGV_UNITS,
75    MAX_BACKEND_IDENTITY_BYTES, MAX_ENVIRONMENT_BLOCK_UNITS, MAX_ENVIRONMENT_VALUE_UNITS,
76    MAX_EXECUTABLE_SEARCH_PATH_COUNT, MAX_EXECUTABLE_SEARCH_PATH_UNITS,
77    MAX_EXECUTABLE_SEARCH_PATHS_UNITS, MAX_PROGRAM_UNITS, MAX_PROJECT_ROOT_UNITS,
78    ResolvedFilesystemGrant, ResolvedFilesystemGrants, Termination, execute,
79};
80
81use sha2::{Digest, Sha256};
82use std::fmt;
83use tapid_policy::{Decision, Evidence, PolicyDecision, ReasonCode};
84
85#[derive(Clone, Debug, Eq, Hash, PartialEq)]
86pub struct ScriptHash(String);
87impl ScriptHash {
88    pub fn as_str(&self) -> &str {
89        &self.0
90    }
91}
92impl fmt::Display for ScriptHash {
93    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94        f.write_str(&self.0)
95    }
96}
97
98pub fn normalize_script(script: &str) -> String {
99    script
100        .replace("\r\n", "\n")
101        .replace('\r', "\n")
102        .trim()
103        .to_owned()
104}
105pub fn normalized_script_hash(script: &str) -> ScriptHash {
106    let digest = Sha256::digest(normalize_script(script).as_bytes());
107    ScriptHash(format!("sha256-{}", hex_lower(&digest)))
108}
109fn hex_lower(bytes: &[u8]) -> String {
110    bytes.iter().map(|b| format!("{b:02x}")).collect()
111}
112
113#[derive(Clone, Debug, Eq, PartialEq)]
114pub struct RunnerRequest {
115    pub artifact_digest: String,
116    pub script: String,
117    pub unattended: bool,
118    pub os: String,
119}
120impl RunnerRequest {
121    pub fn script_hash(&self) -> ScriptHash {
122        normalized_script_hash(&self.script)
123    }
124}
125
126#[derive(Clone, Debug, Eq, PartialEq)]
127pub struct Approval {
128    pub artifact_digest: String,
129    pub script_hash: ScriptHash,
130}
131impl Approval {
132    pub fn for_request(request: &RunnerRequest) -> Self {
133        Self {
134            artifact_digest: request.artifact_digest.clone(),
135            script_hash: request.script_hash(),
136        }
137    }
138}
139
140#[derive(Clone, Debug, Eq, PartialEq)]
141pub enum ValidationError {
142    ArtifactDigestMismatch,
143    ScriptHashMismatch,
144    MissingApproval,
145    UnsupportedOs,
146    PolicyDenied,
147    RequestMismatch,
148}
149
150#[derive(Clone, Debug, Eq, PartialEq)]
151pub struct RunnerPlan {
152    policy: PolicyDecision,
153    approval_required: bool,
154    containment_available: bool,
155    request: RunnerRequest,
156}
157impl RunnerPlan {
158    pub fn policy(&self) -> &PolicyDecision {
159        &self.policy
160    }
161    pub fn approval_required(&self) -> bool {
162        self.approval_required
163    }
164    pub fn containment_available(&self) -> bool {
165        self.containment_available
166    }
167}
168impl RunnerPlan {
169    pub fn validate_approval(
170        &self,
171        request: &RunnerRequest,
172        approval: Option<&Approval>,
173    ) -> Result<(), ValidationError> {
174        if request.artifact_digest != self.request.artifact_digest {
175            return Err(ValidationError::ArtifactDigestMismatch);
176        }
177        if request.script_hash() != self.request.script_hash() {
178            return Err(ValidationError::ScriptHashMismatch);
179        }
180        if request.unattended != self.request.unattended || request.os != self.request.os {
181            return Err(ValidationError::RequestMismatch);
182        }
183        if self.policy.decision() == Decision::Deny {
184            return Err(ValidationError::PolicyDenied);
185        }
186        let Some(approval) = approval else {
187            return if self.approval_required {
188                Err(ValidationError::MissingApproval)
189            } else {
190                Ok(())
191            };
192        };
193        if approval.artifact_digest != request.artifact_digest {
194            return Err(ValidationError::ArtifactDigestMismatch);
195        }
196        if approval.script_hash != request.script_hash() {
197            return Err(ValidationError::ScriptHashMismatch);
198        }
199        Ok(())
200    }
201}
202
203pub fn plan(request: &RunnerRequest, evidence: Vec<Evidence>) -> RunnerPlan {
204    let mut policy = PolicyDecision::from_evidence(evidence, request.unattended);
205    if !matches!(request.os.as_str(), "linux" | "macos" | "windows") {
206        policy = PolicyDecision::new(
207            Decision::Deny,
208            vec![ReasonCode::UnsupportedOs],
209            policy.evidence().to_vec(),
210        );
211    }
212    let approval_required = !matches!(policy.decision(), Decision::Allow);
213    RunnerPlan {
214        policy,
215        approval_required,
216        containment_available: false,
217        request: request.clone(),
218    }
219}
220
221#[cfg(test)]
222mod tests {
223    use super::*;
224    use tapid_policy::{Capability, Evidence};
225    fn request() -> RunnerRequest {
226        RunnerRequest {
227            artifact_digest: "sha256-aaaa".into(),
228            script: " echo hi\r\n".into(),
229            unattended: false,
230            os: "linux".into(),
231        }
232    }
233    #[test]
234    fn approval_binds_exact_artifact_and_normalized_script() {
235        let r = request();
236        let p = plan(&r, vec![]);
237        assert!(
238            p.validate_approval(&r, Some(&Approval::for_request(&r)))
239                .is_ok()
240        );
241        let mut changed = r.clone();
242        changed.artifact_digest = "sha256-bbbb".into();
243        assert_eq!(
244            p.validate_approval(&changed, Some(&Approval::for_request(&r))),
245            Err(ValidationError::ArtifactDigestMismatch)
246        );
247    }
248    #[test]
249    fn changed_script_cannot_reuse_approval() {
250        let r = request();
251        let p = plan(&r, vec![]);
252        let approval = Approval::for_request(&r);
253        let mut changed = r.clone();
254        changed.script.push_str(" && whoami");
255        assert_eq!(
256            p.validate_approval(&changed, Some(&approval)),
257            Err(ValidationError::ScriptHashMismatch)
258        );
259    }
260    #[test]
261    fn unattended_promptable_evidence_fails_closed() {
262        let r = RunnerRequest {
263            unattended: true,
264            ..request()
265        };
266        let p = plan(
267            &r,
268            vec![Evidence::inferred(Capability::Network, "heuristic")],
269        );
270        assert_eq!(p.policy().decision(), Decision::Deny);
271        assert!(p.approval_required());
272    }
273    #[test]
274    fn approval_cannot_override_policy_denial() {
275        let cases = [
276            (
277                RunnerRequest {
278                    unattended: true,
279                    ..request()
280                },
281                vec![Evidence::inferred(Capability::Network, "heuristic")],
282            ),
283            (
284                request(),
285                vec![Evidence::ambiguous(Capability::Network, "unclear")],
286            ),
287            (
288                RunnerRequest {
289                    os: "plan9".into(),
290                    ..request()
291                },
292                vec![],
293            ),
294        ];
295        for (r, evidence) in cases {
296            let p = plan(&r, evidence);
297            assert_eq!(p.policy().decision(), Decision::Deny);
298            assert_eq!(
299                p.validate_approval(&r, Some(&Approval::for_request(&r))),
300                Err(ValidationError::PolicyDenied)
301            );
302        }
303    }
304
305    #[test]
306    fn existing_public_api_remains_source_compatible() {
307        let request = RunnerRequest {
308            artifact_digest: "sha256-aaaa".into(),
309            script: "echo compatible".into(),
310            unattended: false,
311            os: "linux".into(),
312        };
313        let hash: ScriptHash = normalized_script_hash(&request.script);
314        let approval: Approval = Approval::for_request(&request);
315        let plan: RunnerPlan = plan(&request, vec![]);
316
317        assert_eq!(hash, request.script_hash());
318        assert_eq!(approval.script_hash, hash);
319        assert!(plan.policy().evidence().is_empty());
320    }
321
322    #[test]
323    fn unsupported_os_is_explicit_and_not_containment() {
324        let r = RunnerRequest {
325            os: "plan9".into(),
326            ..request()
327        };
328        let p = plan(&r, vec![]);
329        assert_eq!(p.policy().decision(), Decision::Deny);
330        assert!(p.policy().reasons().contains(&ReasonCode::UnsupportedOs));
331        assert!(!p.containment_available());
332    }
333}