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(test)]
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(crate) const REQUIRED_POLICY_ROOT_ENV: &str = "LEAN_CTX_REQUIRED_POLICY_ROOT";
32pub(crate) const REQUIRED_POLICY_DIGEST_ENV: &str = "LEAN_CTX_REQUIRED_POLICY_DIGEST";
33pub(crate) use refresh::{protected_authority_paths, protected_policy_digest};
34#[cfg(test)]
35mod refresh_tests;
36
37tokio::task_local! {
38    /// Per-request project authority; never mutate process CWD for MCP roots.
39    pub(crate) static REQUEST_PROJECT: std::cell::RefCell<Option<PathBuf>>;
40    /// Immutable policy view for one synchronous source-admission operation.
41    pub(crate) static SOURCE_VIEW: std::cell::RefCell<Option<SourceView>>;
42}
43
44#[derive(Clone)]
45pub(crate) struct SourceView {
46    project: PathBuf,
47    policy: Option<Arc<ActivePolicy>>,
48    fingerprint: blake3::Hash,
49    role: crate::core::roles::Role,
50    role_fingerprint: blake3::Hash,
51    valid: Arc<AtomicBool>,
52    live: Arc<AtomicBool>,
53}
54
55struct SourceViewLifetime(Arc<AtomicBool>);
56
57/// Revalidate buffered CLI data at its output and persistence boundaries.
58/// This does not lock policy files against a concurrent administrator write.
59#[derive(Debug)]
60pub(crate) struct PublicationAuthority {
61    project: PathBuf,
62    fingerprint: blake3::Hash,
63    role_fingerprint: blake3::Hash,
64    valid: Arc<AtomicBool>,
65}
66
67impl PublicationAuthority {
68    pub(crate) fn capture() -> Result<Self, String> {
69        let view = current_source_view().ok_or("source authority unavailable")?;
70        Ok(Self {
71            project: view.project,
72            fingerprint: view.fingerprint,
73            role_fingerprint: view.role_fingerprint,
74            valid: view.valid,
75        })
76    }
77
78    pub(crate) fn verify(&self) -> Result<(), String> {
79        if !self.valid.load(Ordering::Acquire)
80            || REQUEST_PROJECT
81                .try_with(|slot| {
82                    slot.borrow()
83                        .as_ref()
84                        .is_some_and(|root| root != &self.project)
85                })
86                .unwrap_or(false)
87        {
88            return Err("source authority changed before publication".into());
89        }
90        REQUEST_PROJECT.sync_scope(std::cell::RefCell::new(Some(self.project.clone())), || {
91            SOURCE_VIEW.sync_scope(std::cell::RefCell::new(None), || {
92                let latest = refresh::current_verified(self.project.clone())?;
93                let role = role_fingerprint(&crate::core::roles::active_role())?;
94                if latest.fingerprint != self.fingerprint || role != self.role_fingerprint {
95                    return Err("source authority changed before publication".into());
96                }
97                Ok(())
98            })
99        })
100    }
101}
102
103impl Drop for SourceViewLifetime {
104    fn drop(&mut self) {
105        self.0.store(false, Ordering::Release);
106    }
107}
108
109fn current_source_view() -> Option<SourceView> {
110    SOURCE_VIEW
111        .try_with(|slot| slot.borrow().clone())
112        .ok()
113        .flatten()
114}
115
116/// Capture the pinned view when propagating a synchronous worker scope.
117pub(crate) fn inherited_source_view() -> Option<SourceView> {
118    current_source_view()
119}
120
121/// Restore a previously captured source view in a detached worker.
122pub(crate) fn with_inherited_source_view<T>(
123    view: Option<SourceView>,
124    operation: impl FnOnce() -> T,
125) -> T {
126    match view {
127        Some(view) => SOURCE_VIEW.sync_scope(std::cell::RefCell::new(Some(view)), operation),
128        None => operation(),
129    }
130}
131
132/// The role paired with the active source view. A closed or rebound inherited
133/// view returns a deny-all role instead of exposing its stale privileges.
134pub(crate) fn pinned_role() -> Option<crate::core::roles::Role> {
135    current_source_view().map(|view| {
136        let project = REQUEST_PROJECT
137            .try_with(|slot| slot.borrow().clone())
138            .ok()
139            .flatten();
140        if !view.live.load(Ordering::Acquire)
141            || !view.valid.load(Ordering::Acquire)
142            || project.as_ref() != Some(&view.project)
143        {
144            view.valid.store(false, Ordering::Release);
145            crate::core::roles::closed_source_view_role()
146        } else {
147            view.role
148        }
149    })
150}
151
152pub(crate) fn bind_request_project(project: Option<&str>) {
153    if current_source_view().is_some() {
154        return;
155    }
156    let _ = REQUEST_PROJECT.try_with(|slot| {
157        *slot.borrow_mut() = project.map(PathBuf::from);
158    });
159}
160
161/// Run a source operation with an explicit fallback project root. An existing
162/// request project remains authoritative; the fallback only fills an unbound
163/// request scope.
164pub(crate) fn with_project_source_view<T>(
165    project_root: &str,
166    operation: impl FnOnce() -> T,
167) -> Result<T, String> {
168    let project = REQUEST_PROJECT
169        .try_with(|slot| slot.borrow().clone())
170        .ok()
171        .flatten()
172        .or_else(|| current_source_view().map(|view| view.project))
173        .unwrap_or_else(|| PathBuf::from(project_root));
174    REQUEST_PROJECT.sync_scope(std::cell::RefCell::new(Some(project)), || {
175        with_source_view(operation)
176    })
177}
178
179/// Run a synchronous source operation against one freshly verified policy
180/// snapshot. Publish the returned value only if the same authority still holds.
181/// Nested calls reuse the parent snapshot; they never refresh into a weaker view.
182pub(crate) fn with_source_view<T>(operation: impl FnOnce() -> T) -> Result<T, String> {
183    if let Some(view) = current_source_view() {
184        let project = REQUEST_PROJECT
185            .try_with(|slot| slot.borrow().clone())
186            .ok()
187            .flatten();
188        if !view.live.load(Ordering::Acquire)
189            || !view.valid.load(Ordering::Acquire)
190            || project.as_ref() != Some(&view.project)
191        {
192            view.valid.store(false, Ordering::Release);
193            return Err("source policy view is no longer active".into());
194        }
195        return Ok(operation());
196    }
197
198    let project = REQUEST_PROJECT
199        .try_with(|slot| slot.borrow().clone())
200        .ok()
201        .flatten()
202        .or_else(|| std::env::current_dir().ok())
203        .ok_or("policy project root unavailable")?;
204    REQUEST_PROJECT.sync_scope(std::cell::RefCell::new(Some(project.clone())), || {
205        let verified = refresh::current_verified(project.clone())?;
206        let role = crate::core::roles::active_role();
207        let pinned_role_fingerprint = role_fingerprint(&role)?;
208        let view = SourceView {
209            project: project.clone(),
210            policy: source_view_policy(verified.policy),
211            fingerprint: verified.fingerprint,
212            role,
213            role_fingerprint: pinned_role_fingerprint,
214            valid: Arc::new(AtomicBool::new(true)),
215            live: Arc::new(AtomicBool::new(true)),
216        };
217
218        let lifetime = SourceViewLifetime(view.live.clone());
219        let value = SOURCE_VIEW.sync_scope(std::cell::RefCell::new(Some(view.clone())), operation);
220        drop(lifetime);
221
222        // SOURCE_VIEW has ended, while REQUEST_PROJECT still identifies the
223        // same request root; re-resolve the complete role before publishing.
224        let project_unchanged = REQUEST_PROJECT
225            .try_with(|slot| slot.borrow().as_ref() == Some(&view.project))
226            .unwrap_or(false);
227        let latest_role = crate::core::roles::active_role();
228        let latest_role_fingerprint = role_fingerprint(&latest_role)?;
229        let latest = refresh::current_verified(project)?;
230        if !project_unchanged
231            || latest.fingerprint != view.fingerprint
232            || latest_role_fingerprint != view.role_fingerprint
233            || !view.valid.load(Ordering::Acquire)
234        {
235            return Err("source policy view changed during operation".into());
236        }
237        Ok(value)
238    })
239}
240
241pub(crate) fn role_fingerprint(role: &crate::core::roles::Role) -> Result<blake3::Hash, String> {
242    serde_json::to_vec(role)
243        .map(|bytes| blake3::hash(&bytes))
244        .map_err(|_| "source role view unavailable".into())
245}
246
247#[cfg(test)]
248fn source_view_policy(fresh: Option<Arc<ActivePolicy>>) -> Option<Arc<ActivePolicy>> {
249    let state = test_override()
250        .read()
251        .unwrap_or_else(std::sync::PoisonError::into_inner);
252    match &*state {
253        OverrideState::Live => fresh,
254        OverrideState::Fixed(policy) => policy.clone(),
255    }
256}
257
258#[cfg(not(test))]
259fn source_view_policy(fresh: Option<Arc<ActivePolicy>>) -> Option<Arc<ActivePolicy>> {
260    fresh
261}
262
263/// Project-local pack location, relative to the working directory (matches the
264/// `lean-ctx policy` CLI's `PROJECT_PACK_PATH`).
265const PROJECT_PACK_PATH: &str = ".lean-ctx/policy.toml";
266
267/// A resolved policy plus its precompiled redaction regexes — the cached,
268/// hot-path-ready form.
269pub struct ActivePolicy {
270    pub resolved: ResolvedPolicy,
271    /// `(label, compiled regex)` — labels are the pack's `[redaction]` keys.
272    /// Invalid/over-budget compilation makes the whole policy fail closed.
273    pub redaction: Vec<(String, Regex)>,
274    pub(crate) blocked_patterns: Vec<(String, Regex)>,
275    pub(crate) content_valid: bool,
276    /// Compiled inbound content filters (GL #675), built once from the pack's
277    /// `[filters]` section.
278    pub filters: FilterConfig,
279    /// Compiled egress/output DLP config (GL #676), built once from the pack's
280    /// `[egress]` section.
281    pub egress: crate::core::egress::EgressConfig,
282}
283
284impl ActivePolicy {
285    pub(crate) fn from_resolved(resolved: ResolvedPolicy) -> Self {
286        use super::content::{MAX_REDACTION_RULES, MAX_RULE_LABEL_BYTES, MAX_RULE_PATTERN_BYTES};
287        let bounded = resolved.redaction.len() + resolved.filters.blocked_patterns.len()
288            <= MAX_REDACTION_RULES
289            && resolved.egress.forbidden_patterns.len() <= MAX_REDACTION_RULES
290            && resolved
291                .egress
292                .forbidden_patterns
293                .iter()
294                .all(|pattern| pattern.len() <= MAX_RULE_PATTERN_BYTES)
295            && resolved
296                .redaction
297                .iter()
298                .chain(&resolved.filters.blocked_patterns)
299                .all(|(label, pattern)| {
300                    !label.is_empty()
301                        && label.len() <= MAX_RULE_LABEL_BYTES
302                        && !label.chars().any(char::is_control)
303                        && pattern.len() <= MAX_RULE_PATTERN_BYTES
304                });
305        let compiled = bounded.then(|| {
306            resolved
307                .redaction
308                .iter()
309                .map(|(label, pattern)| {
310                    regex::RegexBuilder::new(pattern)
311                        .size_limit(1024 * 1024)
312                        .dfa_size_limit(1024 * 1024)
313                        .build()
314                        .map(|re| (label.clone(), re))
315                })
316                .collect::<Result<Vec<_>, _>>()
317        });
318        let content_valid = matches!(&compiled, Some(Ok(_)));
319        let redaction = compiled.and_then(Result::ok).unwrap_or_default();
320        let compiled_blocks = bounded.then(|| {
321            resolved
322                .filters
323                .blocked_patterns
324                .iter()
325                .map(|(label, pattern)| {
326                    regex::RegexBuilder::new(pattern)
327                        .size_limit(1024 * 1024)
328                        .dfa_size_limit(1024 * 1024)
329                        .build()
330                        .map(|re| (label.clone(), re))
331                })
332                .collect::<Result<Vec<_>, _>>()
333        });
334        let content_valid = content_valid && matches!(&compiled_blocks, Some(Ok(_)));
335        let blocked_patterns = compiled_blocks.and_then(Result::ok).unwrap_or_default();
336        let filters = FilterConfig::new(
337            filter_action(resolved.filters.pii.as_ref()),
338            filter_action(resolved.filters.classification.as_ref()),
339            filter_action(resolved.filters.injection.as_ref()),
340            &resolved.filters.blocked_labels,
341        );
342        let egress = crate::core::egress::EgressConfig::new(
343            &resolved.egress.forbidden_patterns,
344            resolved.egress.block_secrets.unwrap_or(false),
345            resolved.egress.max_writes_per_min,
346        );
347        Self {
348            resolved,
349            redaction,
350            blocked_patterns,
351            content_valid,
352            filters,
353            egress,
354        }
355    }
356
357    /// Block every tool after a local policy pack fails to load.
358    pub(crate) fn deny_all() -> Self {
359        let mut active = Self::from_resolved(ResolvedPolicy {
360            name: "invalid-local-policy".into(),
361            version: "0.0.0".into(),
362            description: "deny all because the local policy pack is invalid".into(),
363            chain: Vec::new(),
364            default_read_mode: None,
365            allow_tools: Some(Vec::new()),
366            deny_tools: Vec::new(),
367            max_context_tokens: None,
368            audit_retention_days: None,
369            redaction: std::collections::BTreeMap::new(),
370            filters: crate::core::policy::FilterRules::default(),
371            egress: crate::core::policy::EgressRules::default(),
372            routing: crate::core::policy::RoutingPolicyRules::default(),
373            budgets: crate::core::policy::BudgetRules::default(),
374        });
375        active.content_valid = false;
376        active
377    }
378
379    /// Whether `tool` is permitted by this policy's allow/deny lists.
380    /// `deny_tools` always wins; an `allow_tools` allowlist, when set, is
381    /// exclusive (only listed tools pass).
382    #[must_use]
383    pub fn tool_allowed(&self, tool: &str) -> bool {
384        if !self.content_valid {
385            return false;
386        }
387        if self.resolved.deny_tools.iter().any(|t| t == tool) {
388            return false;
389        }
390        match &self.resolved.allow_tools {
391            Some(allow) => allow.iter().any(|t| t == tool),
392            None => true,
393        }
394    }
395}
396
397/// Map a resolved `[filters]` action string to a [`FilterAction`]. Absent or
398/// (defensively) unparseable ⇒ `Off`; validation already rejects bad tokens.
399fn filter_action(opt: Option<&String>) -> FilterAction {
400    opt.map(String::as_str)
401        .and_then(FilterAction::parse)
402        .unwrap_or(FilterAction::Off)
403}
404
405#[cfg(test)]
406fn load_from_disk() -> Option<Arc<ActivePolicy>> {
407    let local = match load_local_pack() {
408        Ok(local) => local,
409        Err(msg) => {
410            tracing::error!(
411                "policy: failed to load invalid {PROJECT_PACK_PATH} ({msg}); enforcing deny-all"
412            );
413            return Some(Arc::new(ActivePolicy::deny_all()));
414        }
415    };
416    apply_org_floor(local, crate::core::policy::org::active_resolved_checked())
417}
418
419fn apply_org_floor(
420    local: Option<ResolvedPolicy>,
421    org: Result<Option<ResolvedPolicy>, String>,
422) -> Option<Arc<ActivePolicy>> {
423    // Invalid configured org policy must not silently remove the org floor.
424    let effective = match org {
425        Ok(Some(org)) => crate::core::policy::floor::merge_floor(&org, local.as_ref()),
426        Ok(None) => local?,
427        Err(error) => {
428            tracing::error!("org policy rejected; enforcing deny-all: {error}");
429            return Some(Arc::new(ActivePolicy::deny_all()));
430        }
431    };
432    Some(Arc::new(ActivePolicy::from_resolved(effective)))
433}
434
435/// The project-local pack (`.lean-ctx/policy.toml`), resolved. `None` only when
436/// the file is absent; malformed packs return an error so callers fail closed.
437#[cfg(test)]
438fn load_local_pack() -> Result<Option<ResolvedPolicy>, String> {
439    let path = PathBuf::from(PROJECT_PACK_PATH);
440    load_local_pack_at(&path)
441}
442
443#[cfg(test)]
444fn load_local_pack_at(path: &Path) -> Result<Option<ResolvedPolicy>, String> {
445    match std::fs::symlink_metadata(path) {
446        Ok(_) => {}
447        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
448        Err(error) => return Err(format!("{}: {error}", path.display())),
449    }
450    match parse_file(path).and_then(|p| resolve(&p)) {
451        Ok(resolved) => Ok(Some(resolved)),
452        Err(e) => Err(format!("{}: {e}", path.display())),
453    }
454}
455
456/// Resolve the explicit runtime project without using the process-global cache.
457/// Configured local/org errors remain errors rather than granting admission.
458pub fn for_project(project_root: &Path) -> Result<Option<Arc<ActivePolicy>>, String> {
459    refresh::current(project_root.to_path_buf())
460}
461
462/// The active resolved policy, or `None` when no project or org pack exists.
463/// Fresh source bytes are mandatory even when compiled rules are cached.
464#[must_use]
465pub fn active() -> Option<Arc<ActivePolicy>> {
466    if let Some(view) = current_source_view() {
467        if !view.live.load(Ordering::Acquire) || !view.valid.load(Ordering::Acquire) {
468            return Some(Arc::new(ActivePolicy::deny_all()));
469        }
470        let project = REQUEST_PROJECT
471            .try_with(|slot| slot.borrow().clone())
472            .ok()
473            .flatten();
474        if project.as_ref() != Some(&view.project) {
475            view.valid.store(false, Ordering::Release);
476            return Some(Arc::new(ActivePolicy::deny_all()));
477        }
478        return view.policy;
479    }
480    #[cfg(test)]
481    {
482        let state = test_override()
483            .read()
484            .unwrap_or_else(std::sync::PoisonError::into_inner);
485        if let OverrideState::Fixed(policy) = &*state {
486            return policy.clone();
487        }
488    }
489    let scoped = REQUEST_PROJECT
490        .try_with(|slot| slot.borrow().clone())
491        .ok()
492        .flatten();
493    match scoped
494        .map_or_else(std::env::current_dir, Ok)
495        .map_err(|_| "policy project root unavailable".into())
496        .and_then(refresh::current)
497    {
498        Ok(policy) => policy,
499        Err(_) => Some(Arc::new(ActivePolicy::deny_all())),
500    }
501}
502
503/// Current "is a policy active?" probe; refresh failure requires protection.
504#[must_use]
505pub fn is_active() -> bool {
506    active().is_some()
507}
508
509/// Re-read the project pack (e.g. after a `policy` edit). Idempotent.
510pub fn reload() {
511    let _ = active();
512}
513
514#[cfg(test)]
515enum OverrideState {
516    Live,
517    Fixed(Option<Arc<ActivePolicy>>),
518}
519
520#[cfg(test)]
521fn test_override() -> &'static RwLock<OverrideState> {
522    static OVERRIDE: OnceLock<RwLock<OverrideState>> = OnceLock::new();
523    OVERRIDE.get_or_init(|| RwLock::new(OverrideState::Live))
524}
525
526#[cfg(test)]
527fn test_override_lock() -> &'static std::sync::Mutex<()> {
528    static LOCK: OnceLock<std::sync::Mutex<()>> = OnceLock::new();
529    LOCK.get_or_init(|| std::sync::Mutex::new(()))
530}
531
532/// Held while a test pins the process-wide policy override.
533///
534/// Lock order is always `test_env_lock` → override lock. Tests take both in
535/// either order (`isolated_data_dir()` then `TestPolicyOverride::set`, or
536/// `lock_test_override()` then `isolated_data_dir()`); taking them as two
537/// independent locks deadlocked the suite (ABBA) once enough tests ran in
538/// parallel — 28 threads on a 28-core runner hung it for good. The env lock is
539/// reentrant per thread, so acquiring it first here is free for a test that
540/// already holds it.
541#[cfg(test)]
542pub(crate) struct TestOverrideLock {
543    _lock: std::sync::MutexGuard<'static, ()>,
544    _env: crate::core::data_dir::TestEnvGuard,
545}
546
547#[cfg(test)]
548fn acquire_test_override() -> TestOverrideLock {
549    let env = crate::core::data_dir::test_env_lock();
550    let lock = test_override_lock()
551        .lock()
552        .unwrap_or_else(std::sync::PoisonError::into_inner);
553    TestOverrideLock {
554        _lock: lock,
555        _env: env,
556    }
557}
558
559#[cfg(test)]
560pub(crate) fn lock_test_override() -> TestOverrideLock {
561    acquire_test_override()
562}
563
564/// Process-wide test override held under a shared lock for its whole lifetime.
565#[cfg(test)]
566pub struct TestPolicyOverride {
567    previous: OverrideState,
568    _lock: TestOverrideLock,
569}
570
571#[cfg(test)]
572impl TestPolicyOverride {
573    pub fn set(resolved: Option<ResolvedPolicy>) -> Self {
574        let lock = acquire_test_override();
575        let previous = std::mem::replace(
576            &mut *test_override()
577                .write()
578                .unwrap_or_else(std::sync::PoisonError::into_inner),
579            OverrideState::Fixed(
580                resolved.map(|policy| Arc::new(ActivePolicy::from_resolved(policy))),
581            ),
582        );
583        Self {
584            previous,
585            _lock: lock,
586        }
587    }
588}
589
590#[cfg(test)]
591impl Drop for TestPolicyOverride {
592    fn drop(&mut self) {
593        *test_override()
594            .write()
595            .unwrap_or_else(std::sync::PoisonError::into_inner) =
596            std::mem::replace(&mut self.previous, OverrideState::Live);
597    }
598}
599
600#[cfg(test)]
601mod tests {
602    use super::*;
603    use std::collections::BTreeMap;
604    use std::fs;
605
606    struct CurrentDirGuard {
607        previous: std::path::PathBuf,
608        _lock: std::sync::MutexGuard<'static, ()>,
609    }
610
611    impl CurrentDirGuard {
612        fn enter(dir: &std::path::Path) -> Self {
613            static LOCK: OnceLock<std::sync::Mutex<()>> = OnceLock::new();
614            let lock = LOCK.get_or_init(|| std::sync::Mutex::new(()));
615            let guard = lock
616                .lock()
617                .unwrap_or_else(std::sync::PoisonError::into_inner);
618            let previous = std::env::current_dir().expect("read current directory");
619            std::env::set_current_dir(dir).expect("enter temporary directory");
620            Self {
621                previous,
622                _lock: guard,
623            }
624        }
625    }
626
627    impl Drop for CurrentDirGuard {
628        fn drop(&mut self) {
629            std::env::set_current_dir(&self.previous).expect("restore current directory");
630        }
631    }
632
633    fn rp(allow: Option<Vec<&str>>, deny: Vec<&str>, redaction: &[(&str, &str)]) -> ResolvedPolicy {
634        ResolvedPolicy {
635            name: "test".into(),
636            version: "1.0.0".into(),
637            description: "t".into(),
638            chain: vec![],
639            default_read_mode: None,
640            allow_tools: allow.map(|a| a.into_iter().map(String::from).collect()),
641            deny_tools: deny.into_iter().map(String::from).collect(),
642            max_context_tokens: None,
643            audit_retention_days: None,
644            redaction: redaction
645                .iter()
646                .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
647                .collect::<BTreeMap<_, _>>(),
648            filters: crate::core::policy::FilterRules::default(),
649            egress: crate::core::policy::EgressRules::default(),
650            routing: crate::core::policy::RoutingPolicyRules::default(),
651            budgets: crate::core::policy::BudgetRules::default(),
652        }
653    }
654
655    fn write_policy(root: &std::path::Path, name: &str) -> std::path::PathBuf {
656        let directory = root.join(".lean-ctx");
657        fs::create_dir_all(&directory).expect("create policy directory");
658        let path = directory.join("policy.toml");
659        fs::write(
660            &path,
661            format!("name = {name:?}\nversion = \"1.0.0\"\ndescription = \"source view test\"\n"),
662        )
663        .expect("write policy");
664        path
665    }
666
667    #[test]
668    fn deny_list_blocks_listed_tool() {
669        let p = ActivePolicy::from_resolved(rp(None, vec!["ctx_url_read"], &[]));
670        assert!(!p.tool_allowed("ctx_url_read"));
671        assert!(p.tool_allowed("ctx_read"));
672    }
673
674    #[test]
675    fn allow_list_is_exclusive() {
676        let p = ActivePolicy::from_resolved(rp(Some(vec!["ctx_read"]), vec![], &[]));
677        assert!(p.tool_allowed("ctx_read"));
678        assert!(!p.tool_allowed("ctx_shell"));
679    }
680
681    #[test]
682    fn compiles_redaction_patterns() {
683        let p = ActivePolicy::from_resolved(rp(None, vec![], &[("emp", r"EMP-\d{4}")]));
684        assert_eq!(p.redaction.len(), 1);
685        assert_eq!(p.redaction[0].0, "emp");
686    }
687
688    #[test]
689    fn load_from_disk_fails_closed_on_invalid_pack() {
690        let temp = tempfile::tempdir().expect("create temporary directory");
691        let policy_dir = temp.path().join(".lean-ctx");
692        fs::create_dir(&policy_dir).expect("create policy directory");
693        fs::write(policy_dir.join("policy.toml"), "[policy\n").expect("write invalid policy");
694        let _cwd = CurrentDirGuard::enter(temp.path());
695
696        let policy = load_from_disk().expect("invalid pack activates deny-all");
697
698        assert!(!policy.tool_allowed("ctx_read"));
699        assert!(!policy.tool_allowed("ctx_shell"));
700    }
701
702    #[test]
703    fn invalid_org_policy_cannot_fall_back_to_permissive_local_policy() {
704        for local in [None, Some(rp(None, vec![], &[]))] {
705            let policy = apply_org_floor(local, Err("invalid org signature".into())).unwrap();
706            assert!(!policy.tool_allowed("ctx_read"));
707            assert!(!policy.tool_allowed("ctx_shell"));
708        }
709        assert!(apply_org_floor(None, Ok(None)).is_none());
710    }
711
712    #[test]
713    fn explicit_project_policy_does_not_leak_between_roots() {
714        let _data = crate::core::data_dir::isolated_data_dir();
715        let denied = tempfile::tempdir().unwrap();
716        let absent = tempfile::tempdir().unwrap();
717        let directory = denied.path().join(".lean-ctx");
718        fs::create_dir(&directory).unwrap();
719        fs::write(directory.join("policy.toml"),
720            "name = \"project\"\nversion = \"1.0.0\"\ndescription = \"test\"\n[context]\ndeny_tools = [\"ctx_work_graph\"]\n").unwrap();
721        assert!(
722            !for_project(denied.path())
723                .unwrap()
724                .unwrap()
725                .tool_allowed("ctx_work_graph")
726        );
727        assert!(for_project(absent.path()).unwrap().is_none());
728        fs::write(directory.join("policy.toml"), "invalid policy").unwrap();
729        assert!(for_project(denied.path()).is_err());
730        assert!(for_project(&absent.path().join("missing")).is_err());
731    }
732
733    #[test]
734    fn source_view_pins_active_policy_and_rejects_persistent_change() {
735        let _override_guard = lock_test_override();
736        let _data = crate::core::data_dir::isolated_data_dir();
737        let root = tempfile::tempdir().expect("create project");
738        let path = write_policy(root.path(), "view-a");
739
740        let result = REQUEST_PROJECT.sync_scope(
741            std::cell::RefCell::new(Some(root.path().to_path_buf())),
742            || {
743                with_source_view(|| {
744                    assert_eq!(active().unwrap().resolved.name, "view-a");
745                    write_policy(root.path(), "view-b");
746                    assert_eq!(active().unwrap().resolved.name, "view-a");
747                })
748            },
749        );
750
751        assert!(result.is_err());
752        assert!(path.exists());
753    }
754
755    #[test]
756    fn source_view_a_to_b_to_a_never_uses_transient_policy_b() {
757        let _override_guard = lock_test_override();
758        let _data = crate::core::data_dir::isolated_data_dir();
759        let root = tempfile::tempdir().expect("create project");
760        write_policy(root.path(), "view-a");
761
762        let result = REQUEST_PROJECT.sync_scope(
763            std::cell::RefCell::new(Some(root.path().to_path_buf())),
764            || {
765                with_source_view(|| {
766                    write_policy(root.path(), "view-b");
767                    assert_eq!(active().unwrap().resolved.name, "view-a");
768                    write_policy(root.path(), "view-a");
769                    active().unwrap().resolved.name.clone()
770                })
771            },
772        );
773
774        assert_eq!(result.unwrap(), "view-a");
775    }
776
777    #[test]
778    fn source_view_pins_explicit_no_policy_and_rejects_policy_creation() {
779        let _override_guard = lock_test_override();
780        let _data = crate::core::data_dir::isolated_data_dir();
781        let root = tempfile::tempdir().expect("create project");
782
783        let result = REQUEST_PROJECT.sync_scope(
784            std::cell::RefCell::new(Some(root.path().to_path_buf())),
785            || {
786                with_source_view(|| {
787                    assert!(active().is_none());
788                    write_policy(root.path(), "new-policy");
789                    assert!(active().is_none());
790                })
791            },
792        );
793
794        assert!(result.is_err());
795    }
796
797    #[test]
798    fn source_view_rejects_nested_project_rebinding() {
799        let _override_guard = lock_test_override();
800        let _data = crate::core::data_dir::isolated_data_dir();
801        let first = tempfile::tempdir().expect("create first project");
802        let second = tempfile::tempdir().expect("create second project");
803        write_policy(first.path(), "first-project");
804        write_policy(second.path(), "second-project");
805
806        let result = REQUEST_PROJECT.sync_scope(
807            std::cell::RefCell::new(Some(first.path().to_path_buf())),
808            || {
809                with_source_view(|| {
810                    REQUEST_PROJECT.sync_scope(
811                        std::cell::RefCell::new(Some(second.path().to_path_buf())),
812                        || assert!(!active().unwrap().tool_allowed("ctx_read")),
813                    );
814                })
815            },
816        );
817
818        assert!(result.is_err());
819    }
820
821    #[test]
822    fn source_view_rejects_policy_removal_and_invalid_initial_policy() {
823        let _override_guard = lock_test_override();
824        let _data = crate::core::data_dir::isolated_data_dir();
825        let root = tempfile::tempdir().expect("create project");
826        let path = write_policy(root.path(), "view-a");
827
828        let removed = REQUEST_PROJECT.sync_scope(
829            std::cell::RefCell::new(Some(root.path().to_path_buf())),
830            || {
831                with_source_view(|| {
832                    assert_eq!(active().unwrap().resolved.name, "view-a");
833                    fs::remove_file(&path).expect("remove policy");
834                    assert_eq!(active().unwrap().resolved.name, "view-a");
835                })
836            },
837        );
838        assert!(removed.is_err());
839
840        fs::write(&path, "[policy\n").expect("write invalid policy");
841        let called = std::cell::Cell::new(false);
842        let invalid = REQUEST_PROJECT.sync_scope(
843            std::cell::RefCell::new(Some(root.path().to_path_buf())),
844            || with_source_view(|| called.set(true)),
845        );
846        assert!(invalid.is_err());
847        assert!(!called.get());
848    }
849
850    fn fixture_role(
851        name: &str,
852        boundary_mode: &str,
853        allow_secret_paths: bool,
854        allowed: &[&str],
855    ) -> crate::core::roles::Role {
856        use crate::core::roles::{IoPolicy, Role, RoleLimits, RoleMeta, ToolPolicy};
857        Role {
858            role: RoleMeta {
859                name: name.into(),
860                inherits: None,
861                description: "source view test".into(),
862                shell_policy: "deny".into(),
863            },
864            tools: ToolPolicy {
865                allowed: allowed.iter().map(|tool| (*tool).into()).collect(),
866                denied: Vec::new(),
867            },
868            io: IoPolicy {
869                boundary_mode: boundary_mode.into(),
870                allow_secret_paths,
871                ..Default::default()
872            },
873            limits: RoleLimits::default(),
874        }
875    }
876
877    #[test]
878    fn source_view_pins_full_role_through_a_to_b_to_a_and_rejects_persistent_change() {
879        let _override_guard = lock_test_override();
880        let _data = crate::core::data_dir::isolated_data_dir();
881        let root = tempfile::tempdir().expect("create project");
882        let role_a = fixture_role("role-a", "warn", true, &["ctx_read"]);
883        // Secret-path visibility stays fixed so the regression exercises the
884        // full role fingerprint (tool and boundary policy), not only that bit.
885        let role_b = fixture_role("role-b", "enforce", true, &["ctx_shell"]);
886
887        let transient = crate::core::roles::with_test_active_role(role_a.clone(), || {
888            with_project_source_view(root.path().to_str().unwrap(), || {
889                with_source_view(|| {
890                    assert_eq!(
891                        role_fingerprint(&crate::core::roles::active_role()).unwrap(),
892                        role_fingerprint(&role_a).unwrap()
893                    );
894                    crate::core::roles::set_test_active_role(role_b.clone());
895                    let pinned = crate::core::roles::active_role();
896                    assert_eq!(pinned.role.name, "role-a");
897                    assert_eq!(pinned.io.boundary_mode, "warn");
898                    assert!(pinned.io.allow_secret_paths);
899                    assert!(pinned.is_tool_allowed("ctx_read"));
900                    assert!(!pinned.is_tool_allowed("ctx_shell"));
901                    crate::core::roles::set_test_active_role(role_a.clone());
902                })
903            })
904        });
905        assert!(transient.is_ok(), "a transient role B is never observed");
906
907        let persistent = crate::core::roles::with_test_active_role(role_a.clone(), || {
908            with_project_source_view(root.path().to_str().unwrap(), || {
909                with_source_view(|| {
910                    crate::core::roles::set_test_active_role(role_b.clone());
911                    assert_eq!(crate::core::roles::active_role().role.name, "role-a");
912                })
913            })
914        });
915        assert!(
916            persistent.is_err(),
917            "a changed full role invalidates the view"
918        );
919    }
920
921    #[test]
922    fn closed_inherited_source_view_returns_a_denying_pinned_role() {
923        let root = tempfile::tempdir().expect("create project");
924        let role = fixture_role("role-a", "warn", true, &["ctx_read"]);
925        let role_fingerprint = role_fingerprint(&role).unwrap();
926        let view = SourceView {
927            project: root.path().to_path_buf(),
928            policy: None,
929            fingerprint: blake3::hash(b"test"),
930            role,
931            role_fingerprint,
932            valid: Arc::new(AtomicBool::new(true)),
933            live: Arc::new(AtomicBool::new(false)),
934        };
935
936        REQUEST_PROJECT.sync_scope(
937            std::cell::RefCell::new(Some(root.path().to_path_buf())),
938            || {
939                SOURCE_VIEW.sync_scope(std::cell::RefCell::new(Some(view)), || {
940                    let closed = crate::core::roles::active_role();
941                    assert_eq!(closed.role.name, "closed-source-view");
942                    assert!(!closed.is_tool_allowed("ctx_read"));
943                    assert!(!closed.io.allow_secret_paths);
944                });
945            },
946        );
947    }
948
949    #[test]
950    fn project_source_view_uses_fallback_and_preserves_bound_project() {
951        let _override_guard = lock_test_override();
952        let _data = crate::core::data_dir::isolated_data_dir();
953        let fallback = tempfile::tempdir().expect("create fallback project");
954        let bound = tempfile::tempdir().expect("create bound project");
955        write_policy(fallback.path(), "fallback-project");
956        write_policy(bound.path(), "bound-project");
957        let fallback_root = fallback.path().to_str().unwrap();
958
959        let unbound =
960            with_project_source_view(fallback_root, || active().unwrap().resolved.name.clone());
961        assert_eq!(unbound.unwrap(), "fallback-project");
962
963        let already_bound = REQUEST_PROJECT.sync_scope(
964            std::cell::RefCell::new(Some(bound.path().to_path_buf())),
965            || with_project_source_view(fallback_root, || active().unwrap().resolved.name.clone()),
966        );
967        assert_eq!(already_bound.unwrap(), "bound-project");
968    }
969}