Skip to main content

subc_client_rs/
policy_cache.rs

1//! Revision-aware policy resolution for modules that enforce fleet gates.
2
3use 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
21/// The resolver module used when a deployment does not override the target.
22pub 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/// The principal whose policy is being resolved. Wire encoding is the
30/// resolver's UNTAGGED object-key form — `{"agent_id": ...}` or
31/// `{"session_id": ...}` — pinned by the producer-real contract vectors
32/// (tests/fixtures/policy_resolve_contract_vectors.json, vendored from
33/// prefrontal where each committed request is executed against live dispatch).
34/// The first cut serialized a tagged {kind, value} form and every live call
35/// failed shape-parse: prose pinned the field names but only bytes pin an
36/// encoding.
37#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
38pub enum Subject {
39    /// A stable registry agent identifier.
40    #[serde(rename = "agent_id")]
41    AgentId(String),
42    /// A session identifier that the resolver maps to an agent.
43    #[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/// A resolver decision. The vocabulary is closed AT AUTHORING on the resolver
57/// side (policy.set refuses anything but allow | deny | ask, mutation-proved
58/// there), with two reply-only values: `deny` doubles as the policy-less
59/// closed default, and `deny_unknown_domain` marks a domain no producer
60/// declared — a consumer bug surfaced as its own variant rather than folded
61/// into an ordinary deny. `ask` is the ask-first/park spelling: the caller-arm
62/// split (attended parks, unattended treats as transient) happens ABOVE this
63/// type; the helper only carries the verdict. Unknown wire values are retained
64/// so an older consumer does not discard a valid reply from a newer resolver.
65#[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    /// Return the wire spelling of this decision.
76    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/// Bounds owned by the shared resolver helper rather than individual consumers.
113#[derive(Debug, Clone, PartialEq, Eq)]
114pub struct PolicyResolverConfig {
115    /// Maximum duration for opening the resolver route and receiving its reply.
116    pub hard_timeout: Duration,
117    /// Minimum cache lifetime applied to a resolver-provided TTL.
118    pub ttl_floor_ms: u64,
119}
120
121/// A resolver failure rather than a policy decision. The `cause` is
122/// diagnostic prose for logs and operators, never for matching: callers
123/// branch on the VARIANT (per the decision-vs-fault split), and the cause
124/// exists because a unit Fault swallowed three different integration defects
125/// (subject shape, request envelope, wrong route plane) in its first hour,
126/// each costing a raw-probe cycle to see through.
127#[derive(Debug, Clone, PartialEq, Eq)]
128pub enum PolicyResolveError {
129    /// The resolver could not supply a usable decision within the hard timeout.
130    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
151/// Shared resolve-with-cache helper for fleet policy gates.
152///
153/// Each subject (per project root) resolves over its own route, which also
154/// carries a `policy.subscribe` task. State for a subject is released once its
155/// verdicts expire: expired entries are removed, and a route whose last verdict
156/// has expired, with no resolve in flight on it, is closed and its subscription
157/// task aborted. That happens in a sweep at the start of `resolve`, which runs
158/// only once the earliest recorded expiry has passed, so a resolver holds state
159/// only for subjects with a verdict still live, plus at most whatever expired
160/// since its last call. Expiry was chosen over an LRU cap because TTL is what
161/// already bounds a verdict's usefulness, and a cap would either close routes
162/// with live verdicts or need a size nobody can pick for every deployment.
163pub struct PolicyResolver {
164    // Arc so the bump-subscription task can hold the consumer without
165    // demanding Clone on SubcConsumer's public surface.
166    consumer: std::sync::Arc<SubcConsumer>,
167    resolver_module_id: String,
168    config: PolicyResolverConfig,
169    cache: Arc<Mutex<CacheState>>,
170    /// Held by a sweep while it chooses and closes idle routes, and by a
171    /// resolve while it opens its route. Without it a sweep could close a
172    /// route that a resolve had just reopened from the consumer's cache.
173    route_gate: tokio::sync::Mutex<()>,
174    /// Running subscription tasks, counted by the tasks themselves.
175    live_subscriptions: Arc<AtomicUsize>,
176}
177
178/// A resolver route's identity: bind root and route session. Two subjects or
179/// projects that bind the same identity share the route.
180type RouteIdentity = (PathBuf, String);
181
182struct CacheState {
183    last_known_revision: u64,
184    entries: HashMap<CacheKey, CacheEntry>,
185    routes: HashMap<RouteIdentity, RouteState>,
186    /// Earliest instant at which some entry or route may have become
187    /// releasable; `None` when nothing is waiting to expire.
188    next_sweep_at: Option<Instant>,
189    next_subscription_id: u64,
190}
191
192struct RouteState {
193    handle: Option<RouteHandle>,
194    /// Expiry of the latest verdict resolved over this route. A revision bump
195    /// invalidates verdicts but not the route; it stays until this passes.
196    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    /// Remove expired entries and idle routes; return the route handles the
234    /// caller must close. Aborting a subscription task drops its
235    /// `Subscription`, which sends the provider a Cancel.
236    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
263/// Marks a resolve in flight on a route so a sweep leaves the route open.
264struct 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            // A failed or cancelled resolve leaves no verdict to extend the
299            // route's life; let the next sweep consider it.
300            let live_until = route.live_until;
301            state.schedule_sweep(live_until);
302        }
303    }
304}
305
306/// Decrements the live subscription count when its task ends, including by
307/// abort (which drops the task's future, and this with it).
308struct 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/// The project scope being resolved. Untagged params-level form pinned by the
317/// producer vectors: exactly one of `project_root` (filesystem root) or
318/// `project_id` (registry id, resolved through entorhinal) appears in params.
319/// An unknown id REFUSES (`project_unresolved`) rather than draping the
320/// closed default over a typo -- the vector's own name.
321#[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    /// The bind-identity project root: a real root binds as itself; an id has
331    /// no filesystem meaning, so its route identity uses a stable synthetic
332    /// root (the daemon canonicalizes vanished roots, and the resolver never
333    /// reads this field for id-form scope resolution).
334    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)]
357/// The managed-call envelope: `{method, params}` out, `{result}` back — the
358/// module-op convention every consumer speaks (proven against the live
359/// resolver; the first cut sent a flat body its own fake accepted, which is
360/// the build-local trap: the fake must mirror the CONVENTION, not the draft).
361struct 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    /// The CURRENT global policy generation at resolve time — the cache
384    /// watermark — never the matched rule's write stamp (producer-pinned
385    /// semantic: any policy write in any scope bumps it).
386    revision: u64,
387    ttl_ms: u64,
388}
389
390#[derive(Deserialize)]
391struct PolicyRevisionBumpBody {
392    revision: u64,
393}
394
395/// The held-stream event, NESTED framing pinned by the producer's push_event
396/// fixture entry ({op, body: {revision}} -- the rooms.hint_wait emit shape).
397/// A flat {revision} was the eighth encoding drift; the fixture's byte-pin
398/// against the producer's own encoder is what keeps this parser honest.
399#[derive(Deserialize)]
400struct PolicyRevisionBump {
401    op: String,
402    body: PolicyRevisionBumpBody,
403}
404
405/// Per-subject state a [`PolicyResolver`] holds, from [`PolicyResolver::footprint`].
406#[derive(Debug, Clone, Copy, PartialEq, Eq)]
407pub struct PolicyResolverFootprint {
408    /// Cached verdicts.
409    pub entries: usize,
410    /// Resolver routes held open, one per subject and project root.
411    pub routes: usize,
412    /// Running `policy.subscribe` tasks, at most one per held route.
413    pub subscriptions: usize,
414}
415
416impl PolicyResolver {
417    /// Create a resolver that targets [`DEFAULT_POLICY_RESOLVER_MODULE_ID`].
418    pub fn new(consumer: SubcConsumer, config: PolicyResolverConfig) -> Self {
419        Self::with_resolver_target(consumer, DEFAULT_POLICY_RESOLVER_MODULE_ID, config)
420    }
421
422    /// Create a resolver that targets a deployment-specific policy module.
423    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    /// Resolve one gate, using a revision-validated cache entry only while its TTL remains live.
439    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                    // policy.resolve serves on the resolver's MANAGEMENT
485                    // SURFACE (live-proven; a ToolProvider bind reaches the
486                    // wrong plane and faults every call).
487                    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        // Module replies wrap in the `{result}` envelope; a missing wrapper is
506        // a contract violation, not a tolerable variant — the raw shape never
507        // reaches consumers un-enveloped on this convention.
508        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        // A regression cannot be a fresh answer after this process has observed a
518        // newer monotonic generation, so never return or cache it as a decision.
519        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    /// How much per-subject state this resolver holds right now.
541    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    /// Release expired entries and the routes and subscription tasks of
555    /// subjects with no live verdict. A no-op until the earliest recorded
556    /// expiry has passed.
557    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            // A handle from an earlier connection generation fails locally;
565            // that route is already gone with its connection.
566            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            // Never usable again: expired, or from an older revision.
580            cache.entries.remove(key);
581            None
582        }
583    }
584
585    /// Hold the resolver's `policy.subscribe` stream and fold revision bumps
586    /// into the cache watermark. The bump lane is the HOUSE SUBSCRIPTION
587    /// pattern -- a held-open request answered with StreamData events -- not
588    /// spontaneous Push frames; the first cut installed a push receiver its
589    /// own fake satisfied while the live module streamed to nobody (the
590    /// convention-vs-draft class, sixth member). Best-effort by constraint 4:
591    /// the stream dying only means staleness reverts to the TTL bound, so the
592    /// holder re-subscribes on the next resolve rather than retrying in a
593    /// loop.
594    ///
595    /// One task per held route: the task is recorded on the route's state, is
596    /// replaced when the route's handle changes (a reconnect), and is aborted
597    /// when a sweep closes the route.
598    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                    // No bump lane: TTL alone bounds staleness (constraint 4
632                    // makes that correct, merely slower). Clearing the marker
633                    // lets the next resolve retry the subscription.
634                }
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            // A push only makes cached values stale sooner. It never completes a
666            // resolve, creates a verdict, or extends a cached entry's lifetime.
667            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}