1use sha2::{Digest, Sha256};
2use std::fmt;
3use tapid_policy::{Decision, Evidence, PolicyDecision, ReasonCode};
4
5#[derive(Clone, Debug, Eq, Hash, PartialEq)]
6pub struct ScriptHash(String);
7impl ScriptHash {
8 pub fn as_str(&self) -> &str {
9 &self.0
10 }
11}
12impl fmt::Display for ScriptHash {
13 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
14 f.write_str(&self.0)
15 }
16}
17
18pub fn normalize_script(script: &str) -> String {
19 script
20 .replace("\r\n", "\n")
21 .replace('\r', "\n")
22 .trim()
23 .to_owned()
24}
25pub fn normalized_script_hash(script: &str) -> ScriptHash {
26 let digest = Sha256::digest(normalize_script(script).as_bytes());
27 ScriptHash(format!("sha256-{}", hex_lower(&digest)))
28}
29fn hex_lower(bytes: &[u8]) -> String {
30 bytes.iter().map(|b| format!("{b:02x}")).collect()
31}
32
33#[derive(Clone, Debug, Eq, PartialEq)]
34pub struct RunnerRequest {
35 pub artifact_digest: String,
36 pub script: String,
37 pub unattended: bool,
38 pub os: String,
39}
40impl RunnerRequest {
41 pub fn script_hash(&self) -> ScriptHash {
42 normalized_script_hash(&self.script)
43 }
44}
45
46#[derive(Clone, Debug, Eq, PartialEq)]
47pub struct Approval {
48 pub artifact_digest: String,
49 pub script_hash: ScriptHash,
50}
51impl Approval {
52 pub fn for_request(request: &RunnerRequest) -> Self {
53 Self {
54 artifact_digest: request.artifact_digest.clone(),
55 script_hash: request.script_hash(),
56 }
57 }
58}
59
60#[derive(Clone, Debug, Eq, PartialEq)]
61pub enum ValidationError {
62 ArtifactDigestMismatch,
63 ScriptHashMismatch,
64 MissingApproval,
65 UnsupportedOs,
66 PolicyDenied,
67 RequestMismatch,
68}
69
70#[derive(Clone, Debug, Eq, PartialEq)]
71pub struct RunnerPlan {
72 policy: PolicyDecision,
73 approval_required: bool,
74 containment_available: bool,
75 request: RunnerRequest,
76}
77impl RunnerPlan {
78 pub fn policy(&self) -> &PolicyDecision {
79 &self.policy
80 }
81 pub fn approval_required(&self) -> bool {
82 self.approval_required
83 }
84 pub fn containment_available(&self) -> bool {
85 self.containment_available
86 }
87}
88impl RunnerPlan {
89 pub fn validate_approval(
90 &self,
91 request: &RunnerRequest,
92 approval: Option<&Approval>,
93 ) -> Result<(), ValidationError> {
94 if request.artifact_digest != self.request.artifact_digest {
95 return Err(ValidationError::ArtifactDigestMismatch);
96 }
97 if request.script_hash() != self.request.script_hash() {
98 return Err(ValidationError::ScriptHashMismatch);
99 }
100 if request.unattended != self.request.unattended || request.os != self.request.os {
101 return Err(ValidationError::RequestMismatch);
102 }
103 if self.policy.decision() == Decision::Deny {
104 return Err(ValidationError::PolicyDenied);
105 }
106 let Some(approval) = approval else {
107 return if self.approval_required {
108 Err(ValidationError::MissingApproval)
109 } else {
110 Ok(())
111 };
112 };
113 if approval.artifact_digest != request.artifact_digest {
114 return Err(ValidationError::ArtifactDigestMismatch);
115 }
116 if approval.script_hash != request.script_hash() {
117 return Err(ValidationError::ScriptHashMismatch);
118 }
119 Ok(())
120 }
121}
122
123pub fn plan(request: &RunnerRequest, evidence: Vec<Evidence>) -> RunnerPlan {
124 let mut policy = PolicyDecision::from_evidence(evidence, request.unattended);
125 if !matches!(request.os.as_str(), "linux" | "macos" | "windows") {
126 policy = PolicyDecision::new(
127 Decision::Deny,
128 vec![ReasonCode::UnsupportedOs],
129 policy.evidence().to_vec(),
130 );
131 }
132 let approval_required = !matches!(policy.decision(), Decision::Allow);
133 RunnerPlan {
134 policy,
135 approval_required,
136 containment_available: false,
137 request: request.clone(),
138 }
139}
140
141#[cfg(test)]
142mod tests {
143 use super::*;
144 use tapid_policy::{Capability, Evidence};
145 fn request() -> RunnerRequest {
146 RunnerRequest {
147 artifact_digest: "sha256-aaaa".into(),
148 script: " echo hi\r\n".into(),
149 unattended: false,
150 os: "linux".into(),
151 }
152 }
153 #[test]
154 fn approval_binds_exact_artifact_and_normalized_script() {
155 let r = request();
156 let p = plan(&r, vec![]);
157 assert!(
158 p.validate_approval(&r, Some(&Approval::for_request(&r)))
159 .is_ok()
160 );
161 let mut changed = r.clone();
162 changed.artifact_digest = "sha256-bbbb".into();
163 assert_eq!(
164 p.validate_approval(&changed, Some(&Approval::for_request(&r))),
165 Err(ValidationError::ArtifactDigestMismatch)
166 );
167 }
168 #[test]
169 fn changed_script_cannot_reuse_approval() {
170 let r = request();
171 let p = plan(&r, vec![]);
172 let approval = Approval::for_request(&r);
173 let mut changed = r.clone();
174 changed.script.push_str(" && whoami");
175 assert_eq!(
176 p.validate_approval(&changed, Some(&approval)),
177 Err(ValidationError::ScriptHashMismatch)
178 );
179 }
180 #[test]
181 fn unattended_promptable_evidence_fails_closed() {
182 let r = RunnerRequest {
183 unattended: true,
184 ..request()
185 };
186 let p = plan(
187 &r,
188 vec![Evidence::inferred(Capability::Network, "heuristic")],
189 );
190 assert_eq!(p.policy().decision(), Decision::Deny);
191 assert!(p.approval_required());
192 }
193 #[test]
194 fn approval_cannot_override_policy_denial() {
195 let cases = [
196 (
197 RunnerRequest {
198 unattended: true,
199 ..request()
200 },
201 vec![Evidence::inferred(Capability::Network, "heuristic")],
202 ),
203 (
204 request(),
205 vec![Evidence::ambiguous(Capability::Network, "unclear")],
206 ),
207 (
208 RunnerRequest {
209 os: "plan9".into(),
210 ..request()
211 },
212 vec![],
213 ),
214 ];
215 for (r, evidence) in cases {
216 let p = plan(&r, evidence);
217 assert_eq!(p.policy().decision(), Decision::Deny);
218 assert_eq!(
219 p.validate_approval(&r, Some(&Approval::for_request(&r))),
220 Err(ValidationError::PolicyDenied)
221 );
222 }
223 }
224
225 #[test]
226 fn unsupported_os_is_explicit_and_not_containment() {
227 let r = RunnerRequest {
228 os: "plan9".into(),
229 ..request()
230 };
231 let p = plan(&r, vec![]);
232 assert_eq!(p.policy().decision(), Decision::Deny);
233 assert!(p.policy().reasons().contains(&ReasonCode::UnsupportedOs));
234 assert!(!p.containment_available());
235 }
236}