1#![allow(missing_docs)]
16
17use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
18use std::sync::mpsc::{sync_channel, RecvTimeoutError, SyncSender};
19use std::sync::Arc;
20use std::thread::{self, JoinHandle};
21use std::time::Duration;
22
23use crate::bytecode::{CapId, CapRights, CapTarget, TrustLevel};
24
25use super::capability::{CapTable, Capability};
26use super::error::RuntimeError;
27use super::process::FlowId;
28use super::runtime::RuntimeConfig;
29
30const POLICY_VERSION: u8 = 1;
32
33#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
41pub struct PolicyFingerprint([u8; 16]);
42
43impl PolicyFingerprint {
44 pub fn as_bytes(&self) -> &[u8; 16] {
45 &self.0
46 }
47
48 pub fn to_hex(&self) -> String {
49 let mut s = String::with_capacity(32);
50 for b in &self.0 {
51 use std::fmt::Write as _;
52 let _ = write!(s, "{b:02x}");
53 }
54 s
55 }
56}
57
58impl std::fmt::Display for PolicyFingerprint {
59 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60 f.write_str(&self.to_hex())
61 }
62}
63
64pub fn policy_fingerprint(config: &RuntimeConfig) -> PolicyFingerprint {
79 let digest = crate::digest::sha256(&canonical_policy_bytes(config));
80 let mut out = [0u8; 16];
81 out.copy_from_slice(&digest[..16]);
82 PolicyFingerprint(out)
83}
84
85fn canonical_policy_bytes(config: &RuntimeConfig) -> Vec<u8> {
86 let mut buf = Vec::with_capacity(100);
87 buf.extend_from_slice(b"BFQP");
88 buf.push(POLICY_VERSION);
89 buf.push(trust_tag(config.trust));
90 buf.push(root_authority_tag(config.root_authority));
91 push_u32(&mut buf, config.max_flows);
92 push_u32(&mut buf, config.max_ask_waits);
93 push_u32(&mut buf, config.max_host_awaits);
94 push_u32(&mut buf, config.max_links);
95 push_u32(&mut buf, config.max_monitors);
96 push_u32(&mut buf, config.max_registry_names);
97 push_u64(&mut buf, as_u64(config.max_runtime_bytes));
98 push_u32(&mut buf, config.mailbox.capacity().get_u32());
99 push_u64(&mut buf, as_u64(config.mailbox.bytes().get()));
100 buf.push(config.mailbox.overflow() as u8);
101 let q = &config.quota;
102 push_i64(&mut buf, q.cpu_budget);
103 push_u64(&mut buf, as_u64(q.mem_limit));
104 push_i64(&mut buf, q.spawn_burst);
105 push_i64(&mut buf, q.spawn_per_sec);
106 push_i64(&mut buf, q.send_burst);
107 push_i64(&mut buf, q.send_per_sec);
108 buf
109}
110
111fn as_u64(n: usize) -> u64 {
112 match u64::try_from(n) {
113 Ok(v) => v,
114 Err(_) => u64::MAX,
115 }
116}
117
118fn push_u32(buf: &mut Vec<u8>, value: u32) {
119 buf.extend_from_slice(&value.to_le_bytes());
120}
121
122fn push_u64(buf: &mut Vec<u8>, value: u64) {
123 buf.extend_from_slice(&value.to_le_bytes());
124}
125
126fn push_i64(buf: &mut Vec<u8>, value: i64) {
127 buf.extend_from_slice(&value.to_le_bytes());
128}
129
130fn trust_tag(trust: TrustLevel) -> u8 {
131 match trust {
132 TrustLevel::Trusted => 0,
133 TrustLevel::Restricted => 1,
134 TrustLevel::Untrusted => 2,
135 }
136}
137
138fn root_authority_tag(policy: crate::scheduler::RootAuthorityPolicy) -> u8 {
139 match policy {
140 crate::scheduler::RootAuthorityPolicy::TrustedHost => 0,
141 crate::scheduler::RootAuthorityPolicy::Restricted => 1,
142 crate::scheduler::RootAuthorityPolicy::Untrusted => 2,
143 }
144}
145
146#[derive(Default, Debug)]
148pub struct SecurityCounters {
149 pub denied_operations: AtomicU64,
150 pub quota_exceeded: AtomicU64,
151 pub capabilities_created: AtomicU64,
152 pub capabilities_revoked: AtomicU64,
153 pub invalid_modules: AtomicU64,
154 pub native_denied: AtomicU64,
155 pub active_untrusted_flows: AtomicU64,
156}
157
158impl SecurityCounters {
159 #[inline]
160 pub fn inc(counter: &AtomicU64) {
161 counter.fetch_add(1, Ordering::Relaxed);
162 }
163
164 pub fn dec_active_untrusted(&self) {
166 let mut cur = self.active_untrusted_flows.load(Ordering::Relaxed);
167 while cur > 0 {
168 match self.active_untrusted_flows.compare_exchange_weak(
169 cur,
170 cur - 1,
171 Ordering::Relaxed,
172 Ordering::Relaxed,
173 ) {
174 Ok(_) => return,
175 Err(actual) => cur = actual,
176 }
177 }
178 }
179
180 pub fn snapshot(&self) -> SecurityCountersSnapshot {
181 SecurityCountersSnapshot {
182 denied_operations: self.denied_operations.load(Ordering::Relaxed),
183 quota_exceeded: self.quota_exceeded.load(Ordering::Relaxed),
184 capabilities_created: self.capabilities_created.load(Ordering::Relaxed),
185 capabilities_revoked: self.capabilities_revoked.load(Ordering::Relaxed),
186 invalid_modules: self.invalid_modules.load(Ordering::Relaxed),
187 native_denied: self.native_denied.load(Ordering::Relaxed),
188 active_untrusted_flows: self.active_untrusted_flows.load(Ordering::Relaxed),
189 }
190 }
191}
192
193#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
195pub struct SecurityCountersSnapshot {
196 pub denied_operations: u64,
197 pub quota_exceeded: u64,
198 pub capabilities_created: u64,
199 pub capabilities_revoked: u64,
200 pub invalid_modules: u64,
201 pub native_denied: u64,
202 pub active_untrusted_flows: u64,
203}
204
205impl std::fmt::Display for SecurityCountersSnapshot {
206 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
207 write!(
208 f,
209 "denied={} quota={} caps_created={} caps_revoked={} invalid_modules={} native_denied={} untrusted_flows={}",
210 self.denied_operations,
211 self.quota_exceeded,
212 self.capabilities_created,
213 self.capabilities_revoked,
214 self.invalid_modules,
215 self.native_denied,
216 self.active_untrusted_flows,
217 )
218 }
219}
220
221#[derive(Clone, Debug, PartialEq, Eq)]
223pub struct CapabilityGrantView {
224 pub id: CapId,
225 pub holder: FlowId,
226 pub target: CapTarget,
227 pub rights: CapRights,
228}
229
230impl CapabilityGrantView {
231 pub fn from_entry(id: CapId, cap: &Capability) -> Self {
232 Self {
233 id,
234 holder: cap.holder,
235 target: cap.cap.target(),
236 rights: cap.cap.rights(),
237 }
238 }
239}
240
241#[derive(Clone, Debug, PartialEq, Eq)]
245pub struct CapabilityAttestation {
246 pub flow: FlowId,
247 pub trust: TrustLevel,
248 pub policy: PolicyFingerprint,
249 pub grants: Vec<CapabilityGrantView>,
250}
251
252impl CapabilityAttestation {
253 pub fn from_table(
254 table: &CapTable,
255 flow: FlowId,
256 trust: TrustLevel,
257 policy: PolicyFingerprint,
258 ) -> Result<Self, RuntimeError> {
259 Ok(Self {
260 flow,
261 trust,
262 policy,
263 grants: table.list_held_by(flow)?,
264 })
265 }
266}
267
268#[derive(Clone, Debug, PartialEq, Eq)]
270pub enum SecurityEvent {
271 CapabilityCreated { holder: u64 },
272 CapabilityDelegated { from: u64, to: u64 },
273 CapabilityRevoked { flow: u64, removed: usize },
274 AccessDenied { reason: &'static str },
275 QuotaExceeded { kind: &'static str },
276 ModuleRejected { reason: &'static str },
277 NativeDenied { index: u32 },
278 FlowFinalized { flow: u64 },
279}
280
281impl std::fmt::Display for SecurityEvent {
282 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
283 match self {
284 SecurityEvent::CapabilityCreated { holder } => {
285 write!(f, "cap_created holder={holder}")
286 }
287 SecurityEvent::CapabilityDelegated { from, to } => {
288 write!(f, "cap_delegated from={from} to={to}")
289 }
290 SecurityEvent::CapabilityRevoked { flow, removed } => {
291 write!(f, "cap_revoked flow={flow} removed={removed}")
292 }
293 SecurityEvent::AccessDenied { reason } => write!(f, "access_denied {reason}"),
294 SecurityEvent::QuotaExceeded { kind } => write!(f, "quota_exceeded {kind}"),
295 SecurityEvent::ModuleRejected { reason } => write!(f, "module_rejected {reason}"),
296 SecurityEvent::NativeDenied { index } => write!(f, "native_denied idx={index}"),
297 SecurityEvent::FlowFinalized { flow } => write!(f, "flow_finalized id={flow}"),
298 }
299 }
300}
301
302pub trait SecurityAuditSink: Send + Sync + std::fmt::Debug + 'static {
309 fn record(&self, event: &SecurityEvent);
310}
311
312pub(super) const DEFAULT_AUDIT_QUEUE: usize = 1024;
314
315pub(crate) struct AuditWorkerHandle {
317 stop: Arc<AtomicBool>,
318 join: Option<JoinHandle<()>>,
319}
320
321impl AuditWorkerHandle {
322 pub(crate) fn stop(mut self) {
323 self.shutdown();
324 }
325
326 fn shutdown(&mut self) {
327 self.stop.store(true, Ordering::Release);
328 if let Some(join) = self.join.take() {
329 let _ = join.join();
330 }
331 }
332}
333
334impl Drop for AuditWorkerHandle {
335 fn drop(&mut self) {
336 self.shutdown();
337 }
338}
339
340#[derive(Debug)]
341struct QueuedAuditSink {
342 tx: SyncSender<SecurityEvent>,
343}
344
345impl SecurityAuditSink for QueuedAuditSink {
346 fn record(&self, event: &SecurityEvent) {
347 let _ = self.tx.try_send(event.clone());
348 }
349}
350
351pub(crate) fn wrap_audit_sink(
357 sink: Arc<dyn SecurityAuditSink>,
358 capacity: usize,
359) -> (Arc<dyn SecurityAuditSink>, AuditWorkerHandle) {
360 let capacity = capacity.max(1);
361 let (tx, rx) = sync_channel::<SecurityEvent>(capacity);
362 let stop = Arc::new(AtomicBool::new(false));
363 let stop_worker = Arc::clone(&stop);
364 let join = thread::Builder::new()
365 .name("byteflow-audit".into())
366 .spawn(move || {
367 while !stop_worker.load(Ordering::Acquire) {
368 match rx.recv_timeout(Duration::from_millis(50)) {
369 Ok(event) => sink.record(&event),
370 Err(RecvTimeoutError::Timeout) => {}
371 Err(RecvTimeoutError::Disconnected) => break,
372 }
373 }
374 while let Ok(event) = rx.try_recv() {
375 sink.record(&event);
376 }
377 })
378 .ok();
379 (
380 Arc::new(QueuedAuditSink { tx }),
381 AuditWorkerHandle { stop, join },
382 )
383}
384
385#[cfg(test)]
386mod tests {
387 use super::*;
388 use crate::bytecode::TrustLevel;
389 use crate::scheduler::mailbox::{MailboxCapacity, MailboxConfig, OverflowPolicy};
390
391 #[test]
392 fn sandbox_fingerprint_differs_from_default() {
393 let permissive = RuntimeConfig::default();
394 let sandboxed = RuntimeConfig::sandbox();
395 assert_ne!(
396 policy_fingerprint(&permissive),
397 policy_fingerprint(&sandboxed)
398 );
399 }
400
401 #[test]
402 fn fingerprint_is_stable_for_identical_config() {
403 let a = RuntimeConfig::sandbox();
404 let b = RuntimeConfig::sandbox();
405 assert_eq!(policy_fingerprint(&a), policy_fingerprint(&b));
406 }
407
408 #[test]
410 fn fingerprint_matches_canonical_sha256_prefix() {
411 assert_eq!(
412 policy_fingerprint(&RuntimeConfig::default()).to_hex(),
413 "2e1be905f47892334e759d3327a05d46"
414 );
415 assert_eq!(
416 policy_fingerprint(&RuntimeConfig::sandbox()).to_hex(),
417 "d59bbad5eefb7b525a0cdeaf6708be36"
418 );
419 }
420
421 #[test]
422 fn fingerprint_changes_when_trust_changes() {
423 let mut a = RuntimeConfig::sandbox();
424 let mut b = RuntimeConfig::sandbox();
425 a.trust = TrustLevel::Untrusted;
426 b.trust = TrustLevel::Restricted;
427 assert_ne!(policy_fingerprint(&a), policy_fingerprint(&b));
428 }
429
430 #[test]
431 fn fingerprint_changes_when_mailbox_changes() {
432 let a = RuntimeConfig::sandbox();
433 let mut b = RuntimeConfig::sandbox();
434 b.mailbox = MailboxConfig::new(MailboxCapacity::DEFAULT, OverflowPolicy::DropNewest);
435 assert_ne!(policy_fingerprint(&a), policy_fingerprint(&b));
436 }
437}