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#[cfg(test)]
533pub(crate) fn lock_test_override() -> std::sync::MutexGuard<'static, ()> {
534    test_override_lock()
535        .lock()
536        .unwrap_or_else(std::sync::PoisonError::into_inner)
537}
538
539/// Process-wide test override held under a shared lock for its whole lifetime.
540#[cfg(test)]
541pub struct TestPolicyOverride {
542    previous: OverrideState,
543    _lock: std::sync::MutexGuard<'static, ()>,
544}
545
546#[cfg(test)]
547impl TestPolicyOverride {
548    pub fn set(resolved: Option<ResolvedPolicy>) -> Self {
549        let lock = test_override_lock()
550            .lock()
551            .unwrap_or_else(std::sync::PoisonError::into_inner);
552        let previous = std::mem::replace(
553            &mut *test_override()
554                .write()
555                .unwrap_or_else(std::sync::PoisonError::into_inner),
556            OverrideState::Fixed(
557                resolved.map(|policy| Arc::new(ActivePolicy::from_resolved(policy))),
558            ),
559        );
560        Self {
561            previous,
562            _lock: lock,
563        }
564    }
565}
566
567#[cfg(test)]
568impl Drop for TestPolicyOverride {
569    fn drop(&mut self) {
570        *test_override()
571            .write()
572            .unwrap_or_else(std::sync::PoisonError::into_inner) =
573            std::mem::replace(&mut self.previous, OverrideState::Live);
574    }
575}
576
577#[cfg(test)]
578mod tests {
579    use super::*;
580    use std::collections::BTreeMap;
581    use std::fs;
582
583    struct CurrentDirGuard {
584        previous: std::path::PathBuf,
585        _lock: std::sync::MutexGuard<'static, ()>,
586    }
587
588    impl CurrentDirGuard {
589        fn enter(dir: &std::path::Path) -> Self {
590            static LOCK: OnceLock<std::sync::Mutex<()>> = OnceLock::new();
591            let lock = LOCK.get_or_init(|| std::sync::Mutex::new(()));
592            let guard = lock
593                .lock()
594                .unwrap_or_else(std::sync::PoisonError::into_inner);
595            let previous = std::env::current_dir().expect("read current directory");
596            std::env::set_current_dir(dir).expect("enter temporary directory");
597            Self {
598                previous,
599                _lock: guard,
600            }
601        }
602    }
603
604    impl Drop for CurrentDirGuard {
605        fn drop(&mut self) {
606            std::env::set_current_dir(&self.previous).expect("restore current directory");
607        }
608    }
609
610    fn rp(allow: Option<Vec<&str>>, deny: Vec<&str>, redaction: &[(&str, &str)]) -> ResolvedPolicy {
611        ResolvedPolicy {
612            name: "test".into(),
613            version: "1.0.0".into(),
614            description: "t".into(),
615            chain: vec![],
616            default_read_mode: None,
617            allow_tools: allow.map(|a| a.into_iter().map(String::from).collect()),
618            deny_tools: deny.into_iter().map(String::from).collect(),
619            max_context_tokens: None,
620            audit_retention_days: None,
621            redaction: redaction
622                .iter()
623                .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
624                .collect::<BTreeMap<_, _>>(),
625            filters: crate::core::policy::FilterRules::default(),
626            egress: crate::core::policy::EgressRules::default(),
627            routing: crate::core::policy::RoutingPolicyRules::default(),
628            budgets: crate::core::policy::BudgetRules::default(),
629        }
630    }
631
632    fn write_policy(root: &std::path::Path, name: &str) -> std::path::PathBuf {
633        let directory = root.join(".lean-ctx");
634        fs::create_dir_all(&directory).expect("create policy directory");
635        let path = directory.join("policy.toml");
636        fs::write(
637            &path,
638            format!("name = {name:?}\nversion = \"1.0.0\"\ndescription = \"source view test\"\n"),
639        )
640        .expect("write policy");
641        path
642    }
643
644    #[test]
645    fn deny_list_blocks_listed_tool() {
646        let p = ActivePolicy::from_resolved(rp(None, vec!["ctx_url_read"], &[]));
647        assert!(!p.tool_allowed("ctx_url_read"));
648        assert!(p.tool_allowed("ctx_read"));
649    }
650
651    #[test]
652    fn allow_list_is_exclusive() {
653        let p = ActivePolicy::from_resolved(rp(Some(vec!["ctx_read"]), vec![], &[]));
654        assert!(p.tool_allowed("ctx_read"));
655        assert!(!p.tool_allowed("ctx_shell"));
656    }
657
658    #[test]
659    fn compiles_redaction_patterns() {
660        let p = ActivePolicy::from_resolved(rp(None, vec![], &[("emp", r"EMP-\d{4}")]));
661        assert_eq!(p.redaction.len(), 1);
662        assert_eq!(p.redaction[0].0, "emp");
663    }
664
665    #[test]
666    fn load_from_disk_fails_closed_on_invalid_pack() {
667        let temp = tempfile::tempdir().expect("create temporary directory");
668        let policy_dir = temp.path().join(".lean-ctx");
669        fs::create_dir(&policy_dir).expect("create policy directory");
670        fs::write(policy_dir.join("policy.toml"), "[policy\n").expect("write invalid policy");
671        let _cwd = CurrentDirGuard::enter(temp.path());
672
673        let policy = load_from_disk().expect("invalid pack activates deny-all");
674
675        assert!(!policy.tool_allowed("ctx_read"));
676        assert!(!policy.tool_allowed("ctx_shell"));
677    }
678
679    #[test]
680    fn invalid_org_policy_cannot_fall_back_to_permissive_local_policy() {
681        for local in [None, Some(rp(None, vec![], &[]))] {
682            let policy = apply_org_floor(local, Err("invalid org signature".into())).unwrap();
683            assert!(!policy.tool_allowed("ctx_read"));
684            assert!(!policy.tool_allowed("ctx_shell"));
685        }
686        assert!(apply_org_floor(None, Ok(None)).is_none());
687    }
688
689    #[test]
690    fn explicit_project_policy_does_not_leak_between_roots() {
691        let _data = crate::core::data_dir::isolated_data_dir();
692        let denied = tempfile::tempdir().unwrap();
693        let absent = tempfile::tempdir().unwrap();
694        let directory = denied.path().join(".lean-ctx");
695        fs::create_dir(&directory).unwrap();
696        fs::write(directory.join("policy.toml"),
697            "name = \"project\"\nversion = \"1.0.0\"\ndescription = \"test\"\n[context]\ndeny_tools = [\"ctx_work_graph\"]\n").unwrap();
698        assert!(
699            !for_project(denied.path())
700                .unwrap()
701                .unwrap()
702                .tool_allowed("ctx_work_graph")
703        );
704        assert!(for_project(absent.path()).unwrap().is_none());
705        fs::write(directory.join("policy.toml"), "invalid policy").unwrap();
706        assert!(for_project(denied.path()).is_err());
707        assert!(for_project(&absent.path().join("missing")).is_err());
708    }
709
710    #[test]
711    fn source_view_pins_active_policy_and_rejects_persistent_change() {
712        let _override_guard = lock_test_override();
713        let _data = crate::core::data_dir::isolated_data_dir();
714        let root = tempfile::tempdir().expect("create project");
715        let path = write_policy(root.path(), "view-a");
716
717        let result = REQUEST_PROJECT.sync_scope(
718            std::cell::RefCell::new(Some(root.path().to_path_buf())),
719            || {
720                with_source_view(|| {
721                    assert_eq!(active().unwrap().resolved.name, "view-a");
722                    write_policy(root.path(), "view-b");
723                    assert_eq!(active().unwrap().resolved.name, "view-a");
724                })
725            },
726        );
727
728        assert!(result.is_err());
729        assert!(path.exists());
730    }
731
732    #[test]
733    fn source_view_a_to_b_to_a_never_uses_transient_policy_b() {
734        let _override_guard = lock_test_override();
735        let _data = crate::core::data_dir::isolated_data_dir();
736        let root = tempfile::tempdir().expect("create project");
737        write_policy(root.path(), "view-a");
738
739        let result = REQUEST_PROJECT.sync_scope(
740            std::cell::RefCell::new(Some(root.path().to_path_buf())),
741            || {
742                with_source_view(|| {
743                    write_policy(root.path(), "view-b");
744                    assert_eq!(active().unwrap().resolved.name, "view-a");
745                    write_policy(root.path(), "view-a");
746                    active().unwrap().resolved.name.clone()
747                })
748            },
749        );
750
751        assert_eq!(result.unwrap(), "view-a");
752    }
753
754    #[test]
755    fn source_view_pins_explicit_no_policy_and_rejects_policy_creation() {
756        let _override_guard = lock_test_override();
757        let _data = crate::core::data_dir::isolated_data_dir();
758        let root = tempfile::tempdir().expect("create project");
759
760        let result = REQUEST_PROJECT.sync_scope(
761            std::cell::RefCell::new(Some(root.path().to_path_buf())),
762            || {
763                with_source_view(|| {
764                    assert!(active().is_none());
765                    write_policy(root.path(), "new-policy");
766                    assert!(active().is_none());
767                })
768            },
769        );
770
771        assert!(result.is_err());
772    }
773
774    #[test]
775    fn source_view_rejects_nested_project_rebinding() {
776        let _override_guard = lock_test_override();
777        let _data = crate::core::data_dir::isolated_data_dir();
778        let first = tempfile::tempdir().expect("create first project");
779        let second = tempfile::tempdir().expect("create second project");
780        write_policy(first.path(), "first-project");
781        write_policy(second.path(), "second-project");
782
783        let result = REQUEST_PROJECT.sync_scope(
784            std::cell::RefCell::new(Some(first.path().to_path_buf())),
785            || {
786                with_source_view(|| {
787                    REQUEST_PROJECT.sync_scope(
788                        std::cell::RefCell::new(Some(second.path().to_path_buf())),
789                        || assert!(!active().unwrap().tool_allowed("ctx_read")),
790                    );
791                })
792            },
793        );
794
795        assert!(result.is_err());
796    }
797
798    #[test]
799    fn source_view_rejects_policy_removal_and_invalid_initial_policy() {
800        let _override_guard = lock_test_override();
801        let _data = crate::core::data_dir::isolated_data_dir();
802        let root = tempfile::tempdir().expect("create project");
803        let path = write_policy(root.path(), "view-a");
804
805        let removed = REQUEST_PROJECT.sync_scope(
806            std::cell::RefCell::new(Some(root.path().to_path_buf())),
807            || {
808                with_source_view(|| {
809                    assert_eq!(active().unwrap().resolved.name, "view-a");
810                    fs::remove_file(&path).expect("remove policy");
811                    assert_eq!(active().unwrap().resolved.name, "view-a");
812                })
813            },
814        );
815        assert!(removed.is_err());
816
817        fs::write(&path, "[policy\n").expect("write invalid policy");
818        let called = std::cell::Cell::new(false);
819        let invalid = REQUEST_PROJECT.sync_scope(
820            std::cell::RefCell::new(Some(root.path().to_path_buf())),
821            || with_source_view(|| called.set(true)),
822        );
823        assert!(invalid.is_err());
824        assert!(!called.get());
825    }
826
827    fn fixture_role(
828        name: &str,
829        boundary_mode: &str,
830        allow_secret_paths: bool,
831        allowed: &[&str],
832    ) -> crate::core::roles::Role {
833        use crate::core::roles::{IoPolicy, Role, RoleLimits, RoleMeta, ToolPolicy};
834        Role {
835            role: RoleMeta {
836                name: name.into(),
837                inherits: None,
838                description: "source view test".into(),
839                shell_policy: "deny".into(),
840            },
841            tools: ToolPolicy {
842                allowed: allowed.iter().map(|tool| (*tool).into()).collect(),
843                denied: Vec::new(),
844            },
845            io: IoPolicy {
846                boundary_mode: boundary_mode.into(),
847                allow_secret_paths,
848                ..Default::default()
849            },
850            limits: RoleLimits::default(),
851        }
852    }
853
854    #[test]
855    fn source_view_pins_full_role_through_a_to_b_to_a_and_rejects_persistent_change() {
856        let _override_guard = lock_test_override();
857        let _data = crate::core::data_dir::isolated_data_dir();
858        let root = tempfile::tempdir().expect("create project");
859        let role_a = fixture_role("role-a", "warn", true, &["ctx_read"]);
860        // Secret-path visibility stays fixed so the regression exercises the
861        // full role fingerprint (tool and boundary policy), not only that bit.
862        let role_b = fixture_role("role-b", "enforce", true, &["ctx_shell"]);
863
864        let transient = crate::core::roles::with_test_active_role(role_a.clone(), || {
865            with_project_source_view(root.path().to_str().unwrap(), || {
866                with_source_view(|| {
867                    assert_eq!(
868                        role_fingerprint(&crate::core::roles::active_role()).unwrap(),
869                        role_fingerprint(&role_a).unwrap()
870                    );
871                    crate::core::roles::set_test_active_role(role_b.clone());
872                    let pinned = crate::core::roles::active_role();
873                    assert_eq!(pinned.role.name, "role-a");
874                    assert_eq!(pinned.io.boundary_mode, "warn");
875                    assert!(pinned.io.allow_secret_paths);
876                    assert!(pinned.is_tool_allowed("ctx_read"));
877                    assert!(!pinned.is_tool_allowed("ctx_shell"));
878                    crate::core::roles::set_test_active_role(role_a.clone());
879                })
880            })
881        });
882        assert!(transient.is_ok(), "a transient role B is never observed");
883
884        let persistent = crate::core::roles::with_test_active_role(role_a.clone(), || {
885            with_project_source_view(root.path().to_str().unwrap(), || {
886                with_source_view(|| {
887                    crate::core::roles::set_test_active_role(role_b.clone());
888                    assert_eq!(crate::core::roles::active_role().role.name, "role-a");
889                })
890            })
891        });
892        assert!(
893            persistent.is_err(),
894            "a changed full role invalidates the view"
895        );
896    }
897
898    #[test]
899    fn closed_inherited_source_view_returns_a_denying_pinned_role() {
900        let root = tempfile::tempdir().expect("create project");
901        let role = fixture_role("role-a", "warn", true, &["ctx_read"]);
902        let role_fingerprint = role_fingerprint(&role).unwrap();
903        let view = SourceView {
904            project: root.path().to_path_buf(),
905            policy: None,
906            fingerprint: blake3::hash(b"test"),
907            role,
908            role_fingerprint,
909            valid: Arc::new(AtomicBool::new(true)),
910            live: Arc::new(AtomicBool::new(false)),
911        };
912
913        REQUEST_PROJECT.sync_scope(
914            std::cell::RefCell::new(Some(root.path().to_path_buf())),
915            || {
916                SOURCE_VIEW.sync_scope(std::cell::RefCell::new(Some(view)), || {
917                    let closed = crate::core::roles::active_role();
918                    assert_eq!(closed.role.name, "closed-source-view");
919                    assert!(!closed.is_tool_allowed("ctx_read"));
920                    assert!(!closed.io.allow_secret_paths);
921                });
922            },
923        );
924    }
925
926    #[test]
927    fn project_source_view_uses_fallback_and_preserves_bound_project() {
928        let _override_guard = lock_test_override();
929        let _data = crate::core::data_dir::isolated_data_dir();
930        let fallback = tempfile::tempdir().expect("create fallback project");
931        let bound = tempfile::tempdir().expect("create bound project");
932        write_policy(fallback.path(), "fallback-project");
933        write_policy(bound.path(), "bound-project");
934        let fallback_root = fallback.path().to_str().unwrap();
935
936        let unbound =
937            with_project_source_view(fallback_root, || active().unwrap().resolved.name.clone());
938        assert_eq!(unbound.unwrap(), "fallback-project");
939
940        let already_bound = REQUEST_PROJECT.sync_scope(
941            std::cell::RefCell::new(Some(bound.path().to_path_buf())),
942            || with_project_source_view(fallback_root, || active().unwrap().resolved.name.clone()),
943        );
944        assert_eq!(already_bound.unwrap(), "bound-project");
945    }
946}