1use std::collections::hash_map::DefaultHasher;
14use std::hash::{Hash, Hasher};
15use std::sync::atomic::{AtomicU64, Ordering};
16
17use crate::bytecode::{CapId, CapRights, CapTarget, TrustLevel};
18
19use super::capability::{CapTable, Capability};
20use super::error::RuntimeError;
21use super::process::FlowId;
22use super::quota::QuotaConfig;
23use super::runtime::RuntimeConfig;
24
25const POLICY_DOMAIN: u64 = 0xBF51_5341_4E44_5031; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
33pub struct PolicyFingerprint([u8; 16]);
34
35impl PolicyFingerprint {
36 pub fn as_bytes(&self) -> &[u8; 16] {
37 &self.0
38 }
39
40 pub fn to_hex(&self) -> String {
41 let mut s = String::with_capacity(32);
42 for b in &self.0 {
43 use std::fmt::Write as _;
44 let _ = write!(s, "{b:02x}");
45 }
46 s
47 }
48}
49
50impl std::fmt::Display for PolicyFingerprint {
51 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52 f.write_str(&self.to_hex())
53 }
54}
55
56pub fn policy_fingerprint(config: &RuntimeConfig) -> PolicyFingerprint {
58 let mut hasher = DefaultHasher::new();
59 POLICY_DOMAIN.hash(&mut hasher);
60 trust_tag(config.trust).hash(&mut hasher);
61 root_authority_tag(config.root_authority).hash(&mut hasher);
62 config.max_flows.hash(&mut hasher);
63 config.max_ask_waits.hash(&mut hasher);
64 config.max_host_awaits.hash(&mut hasher);
65 config.max_links.hash(&mut hasher);
66 config.max_monitors.hash(&mut hasher);
67 config.max_registry_names.hash(&mut hasher);
68 config.max_runtime_bytes.hash(&mut hasher);
69 config.mailbox.capacity().get().hash(&mut hasher);
70 config.mailbox.bytes().get().hash(&mut hasher);
71 (config.mailbox.overflow() as u8).hash(&mut hasher);
72 hash_quota(&mut hasher, &config.quota);
73 let lo = hasher.finish();
74 let mut hasher2 = DefaultHasher::new();
76 POLICY_DOMAIN.hash(&mut hasher2);
77 lo.hash(&mut hasher2);
78 hash_quota(&mut hasher2, &config.quota);
79 config.max_runtime_bytes.hash(&mut hasher2);
80 let hi = hasher2.finish();
81 let mut out = [0u8; 16];
82 out[..8].copy_from_slice(&lo.to_le_bytes());
83 out[8..].copy_from_slice(&hi.to_le_bytes());
84 PolicyFingerprint(out)
85}
86
87fn trust_tag(trust: TrustLevel) -> u8 {
88 match trust {
89 TrustLevel::Trusted => 0,
90 TrustLevel::Restricted => 1,
91 TrustLevel::Untrusted => 2,
92 }
93}
94
95fn root_authority_tag(policy: crate::scheduler::RootAuthorityPolicy) -> u8 {
96 match policy {
97 crate::scheduler::RootAuthorityPolicy::TrustedHost => 0,
98 crate::scheduler::RootAuthorityPolicy::Restricted => 1,
99 crate::scheduler::RootAuthorityPolicy::Untrusted => 2,
100 }
101}
102
103fn hash_quota(hasher: &mut DefaultHasher, q: &QuotaConfig) {
104 q.cpu_budget.hash(hasher);
105 q.mem_limit.hash(hasher);
106 q.spawn_burst.hash(hasher);
107 q.spawn_per_sec.hash(hasher);
108 q.send_burst.hash(hasher);
109 q.send_per_sec.hash(hasher);
110}
111
112#[derive(Default, Debug)]
114pub struct SecurityCounters {
115 pub denied_operations: AtomicU64,
116 pub quota_exceeded: AtomicU64,
117 pub capabilities_created: AtomicU64,
118 pub capabilities_revoked: AtomicU64,
119 pub invalid_modules: AtomicU64,
120 pub native_denied: AtomicU64,
121 pub active_untrusted_flows: AtomicU64,
122}
123
124impl SecurityCounters {
125 #[inline]
126 pub fn inc(counter: &AtomicU64) {
127 counter.fetch_add(1, Ordering::Relaxed);
128 }
129
130 pub fn dec_active_untrusted(&self) {
132 let mut cur = self.active_untrusted_flows.load(Ordering::Relaxed);
133 while cur > 0 {
134 match self.active_untrusted_flows.compare_exchange_weak(
135 cur,
136 cur - 1,
137 Ordering::Relaxed,
138 Ordering::Relaxed,
139 ) {
140 Ok(_) => return,
141 Err(actual) => cur = actual,
142 }
143 }
144 }
145
146 pub fn snapshot(&self) -> SecurityCountersSnapshot {
147 SecurityCountersSnapshot {
148 denied_operations: self.denied_operations.load(Ordering::Relaxed),
149 quota_exceeded: self.quota_exceeded.load(Ordering::Relaxed),
150 capabilities_created: self.capabilities_created.load(Ordering::Relaxed),
151 capabilities_revoked: self.capabilities_revoked.load(Ordering::Relaxed),
152 invalid_modules: self.invalid_modules.load(Ordering::Relaxed),
153 native_denied: self.native_denied.load(Ordering::Relaxed),
154 active_untrusted_flows: self.active_untrusted_flows.load(Ordering::Relaxed),
155 }
156 }
157}
158
159#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
161pub struct SecurityCountersSnapshot {
162 pub denied_operations: u64,
163 pub quota_exceeded: u64,
164 pub capabilities_created: u64,
165 pub capabilities_revoked: u64,
166 pub invalid_modules: u64,
167 pub native_denied: u64,
168 pub active_untrusted_flows: u64,
169}
170
171impl std::fmt::Display for SecurityCountersSnapshot {
172 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
173 write!(
174 f,
175 "denied={} quota={} caps_created={} caps_revoked={} invalid_modules={} native_denied={} untrusted_flows={}",
176 self.denied_operations,
177 self.quota_exceeded,
178 self.capabilities_created,
179 self.capabilities_revoked,
180 self.invalid_modules,
181 self.native_denied,
182 self.active_untrusted_flows,
183 )
184 }
185}
186
187#[derive(Clone, Debug, PartialEq, Eq)]
189pub struct CapabilityGrantView {
190 pub id: CapId,
191 pub holder: FlowId,
192 pub target: CapTarget,
193 pub rights: CapRights,
194}
195
196impl CapabilityGrantView {
197 pub fn from_entry(id: CapId, cap: &Capability) -> Self {
198 Self {
199 id,
200 holder: cap.holder,
201 target: cap.cap.target(),
202 rights: cap.cap.rights(),
203 }
204 }
205}
206
207#[derive(Clone, Debug, PartialEq, Eq)]
211pub struct CapabilityAttestation {
212 pub flow: FlowId,
213 pub trust: TrustLevel,
214 pub policy: PolicyFingerprint,
215 pub grants: Vec<CapabilityGrantView>,
216}
217
218impl CapabilityAttestation {
219 pub fn from_table(
220 table: &CapTable,
221 flow: FlowId,
222 trust: TrustLevel,
223 policy: PolicyFingerprint,
224 ) -> Result<Self, RuntimeError> {
225 Ok(Self {
226 flow,
227 trust,
228 policy,
229 grants: table.list_held_by(flow)?,
230 })
231 }
232}
233
234#[derive(Clone, Debug, PartialEq, Eq)]
236pub enum SecurityEvent {
237 CapabilityCreated { holder: u64 },
238 CapabilityDelegated { from: u64, to: u64 },
239 CapabilityRevoked { flow: u64, removed: usize },
240 AccessDenied { reason: &'static str },
241 QuotaExceeded { kind: &'static str },
242 ModuleRejected { reason: &'static str },
243 NativeDenied { index: u32 },
244 FlowFinalized { flow: u64 },
245}
246
247impl std::fmt::Display for SecurityEvent {
248 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
249 match self {
250 SecurityEvent::CapabilityCreated { holder } => {
251 write!(f, "cap_created holder={holder}")
252 }
253 SecurityEvent::CapabilityDelegated { from, to } => {
254 write!(f, "cap_delegated from={from} to={to}")
255 }
256 SecurityEvent::CapabilityRevoked { flow, removed } => {
257 write!(f, "cap_revoked flow={flow} removed={removed}")
258 }
259 SecurityEvent::AccessDenied { reason } => write!(f, "access_denied {reason}"),
260 SecurityEvent::QuotaExceeded { kind } => write!(f, "quota_exceeded {kind}"),
261 SecurityEvent::ModuleRejected { reason } => write!(f, "module_rejected {reason}"),
262 SecurityEvent::NativeDenied { index } => write!(f, "native_denied idx={index}"),
263 SecurityEvent::FlowFinalized { flow } => write!(f, "flow_finalized id={flow}"),
264 }
265 }
266}
267
268pub trait SecurityAuditSink: Send + Sync + std::fmt::Debug + 'static {
270 fn record(&self, event: &SecurityEvent);
271}
272
273#[cfg(test)]
274mod tests {
275 use super::*;
276 use crate::bytecode::TrustLevel;
277 use crate::scheduler::mailbox::{MailboxCapacity, MailboxConfig, OverflowPolicy};
278
279 #[test]
280 fn sandbox_fingerprint_differs_from_default() {
281 let permissive = RuntimeConfig::default();
282 let sandboxed = RuntimeConfig::sandbox();
283 assert_ne!(
284 policy_fingerprint(&permissive),
285 policy_fingerprint(&sandboxed)
286 );
287 }
288
289 #[test]
290 fn fingerprint_is_stable_for_identical_config() {
291 let a = RuntimeConfig::sandbox();
292 let b = RuntimeConfig::sandbox();
293 assert_eq!(policy_fingerprint(&a), policy_fingerprint(&b));
294 }
295
296 #[test]
297 fn fingerprint_changes_when_trust_changes() {
298 let mut a = RuntimeConfig::sandbox();
299 let mut b = RuntimeConfig::sandbox();
300 a.trust = TrustLevel::Untrusted;
301 b.trust = TrustLevel::Restricted;
302 assert_ne!(policy_fingerprint(&a), policy_fingerprint(&b));
303 }
304
305 #[test]
306 fn fingerprint_changes_when_mailbox_changes() {
307 let a = RuntimeConfig::sandbox();
308 let mut b = RuntimeConfig::sandbox();
309 b.mailbox = MailboxConfig::new(MailboxCapacity::DEFAULT, OverflowPolicy::DropNewest);
310 assert_ne!(policy_fingerprint(&a), policy_fingerprint(&b));
311 }
312}