1use 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;
30pub(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 held_horizon_tests;
36#[cfg(test)]
37mod refresh_tests;
38
39tokio::task_local! {
40 pub(crate) static REQUEST_PROJECT: std::cell::RefCell<Option<PathBuf>>;
42 pub(crate) static SOURCE_VIEW: std::cell::RefCell<Option<SourceView>>;
44}
45
46#[derive(Clone)]
47pub(crate) struct SourceView {
48 project: PathBuf,
49 policy: Option<Arc<ActivePolicy>>,
50 fingerprint: blake3::Hash,
51 role: crate::core::roles::Role,
52 role_fingerprint: blake3::Hash,
53 lifetime: Option<super::org::Lifetime>,
64 observation: Option<super::org::Observation>,
67 valid: Arc<AtomicBool>,
68 live: Arc<AtomicBool>,
69}
70
71impl SourceView {
72 fn within_horizon(&self) -> bool {
75 let holds = self
76 .lifetime
77 .is_none_or(|lifetime| lifetime.check_horizon().is_ok());
78 if !holds {
79 self.valid.store(false, Ordering::Release);
80 }
81 holds
82 }
83
84 fn invalidate_if_live(&self) {
92 if self.live.load(Ordering::Acquire) {
93 self.valid.store(false, Ordering::Release);
94 }
95 }
96}
97
98struct SourceViewLifetime(Arc<AtomicBool>);
99
100#[derive(Debug)]
103pub(crate) struct PublicationAuthority {
104 project: PathBuf,
105 fingerprint: blake3::Hash,
106 role_fingerprint: blake3::Hash,
107 lifetime: Option<super::org::Lifetime>,
109 valid: Arc<AtomicBool>,
110}
111
112impl PublicationAuthority {
113 pub(crate) fn capture() -> Result<Self, String> {
114 let view = current_source_view().ok_or("source authority unavailable")?;
115 if !view.within_horizon() {
116 return Err("source authority unavailable".into());
117 }
118 Ok(Self {
119 project: view.project,
120 fingerprint: view.fingerprint,
121 role_fingerprint: view.role_fingerprint,
122 lifetime: view.lifetime,
123 valid: view.valid,
124 })
125 }
126
127 pub(crate) fn verify(&self) -> Result<(), String> {
128 if !self.valid.load(Ordering::Acquire)
129 || REQUEST_PROJECT
130 .try_with(|slot| {
131 slot.borrow()
132 .as_ref()
133 .is_some_and(|root| root != &self.project)
134 })
135 .unwrap_or(false)
136 {
137 return Err("source authority changed before publication".into());
138 }
139 REQUEST_PROJECT.sync_scope(std::cell::RefCell::new(Some(self.project.clone())), || {
140 SOURCE_VIEW.sync_scope(std::cell::RefCell::new(None), || {
141 let latest = refresh::current_verified(self.project.clone())?;
142 let role = role_fingerprint(&crate::core::roles::active_role())?;
143 if latest.fingerprint != self.fingerprint || role != self.role_fingerprint {
144 return Err("source authority changed before publication".into());
145 }
146 if let Some(lifetime) = &self.lifetime {
150 lifetime.check_horizon()?;
151 }
152 Ok(())
153 })
154 })
155 }
156
157 pub(crate) fn fingerprint_bytes(&self) -> [u8; 32] {
160 *self.fingerprint.as_bytes()
161 }
162
163 #[cfg(any(test, feature = "http-server"))]
166 pub(crate) fn role_fingerprint_bytes(&self) -> [u8; 32] {
167 *self.role_fingerprint.as_bytes()
168 }
169}
170
171impl Drop for SourceViewLifetime {
172 fn drop(&mut self) {
173 self.0.store(false, Ordering::Release);
174 }
175}
176
177fn current_source_view() -> Option<SourceView> {
178 SOURCE_VIEW
179 .try_with(|slot| slot.borrow().clone())
180 .ok()
181 .flatten()
182}
183
184pub(crate) fn inherited_source_view() -> Option<SourceView> {
186 current_source_view()
187}
188
189pub(crate) fn detached_project_root(fallback: &Path) -> Result<PathBuf, String> {
193 let request_project = REQUEST_PROJECT
194 .try_with(|slot| slot.borrow().clone())
195 .ok()
196 .flatten();
197 if let Some(view) = current_source_view() {
198 if !view.live.load(Ordering::Acquire)
199 || !view.valid.load(Ordering::Acquire)
200 || request_project.as_ref() != Some(&view.project)
201 {
202 view.invalidate_if_live();
203 return Err("source policy view is no longer active".into());
204 }
205 return Ok(view.project);
206 }
207 Ok(request_project.unwrap_or_else(|| fallback.to_path_buf()))
208}
209
210pub(crate) fn with_inherited_source_view<T>(
212 view: Option<SourceView>,
213 operation: impl FnOnce() -> T,
214) -> T {
215 match view {
216 Some(view) => SOURCE_VIEW.sync_scope(std::cell::RefCell::new(Some(view)), operation),
217 None => operation(),
218 }
219}
220
221pub(crate) fn pinned_role() -> Option<crate::core::roles::Role> {
224 current_source_view().map(|view| {
225 let project = REQUEST_PROJECT
226 .try_with(|slot| slot.borrow().clone())
227 .ok()
228 .flatten();
229 if !view.live.load(Ordering::Acquire)
230 || !view.valid.load(Ordering::Acquire)
231 || project.as_ref() != Some(&view.project)
232 {
233 view.invalidate_if_live();
234 crate::core::roles::closed_source_view_role()
235 } else {
236 view.role
237 }
238 })
239}
240
241pub(crate) fn in_project<T>(project: impl Into<PathBuf>, operation: impl FnOnce() -> T) -> T {
243 REQUEST_PROJECT.sync_scope(std::cell::RefCell::new(Some(project.into())), operation)
244}
245
246pub(crate) fn spawn_for_project<T: Send + 'static>(
250 project: impl Into<PathBuf>,
251 operation: impl FnOnce() -> T + Send + 'static,
252) -> std::thread::JoinHandle<T> {
253 let project = project.into();
254 std::thread::spawn(move || in_project(project, operation))
255}
256
257pub(crate) fn bind_request_project(project: Option<&str>) {
258 if current_source_view().is_some() {
259 return;
260 }
261 let _ = REQUEST_PROJECT.try_with(|slot| {
262 *slot.borrow_mut() = project.map(PathBuf::from);
263 });
264}
265
266fn canonical_project_root(project: &Path) -> Result<PathBuf, String> {
272 let project = crate::core::pathutil::canonicalize_secure(project)
273 .map_err(|_| "policy project root unavailable")?;
274 if !project.is_dir() {
275 return Err("policy project root unavailable".into());
276 }
277 Ok(project)
278}
279
280pub(crate) fn request_project_is(root: &Path) -> bool {
286 match REQUEST_PROJECT.try_with(|slot| slot.borrow().clone()) {
287 Ok(Some(bound)) => canonical_project_root(&bound).is_ok_and(|bound| bound == root),
288 _ => true,
289 }
290}
291
292pub(crate) fn with_project_source_view<T>(
296 project_root: &str,
297 operation: impl FnOnce() -> T,
298) -> Result<T, String> {
299 let project = REQUEST_PROJECT
300 .try_with(|slot| slot.borrow().clone())
301 .ok()
302 .flatten()
303 .or_else(|| current_source_view().map(|view| view.project))
304 .unwrap_or_else(|| PathBuf::from(project_root));
305 let project = canonical_project_root(&project)?;
306 REQUEST_PROJECT.sync_scope(std::cell::RefCell::new(Some(project)), || {
307 with_source_view(operation)
308 })
309}
310
311pub(crate) fn with_explicit_project_source_view<T>(
315 project_root: &Path,
316 operation: impl FnOnce(&PublicationAuthority) -> T,
317) -> Result<T, String> {
318 let project = canonical_project_root(project_root)?;
319
320 let bound = REQUEST_PROJECT
321 .try_with(|slot| slot.borrow().clone())
322 .ok()
323 .flatten();
324 if let Some(bound) = bound {
325 let bound = crate::core::pathutil::canonicalize_secure(&bound)
326 .map_err(|_| "request project authority unavailable")?;
327 if bound != project {
328 return Err("request project authority does not match egress root".into());
329 }
330 }
331 if let Some(view) = current_source_view()
332 && (!view.live.load(Ordering::Acquire)
333 || !view.valid.load(Ordering::Acquire)
334 || view.project != project)
335 {
336 view.invalidate_if_live();
337 return Err("source policy view does not match egress root".into());
338 }
339
340 REQUEST_PROJECT.sync_scope(std::cell::RefCell::new(Some(project)), || {
341 with_source_view(|| {
342 let authority = PublicationAuthority::capture()?;
343 let result = operation(&authority);
344 authority.verify()?;
345 Ok(result)
346 })?
347 })
348}
349
350pub(crate) fn with_source_view<T>(operation: impl FnOnce() -> T) -> Result<T, String> {
354 with_source_view_when(|_, _| true, operation)?
355 .ok_or_else(|| "source policy view is no longer active".into())
356}
357
358#[cfg(feature = "http-server")]
370pub(crate) fn with_governed_source_view<T>(
371 operation: impl FnOnce() -> T,
372) -> Result<Option<T>, String> {
373 with_source_view_when(|policy, observed| policy || observed, operation)
374}
375
376fn with_source_view_when<T>(
379 enter: impl FnOnce(bool, bool) -> bool,
380 operation: impl FnOnce() -> T,
381) -> Result<Option<T>, String> {
382 if let Some(view) = current_source_view() {
383 let project = REQUEST_PROJECT
384 .try_with(|slot| slot.borrow().clone())
385 .ok()
386 .flatten()
387 .ok_or("source policy view is no longer active")?;
388 let project = canonical_project_root(&project)
389 .map_err(|_| "source policy view is no longer active")?;
390 if !view.live.load(Ordering::Acquire)
391 || !view.valid.load(Ordering::Acquire)
392 || project != view.project
393 || !view.within_horizon()
394 {
395 view.invalidate_if_live();
396 return Err("source policy view is no longer active".into());
397 }
398 if !enter(view.policy.is_some(), view.observation.is_some()) {
399 return Ok(None);
400 }
401 return REQUEST_PROJECT
402 .sync_scope(std::cell::RefCell::new(Some(view.project.clone())), || {
403 Ok(Some(operation()))
404 });
405 }
406
407 let project = match REQUEST_PROJECT.try_with(|slot| slot.borrow().clone()) {
411 Ok(project) => project.ok_or("project_unresolved")?,
412 Err(_) => std::env::current_dir().map_err(|_| "policy project root unavailable")?,
413 };
414 let project = canonical_project_root(&project)?;
415 REQUEST_PROJECT.sync_scope(std::cell::RefCell::new(Some(project.clone())), || {
416 let verified = refresh::current_verified_settled(&project)?;
417 let lifetime = verified.lifetime;
418 let observation = verified.observation;
419 let role = crate::core::roles::active_role();
420 let pinned_role_fingerprint = role_fingerprint(&role)?;
421 let view = SourceView {
422 project: project.clone(),
423 policy: source_view_policy(verified.policy),
424 fingerprint: verified.fingerprint,
425 role,
426 role_fingerprint: pinned_role_fingerprint,
427 lifetime,
428 observation,
429 valid: Arc::new(AtomicBool::new(true)),
430 live: Arc::new(AtomicBool::new(true)),
431 };
432
433 if !view.within_horizon() {
436 return Err("source policy view is no longer active".into());
437 }
438 if !enter(view.policy.is_some(), view.observation.is_some()) {
440 return Ok(None);
441 }
442 let view_lifetime = SourceViewLifetime(view.live.clone());
443 let value = SOURCE_VIEW.sync_scope(std::cell::RefCell::new(Some(view.clone())), operation);
444 drop(view_lifetime);
445
446 let project_unchanged = REQUEST_PROJECT
449 .try_with(|slot| slot.borrow().as_ref() == Some(&view.project))
450 .unwrap_or(false);
451 let latest_role = crate::core::roles::active_role();
452 let latest_role_fingerprint = role_fingerprint(&latest_role)?;
453 let latest = refresh::current_verified_settled(&project)?;
454 if !project_unchanged
455 || latest.fingerprint != view.fingerprint
456 || latest_role_fingerprint != view.role_fingerprint
457 || !view.valid.load(Ordering::Acquire)
458 {
459 return Err("source policy view changed during operation".into());
460 }
461 if !view.within_horizon() {
465 return Err("source policy view changed during operation".into());
466 }
467 Ok(Some(value))
468 })
469}
470
471pub(crate) fn role_fingerprint(role: &crate::core::roles::Role) -> Result<blake3::Hash, String> {
472 serde_json::to_vec(role)
473 .map(|bytes| blake3::hash(&bytes))
474 .map_err(|_| "source role view unavailable".into())
475}
476
477#[cfg(test)]
478fn source_view_policy(fresh: Option<Arc<ActivePolicy>>) -> Option<Arc<ActivePolicy>> {
479 let state = test_override()
480 .read()
481 .unwrap_or_else(std::sync::PoisonError::into_inner);
482 match &*state {
483 OverrideState::Live => fresh,
484 OverrideState::Fixed(policy) => policy.clone(),
485 }
486}
487
488#[cfg(not(test))]
489fn source_view_policy(fresh: Option<Arc<ActivePolicy>>) -> Option<Arc<ActivePolicy>> {
490 fresh
491}
492
493const PROJECT_PACK_PATH: &str = ".lean-ctx/policy.toml";
496
497pub struct ActivePolicy {
500 pub resolved: ResolvedPolicy,
501 pub redaction: Vec<(String, Regex)>,
504 pub(crate) blocked_patterns: Vec<(String, Regex)>,
505 pub(crate) hive_rules: usize,
508 pub(crate) content_valid: bool,
509 pub filters: FilterConfig,
512 pub egress: crate::core::egress::EgressConfig,
515 horizon: Option<chrono::DateTime<chrono::Utc>>,
521 expired: AtomicBool,
525}
526
527impl ActivePolicy {
528 #[must_use]
534 pub fn within_horizon(&self) -> bool {
535 if self.expired.load(Ordering::Acquire) {
536 return false;
537 }
538 let holds = self
539 .horizon
540 .is_none_or(|horizon| chrono::Utc::now() < horizon);
541 if !holds {
542 self.expired.store(true, Ordering::Release);
543 }
544 holds
545 }
546
547 fn until(mut self, horizon: Option<chrono::DateTime<chrono::Utc>>) -> Self {
549 self.horizon = horizon;
550 self
551 }
552
553 pub(crate) fn from_resolved(resolved: ResolvedPolicy) -> Self {
554 Self::from_resolved_with_hive(resolved, &crate::core::hive::policy::FilterRules::default())
555 }
556
557 pub(crate) fn from_resolved_with_hive(
562 mut resolved: ResolvedPolicy,
563 hive: &crate::core::hive::policy::FilterRules,
564 ) -> Self {
565 use super::content::{MAX_REDACTION_RULES, MAX_RULE_LABEL_BYTES, MAX_RULE_PATTERN_BYTES};
566 let hive_rules = hive.redaction.len() + hive.blocked.len();
567 let hive_bounded = hive_rules <= crate::core::hive::policy::HIVE_MAX_RULES
568 && hive
569 .redaction
570 .iter()
571 .chain(&hive.blocked)
572 .all(|(label, pattern)| {
573 label.starts_with(super::HIVE_LABEL_PREFIX)
574 && label.len() <= MAX_RULE_LABEL_BYTES
575 && !label.chars().any(char::is_control)
576 && pattern.len() <= MAX_RULE_PATTERN_BYTES
577 });
578 let bounded = hive_bounded
579 && resolved.redaction.len() + resolved.filters.blocked_patterns.len()
580 <= MAX_REDACTION_RULES
581 && resolved.egress.forbidden_patterns.len() <= MAX_REDACTION_RULES
582 && resolved
583 .egress
584 .forbidden_patterns
585 .iter()
586 .all(|pattern| pattern.len() <= MAX_RULE_PATTERN_BYTES)
587 && resolved
588 .redaction
589 .iter()
590 .chain(&resolved.filters.blocked_patterns)
591 .all(|(label, pattern)| {
592 !label.is_empty()
593 && label.len() <= MAX_RULE_LABEL_BYTES
594 && !label.chars().any(char::is_control)
595 && pattern.len() <= MAX_RULE_PATTERN_BYTES
596 });
597 resolved.redaction.extend(hive.redaction.iter().cloned());
600 resolved
601 .filters
602 .blocked_patterns
603 .extend(hive.blocked.iter().cloned());
604 let compiled = bounded.then(|| {
605 resolved
606 .redaction
607 .iter()
608 .map(|(label, pattern)| {
609 regex::RegexBuilder::new(pattern)
610 .size_limit(1024 * 1024)
611 .dfa_size_limit(1024 * 1024)
612 .build()
613 .map(|re| (label.clone(), re))
614 })
615 .collect::<Result<Vec<_>, _>>()
616 });
617 let content_valid = matches!(&compiled, Some(Ok(_)));
618 let redaction = compiled.and_then(Result::ok).unwrap_or_default();
619 let compiled_blocks = bounded.then(|| {
620 resolved
621 .filters
622 .blocked_patterns
623 .iter()
624 .map(|(label, pattern)| {
625 regex::RegexBuilder::new(pattern)
626 .size_limit(1024 * 1024)
627 .dfa_size_limit(1024 * 1024)
628 .build()
629 .map(|re| (label.clone(), re))
630 })
631 .collect::<Result<Vec<_>, _>>()
632 });
633 let content_valid = content_valid && matches!(&compiled_blocks, Some(Ok(_)));
634 let blocked_patterns = compiled_blocks.and_then(Result::ok).unwrap_or_default();
635 let filters = FilterConfig::new(
636 filter_action(resolved.filters.pii.as_ref()),
637 filter_action(resolved.filters.classification.as_ref()),
638 filter_action(resolved.filters.injection.as_ref()),
639 &resolved.filters.blocked_labels,
640 );
641 let egress = crate::core::egress::EgressConfig::new(
642 &resolved.egress.forbidden_patterns,
643 resolved.egress.block_secrets.unwrap_or(false),
644 resolved.egress.max_writes_per_min,
645 );
646 Self {
647 resolved,
648 redaction,
649 blocked_patterns,
650 hive_rules,
651 content_valid,
652 filters,
653 egress,
654 horizon: None,
655 expired: AtomicBool::new(false),
656 }
657 }
658
659 pub(crate) fn deny_all() -> Self {
661 let mut active = Self::from_resolved(ResolvedPolicy {
662 name: "invalid-local-policy".into(),
663 version: "0.0.0".into(),
664 description: "deny all because the local policy pack is invalid".into(),
665 chain: Vec::new(),
666 default_read_mode: None,
667 allow_tools: Some(Vec::new()),
668 deny_tools: Vec::new(),
669 max_context_tokens: None,
670 audit_retention_days: None,
671 redaction: std::collections::BTreeMap::new(),
672 filters: crate::core::policy::FilterRules::default(),
673 egress: crate::core::policy::EgressRules::default(),
674 routing: crate::core::policy::RoutingPolicyRules::default(),
675 budgets: crate::core::policy::BudgetRules::default(),
676 });
677 active.content_valid = false;
678 active
679 }
680
681 #[must_use]
685 pub fn tool_allowed(&self, tool: &str) -> bool {
686 if !self.content_valid || !self.within_horizon() {
687 return false;
688 }
689 if self.resolved.deny_tools.iter().any(|t| t == tool) {
690 return false;
691 }
692 match &self.resolved.allow_tools {
693 Some(allow) => allow.iter().any(|t| t == tool),
694 None => true,
695 }
696 }
697}
698
699fn filter_action(opt: Option<&String>) -> FilterAction {
702 opt.map(String::as_str)
703 .and_then(FilterAction::parse)
704 .unwrap_or(FilterAction::Off)
705}
706
707#[cfg(test)]
708fn load_from_disk() -> Option<Arc<ActivePolicy>> {
709 let local = match load_local_pack() {
710 Ok(local) => local,
711 Err(msg) => {
712 tracing::error!(
713 "policy: failed to load invalid {PROJECT_PACK_PATH} ({msg}); enforcing deny-all"
714 );
715 return Some(Arc::new(ActivePolicy::deny_all()));
716 }
717 };
718 apply_org_floor(
719 local,
720 crate::core::policy::org::active_resolved_checked(),
721 None,
722 &crate::core::hive::policy::FilterRules::default(),
723 None,
724 )
725}
726
727fn apply_org_floor(
732 local: Option<ResolvedPolicy>,
733 org: Result<Option<ResolvedPolicy>, String>,
734 horizon: Option<chrono::DateTime<chrono::Utc>>,
735 hive: &crate::core::hive::policy::FilterRules,
736 hive_floor: Option<&ResolvedPolicy>,
737) -> Option<Arc<ActivePolicy>> {
738 let effective = match org {
740 Ok(Some(org)) => Some(crate::core::policy::floor::merge_floor(
741 &org,
742 local.as_ref(),
743 )),
744 Ok(None) => local,
745 Err(error) => {
746 tracing::error!("org policy rejected; enforcing deny-all: {error}");
747 return Some(Arc::new(ActivePolicy::deny_all()));
748 }
749 };
750 let effective = match hive_floor {
751 Some(floor) => Some(crate::core::hive::effective_floor::apply(
752 floor,
753 effective.as_ref(),
754 )),
755 None => effective,
756 };
757 let effective = match effective {
758 Some(effective) => effective,
759 None if hive.redaction.is_empty() && hive.blocked.is_empty() => return None,
760 None => hive_filters_only(),
762 };
763 Some(Arc::new(
764 ActivePolicy::from_resolved_with_hive(effective, hive).until(horizon),
765 ))
766}
767
768fn hive_filters_only() -> ResolvedPolicy {
770 ResolvedPolicy {
771 name: "hive-filters".into(),
772 version: "1.0.0".into(),
773 description: "content rules of the installed Hive filter packs".into(),
774 chain: Vec::new(),
775 default_read_mode: None,
776 allow_tools: None,
777 deny_tools: Vec::new(),
778 max_context_tokens: None,
779 audit_retention_days: None,
780 redaction: std::collections::BTreeMap::new(),
781 filters: crate::core::policy::FilterRules::default(),
782 egress: crate::core::policy::EgressRules::default(),
783 routing: crate::core::policy::RoutingPolicyRules::default(),
784 budgets: crate::core::policy::BudgetRules::default(),
785 }
786}
787
788#[cfg(test)]
791fn load_local_pack() -> Result<Option<ResolvedPolicy>, String> {
792 let path = PathBuf::from(PROJECT_PACK_PATH);
793 load_local_pack_at(&path)
794}
795
796#[cfg(test)]
797fn load_local_pack_at(path: &Path) -> Result<Option<ResolvedPolicy>, String> {
798 match std::fs::symlink_metadata(path) {
799 Ok(_) => {}
800 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
801 Err(error) => return Err(format!("{}: {error}", path.display())),
802 }
803 match parse_file(path).and_then(|p| resolve(&p)) {
804 Ok(resolved) => Ok(Some(resolved)),
805 Err(e) => Err(format!("{}: {e}", path.display())),
806 }
807}
808
809pub fn for_project(project_root: &Path) -> Result<Option<Arc<ActivePolicy>>, String> {
812 refresh::current(project_root.to_path_buf())
813}
814
815#[must_use]
818pub fn active() -> Option<Arc<ActivePolicy>> {
819 active_observed().0
820}
821
822#[must_use]
834pub(crate) fn active_observed() -> (Option<Arc<ActivePolicy>>, Option<super::org::Observation>) {
835 let deny_all = || (Some(Arc::new(ActivePolicy::deny_all())), None);
836 if let Some(view) = current_source_view() {
837 if !view.live.load(Ordering::Acquire) || !view.valid.load(Ordering::Acquire) {
838 return deny_all();
839 }
840 let project = REQUEST_PROJECT
841 .try_with(|slot| slot.borrow().clone())
842 .ok()
843 .flatten();
844 if project.as_ref() != Some(&view.project) || !view.within_horizon() {
845 view.invalidate_if_live();
846 return deny_all();
847 }
848 return (view.policy, view.observation);
849 }
850 #[cfg(test)]
851 {
852 let state = test_override()
853 .read()
854 .unwrap_or_else(std::sync::PoisonError::into_inner);
855 if let OverrideState::Fixed(policy) = &*state {
856 return (policy.clone(), None);
857 }
858 }
859 let scoped = REQUEST_PROJECT
860 .try_with(|slot| slot.borrow().clone())
861 .ok()
862 .flatten();
863 match scoped
864 .map_or_else(std::env::current_dir, Ok)
865 .map_err(|_| "policy project root unavailable".into())
866 .and_then(refresh::current_verified)
867 {
868 Ok(verified) => (verified.policy, verified.observation),
869 Err(_) => deny_all(),
870 }
871}
872
873#[cfg(test)]
878pub(crate) fn with_observed_view_for_test<T>(
879 project: &Path,
880 observation: Option<super::org::Observation>,
881 operation: impl FnOnce() -> T,
882) -> T {
883 let project = canonical_project_root(project).expect("test project root");
884 let role = crate::core::roles::active_role();
885 let verified = refresh::current_verified(project.clone()).expect("test authority");
889 let view = SourceView {
890 project: project.clone(),
891 policy: verified.policy,
892 fingerprint: verified.fingerprint,
893 role_fingerprint: role_fingerprint(&role).expect("test role"),
894 role,
895 lifetime: None,
896 observation,
897 valid: Arc::new(AtomicBool::new(true)),
898 live: Arc::new(AtomicBool::new(true)),
899 };
900 REQUEST_PROJECT.sync_scope(std::cell::RefCell::new(Some(project)), || {
901 SOURCE_VIEW.sync_scope(std::cell::RefCell::new(Some(view)), operation)
902 })
903}
904
905pub(crate) enum HeldObservation {
907 NotHeld,
909 Held(Option<super::org::Observation>),
912}
913
914pub(crate) fn held_observation() -> HeldObservation {
921 let Some(view) = current_source_view() else {
922 return HeldObservation::NotHeld;
923 };
924 let project = REQUEST_PROJECT
925 .try_with(|slot| slot.borrow().clone())
926 .ok()
927 .flatten();
928 if !view.live.load(Ordering::Acquire)
929 || !view.valid.load(Ordering::Acquire)
930 || project.as_ref() != Some(&view.project)
931 || !view.within_horizon()
932 {
933 return HeldObservation::NotHeld;
934 }
935 HeldObservation::Held(view.observation)
936}
937
938#[must_use]
940pub fn is_active() -> bool {
941 active().is_some()
942}
943
944pub fn reload() {
946 let _ = active();
947}
948
949#[cfg(test)]
950enum OverrideState {
951 Live,
952 Fixed(Option<Arc<ActivePolicy>>),
953}
954
955#[cfg(test)]
956fn test_override() -> &'static RwLock<OverrideState> {
957 static OVERRIDE: OnceLock<RwLock<OverrideState>> = OnceLock::new();
958 OVERRIDE.get_or_init(|| RwLock::new(OverrideState::Live))
959}
960
961#[cfg(test)]
962fn test_override_lock() -> &'static std::sync::Mutex<()> {
963 static LOCK: OnceLock<std::sync::Mutex<()>> = OnceLock::new();
964 LOCK.get_or_init(|| std::sync::Mutex::new(()))
965}
966
967#[cfg(test)]
972pub(crate) struct TestOverrideGuard {
973 _policy: std::sync::MutexGuard<'static, ()>,
974 _environment: crate::core::data_dir::TestEnvGuard,
975}
976
977#[cfg(test)]
978pub(crate) fn lock_test_override() -> TestOverrideGuard {
979 let environment = crate::core::data_dir::test_env_lock();
980 let policy = test_override_lock()
981 .lock()
982 .unwrap_or_else(std::sync::PoisonError::into_inner);
983 TestOverrideGuard {
984 _policy: policy,
985 _environment: environment,
986 }
987}
988
989#[cfg(test)]
991pub struct TestPolicyOverride {
992 previous: OverrideState,
993 _lock: TestOverrideGuard,
994}
995
996#[cfg(test)]
997impl TestPolicyOverride {
998 pub fn set(resolved: Option<ResolvedPolicy>) -> Self {
999 let lock = lock_test_override();
1000 let previous = std::mem::replace(
1001 &mut *test_override()
1002 .write()
1003 .unwrap_or_else(std::sync::PoisonError::into_inner),
1004 OverrideState::Fixed(
1005 resolved.map(|policy| Arc::new(ActivePolicy::from_resolved(policy))),
1006 ),
1007 );
1008 Self {
1009 previous,
1010 _lock: lock,
1011 }
1012 }
1013}
1014
1015#[cfg(test)]
1016impl Drop for TestPolicyOverride {
1017 fn drop(&mut self) {
1018 *test_override()
1019 .write()
1020 .unwrap_or_else(std::sync::PoisonError::into_inner) =
1021 std::mem::replace(&mut self.previous, OverrideState::Live);
1022 }
1023}
1024
1025#[cfg(test)]
1026#[path = "runtime/tests.rs"]
1027mod tests;