1use std::{
4 collections::HashMap,
5 error::Error,
6 fmt,
7 path::PathBuf,
8 sync::{
9 atomic::{AtomicUsize, Ordering as AtomicOrdering},
10 Arc, Mutex,
11 },
12 time::{Duration, Instant},
13};
14
15use serde::{Deserialize, Deserializer, Serialize, Serializer};
16use subc_protocol::{BindIdentity, RouteTarget};
17use tokio::time::timeout;
18
19use crate::{CallOptions, CloseRouteOptions, RouteHandle, SubcConsumer, SubscribeOptions};
20
21pub const DEFAULT_POLICY_RESOLVER_MODULE_ID: &str = "prefrontal-core";
23
24const POLICY_RESOLVER_HARNESS: &str = "subc-client-rs-policy-resolver";
25const POLICY_RESOLVE_OP: &str = "policy.resolve";
26const POLICY_REVISION_BUMP_OP: &str = "policy.revision_bump";
27const POLICY_SUBSCRIBE_OP: &str = "policy.subscribe";
28
29#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
38pub enum Subject {
39 #[serde(rename = "agent_id")]
41 AgentId(String),
42 #[serde(rename = "session_id")]
44 SessionToResolve(String),
45}
46
47impl Subject {
48 fn route_session(&self) -> String {
49 match self {
50 Self::AgentId(agent_id) => format!("agent:{agent_id}"),
51 Self::SessionToResolve(session_id) => format!("session:{session_id}"),
52 }
53 }
54}
55
56#[derive(Debug, Clone, PartialEq, Eq, Hash)]
66pub enum PolicyVerdict {
67 Allow,
68 Deny,
69 Ask,
70 DenyUnknownDomain,
71 Unknown(String),
72}
73
74impl PolicyVerdict {
75 pub fn as_str(&self) -> &str {
77 match self {
78 Self::Allow => "allow",
79 Self::Deny => "deny",
80 Self::Ask => "ask",
81 Self::DenyUnknownDomain => "deny_unknown_domain",
82 Self::Unknown(value) => value,
83 }
84 }
85}
86
87impl Serialize for PolicyVerdict {
88 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
89 where
90 S: Serializer,
91 {
92 serializer.serialize_str(self.as_str())
93 }
94}
95
96impl<'de> Deserialize<'de> for PolicyVerdict {
97 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
98 where
99 D: Deserializer<'de>,
100 {
101 let value = String::deserialize(deserializer)?;
102 Ok(match value.as_str() {
103 "allow" => Self::Allow,
104 "deny" => Self::Deny,
105 "ask" => Self::Ask,
106 "deny_unknown_domain" => Self::DenyUnknownDomain,
107 _ => Self::Unknown(value),
108 })
109 }
110}
111
112#[derive(Debug, Clone, PartialEq, Eq)]
114pub struct PolicyResolverConfig {
115 pub hard_timeout: Duration,
117 pub ttl_floor_ms: u64,
119}
120
121#[derive(Debug, Clone, PartialEq, Eq)]
128pub enum PolicyResolveError {
129 Fault { cause: String },
131}
132
133impl PolicyResolveError {
134 fn fault(cause: impl Into<String>) -> Self {
135 Self::Fault {
136 cause: cause.into(),
137 }
138 }
139}
140
141impl fmt::Display for PolicyResolveError {
142 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143 match self {
144 Self::Fault { cause } => write!(f, "policy resolver fault: {cause}"),
145 }
146 }
147}
148
149impl Error for PolicyResolveError {}
150
151pub struct PolicyResolver {
164 consumer: std::sync::Arc<SubcConsumer>,
167 resolver_module_id: String,
168 config: PolicyResolverConfig,
169 cache: Arc<Mutex<CacheState>>,
170 route_gate: tokio::sync::Mutex<()>,
174 live_subscriptions: Arc<AtomicUsize>,
176}
177
178type RouteIdentity = (PathBuf, String);
181
182struct CacheState {
183 last_known_revision: u64,
184 entries: HashMap<CacheKey, CacheEntry>,
185 routes: HashMap<RouteIdentity, RouteState>,
186 next_sweep_at: Option<Instant>,
189 next_subscription_id: u64,
190}
191
192struct RouteState {
193 handle: Option<RouteHandle>,
194 live_until: Instant,
197 in_flight: usize,
198 subscription: Option<SubscriptionTask>,
199}
200
201struct SubscriptionTask {
202 id: u64,
203 handle: RouteHandle,
204 abort: tokio::task::AbortHandle,
205}
206
207impl CacheState {
208 fn new() -> Self {
209 Self {
210 last_known_revision: 0,
211 entries: HashMap::new(),
212 routes: HashMap::new(),
213 next_sweep_at: None,
214 next_subscription_id: 0,
215 }
216 }
217
218 fn observe_revision(&mut self, revision: u64) {
219 if revision > self.last_known_revision {
220 self.last_known_revision = revision;
221 self.entries.clear();
222 }
223 }
224
225 fn schedule_sweep(&mut self, at: Instant) {
226 self.next_sweep_at = Some(self.next_sweep_at.map_or(at, |next| next.min(at)));
227 }
228
229 fn sweep_due(&self, now: Instant) -> bool {
230 self.next_sweep_at.is_some_and(|at| at <= now)
231 }
232
233 fn evict_expired(&mut self, now: Instant) -> Vec<RouteHandle> {
237 self.entries.retain(|_, entry| entry.expires_at > now);
238 let mut closing = Vec::new();
239 self.routes.retain(|_, route| {
240 if route.in_flight > 0 || route.live_until > now {
241 return true;
242 }
243 if let Some(subscription) = route.subscription.take() {
244 subscription.abort.abort();
245 }
246 closing.extend(route.handle);
247 false
248 });
249 self.next_sweep_at = None;
250 let pending = self
251 .entries
252 .values()
253 .map(|entry| entry.expires_at)
254 .chain(self.routes.values().map(|route| route.live_until))
255 .collect::<Vec<_>>();
256 for at in pending {
257 self.schedule_sweep(at);
258 }
259 closing
260 }
261}
262
263struct InFlight {
265 cache: Arc<Mutex<CacheState>>,
266 route: RouteIdentity,
267}
268
269impl InFlight {
270 fn enter(cache: &Arc<Mutex<CacheState>>, route: RouteIdentity) -> Self {
271 let now = Instant::now();
272 let mut state = lock(cache);
273 state
274 .routes
275 .entry(route.clone())
276 .or_insert_with(|| RouteState {
277 handle: None,
278 live_until: now,
279 in_flight: 0,
280 subscription: None,
281 })
282 .in_flight += 1;
283 Self {
284 cache: Arc::clone(cache),
285 route,
286 }
287 }
288}
289
290impl Drop for InFlight {
291 fn drop(&mut self) {
292 let mut state = lock(&self.cache);
293 let Some(route) = state.routes.get_mut(&self.route) else {
294 return;
295 };
296 route.in_flight -= 1;
297 if route.in_flight == 0 {
298 let live_until = route.live_until;
301 state.schedule_sweep(live_until);
302 }
303 }
304}
305
306struct LiveSubscription(Arc<AtomicUsize>);
309
310impl Drop for LiveSubscription {
311 fn drop(&mut self) {
312 self.0.fetch_sub(1, AtomicOrdering::SeqCst);
313 }
314}
315
316#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
322pub enum ProjectRef {
323 #[serde(rename = "project_root")]
324 Root(String),
325 #[serde(rename = "project_id")]
326 Id(String),
327}
328
329impl ProjectRef {
330 fn bind_root(&self) -> PathBuf {
335 match self {
336 Self::Root(root) => PathBuf::from(root),
337 Self::Id(_) => PathBuf::from("/"),
338 }
339 }
340}
341
342#[derive(Clone, PartialEq, Eq, Hash)]
343struct CacheKey {
344 domain: String,
345 gate_id: String,
346 subject: Subject,
347 project: ProjectRef,
348}
349
350struct CacheEntry {
351 verdict: PolicyVerdict,
352 revision: u64,
353 expires_at: Instant,
354}
355
356#[derive(Serialize)]
357struct PolicyResolveRequest<'a> {
362 method: &'static str,
363 params: PolicyResolveParams<'a>,
364}
365
366#[derive(Serialize)]
367struct PolicyResolveParams<'a> {
368 domain: &'a str,
369 gate_id: &'a str,
370 subject: &'a Subject,
371 #[serde(flatten)]
372 project: &'a ProjectRef,
373}
374
375#[derive(Deserialize)]
376struct PolicyResolveEnvelope {
377 result: PolicyResolveReply,
378}
379
380#[derive(Deserialize)]
381struct PolicyResolveReply {
382 verdict: PolicyVerdict,
383 revision: u64,
387 ttl_ms: u64,
388}
389
390#[derive(Deserialize)]
391struct PolicyRevisionBumpBody {
392 revision: u64,
393}
394
395#[derive(Deserialize)]
400struct PolicyRevisionBump {
401 op: String,
402 body: PolicyRevisionBumpBody,
403}
404
405#[derive(Debug, Clone, Copy, PartialEq, Eq)]
407pub struct PolicyResolverFootprint {
408 pub entries: usize,
410 pub routes: usize,
412 pub subscriptions: usize,
414}
415
416impl PolicyResolver {
417 pub fn new(consumer: SubcConsumer, config: PolicyResolverConfig) -> Self {
419 Self::with_resolver_target(consumer, DEFAULT_POLICY_RESOLVER_MODULE_ID, config)
420 }
421
422 pub fn with_resolver_target(
424 consumer: SubcConsumer,
425 resolver_module_id: impl Into<String>,
426 config: PolicyResolverConfig,
427 ) -> Self {
428 Self {
429 consumer: std::sync::Arc::new(consumer),
430 resolver_module_id: resolver_module_id.into(),
431 config,
432 cache: Arc::new(Mutex::new(CacheState::new())),
433 route_gate: tokio::sync::Mutex::new(()),
434 live_subscriptions: Arc::new(AtomicUsize::new(0)),
435 }
436 }
437
438 pub async fn resolve(
440 &self,
441 domain: &str,
442 gate_id: &str,
443 subject: Subject,
444 project: ProjectRef,
445 ) -> Result<PolicyVerdict, PolicyResolveError> {
446 let key = CacheKey {
447 domain: domain.to_string(),
448 gate_id: gate_id.to_string(),
449 subject: subject.clone(),
450 project: project.clone(),
451 };
452
453 self.sweep_expired().await;
454 if let Some(verdict) = self.cached_verdict(&key) {
455 return Ok(verdict);
456 }
457 let route_id: RouteIdentity = (project.bind_root(), subject.route_session());
458 let _in_flight = InFlight::enter(&self.cache, route_id.clone());
459
460 let request = PolicyResolveRequest {
461 method: POLICY_RESOLVE_OP,
462 params: PolicyResolveParams {
463 domain,
464 gate_id,
465 subject: &subject,
466 project: &project,
467 },
468 };
469 let body = serde_json::to_vec(&request)
470 .map_err(|e| PolicyResolveError::fault(format!("request encode: {e}")))?;
471 let route_identity =
472 BindIdentity::new(POLICY_RESOLVER_HARNESS.to_string(), subject.route_session());
473 let call_options = CallOptions {
474 timeout: self.config.hard_timeout,
475 route_retry_deadline: self.config.hard_timeout,
476 ..CallOptions::default()
477 };
478
479 let wire_call = async {
480 let gate = self.route_gate.lock().await;
481 let route = self
482 .consumer
483 .open_route(
484 RouteTarget::ManagementSurface {
488 module_id: self.resolver_module_id.clone(),
489 },
490 route_identity,
491 call_options.clone(),
492 )
493 .await
494 .map_err(|e| PolicyResolveError::fault(format!("route open: {e}")))?;
495 drop(gate);
496 self.install_push_receiver(&route_id, route);
497 self.consumer
498 .request(&route, body, call_options)
499 .await
500 .map_err(|e| PolicyResolveError::fault(format!("request: {e}")))
501 };
502 let response = timeout(self.config.hard_timeout, wire_call)
503 .await
504 .map_err(|_| PolicyResolveError::fault("hard timeout elapsed"))??;
505 let envelope: PolicyResolveEnvelope = serde_json::from_slice(&response)
509 .map_err(|e| PolicyResolveError::fault(format!("reply envelope: {e}")))?;
510 let reply = envelope.result;
511 let ttl = Duration::from_millis(reply.ttl_ms.max(self.config.ttl_floor_ms));
512 let expires_at = Instant::now()
513 .checked_add(ttl)
514 .ok_or_else(|| PolicyResolveError::fault("ttl overflow"))?;
515
516 let mut cache = lock(&self.cache);
517 if reply.revision < cache.last_known_revision {
520 return Err(PolicyResolveError::fault(
521 "reply revision regressed below an observed generation",
522 ));
523 }
524 cache.observe_revision(reply.revision);
525 if let Some(route) = cache.routes.get_mut(&route_id) {
526 route.live_until = route.live_until.max(expires_at);
527 }
528 cache.schedule_sweep(expires_at);
529 cache.entries.insert(
530 key,
531 CacheEntry {
532 verdict: reply.verdict.clone(),
533 revision: reply.revision,
534 expires_at,
535 },
536 );
537 Ok(reply.verdict)
538 }
539
540 pub fn footprint(&self) -> PolicyResolverFootprint {
542 let cache = lock(&self.cache);
543 PolicyResolverFootprint {
544 entries: cache.entries.len(),
545 routes: cache
546 .routes
547 .values()
548 .filter(|route| route.handle.is_some())
549 .count(),
550 subscriptions: self.live_subscriptions.load(AtomicOrdering::SeqCst),
551 }
552 }
553
554 async fn sweep_expired(&self) {
558 if !lock(&self.cache).sweep_due(Instant::now()) {
559 return;
560 }
561 let _gate = self.route_gate.lock().await;
562 let closing = lock(&self.cache).evict_expired(Instant::now());
563 for handle in closing {
564 let _ = self
567 .consumer
568 .close_handle(&handle, CloseRouteOptions::default())
569 .await;
570 }
571 }
572
573 fn cached_verdict(&self, key: &CacheKey) -> Option<PolicyVerdict> {
574 let mut cache = lock(&self.cache);
575 let entry = cache.entries.get(key)?;
576 if entry.expires_at > Instant::now() && entry.revision == cache.last_known_revision {
577 Some(entry.verdict.clone())
578 } else {
579 cache.entries.remove(key);
581 None
582 }
583 }
584
585 fn install_push_receiver(&self, route_id: &RouteIdentity, route: RouteHandle) {
599 let mut cache = lock(&self.cache);
600 let id = cache.next_subscription_id;
601 let Some(state) = cache.routes.get_mut(route_id) else {
602 return;
603 };
604 state.handle = Some(route);
605 if let Some(existing) = &state.subscription {
606 if existing.handle == route {
607 return;
608 }
609 existing.abort.abort();
610 }
611 let consumer = std::sync::Arc::clone(&self.consumer);
612 let task_cache = Arc::clone(&self.cache);
613 let task_route_id = route_id.clone();
614 self.live_subscriptions.fetch_add(1, AtomicOrdering::SeqCst);
615 let live = LiveSubscription(Arc::clone(&self.live_subscriptions));
616 let body = serde_json::to_vec(&serde_json::json!({
617 "method": POLICY_SUBSCRIBE_OP,
618 "params": {},
619 }))
620 .expect("static subscribe body serializes");
621 let task = tokio::spawn(async move {
622 let _live = live;
623 match consumer
624 .subscribe_route(&route, body, SubscribeOptions::default())
625 .await
626 {
627 Ok(mut subscription) => {
628 drain_revision_bumps(subscription.events(), Arc::clone(&task_cache)).await;
629 }
630 Err(_) => {
631 }
635 }
636 let mut cache = lock(&task_cache);
637 if let Some(state) = cache.routes.get_mut(&task_route_id) {
638 if state
639 .subscription
640 .as_ref()
641 .is_some_and(|task| task.id == id)
642 {
643 state.subscription = None;
644 }
645 }
646 });
647 state.subscription = Some(SubscriptionTask {
648 id,
649 handle: route,
650 abort: task.abort_handle(),
651 });
652 cache.next_subscription_id += 1;
653 }
654}
655
656async fn drain_revision_bumps(
657 events: &mut tokio::sync::mpsc::Receiver<Vec<u8>>,
658 cache: Arc<Mutex<CacheState>>,
659) {
660 while let Some(body) = events.recv().await {
661 let Ok(bump) = serde_json::from_slice::<PolicyRevisionBump>(&body) else {
662 continue;
663 };
664 if bump.op == POLICY_REVISION_BUMP_OP {
665 lock(&cache).observe_revision(bump.body.revision);
668 }
669 }
670}
671
672fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
673 mutex
674 .lock()
675 .unwrap_or_else(|poisoned| poisoned.into_inner())
676}
677
678#[cfg(test)]
679mod tests {
680 use super::PolicyVerdict;
681
682 #[test]
683 fn unknown_verdict_strings_are_retained_for_forward_compatibility() {
684 let verdict: PolicyVerdict = serde_json::from_str("\"future_verdict\"").unwrap();
685 assert_eq!(
686 verdict,
687 PolicyVerdict::Unknown("future_verdict".to_string())
688 );
689 }
690}