1use std::collections::hash_map::DefaultHasher;
14use std::hash::{Hash, Hasher};
15use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
16use std::sync::mpsc::{sync_channel, RecvTimeoutError, SyncSender};
17use std::sync::Arc;
18use std::thread::{self, JoinHandle};
19use std::time::Duration;
20
21use crate::bytecode::{CapId, CapRights, CapTarget, TrustLevel};
22
23use super::capability::{CapTable, Capability};
24use super::error::RuntimeError;
25use super::process::FlowId;
26use super::quota::QuotaConfig;
27use super::runtime::RuntimeConfig;
28
29const POLICY_DOMAIN: u64 = 0xBF51_5341_4E44_5031; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
37pub struct PolicyFingerprint([u8; 16]);
38
39impl PolicyFingerprint {
40 pub fn as_bytes(&self) -> &[u8; 16] {
41 &self.0
42 }
43
44 pub fn to_hex(&self) -> String {
45 let mut s = String::with_capacity(32);
46 for b in &self.0 {
47 use std::fmt::Write as _;
48 let _ = write!(s, "{b:02x}");
49 }
50 s
51 }
52}
53
54impl std::fmt::Display for PolicyFingerprint {
55 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56 f.write_str(&self.to_hex())
57 }
58}
59
60pub fn policy_fingerprint(config: &RuntimeConfig) -> PolicyFingerprint {
62 let mut hasher = DefaultHasher::new();
63 POLICY_DOMAIN.hash(&mut hasher);
64 trust_tag(config.trust).hash(&mut hasher);
65 root_authority_tag(config.root_authority).hash(&mut hasher);
66 config.max_flows.hash(&mut hasher);
67 config.max_ask_waits.hash(&mut hasher);
68 config.max_host_awaits.hash(&mut hasher);
69 config.max_links.hash(&mut hasher);
70 config.max_monitors.hash(&mut hasher);
71 config.max_registry_names.hash(&mut hasher);
72 config.max_runtime_bytes.hash(&mut hasher);
73 config.mailbox.capacity().get().hash(&mut hasher);
74 config.mailbox.bytes().get().hash(&mut hasher);
75 (config.mailbox.overflow() as u8).hash(&mut hasher);
76 hash_quota(&mut hasher, &config.quota);
77 let lo = hasher.finish();
78 let mut hasher2 = DefaultHasher::new();
80 POLICY_DOMAIN.hash(&mut hasher2);
81 lo.hash(&mut hasher2);
82 hash_quota(&mut hasher2, &config.quota);
83 config.max_runtime_bytes.hash(&mut hasher2);
84 let hi = hasher2.finish();
85 let mut out = [0u8; 16];
86 out[..8].copy_from_slice(&lo.to_le_bytes());
87 out[8..].copy_from_slice(&hi.to_le_bytes());
88 PolicyFingerprint(out)
89}
90
91fn trust_tag(trust: TrustLevel) -> u8 {
92 match trust {
93 TrustLevel::Trusted => 0,
94 TrustLevel::Restricted => 1,
95 TrustLevel::Untrusted => 2,
96 }
97}
98
99fn root_authority_tag(policy: crate::scheduler::RootAuthorityPolicy) -> u8 {
100 match policy {
101 crate::scheduler::RootAuthorityPolicy::TrustedHost => 0,
102 crate::scheduler::RootAuthorityPolicy::Restricted => 1,
103 crate::scheduler::RootAuthorityPolicy::Untrusted => 2,
104 }
105}
106
107fn hash_quota(hasher: &mut DefaultHasher, q: &QuotaConfig) {
108 q.cpu_budget.hash(hasher);
109 q.mem_limit.hash(hasher);
110 q.spawn_burst.hash(hasher);
111 q.spawn_per_sec.hash(hasher);
112 q.send_burst.hash(hasher);
113 q.send_per_sec.hash(hasher);
114}
115
116#[derive(Default, Debug)]
118pub struct SecurityCounters {
119 pub denied_operations: AtomicU64,
120 pub quota_exceeded: AtomicU64,
121 pub capabilities_created: AtomicU64,
122 pub capabilities_revoked: AtomicU64,
123 pub invalid_modules: AtomicU64,
124 pub native_denied: AtomicU64,
125 pub active_untrusted_flows: AtomicU64,
126}
127
128impl SecurityCounters {
129 #[inline]
130 pub fn inc(counter: &AtomicU64) {
131 counter.fetch_add(1, Ordering::Relaxed);
132 }
133
134 pub fn dec_active_untrusted(&self) {
136 let mut cur = self.active_untrusted_flows.load(Ordering::Relaxed);
137 while cur > 0 {
138 match self.active_untrusted_flows.compare_exchange_weak(
139 cur,
140 cur - 1,
141 Ordering::Relaxed,
142 Ordering::Relaxed,
143 ) {
144 Ok(_) => return,
145 Err(actual) => cur = actual,
146 }
147 }
148 }
149
150 pub fn snapshot(&self) -> SecurityCountersSnapshot {
151 SecurityCountersSnapshot {
152 denied_operations: self.denied_operations.load(Ordering::Relaxed),
153 quota_exceeded: self.quota_exceeded.load(Ordering::Relaxed),
154 capabilities_created: self.capabilities_created.load(Ordering::Relaxed),
155 capabilities_revoked: self.capabilities_revoked.load(Ordering::Relaxed),
156 invalid_modules: self.invalid_modules.load(Ordering::Relaxed),
157 native_denied: self.native_denied.load(Ordering::Relaxed),
158 active_untrusted_flows: self.active_untrusted_flows.load(Ordering::Relaxed),
159 }
160 }
161}
162
163#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
165pub struct SecurityCountersSnapshot {
166 pub denied_operations: u64,
167 pub quota_exceeded: u64,
168 pub capabilities_created: u64,
169 pub capabilities_revoked: u64,
170 pub invalid_modules: u64,
171 pub native_denied: u64,
172 pub active_untrusted_flows: u64,
173}
174
175impl std::fmt::Display for SecurityCountersSnapshot {
176 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
177 write!(
178 f,
179 "denied={} quota={} caps_created={} caps_revoked={} invalid_modules={} native_denied={} untrusted_flows={}",
180 self.denied_operations,
181 self.quota_exceeded,
182 self.capabilities_created,
183 self.capabilities_revoked,
184 self.invalid_modules,
185 self.native_denied,
186 self.active_untrusted_flows,
187 )
188 }
189}
190
191#[derive(Clone, Debug, PartialEq, Eq)]
193pub struct CapabilityGrantView {
194 pub id: CapId,
195 pub holder: FlowId,
196 pub target: CapTarget,
197 pub rights: CapRights,
198}
199
200impl CapabilityGrantView {
201 pub fn from_entry(id: CapId, cap: &Capability) -> Self {
202 Self {
203 id,
204 holder: cap.holder,
205 target: cap.cap.target(),
206 rights: cap.cap.rights(),
207 }
208 }
209}
210
211#[derive(Clone, Debug, PartialEq, Eq)]
215pub struct CapabilityAttestation {
216 pub flow: FlowId,
217 pub trust: TrustLevel,
218 pub policy: PolicyFingerprint,
219 pub grants: Vec<CapabilityGrantView>,
220}
221
222impl CapabilityAttestation {
223 pub fn from_table(
224 table: &CapTable,
225 flow: FlowId,
226 trust: TrustLevel,
227 policy: PolicyFingerprint,
228 ) -> Result<Self, RuntimeError> {
229 Ok(Self {
230 flow,
231 trust,
232 policy,
233 grants: table.list_held_by(flow)?,
234 })
235 }
236}
237
238#[derive(Clone, Debug, PartialEq, Eq)]
240pub enum SecurityEvent {
241 CapabilityCreated { holder: u64 },
242 CapabilityDelegated { from: u64, to: u64 },
243 CapabilityRevoked { flow: u64, removed: usize },
244 AccessDenied { reason: &'static str },
245 QuotaExceeded { kind: &'static str },
246 ModuleRejected { reason: &'static str },
247 NativeDenied { index: u32 },
248 FlowFinalized { flow: u64 },
249}
250
251impl std::fmt::Display for SecurityEvent {
252 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
253 match self {
254 SecurityEvent::CapabilityCreated { holder } => {
255 write!(f, "cap_created holder={holder}")
256 }
257 SecurityEvent::CapabilityDelegated { from, to } => {
258 write!(f, "cap_delegated from={from} to={to}")
259 }
260 SecurityEvent::CapabilityRevoked { flow, removed } => {
261 write!(f, "cap_revoked flow={flow} removed={removed}")
262 }
263 SecurityEvent::AccessDenied { reason } => write!(f, "access_denied {reason}"),
264 SecurityEvent::QuotaExceeded { kind } => write!(f, "quota_exceeded {kind}"),
265 SecurityEvent::ModuleRejected { reason } => write!(f, "module_rejected {reason}"),
266 SecurityEvent::NativeDenied { index } => write!(f, "native_denied idx={index}"),
267 SecurityEvent::FlowFinalized { flow } => write!(f, "flow_finalized id={flow}"),
268 }
269 }
270}
271
272pub trait SecurityAuditSink: Send + Sync + std::fmt::Debug + 'static {
279 fn record(&self, event: &SecurityEvent);
280}
281
282pub const DEFAULT_AUDIT_QUEUE: usize = 1024;
284
285pub(crate) struct AuditWorkerHandle {
287 stop: Arc<AtomicBool>,
288 join: Option<JoinHandle<()>>,
289}
290
291impl AuditWorkerHandle {
292 pub(crate) fn stop(mut self) {
293 self.shutdown();
294 }
295
296 fn shutdown(&mut self) {
297 self.stop.store(true, Ordering::Release);
298 if let Some(join) = self.join.take() {
299 let _ = join.join();
300 }
301 }
302}
303
304impl Drop for AuditWorkerHandle {
305 fn drop(&mut self) {
306 self.shutdown();
307 }
308}
309
310#[derive(Debug)]
311struct QueuedAuditSink {
312 tx: SyncSender<SecurityEvent>,
313}
314
315impl SecurityAuditSink for QueuedAuditSink {
316 fn record(&self, event: &SecurityEvent) {
317 let _ = self.tx.try_send(event.clone());
318 }
319}
320
321pub(crate) fn wrap_audit_sink(
327 sink: Arc<dyn SecurityAuditSink>,
328 capacity: usize,
329) -> (Arc<dyn SecurityAuditSink>, AuditWorkerHandle) {
330 let capacity = capacity.max(1);
331 let (tx, rx) = sync_channel::<SecurityEvent>(capacity);
332 let stop = Arc::new(AtomicBool::new(false));
333 let stop_worker = Arc::clone(&stop);
334 let join = thread::Builder::new()
335 .name("byteflow-audit".into())
336 .spawn(move || {
337 while !stop_worker.load(Ordering::Acquire) {
338 match rx.recv_timeout(Duration::from_millis(50)) {
339 Ok(event) => sink.record(&event),
340 Err(RecvTimeoutError::Timeout) => {}
341 Err(RecvTimeoutError::Disconnected) => break,
342 }
343 }
344 while let Ok(event) = rx.try_recv() {
345 sink.record(&event);
346 }
347 })
348 .ok();
349 (
350 Arc::new(QueuedAuditSink { tx }),
351 AuditWorkerHandle { stop, join },
352 )
353}
354
355#[cfg(test)]
356mod tests {
357 use super::*;
358 use crate::bytecode::TrustLevel;
359 use crate::scheduler::mailbox::{MailboxCapacity, MailboxConfig, OverflowPolicy};
360
361 #[test]
362 fn sandbox_fingerprint_differs_from_default() {
363 let permissive = RuntimeConfig::default();
364 let sandboxed = RuntimeConfig::sandbox();
365 assert_ne!(
366 policy_fingerprint(&permissive),
367 policy_fingerprint(&sandboxed)
368 );
369 }
370
371 #[test]
372 fn fingerprint_is_stable_for_identical_config() {
373 let a = RuntimeConfig::sandbox();
374 let b = RuntimeConfig::sandbox();
375 assert_eq!(policy_fingerprint(&a), policy_fingerprint(&b));
376 }
377
378 #[test]
379 fn fingerprint_changes_when_trust_changes() {
380 let mut a = RuntimeConfig::sandbox();
381 let mut b = RuntimeConfig::sandbox();
382 a.trust = TrustLevel::Untrusted;
383 b.trust = TrustLevel::Restricted;
384 assert_ne!(policy_fingerprint(&a), policy_fingerprint(&b));
385 }
386
387 #[test]
388 fn fingerprint_changes_when_mailbox_changes() {
389 let a = RuntimeConfig::sandbox();
390 let mut b = RuntimeConfig::sandbox();
391 b.mailbox = MailboxConfig::new(MailboxCapacity::DEFAULT, OverflowPolicy::DropNewest);
392 assert_ne!(policy_fingerprint(&a), policy_fingerprint(&b));
393 }
394}