Skip to main content

lean_ctx/core/policy/
runtime.rs

1//! Runtime view of the active context policy pack (GL #673 / #489 enforcement).
2//!
3//! [`active`] refreshes bounded policy and organization trust bytes on every
4//! admission. Identical snapshots reuse prepared rules; changed or unreadable
5//! inputs never reuse a stale authorization. One bounded worker serializes file
6//! resolution and compilation without accumulating timed-out reader threads.
7//!
8//! **Opt-in & backward-compatible:** with no project pack present, [`active`]
9//! returns `None` and nothing is gated — existing behavior is preserved
10//! exactly. An invalid local pack activates a deny-all policy so enforcement
11//! never fails open.
12//!
13//! **Local-Free Invariant:** enforcement derived from this view only ever
14//! constrains the *agent* pipeline; it never gates a human's own local reads.
15
16use std::path::{Path, PathBuf};
17use std::sync::Arc;
18use std::sync::atomic::{AtomicBool, Ordering};
19#[cfg(any(test, feature = "test-support"))]
20use std::sync::{OnceLock, RwLock};
21
22use regex::Regex;
23
24use super::ResolvedPolicy;
25#[cfg(test)]
26use super::{parse_file, resolve};
27use crate::core::input_filters::{FilterAction, FilterConfig};
28
29mod refresh;
30/// Process-scoped pin set by explicit protected launchers; absent in Community.
31pub const REQUIRED_POLICY_ROOT_ENV: &str = "LEAN_CTX_REQUIRED_POLICY_ROOT";
32pub const REQUIRED_POLICY_DIGEST_ENV: &str = "LEAN_CTX_REQUIRED_POLICY_DIGEST";
33pub use refresh::{protected_authority_paths, protected_policy_digest};
34#[cfg(any(test, feature = "test-support"))]
35pub mod held_horizon_support;
36#[cfg(test)]
37pub(crate) mod held_horizon_tests;
38#[cfg(test)]
39mod refresh_tests;
40
41tokio::task_local! {
42    /// Per-request project authority; never mutate process CWD for MCP roots.
43    pub static REQUEST_PROJECT: std::cell::RefCell<Option<PathBuf>>;
44    /// Immutable policy view for one synchronous source-admission operation.
45    pub(crate) static SOURCE_VIEW: std::cell::RefCell<Option<SourceView>>;
46}
47
48#[derive(Clone)]
49pub struct SourceView {
50    project: PathBuf,
51    policy: Option<Arc<ActivePolicy>>,
52    fingerprint: blake3::Hash,
53    role: crate::core::roles::Role,
54    role_fingerprint: blake3::Hash,
55    /// Set when the pinned policy rests on a verifier's decision.
56    ///
57    /// Two different bounds, deliberately: the request deadline bounded the
58    /// decision itself — asking, recording, handing out — and ended with the
59    /// refresh that produced this view. The operation running on the view is
60    /// bounded by the signed horizon instead, checked on a fresh clock at
61    /// every use of the held policy, at every nested admission and last,
62    /// after all closing waits, before anything is published. A lifted
63    /// requirement has no horizon: it is durable marker state, and the view
64    /// stays bound to it through the fingerprint.
65    lifetime: Option<super::org::Lifetime>,
66    /// What the verifier's answer stated, from the same verification the
67    /// pinned policy rests on. Never read again for this view.
68    observation: Option<super::org::Observation>,
69    valid: Arc<AtomicBool>,
70    live: Arc<AtomicBool>,
71}
72
73impl SourceView {
74    /// Whether the signed horizon still holds; a view past it is invalid for
75    /// good, like one whose authority changed.
76    fn within_horizon(&self) -> bool {
77        let holds = self
78            .lifetime
79            .is_none_or(|lifetime| lifetime.check_horizon().is_ok());
80        if !holds {
81            self.valid.store(false, Ordering::Release);
82        }
83        holds
84    }
85
86    /// Invalidate the view for its owner — but only while it is still live.
87    /// A straggler that merely finds the view ended (a timed-out worker whose
88    /// result its caller already discarded) must not poison the owner's
89    /// closing check: that turned complete, unchanged `ctx_compose` results
90    /// into "source authority changed" refusals (~3 % of calls, focus
91    /// analysis 2026-10-15). Inconsistencies seen during the view's life
92    /// still invalidate it.
93    fn invalidate_if_live(&self) {
94        if self.live.load(Ordering::Acquire) {
95            self.valid.store(false, Ordering::Release);
96        }
97    }
98}
99
100struct SourceViewLifetime(Arc<AtomicBool>);
101
102/// The stored form of a [`PublicationAuthority`]: project root, policy and
103/// role fingerprints and the lifetime of the view it was captured from.
104/// Content-free.
105#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
106#[serde(deny_unknown_fields)]
107pub struct StoredPublicationAuthority {
108    project: PathBuf,
109    fingerprint: [u8; 32],
110    role_fingerprint: [u8; 32],
111    lifetime: Option<StoredLifetime>,
112}
113
114/// The stored lifetime of a view: its signed horizon, `None` for a view bound
115/// to a lifted requirement, which has none.
116#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
117#[serde(deny_unknown_fields)]
118pub struct StoredLifetime {
119    horizon: Option<lean_ctx_time::UtcDateTime>,
120}
121
122/// Revalidate buffered CLI data at its output and persistence boundaries.
123/// This does not lock policy files against a concurrent administrator write.
124#[derive(Debug)]
125pub struct PublicationAuthority {
126    project: PathBuf,
127    fingerprint: blake3::Hash,
128    role_fingerprint: blake3::Hash,
129    /// The horizon of the view the buffered data was produced under.
130    lifetime: Option<super::org::Lifetime>,
131    valid: Arc<AtomicBool>,
132}
133
134impl PublicationAuthority {
135    pub fn capture() -> Result<Self, String> {
136        let view = current_source_view().ok_or("source authority unavailable")?;
137        if !view.within_horizon() {
138            return Err("source authority unavailable".into());
139        }
140        Ok(Self {
141            project: view.project,
142            fingerprint: view.fingerprint,
143            role_fingerprint: view.role_fingerprint,
144            lifetime: view.lifetime,
145            valid: view.valid,
146        })
147    }
148
149    /// The content-free form a holder that outlives this process keeps (the
150    /// proxy's register of provider-sealed items, #2177). `None` once the
151    /// view this authority was captured from was invalidated: such an
152    /// authority never verifies again, so nothing of it is kept. The flag is
153    /// read at this moment; what can still invalidate the view afterwards is
154    /// its signed horizon, which the stored form carries and checks.
155    pub fn stored(&self) -> Option<StoredPublicationAuthority> {
156        self.valid
157            .load(Ordering::Acquire)
158            .then(|| StoredPublicationAuthority {
159                project: self.project.clone(),
160                fingerprint: *self.fingerprint.as_bytes(),
161                role_fingerprint: *self.role_fingerprint.as_bytes(),
162                lifetime: self.lifetime.map(|lifetime| StoredLifetime {
163                    horizon: lifetime.horizon(),
164                }),
165            })
166    }
167
168    /// An authority from its stored form. It proves nothing by itself:
169    /// [`Self::verify`] re-verifies the project policy and role afresh and
170    /// checks the signed horizon, exactly as for an authority captured in
171    /// this process — only the in-process invalidation of the original view
172    /// is not carried over (an invalidated authority is never stored).
173    #[must_use]
174    pub fn restore(stored: StoredPublicationAuthority) -> Self {
175        Self {
176            project: stored.project,
177            fingerprint: blake3::Hash::from_bytes(stored.fingerprint),
178            role_fingerprint: blake3::Hash::from_bytes(stored.role_fingerprint),
179            lifetime: stored
180                .lifetime
181                .map(|lifetime| super::org::Lifetime::restored(lifetime.horizon)),
182            valid: Arc::new(AtomicBool::new(true)),
183        }
184    }
185
186    pub fn verify(&self) -> Result<(), String> {
187        if !self.valid.load(Ordering::Acquire)
188            || REQUEST_PROJECT
189                .try_with(|slot| {
190                    slot.borrow()
191                        .as_ref()
192                        .is_some_and(|root| root != &self.project)
193                })
194                .unwrap_or(false)
195        {
196            return Err("source authority changed before publication".into());
197        }
198        REQUEST_PROJECT.sync_scope(std::cell::RefCell::new(Some(self.project.clone())), || {
199            SOURCE_VIEW.sync_scope(std::cell::RefCell::new(None), || {
200                let latest = refresh::current_verified(self.project.clone())?;
201                let role = role_fingerprint(&crate::core::roles::active_role())?;
202                if latest.fingerprint != self.fingerprint || role != self.role_fingerprint {
203                    return Err("source authority changed before publication".into());
204                }
205                // Last, after the waits above: the buffered data was made
206                // under a floor signed up to a horizon, and is not published
207                // past it even though the authority verifies afresh.
208                if let Some(lifetime) = &self.lifetime {
209                    lifetime.check_horizon()?;
210                }
211                Ok(())
212            })
213        })
214    }
215
216    /// Fingerprint used to bind derived decisions to this exact project and
217    /// policy snapshot without exposing any policy contents.
218    pub fn fingerprint_bytes(&self) -> [u8; 32] {
219        *self.fingerprint.as_bytes()
220    }
221
222    /// Role authorization is a separate part of source authority and must be
223    /// bound independently into persisted provenance metadata.
224    #[cfg(any(test, feature = "http-server"))]
225    pub fn role_fingerprint_bytes(&self) -> [u8; 32] {
226        *self.role_fingerprint.as_bytes()
227    }
228}
229
230impl Drop for SourceViewLifetime {
231    fn drop(&mut self) {
232        self.0.store(false, Ordering::Release);
233    }
234}
235
236fn current_source_view() -> Option<SourceView> {
237    SOURCE_VIEW
238        .try_with(|slot| slot.borrow().clone())
239        .ok()
240        .flatten()
241}
242
243/// Capture the pinned view when propagating a synchronous worker scope.
244pub fn inherited_source_view() -> Option<SourceView> {
245    current_source_view()
246}
247
248/// Resolve the project root for a detached worker without retaining request-
249/// lifetime policy or capture state. The worker must reopen a fresh source view
250/// from this root when it stores output.
251pub fn detached_project_root(fallback: &Path) -> Result<PathBuf, String> {
252    let request_project = REQUEST_PROJECT
253        .try_with(|slot| slot.borrow().clone())
254        .ok()
255        .flatten();
256    if let Some(view) = current_source_view() {
257        if !view.live.load(Ordering::Acquire)
258            || !view.valid.load(Ordering::Acquire)
259            || request_project.as_ref() != Some(&view.project)
260        {
261            view.invalidate_if_live();
262            return Err("source policy view is no longer active".into());
263        }
264        return Ok(view.project);
265    }
266    Ok(request_project.unwrap_or_else(|| fallback.to_path_buf()))
267}
268
269/// Restore a previously captured source view in a detached worker.
270pub(crate) fn with_inherited_source_view<T>(
271    view: Option<SourceView>,
272    operation: impl FnOnce() -> T,
273) -> T {
274    match view {
275        Some(view) => SOURCE_VIEW.sync_scope(std::cell::RefCell::new(Some(view)), operation),
276        None => operation(),
277    }
278}
279
280/// The role paired with the active source view. A closed or rebound inherited
281/// view returns a deny-all role instead of exposing its stale privileges.
282pub(crate) fn pinned_role() -> Option<crate::core::roles::Role> {
283    current_source_view().map(|view| {
284        let project = REQUEST_PROJECT
285            .try_with(|slot| slot.borrow().clone())
286            .ok()
287            .flatten();
288        if !view.live.load(Ordering::Acquire)
289            || !view.valid.load(Ordering::Acquire)
290            || project.as_ref() != Some(&view.project)
291        {
292            view.invalidate_if_live();
293            crate::core::roles::closed_source_view_role()
294        } else {
295            view.role
296        }
297    })
298}
299
300/// Run `operation` as part of a request for `project`.
301pub fn in_project<T>(project: impl Into<PathBuf>, operation: impl FnOnce() -> T) -> T {
302    REQUEST_PROJECT.sync_scope(std::cell::RefCell::new(Some(project.into())), operation)
303}
304
305/// Start `operation` on its own thread as part of a request for `project`.
306/// A spawned thread inherits no task-local: without this it reads the
307/// configuration and admission state of the process's own project (AP04-G3).
308pub fn spawn_for_project<T: Send + 'static>(
309    project: impl Into<PathBuf>,
310    operation: impl FnOnce() -> T + Send + 'static,
311) -> std::thread::JoinHandle<T> {
312    let project = project.into();
313    std::thread::spawn(move || in_project(project, operation))
314}
315
316pub fn bind_request_project(project: Option<&str>) {
317    if current_source_view().is_some() {
318        return;
319    }
320    let _ = REQUEST_PROJECT.try_with(|slot| {
321        *slot.borrow_mut() = project.map(PathBuf::from);
322    });
323}
324
325/// The one spelling of a request project: resolved, and on Windows without
326/// the verbatim `\\?\` prefix (`pathutil::canonicalize_secure`), as the proxy
327/// (`request_project`) and the policy refresh resolve it. A source view
328/// pinned to another spelling of the same root no longer matched the request
329/// project and fell to deny-all on every governed Windows request.
330fn canonical_project_root(project: &Path) -> Result<PathBuf, String> {
331    let project = crate::core::pathutil::canonicalize_secure(project)
332        .map_err(|_| "policy project root unavailable")?;
333    if !project.is_dir() {
334        return Err("policy project root unavailable".into());
335    }
336    Ok(project)
337}
338
339/// Whether the bound request project (if any) is `root`, a root already in
340/// the one spelling of `canonical_project_root`. The bound side is resolved
341/// the same way first: a caller may have bound another spelling of the same
342/// directory (on Windows the verbatim `\\?\` form of `std::fs::canonicalize`).
343/// No bound request project: `true`, the operation's own root governs.
344pub(crate) fn request_project_is(root: &Path) -> bool {
345    match REQUEST_PROJECT.try_with(|slot| slot.borrow().clone()) {
346        Ok(Some(bound)) => canonical_project_root(&bound).is_ok_and(|bound| bound == root),
347        _ => true,
348    }
349}
350
351/// Run a source operation with an explicit fallback project root. An existing
352/// request project remains authoritative; the fallback only fills an unbound
353/// request scope.
354pub fn with_project_source_view<T>(
355    project_root: &str,
356    operation: impl FnOnce() -> T,
357) -> Result<T, String> {
358    let project = REQUEST_PROJECT
359        .try_with(|slot| slot.borrow().clone())
360        .ok()
361        .flatten()
362        .or_else(|| current_source_view().map(|view| view.project))
363        .unwrap_or_else(|| PathBuf::from(project_root));
364    let project = canonical_project_root(&project)?;
365    REQUEST_PROJECT.sync_scope(std::cell::RefCell::new(Some(project)), || {
366        with_source_view(operation)
367    })
368}
369
370/// Run an egress preparation for one explicitly selected project. Unlike the
371/// source-view fallback helper, this rejects a conflicting trusted request root
372/// and revalidates authority after the operation before its result is published.
373pub fn with_explicit_project_source_view<T>(
374    project_root: &Path,
375    operation: impl FnOnce(&PublicationAuthority) -> T,
376) -> Result<T, String> {
377    let project = canonical_project_root(project_root)?;
378
379    let bound = REQUEST_PROJECT
380        .try_with(|slot| slot.borrow().clone())
381        .ok()
382        .flatten();
383    if let Some(bound) = bound {
384        let bound = crate::core::pathutil::canonicalize_secure(&bound)
385            .map_err(|_| "request project authority unavailable")?;
386        if bound != project {
387            return Err("request project authority does not match egress root".into());
388        }
389    }
390    if let Some(view) = current_source_view()
391        && (!view.live.load(Ordering::Acquire)
392            || !view.valid.load(Ordering::Acquire)
393            || view.project != project)
394    {
395        view.invalidate_if_live();
396        return Err("source policy view does not match egress root".into());
397    }
398
399    REQUEST_PROJECT.sync_scope(std::cell::RefCell::new(Some(project)), || {
400        with_source_view(|| {
401            let authority = PublicationAuthority::capture()?;
402            let result = operation(&authority);
403            authority.verify()?;
404            Ok(result)
405        })?
406    })
407}
408
409/// Run a synchronous source operation against one freshly verified policy
410/// snapshot. Publish the returned value only if the same authority still holds.
411/// Nested calls reuse the parent snapshot; they never refresh into a weaker view.
412pub fn with_source_view<T>(operation: impl FnOnce() -> T) -> Result<T, String> {
413    with_source_view_when(|_, _| true, operation)?
414        .ok_or_else(|| "source policy view is no longer active".into())
415}
416
417/// [`with_source_view`] for the project `root` itself, whatever project the
418/// request is bound to. An operation over several roots (`ctx_multi_repo
419/// search`) judges each root under that root's own policy, one view per root:
420/// one request view stretched over another root rebinds the request project
421/// inside it, which ends the view (the operation fails closed) — every
422/// cross-repo search failed that way (#2244). Called inside an open view of
423/// another project, this still ends that view and fails closed.
424pub fn with_root_source_view<T>(root: &Path, operation: impl FnOnce() -> T) -> Result<T, String> {
425    let root = canonical_project_root(root)?;
426    REQUEST_PROJECT.sync_scope(std::cell::RefCell::new(Some(root)), || {
427        with_source_view(operation)
428    })
429}
430
431/// [`with_source_view`], entered only when the verification the view is
432/// pinned to established something to act under: a policy, or an observed
433/// organization decision (a signed unpin leaves no policy and is one all the
434/// same). `Ok(None)`: it established neither, no view was opened and
435/// `operation` did not run.
436///
437/// The decision whether to enter and the view are made of ONE verification:
438/// there is no probe first and a second resolution after, so what the caller
439/// branched on is what its view holds. Everything else is `with_source_view`
440/// — the nested-view rules, the closing recheck and the horizon. Inside,
441/// [`is_active`] and `active_observed` read the held view.
442#[cfg(feature = "http-server")]
443pub fn with_governed_source_view<T>(operation: impl FnOnce() -> T) -> Result<Option<T>, String> {
444    with_source_view_when(|policy, observed| policy || observed, operation)
445}
446
447/// `enter(policy present, organization decision observed)` is asked once, of
448/// the view that would be used; `false` leaves without running `operation`.
449fn with_source_view_when<T>(
450    enter: impl FnOnce(bool, bool) -> bool,
451    operation: impl FnOnce() -> T,
452) -> Result<Option<T>, String> {
453    if let Some(view) = current_source_view() {
454        let project = REQUEST_PROJECT
455            .try_with(|slot| slot.borrow().clone())
456            .ok()
457            .flatten()
458            .ok_or("source policy view is no longer active")?;
459        let project = canonical_project_root(&project)
460            .map_err(|_| "source policy view is no longer active")?;
461        if !view.live.load(Ordering::Acquire)
462            || !view.valid.load(Ordering::Acquire)
463            || project != view.project
464            || !view.within_horizon()
465        {
466            view.invalidate_if_live();
467            return Err("source policy view is no longer active".into());
468        }
469        if !enter(view.policy.is_some(), view.observation.is_some()) {
470            return Ok(None);
471        }
472        return REQUEST_PROJECT
473            .sync_scope(std::cell::RefCell::new(Some(view.project.clone())), || {
474                Ok(Some(operation()))
475            });
476    }
477
478    // A request bound to no project gets no source view: its project is not
479    // invented from the process's working directory (AP01 §3). Only work
480    // outside any request (the CLI) acts for the directory it runs in.
481    let project = match REQUEST_PROJECT.try_with(|slot| slot.borrow().clone()) {
482        Ok(project) => project.ok_or("project_unresolved")?,
483        Err(_) => std::env::current_dir().map_err(|_| "policy project root unavailable")?,
484    };
485    let project = canonical_project_root(&project)?;
486    REQUEST_PROJECT.sync_scope(std::cell::RefCell::new(Some(project.clone())), || {
487        let verified = refresh::current_verified_settled(&project)?;
488        let lifetime = verified.lifetime;
489        let observation = verified.observation;
490        let role = crate::core::roles::active_role();
491        let pinned_role_fingerprint = role_fingerprint(&role)?;
492        let view = SourceView {
493            project: project.clone(),
494            policy: source_view_policy(verified.policy),
495            fingerprint: verified.fingerprint,
496            role,
497            role_fingerprint: pinned_role_fingerprint,
498            lifetime,
499            observation,
500            valid: Arc::new(AtomicBool::new(true)),
501            live: Arc::new(AtomicBool::new(true)),
502        };
503
504        // The reads since the verification took time: the operation is not
505        // entered on a floor whose horizon has already passed.
506        if !view.within_horizon() {
507            return Err("source policy view is no longer active".into());
508        }
509        // Asked of this very verification, before anything runs on it.
510        if !enter(view.policy.is_some(), view.observation.is_some()) {
511            return Ok(None);
512        }
513        let view_lifetime = SourceViewLifetime(view.live.clone());
514        let value = SOURCE_VIEW.sync_scope(std::cell::RefCell::new(Some(view.clone())), operation);
515        drop(view_lifetime);
516
517        // SOURCE_VIEW has ended, while REQUEST_PROJECT still identifies the
518        // same request root; re-resolve the complete role before publishing.
519        let project_unchanged = REQUEST_PROJECT
520            .try_with(|slot| slot.borrow().as_ref() == Some(&view.project))
521            .unwrap_or(false);
522        let latest_role = crate::core::roles::active_role();
523        let latest_role_fingerprint = role_fingerprint(&latest_role)?;
524        let latest = refresh::current_verified_settled(&project)?;
525        if !project_unchanged
526            || latest.fingerprint != view.fingerprint
527            || latest_role_fingerprint != view.role_fingerprint
528            || !view.valid.load(Ordering::Acquire)
529        {
530            return Err("source policy view changed during operation".into());
531        }
532        // Last, after every closing wait: the operation ran on a floor signed
533        // up to a horizon. If that passed in the meantime its result is not
534        // published, whatever the fresh verification above said.
535        if !view.within_horizon() {
536            return Err("source policy view changed during operation".into());
537        }
538        Ok(Some(value))
539    })
540}
541
542pub(crate) fn role_fingerprint(role: &crate::core::roles::Role) -> Result<blake3::Hash, String> {
543    serde_json::to_vec(role)
544        .map(|bytes| blake3::hash(&bytes))
545        .map_err(|_| "source role view unavailable".into())
546}
547
548#[cfg(any(test, feature = "test-support"))]
549fn source_view_policy(fresh: Option<Arc<ActivePolicy>>) -> Option<Arc<ActivePolicy>> {
550    let state = test_override()
551        .read()
552        .unwrap_or_else(std::sync::PoisonError::into_inner);
553    match &*state {
554        OverrideState::Live => fresh,
555        OverrideState::Fixed(policy) => policy.clone(),
556    }
557}
558
559#[cfg(not(any(test, feature = "test-support")))]
560fn source_view_policy(fresh: Option<Arc<ActivePolicy>>) -> Option<Arc<ActivePolicy>> {
561    fresh
562}
563
564/// Project-local pack location, relative to the working directory (matches the
565/// `lean-ctx policy` CLI's `PROJECT_PACK_PATH`).
566const PROJECT_PACK_PATH: &str = ".lean-ctx/policy.toml";
567
568/// A resolved policy plus its precompiled redaction regexes — the cached,
569/// hot-path-ready form.
570pub struct ActivePolicy {
571    pub resolved: ResolvedPolicy,
572    /// `(label, compiled regex)` — labels are the pack's `[redaction]` keys.
573    /// Invalid/over-budget compilation makes the whole policy fail closed.
574    pub redaction: Vec<(String, Regex)>,
575    pub(crate) blocked_patterns: Vec<(String, Regex)>,
576    /// How many of `redaction` + `blocked_patterns` a Cloud filter pack
577    /// added; they have their own budget next to the pack's.
578    pub(crate) cloud_rules: usize,
579    pub content_valid: bool,
580    /// Compiled inbound content filters (GL #675), built once from the pack's
581    /// `[filters]` section.
582    pub filters: FilterConfig,
583    /// Compiled egress/output DLP config (GL #676), built once from the pack's
584    /// `[egress]` section.
585    pub egress: crate::core::egress::EgressConfig,
586    /// The signed instant this policy's organization floor runs out at, set
587    /// before the policy is shared and never changed. `None` for every policy
588    /// that rests on no verifier decision: local, version one, or a lifted
589    /// requirement. The fields above describe the policy; they authorize
590    /// nothing once this instant has passed — see [`Self::within_horizon`].
591    horizon: Option<lean_ctx_time::UtcDateTime>,
592    /// Set the first time the horizon is observed to have passed, and never
593    /// cleared. It lives in the policy itself, so every holder of the same
594    /// shared policy sees it: once expired, a clock set back revives nothing.
595    expired: AtomicBool,
596}
597
598impl ActivePolicy {
599    /// Whether this policy may still be acted on: read on the real clock at
600    /// every use, so a policy that is kept — in a view, a snapshot or a
601    /// caller's variable — ends with its signed horizon and not with the
602    /// request that obtained it. Exclusive, like the verifier's own check.
603    /// An expiry once observed is final for this policy.
604    #[must_use]
605    pub fn within_horizon(&self) -> bool {
606        if self.expired.load(Ordering::Acquire) {
607            return false;
608        }
609        let holds = self
610            .horizon
611            .is_none_or(|horizon| lean_ctx_time::UtcDateTime::now() < horizon);
612        if !holds {
613            self.expired.store(true, Ordering::Release);
614        }
615        holds
616    }
617
618    /// This policy, ending at `horizon`. Only for a policy not yet shared.
619    fn until(mut self, horizon: Option<lean_ctx_time::UtcDateTime>) -> Self {
620        self.horizon = horizon;
621        self
622    }
623
624    pub fn from_resolved(resolved: ResolvedPolicy) -> Self {
625        Self::from_resolved_with_cloud(
626            resolved,
627            &crate::core::policy::cloud_filters::FilterRules::default(),
628        )
629    }
630
631    /// As [`Self::from_resolved`], with the rules of the installed Cloud
632    /// filter packs added under their own budget. A Cloud rule over its
633    /// bounds fails the policy closed like a pack rule; installation
634    /// refuses such sets, so this is defensive.
635    pub(crate) fn from_resolved_with_cloud(
636        mut resolved: ResolvedPolicy,
637        cloud: &crate::core::policy::cloud_filters::FilterRules,
638    ) -> Self {
639        use super::content::{MAX_REDACTION_RULES, MAX_RULE_LABEL_BYTES, MAX_RULE_PATTERN_BYTES};
640        let cloud_rules = cloud.redaction.len() + cloud.blocked.len();
641        let cloud_bounded = cloud_rules <= crate::core::policy::cloud_filters::CLOUD_MAX_RULES
642            && cloud
643                .redaction
644                .iter()
645                .chain(&cloud.blocked)
646                .all(|(label, pattern)| {
647                    super::is_cloud_label(label)
648                        && label.len() <= MAX_RULE_LABEL_BYTES
649                        && !label.chars().any(char::is_control)
650                        && pattern.len() <= MAX_RULE_PATTERN_BYTES
651                });
652        let bounded = cloud_bounded
653            && resolved.redaction.len() + resolved.filters.blocked_patterns.len()
654                <= MAX_REDACTION_RULES
655            && resolved.egress.forbidden_patterns.len() <= MAX_REDACTION_RULES
656            && resolved
657                .egress
658                .forbidden_patterns
659                .iter()
660                .all(|pattern| pattern.len() <= MAX_RULE_PATTERN_BYTES)
661            && resolved
662                .redaction
663                .iter()
664                .chain(&resolved.filters.blocked_patterns)
665                .all(|(label, pattern)| {
666                    !label.is_empty()
667                        && label.len() <= MAX_RULE_LABEL_BYTES
668                        && !label.chars().any(char::is_control)
669                        && pattern.len() <= MAX_RULE_PATTERN_BYTES
670                });
671        // Pack labels never start with the Cloud prefix (pack validation), so
672        // a Cloud rule neither replaces nor is replaced by a pack rule.
673        resolved.redaction.extend(cloud.redaction.iter().cloned());
674        resolved
675            .filters
676            .blocked_patterns
677            .extend(cloud.blocked.iter().cloned());
678        let compiled = bounded.then(|| {
679            resolved
680                .redaction
681                .iter()
682                .map(|(label, pattern)| {
683                    regex::RegexBuilder::new(pattern)
684                        .size_limit(1024 * 1024)
685                        .dfa_size_limit(1024 * 1024)
686                        .build()
687                        .map(|re| (label.clone(), re))
688                })
689                .collect::<Result<Vec<_>, _>>()
690        });
691        let content_valid = matches!(&compiled, Some(Ok(_)));
692        let redaction = compiled.and_then(Result::ok).unwrap_or_default();
693        let compiled_blocks = bounded.then(|| {
694            resolved
695                .filters
696                .blocked_patterns
697                .iter()
698                .map(|(label, pattern)| {
699                    regex::RegexBuilder::new(pattern)
700                        .size_limit(1024 * 1024)
701                        .dfa_size_limit(1024 * 1024)
702                        .build()
703                        .map(|re| (label.clone(), re))
704                })
705                .collect::<Result<Vec<_>, _>>()
706        });
707        let content_valid = content_valid && matches!(&compiled_blocks, Some(Ok(_)));
708        let blocked_patterns = compiled_blocks.and_then(Result::ok).unwrap_or_default();
709        let filters = FilterConfig::new(
710            filter_action(resolved.filters.pii.as_ref()),
711            filter_action(resolved.filters.classification.as_ref()),
712            filter_action(resolved.filters.injection.as_ref()),
713            &resolved.filters.blocked_labels,
714        );
715        let egress = crate::core::egress::EgressConfig::new(
716            &resolved.egress.forbidden_patterns,
717            resolved.egress.block_secrets.unwrap_or(false),
718            resolved.egress.max_writes_per_min,
719        );
720        Self {
721            resolved,
722            redaction,
723            blocked_patterns,
724            cloud_rules,
725            content_valid,
726            filters,
727            egress,
728            horizon: None,
729            expired: AtomicBool::new(false),
730        }
731    }
732
733    /// Block every tool after a local policy pack fails to load.
734    pub(crate) fn deny_all() -> Self {
735        let mut active = Self::from_resolved(ResolvedPolicy {
736            name: "invalid-local-policy".into(),
737            version: "0.0.0".into(),
738            description: "deny all because the local policy pack is invalid".into(),
739            chain: Vec::new(),
740            default_read_mode: None,
741            allow_tools: Some(Vec::new()),
742            deny_tools: Vec::new(),
743            max_context_tokens: None,
744            audit_retention_days: None,
745            redaction: std::collections::BTreeMap::new(),
746            filters: crate::core::policy::FilterRules::default(),
747            egress: crate::core::policy::EgressRules::default(),
748            routing: crate::core::policy::RoutingPolicyRules::default(),
749            budgets: crate::core::policy::BudgetRules::default(),
750        });
751        active.content_valid = false;
752        active
753    }
754
755    /// Whether `tool` is permitted by this policy's allow/deny lists.
756    /// `deny_tools` always wins; an `allow_tools` allowlist, when set, is
757    /// exclusive (only listed tools pass).
758    #[must_use]
759    pub fn tool_allowed(&self, tool: &str) -> bool {
760        if !self.content_valid || !self.within_horizon() {
761            return false;
762        }
763        if self.resolved.deny_tools.iter().any(|t| t == tool) {
764            return false;
765        }
766        match &self.resolved.allow_tools {
767            Some(allow) => allow.iter().any(|t| t == tool),
768            None => true,
769        }
770    }
771}
772
773/// Map a resolved `[filters]` action string to a [`FilterAction`]. Absent or
774/// (defensively) unparseable ⇒ `Off`; validation already rejects bad tokens.
775fn filter_action(opt: Option<&String>) -> FilterAction {
776    opt.map(String::as_str)
777        .and_then(FilterAction::parse)
778        .unwrap_or(FilterAction::Off)
779}
780
781#[cfg(test)]
782fn load_from_disk() -> Option<Arc<ActivePolicy>> {
783    let local = match load_local_pack() {
784        Ok(local) => local,
785        Err(msg) => {
786            tracing::error!(
787                "policy: failed to load invalid {PROJECT_PACK_PATH} ({msg}); enforcing deny-all"
788            );
789            return Some(Arc::new(ActivePolicy::deny_all()));
790        }
791    };
792    apply_org_floor(
793        local,
794        crate::core::policy::org::active_resolved_checked(),
795        None,
796        &crate::core::policy::cloud_filters::FilterRules::default(),
797        None,
798    )
799}
800
801/// `horizon` is the signed end of the organization floor, when a verifier
802/// decided it; it is attached here, before the policy is shared.
803/// `cloud_floor` is the Cloud effective policy (Release B): folded under
804/// everything else, so nothing local can loosen it.
805fn apply_org_floor(
806    local: Option<ResolvedPolicy>,
807    org: Result<Option<ResolvedPolicy>, String>,
808    horizon: Option<lean_ctx_time::UtcDateTime>,
809    cloud: &crate::core::policy::cloud_filters::FilterRules,
810    cloud_floor: Option<&ResolvedPolicy>,
811) -> Option<Arc<ActivePolicy>> {
812    // Invalid configured org policy must not silently remove the org floor.
813    let effective = match org {
814        Ok(Some(org)) => Some(crate::core::policy::floor::merge_floor(
815            &org,
816            local.as_ref(),
817        )),
818        Ok(None) => local,
819        Err(error) => {
820            tracing::error!("org policy rejected; enforcing deny-all: {error}");
821            return Some(Arc::new(ActivePolicy::deny_all()));
822        }
823    };
824    let effective = match cloud_floor {
825        Some(floor) => Some(crate::core::policy::cloud_floor::apply(
826            floor,
827            effective.as_ref(),
828        )),
829        None => effective,
830    };
831    let effective = match effective {
832        Some(effective) => effective,
833        None if cloud.redaction.is_empty() && cloud.blocked.is_empty() => return None,
834        // Cloud filter packs alone: content rules only, no tool or path rule.
835        None => cloud_filters_only(),
836    };
837    Some(Arc::new(
838        ActivePolicy::from_resolved_with_cloud(effective, cloud).until(horizon),
839    ))
840}
841
842/// The policy that carries nothing but the rules of Cloud filter packs.
843fn cloud_filters_only() -> ResolvedPolicy {
844    ResolvedPolicy {
845        name: "cloud-filters".into(),
846        version: "1.0.0".into(),
847        description: "content rules of the installed LeanCTX Cloud filter packs".into(),
848        chain: Vec::new(),
849        default_read_mode: None,
850        allow_tools: None,
851        deny_tools: Vec::new(),
852        max_context_tokens: None,
853        audit_retention_days: None,
854        redaction: std::collections::BTreeMap::new(),
855        filters: crate::core::policy::FilterRules::default(),
856        egress: crate::core::policy::EgressRules::default(),
857        routing: crate::core::policy::RoutingPolicyRules::default(),
858        budgets: crate::core::policy::BudgetRules::default(),
859    }
860}
861
862/// The project-local pack (`.lean-ctx/policy.toml`), resolved. `None` only when
863/// the file is absent; malformed packs return an error so callers fail closed.
864#[cfg(test)]
865fn load_local_pack() -> Result<Option<ResolvedPolicy>, String> {
866    let path = PathBuf::from(PROJECT_PACK_PATH);
867    load_local_pack_at(&path)
868}
869
870#[cfg(test)]
871fn load_local_pack_at(path: &Path) -> Result<Option<ResolvedPolicy>, String> {
872    match std::fs::symlink_metadata(path) {
873        Ok(_) => {}
874        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
875        Err(error) => return Err(format!("{}: {error}", path.display())),
876    }
877    match parse_file(path).and_then(|p| resolve(&p)) {
878        Ok(resolved) => Ok(Some(resolved)),
879        Err(e) => Err(format!("{}: {e}", path.display())),
880    }
881}
882
883/// Resolve the explicit runtime project without using the process-global cache.
884/// Configured local/org errors remain errors rather than granting admission.
885pub fn for_project(project_root: &Path) -> Result<Option<Arc<ActivePolicy>>, String> {
886    refresh::current(project_root.to_path_buf())
887}
888
889/// The active resolved policy, or `None` when no project or org pack exists.
890/// Fresh source bytes are mandatory even when compiled rules are cached.
891#[must_use]
892pub fn active() -> Option<Arc<ActivePolicy>> {
893    active_observed().0
894}
895
896/// [`active`], together with the organization decision the verifier stated
897/// in the very verification that policy comes from — one read, one answer,
898/// no second look at policy, trust store or marker. For whoever records what
899/// it decided under: the observation it files is the one of its own
900/// snapshot, never a later one.
901///
902/// The observation is `None` whenever no verifier was asked (no organization
903/// policy, a version-one one) and whenever the policy is the deny-all that
904/// stands for an authority that could not be established: a refusal records
905/// no organization decision it did not get. A lifted requirement is observed
906/// although it leaves no floor, and so possibly no policy at all.
907#[must_use]
908pub(crate) fn active_observed() -> (Option<Arc<ActivePolicy>>, Option<super::org::Observation>) {
909    let deny_all = || (Some(Arc::new(ActivePolicy::deny_all())), None);
910    if let Some(view) = current_source_view() {
911        if !view.live.load(Ordering::Acquire) || !view.valid.load(Ordering::Acquire) {
912            return deny_all();
913        }
914        let project = REQUEST_PROJECT
915            .try_with(|slot| slot.borrow().clone())
916            .ok()
917            .flatten();
918        if project.as_ref() != Some(&view.project) || !view.within_horizon() {
919            view.invalidate_if_live();
920            return deny_all();
921        }
922        return (view.policy, view.observation);
923    }
924    #[cfg(any(test, feature = "test-support"))]
925    {
926        let state = test_override()
927            .read()
928            .unwrap_or_else(std::sync::PoisonError::into_inner);
929        if let OverrideState::Fixed(policy) = &*state {
930            return (policy.clone(), None);
931        }
932    }
933    let scoped = REQUEST_PROJECT
934        .try_with(|slot| slot.borrow().clone())
935        .ok()
936        .flatten();
937    match scoped
938        .map_or_else(std::env::current_dir, Ok)
939        .map_err(|_| "policy project root unavailable".into())
940        .and_then(refresh::current_verified)
941    {
942        Ok(verified) => (verified.policy, verified.observation),
943        Err(_) => deny_all(),
944    }
945}
946
947/// Run `operation` under a pinned view of `project` whose verification
948/// observed `observation` and left no policy — the state after a signed
949/// unpin on an endpoint without a project pack. Tests only: a real view comes
950/// from `with_source_view` and nowhere else.
951#[cfg(any(test, feature = "test-support"))]
952pub fn with_observed_view_for_test<T>(
953    project: &Path,
954    observation: Option<super::org::Observation>,
955    operation: impl FnOnce() -> T,
956) -> T {
957    let project = canonical_project_root(project).expect("test project root");
958    let role = crate::core::roles::active_role();
959    // The authority as it really verifies for this root (no organization
960    // artifact in a test's data directory), so that a holder's own closing
961    // verification finds the same fingerprint; only the observation is given.
962    let verified = refresh::current_verified(project.clone()).expect("test authority");
963    let view = SourceView {
964        project: project.clone(),
965        policy: verified.policy,
966        fingerprint: verified.fingerprint,
967        role_fingerprint: role_fingerprint(&role).expect("test role"),
968        role,
969        lifetime: None,
970        observation,
971        valid: Arc::new(AtomicBool::new(true)),
972        live: Arc::new(AtomicBool::new(true)),
973    };
974    REQUEST_PROJECT.sync_scope(std::cell::RefCell::new(Some(project)), || {
975        SOURCE_VIEW.sync_scope(std::cell::RefCell::new(Some(view)), operation)
976    })
977}
978
979/// What a source view that is already held says about the organization.
980pub(crate) enum HeldObservation {
981    /// No usable view is held here: nothing can be said, and nothing is.
982    NotHeld,
983    /// The held view's own observation (`None`: its verification asked no
984    /// verifier).
985    Held(Option<super::org::Observation>),
986}
987
988/// The organization observation of the source view the caller already runs
989/// under — and nothing else. It never resolves, refreshes or reads: without a
990/// held view that is live, valid, of the request's own project and within its
991/// signed horizon, the answer is [`HeldObservation::NotHeld`]. For a path
992/// that must not start a verification of its own but may record the decision
993/// its caller's view was verified with.
994pub(crate) fn held_observation() -> HeldObservation {
995    let Some(view) = current_source_view() else {
996        return HeldObservation::NotHeld;
997    };
998    let project = REQUEST_PROJECT
999        .try_with(|slot| slot.borrow().clone())
1000        .ok()
1001        .flatten();
1002    if !view.live.load(Ordering::Acquire)
1003        || !view.valid.load(Ordering::Acquire)
1004        || project.as_ref() != Some(&view.project)
1005        || !view.within_horizon()
1006    {
1007        return HeldObservation::NotHeld;
1008    }
1009    HeldObservation::Held(view.observation)
1010}
1011
1012/// Current "is a policy active?" probe; refresh failure requires protection.
1013#[must_use]
1014pub fn is_active() -> bool {
1015    active().is_some()
1016}
1017
1018/// Re-read the project pack (e.g. after a `policy` edit). Idempotent.
1019pub fn reload() {
1020    let _ = active();
1021}
1022
1023#[cfg(any(test, feature = "test-support"))]
1024enum OverrideState {
1025    Live,
1026    Fixed(Option<Arc<ActivePolicy>>),
1027}
1028
1029#[cfg(any(test, feature = "test-support"))]
1030fn test_override() -> &'static RwLock<OverrideState> {
1031    static OVERRIDE: OnceLock<RwLock<OverrideState>> = OnceLock::new();
1032    OVERRIDE.get_or_init(|| RwLock::new(OverrideState::Live))
1033}
1034
1035#[cfg(any(test, feature = "test-support"))]
1036fn test_override_lock() -> &'static std::sync::Mutex<()> {
1037    static LOCK: OnceLock<std::sync::Mutex<()>> = OnceLock::new();
1038    LOCK.get_or_init(|| std::sync::Mutex::new(()))
1039}
1040
1041/// The policy-override lock together with the test environment lock, in the
1042/// one order every test takes them: environment first, then policy. Held as
1043/// one value so that neither outlives the other; the fields are declared in
1044/// release order — policy before environment.
1045#[cfg(any(test, feature = "test-support"))]
1046pub struct TestOverrideGuard {
1047    _policy: std::sync::MutexGuard<'static, ()>,
1048    _environment: crate::core::data_dir::TestEnvGuard,
1049}
1050
1051#[cfg(any(test, feature = "test-support"))]
1052pub fn lock_test_override() -> TestOverrideGuard {
1053    let environment = crate::core::data_dir::test_env_lock();
1054    let policy = test_override_lock()
1055        .lock()
1056        .unwrap_or_else(std::sync::PoisonError::into_inner);
1057    TestOverrideGuard {
1058        _policy: policy,
1059        _environment: environment,
1060    }
1061}
1062
1063/// Process-wide test override held under a shared lock for its whole lifetime.
1064#[cfg(any(test, feature = "test-support"))]
1065pub struct TestPolicyOverride {
1066    previous: OverrideState,
1067    _lock: TestOverrideGuard,
1068}
1069
1070#[cfg(any(test, feature = "test-support"))]
1071impl TestPolicyOverride {
1072    pub fn set(resolved: Option<ResolvedPolicy>) -> Self {
1073        let lock = lock_test_override();
1074        let previous = std::mem::replace(
1075            &mut *test_override()
1076                .write()
1077                .unwrap_or_else(std::sync::PoisonError::into_inner),
1078            OverrideState::Fixed(
1079                resolved.map(|policy| Arc::new(ActivePolicy::from_resolved(policy))),
1080            ),
1081        );
1082        Self {
1083            previous,
1084            _lock: lock,
1085        }
1086    }
1087}
1088
1089#[cfg(any(test, feature = "test-support"))]
1090impl Drop for TestPolicyOverride {
1091    fn drop(&mut self) {
1092        *test_override()
1093            .write()
1094            .unwrap_or_else(std::sync::PoisonError::into_inner) =
1095            std::mem::replace(&mut self.previous, OverrideState::Live);
1096    }
1097}
1098
1099#[cfg(test)]
1100#[path = "runtime/tests.rs"]
1101mod tests;