1use std::path::{Path, PathBuf};
17use std::sync::Arc;
18use std::sync::atomic::{AtomicBool, Ordering};
19#[cfg(any(test, feature = "test-support"))]
20use std::sync::{OnceLock, RwLock};
21
22use regex::Regex;
23
24use super::ResolvedPolicy;
25#[cfg(test)]
26use super::{parse_file, resolve};
27use crate::core::input_filters::{FilterAction, FilterConfig};
28
29mod refresh;
30pub const REQUIRED_POLICY_ROOT_ENV: &str = "LEAN_CTX_REQUIRED_POLICY_ROOT";
32pub const REQUIRED_POLICY_DIGEST_ENV: &str = "LEAN_CTX_REQUIRED_POLICY_DIGEST";
33pub use refresh::{protected_authority_paths, protected_policy_digest};
34#[cfg(any(test, feature = "test-support"))]
35pub mod held_horizon_support;
36#[cfg(test)]
37pub(crate) mod held_horizon_tests;
38#[cfg(test)]
39mod refresh_tests;
40
41tokio::task_local! {
42 pub static REQUEST_PROJECT: std::cell::RefCell<Option<PathBuf>>;
44 pub(crate) static SOURCE_VIEW: std::cell::RefCell<Option<SourceView>>;
46}
47
48#[derive(Clone)]
49pub struct SourceView {
50 project: PathBuf,
51 policy: Option<Arc<ActivePolicy>>,
52 fingerprint: blake3::Hash,
53 role: crate::core::roles::Role,
54 role_fingerprint: blake3::Hash,
55 lifetime: Option<super::org::Lifetime>,
66 observation: Option<super::org::Observation>,
69 valid: Arc<AtomicBool>,
70 live: Arc<AtomicBool>,
71}
72
73impl SourceView {
74 fn within_horizon(&self) -> bool {
77 let holds = self
78 .lifetime
79 .is_none_or(|lifetime| lifetime.check_horizon().is_ok());
80 if !holds {
81 self.valid.store(false, Ordering::Release);
82 }
83 holds
84 }
85
86 fn invalidate_if_live(&self) {
94 if self.live.load(Ordering::Acquire) {
95 self.valid.store(false, Ordering::Release);
96 }
97 }
98}
99
100struct SourceViewLifetime(Arc<AtomicBool>);
101
102#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
106#[serde(deny_unknown_fields)]
107pub struct StoredPublicationAuthority {
108 project: PathBuf,
109 fingerprint: [u8; 32],
110 role_fingerprint: [u8; 32],
111 lifetime: Option<StoredLifetime>,
112}
113
114#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
117#[serde(deny_unknown_fields)]
118pub struct StoredLifetime {
119 horizon: Option<lean_ctx_time::UtcDateTime>,
120}
121
122#[derive(Debug)]
125pub struct PublicationAuthority {
126 project: PathBuf,
127 fingerprint: blake3::Hash,
128 role_fingerprint: blake3::Hash,
129 lifetime: Option<super::org::Lifetime>,
131 valid: Arc<AtomicBool>,
132}
133
134impl PublicationAuthority {
135 pub fn capture() -> Result<Self, String> {
136 let view = current_source_view().ok_or("source authority unavailable")?;
137 if !view.within_horizon() {
138 return Err("source authority unavailable".into());
139 }
140 Ok(Self {
141 project: view.project,
142 fingerprint: view.fingerprint,
143 role_fingerprint: view.role_fingerprint,
144 lifetime: view.lifetime,
145 valid: view.valid,
146 })
147 }
148
149 pub fn stored(&self) -> Option<StoredPublicationAuthority> {
156 self.valid
157 .load(Ordering::Acquire)
158 .then(|| StoredPublicationAuthority {
159 project: self.project.clone(),
160 fingerprint: *self.fingerprint.as_bytes(),
161 role_fingerprint: *self.role_fingerprint.as_bytes(),
162 lifetime: self.lifetime.map(|lifetime| StoredLifetime {
163 horizon: lifetime.horizon(),
164 }),
165 })
166 }
167
168 #[must_use]
174 pub fn restore(stored: StoredPublicationAuthority) -> Self {
175 Self {
176 project: stored.project,
177 fingerprint: blake3::Hash::from_bytes(stored.fingerprint),
178 role_fingerprint: blake3::Hash::from_bytes(stored.role_fingerprint),
179 lifetime: stored
180 .lifetime
181 .map(|lifetime| super::org::Lifetime::restored(lifetime.horizon)),
182 valid: Arc::new(AtomicBool::new(true)),
183 }
184 }
185
186 pub fn verify(&self) -> Result<(), String> {
187 if !self.valid.load(Ordering::Acquire)
188 || REQUEST_PROJECT
189 .try_with(|slot| {
190 slot.borrow()
191 .as_ref()
192 .is_some_and(|root| root != &self.project)
193 })
194 .unwrap_or(false)
195 {
196 return Err("source authority changed before publication".into());
197 }
198 REQUEST_PROJECT.sync_scope(std::cell::RefCell::new(Some(self.project.clone())), || {
199 SOURCE_VIEW.sync_scope(std::cell::RefCell::new(None), || {
200 let latest = refresh::current_verified(self.project.clone())?;
201 let role = role_fingerprint(&crate::core::roles::active_role())?;
202 if latest.fingerprint != self.fingerprint || role != self.role_fingerprint {
203 return Err("source authority changed before publication".into());
204 }
205 if let Some(lifetime) = &self.lifetime {
209 lifetime.check_horizon()?;
210 }
211 Ok(())
212 })
213 })
214 }
215
216 pub fn fingerprint_bytes(&self) -> [u8; 32] {
219 *self.fingerprint.as_bytes()
220 }
221
222 #[cfg(any(test, feature = "http-server"))]
225 pub fn role_fingerprint_bytes(&self) -> [u8; 32] {
226 *self.role_fingerprint.as_bytes()
227 }
228}
229
230impl Drop for SourceViewLifetime {
231 fn drop(&mut self) {
232 self.0.store(false, Ordering::Release);
233 }
234}
235
236fn current_source_view() -> Option<SourceView> {
237 SOURCE_VIEW
238 .try_with(|slot| slot.borrow().clone())
239 .ok()
240 .flatten()
241}
242
243pub fn inherited_source_view() -> Option<SourceView> {
245 current_source_view()
246}
247
248pub fn detached_project_root(fallback: &Path) -> Result<PathBuf, String> {
252 let request_project = REQUEST_PROJECT
253 .try_with(|slot| slot.borrow().clone())
254 .ok()
255 .flatten();
256 if let Some(view) = current_source_view() {
257 if !view.live.load(Ordering::Acquire)
258 || !view.valid.load(Ordering::Acquire)
259 || request_project.as_ref() != Some(&view.project)
260 {
261 view.invalidate_if_live();
262 return Err("source policy view is no longer active".into());
263 }
264 return Ok(view.project);
265 }
266 Ok(request_project.unwrap_or_else(|| fallback.to_path_buf()))
267}
268
269pub(crate) fn with_inherited_source_view<T>(
271 view: Option<SourceView>,
272 operation: impl FnOnce() -> T,
273) -> T {
274 match view {
275 Some(view) => SOURCE_VIEW.sync_scope(std::cell::RefCell::new(Some(view)), operation),
276 None => operation(),
277 }
278}
279
280pub(crate) fn pinned_role() -> Option<crate::core::roles::Role> {
283 current_source_view().map(|view| {
284 let project = REQUEST_PROJECT
285 .try_with(|slot| slot.borrow().clone())
286 .ok()
287 .flatten();
288 if !view.live.load(Ordering::Acquire)
289 || !view.valid.load(Ordering::Acquire)
290 || project.as_ref() != Some(&view.project)
291 {
292 view.invalidate_if_live();
293 crate::core::roles::closed_source_view_role()
294 } else {
295 view.role
296 }
297 })
298}
299
300pub fn in_project<T>(project: impl Into<PathBuf>, operation: impl FnOnce() -> T) -> T {
302 REQUEST_PROJECT.sync_scope(std::cell::RefCell::new(Some(project.into())), operation)
303}
304
305pub fn spawn_for_project<T: Send + 'static>(
309 project: impl Into<PathBuf>,
310 operation: impl FnOnce() -> T + Send + 'static,
311) -> std::thread::JoinHandle<T> {
312 let project = project.into();
313 std::thread::spawn(move || in_project(project, operation))
314}
315
316pub fn bind_request_project(project: Option<&str>) {
317 if current_source_view().is_some() {
318 return;
319 }
320 let _ = REQUEST_PROJECT.try_with(|slot| {
321 *slot.borrow_mut() = project.map(PathBuf::from);
322 });
323}
324
325fn canonical_project_root(project: &Path) -> Result<PathBuf, String> {
331 let project = crate::core::pathutil::canonicalize_secure(project)
332 .map_err(|_| "policy project root unavailable")?;
333 if !project.is_dir() {
334 return Err("policy project root unavailable".into());
335 }
336 Ok(project)
337}
338
339pub(crate) fn request_project_is(root: &Path) -> bool {
345 match REQUEST_PROJECT.try_with(|slot| slot.borrow().clone()) {
346 Ok(Some(bound)) => canonical_project_root(&bound).is_ok_and(|bound| bound == root),
347 _ => true,
348 }
349}
350
351pub fn with_project_source_view<T>(
355 project_root: &str,
356 operation: impl FnOnce() -> T,
357) -> Result<T, String> {
358 let project = REQUEST_PROJECT
359 .try_with(|slot| slot.borrow().clone())
360 .ok()
361 .flatten()
362 .or_else(|| current_source_view().map(|view| view.project))
363 .unwrap_or_else(|| PathBuf::from(project_root));
364 let project = canonical_project_root(&project)?;
365 REQUEST_PROJECT.sync_scope(std::cell::RefCell::new(Some(project)), || {
366 with_source_view(operation)
367 })
368}
369
370pub fn with_explicit_project_source_view<T>(
374 project_root: &Path,
375 operation: impl FnOnce(&PublicationAuthority) -> T,
376) -> Result<T, String> {
377 let project = canonical_project_root(project_root)?;
378
379 let bound = REQUEST_PROJECT
380 .try_with(|slot| slot.borrow().clone())
381 .ok()
382 .flatten();
383 if let Some(bound) = bound {
384 let bound = crate::core::pathutil::canonicalize_secure(&bound)
385 .map_err(|_| "request project authority unavailable")?;
386 if bound != project {
387 return Err("request project authority does not match egress root".into());
388 }
389 }
390 if let Some(view) = current_source_view()
391 && (!view.live.load(Ordering::Acquire)
392 || !view.valid.load(Ordering::Acquire)
393 || view.project != project)
394 {
395 view.invalidate_if_live();
396 return Err("source policy view does not match egress root".into());
397 }
398
399 REQUEST_PROJECT.sync_scope(std::cell::RefCell::new(Some(project)), || {
400 with_source_view(|| {
401 let authority = PublicationAuthority::capture()?;
402 let result = operation(&authority);
403 authority.verify()?;
404 Ok(result)
405 })?
406 })
407}
408
409pub fn with_source_view<T>(operation: impl FnOnce() -> T) -> Result<T, String> {
413 with_source_view_when(|_, _| true, operation)?
414 .ok_or_else(|| "source policy view is no longer active".into())
415}
416
417pub fn with_root_source_view<T>(root: &Path, operation: impl FnOnce() -> T) -> Result<T, String> {
425 let root = canonical_project_root(root)?;
426 REQUEST_PROJECT.sync_scope(std::cell::RefCell::new(Some(root)), || {
427 with_source_view(operation)
428 })
429}
430
431#[cfg(feature = "http-server")]
443pub fn with_governed_source_view<T>(operation: impl FnOnce() -> T) -> Result<Option<T>, String> {
444 with_source_view_when(|policy, observed| policy || observed, operation)
445}
446
447fn with_source_view_when<T>(
450 enter: impl FnOnce(bool, bool) -> bool,
451 operation: impl FnOnce() -> T,
452) -> Result<Option<T>, String> {
453 if let Some(view) = current_source_view() {
454 let project = REQUEST_PROJECT
455 .try_with(|slot| slot.borrow().clone())
456 .ok()
457 .flatten()
458 .ok_or("source policy view is no longer active")?;
459 let project = canonical_project_root(&project)
460 .map_err(|_| "source policy view is no longer active")?;
461 if !view.live.load(Ordering::Acquire)
462 || !view.valid.load(Ordering::Acquire)
463 || project != view.project
464 || !view.within_horizon()
465 {
466 view.invalidate_if_live();
467 return Err("source policy view is no longer active".into());
468 }
469 if !enter(view.policy.is_some(), view.observation.is_some()) {
470 return Ok(None);
471 }
472 return REQUEST_PROJECT
473 .sync_scope(std::cell::RefCell::new(Some(view.project.clone())), || {
474 Ok(Some(operation()))
475 });
476 }
477
478 let project = match REQUEST_PROJECT.try_with(|slot| slot.borrow().clone()) {
482 Ok(project) => project.ok_or("project_unresolved")?,
483 Err(_) => std::env::current_dir().map_err(|_| "policy project root unavailable")?,
484 };
485 let project = canonical_project_root(&project)?;
486 REQUEST_PROJECT.sync_scope(std::cell::RefCell::new(Some(project.clone())), || {
487 let verified = refresh::current_verified_settled(&project)?;
488 let lifetime = verified.lifetime;
489 let observation = verified.observation;
490 let role = crate::core::roles::active_role();
491 let pinned_role_fingerprint = role_fingerprint(&role)?;
492 let view = SourceView {
493 project: project.clone(),
494 policy: source_view_policy(verified.policy),
495 fingerprint: verified.fingerprint,
496 role,
497 role_fingerprint: pinned_role_fingerprint,
498 lifetime,
499 observation,
500 valid: Arc::new(AtomicBool::new(true)),
501 live: Arc::new(AtomicBool::new(true)),
502 };
503
504 if !view.within_horizon() {
507 return Err("source policy view is no longer active".into());
508 }
509 if !enter(view.policy.is_some(), view.observation.is_some()) {
511 return Ok(None);
512 }
513 let view_lifetime = SourceViewLifetime(view.live.clone());
514 let value = SOURCE_VIEW.sync_scope(std::cell::RefCell::new(Some(view.clone())), operation);
515 drop(view_lifetime);
516
517 let project_unchanged = REQUEST_PROJECT
520 .try_with(|slot| slot.borrow().as_ref() == Some(&view.project))
521 .unwrap_or(false);
522 let latest_role = crate::core::roles::active_role();
523 let latest_role_fingerprint = role_fingerprint(&latest_role)?;
524 let latest = refresh::current_verified_settled(&project)?;
525 if !project_unchanged
526 || latest.fingerprint != view.fingerprint
527 || latest_role_fingerprint != view.role_fingerprint
528 || !view.valid.load(Ordering::Acquire)
529 {
530 return Err("source policy view changed during operation".into());
531 }
532 if !view.within_horizon() {
536 return Err("source policy view changed during operation".into());
537 }
538 Ok(Some(value))
539 })
540}
541
542pub(crate) fn role_fingerprint(role: &crate::core::roles::Role) -> Result<blake3::Hash, String> {
543 serde_json::to_vec(role)
544 .map(|bytes| blake3::hash(&bytes))
545 .map_err(|_| "source role view unavailable".into())
546}
547
548#[cfg(any(test, feature = "test-support"))]
549fn source_view_policy(fresh: Option<Arc<ActivePolicy>>) -> Option<Arc<ActivePolicy>> {
550 let state = test_override()
551 .read()
552 .unwrap_or_else(std::sync::PoisonError::into_inner);
553 match &*state {
554 OverrideState::Live => fresh,
555 OverrideState::Fixed(policy) => policy.clone(),
556 }
557}
558
559#[cfg(not(any(test, feature = "test-support")))]
560fn source_view_policy(fresh: Option<Arc<ActivePolicy>>) -> Option<Arc<ActivePolicy>> {
561 fresh
562}
563
564const PROJECT_PACK_PATH: &str = ".lean-ctx/policy.toml";
567
568pub struct ActivePolicy {
571 pub resolved: ResolvedPolicy,
572 pub redaction: Vec<(String, Regex)>,
575 pub(crate) blocked_patterns: Vec<(String, Regex)>,
576 pub(crate) cloud_rules: usize,
579 pub content_valid: bool,
580 pub filters: FilterConfig,
583 pub egress: crate::core::egress::EgressConfig,
586 horizon: Option<lean_ctx_time::UtcDateTime>,
592 expired: AtomicBool,
596}
597
598impl ActivePolicy {
599 #[must_use]
605 pub fn within_horizon(&self) -> bool {
606 if self.expired.load(Ordering::Acquire) {
607 return false;
608 }
609 let holds = self
610 .horizon
611 .is_none_or(|horizon| lean_ctx_time::UtcDateTime::now() < horizon);
612 if !holds {
613 self.expired.store(true, Ordering::Release);
614 }
615 holds
616 }
617
618 fn until(mut self, horizon: Option<lean_ctx_time::UtcDateTime>) -> Self {
620 self.horizon = horizon;
621 self
622 }
623
624 pub fn from_resolved(resolved: ResolvedPolicy) -> Self {
625 Self::from_resolved_with_cloud(
626 resolved,
627 &crate::core::policy::cloud_filters::FilterRules::default(),
628 )
629 }
630
631 pub(crate) fn from_resolved_with_cloud(
636 mut resolved: ResolvedPolicy,
637 cloud: &crate::core::policy::cloud_filters::FilterRules,
638 ) -> Self {
639 use super::content::{MAX_REDACTION_RULES, MAX_RULE_LABEL_BYTES, MAX_RULE_PATTERN_BYTES};
640 let cloud_rules = cloud.redaction.len() + cloud.blocked.len();
641 let cloud_bounded = cloud_rules <= crate::core::policy::cloud_filters::CLOUD_MAX_RULES
642 && cloud
643 .redaction
644 .iter()
645 .chain(&cloud.blocked)
646 .all(|(label, pattern)| {
647 super::is_cloud_label(label)
648 && label.len() <= MAX_RULE_LABEL_BYTES
649 && !label.chars().any(char::is_control)
650 && pattern.len() <= MAX_RULE_PATTERN_BYTES
651 });
652 let bounded = cloud_bounded
653 && resolved.redaction.len() + resolved.filters.blocked_patterns.len()
654 <= MAX_REDACTION_RULES
655 && resolved.egress.forbidden_patterns.len() <= MAX_REDACTION_RULES
656 && resolved
657 .egress
658 .forbidden_patterns
659 .iter()
660 .all(|pattern| pattern.len() <= MAX_RULE_PATTERN_BYTES)
661 && resolved
662 .redaction
663 .iter()
664 .chain(&resolved.filters.blocked_patterns)
665 .all(|(label, pattern)| {
666 !label.is_empty()
667 && label.len() <= MAX_RULE_LABEL_BYTES
668 && !label.chars().any(char::is_control)
669 && pattern.len() <= MAX_RULE_PATTERN_BYTES
670 });
671 resolved.redaction.extend(cloud.redaction.iter().cloned());
674 resolved
675 .filters
676 .blocked_patterns
677 .extend(cloud.blocked.iter().cloned());
678 let compiled = bounded.then(|| {
679 resolved
680 .redaction
681 .iter()
682 .map(|(label, pattern)| {
683 regex::RegexBuilder::new(pattern)
684 .size_limit(1024 * 1024)
685 .dfa_size_limit(1024 * 1024)
686 .build()
687 .map(|re| (label.clone(), re))
688 })
689 .collect::<Result<Vec<_>, _>>()
690 });
691 let content_valid = matches!(&compiled, Some(Ok(_)));
692 let redaction = compiled.and_then(Result::ok).unwrap_or_default();
693 let compiled_blocks = bounded.then(|| {
694 resolved
695 .filters
696 .blocked_patterns
697 .iter()
698 .map(|(label, pattern)| {
699 regex::RegexBuilder::new(pattern)
700 .size_limit(1024 * 1024)
701 .dfa_size_limit(1024 * 1024)
702 .build()
703 .map(|re| (label.clone(), re))
704 })
705 .collect::<Result<Vec<_>, _>>()
706 });
707 let content_valid = content_valid && matches!(&compiled_blocks, Some(Ok(_)));
708 let blocked_patterns = compiled_blocks.and_then(Result::ok).unwrap_or_default();
709 let filters = FilterConfig::new(
710 filter_action(resolved.filters.pii.as_ref()),
711 filter_action(resolved.filters.classification.as_ref()),
712 filter_action(resolved.filters.injection.as_ref()),
713 &resolved.filters.blocked_labels,
714 );
715 let egress = crate::core::egress::EgressConfig::new(
716 &resolved.egress.forbidden_patterns,
717 resolved.egress.block_secrets.unwrap_or(false),
718 resolved.egress.max_writes_per_min,
719 );
720 Self {
721 resolved,
722 redaction,
723 blocked_patterns,
724 cloud_rules,
725 content_valid,
726 filters,
727 egress,
728 horizon: None,
729 expired: AtomicBool::new(false),
730 }
731 }
732
733 pub(crate) fn deny_all() -> Self {
735 let mut active = Self::from_resolved(ResolvedPolicy {
736 name: "invalid-local-policy".into(),
737 version: "0.0.0".into(),
738 description: "deny all because the local policy pack is invalid".into(),
739 chain: Vec::new(),
740 default_read_mode: None,
741 allow_tools: Some(Vec::new()),
742 deny_tools: Vec::new(),
743 max_context_tokens: None,
744 audit_retention_days: None,
745 redaction: std::collections::BTreeMap::new(),
746 filters: crate::core::policy::FilterRules::default(),
747 egress: crate::core::policy::EgressRules::default(),
748 routing: crate::core::policy::RoutingPolicyRules::default(),
749 budgets: crate::core::policy::BudgetRules::default(),
750 });
751 active.content_valid = false;
752 active
753 }
754
755 #[must_use]
759 pub fn tool_allowed(&self, tool: &str) -> bool {
760 if !self.content_valid || !self.within_horizon() {
761 return false;
762 }
763 if self.resolved.deny_tools.iter().any(|t| t == tool) {
764 return false;
765 }
766 match &self.resolved.allow_tools {
767 Some(allow) => allow.iter().any(|t| t == tool),
768 None => true,
769 }
770 }
771}
772
773fn filter_action(opt: Option<&String>) -> FilterAction {
776 opt.map(String::as_str)
777 .and_then(FilterAction::parse)
778 .unwrap_or(FilterAction::Off)
779}
780
781#[cfg(test)]
782fn load_from_disk() -> Option<Arc<ActivePolicy>> {
783 let local = match load_local_pack() {
784 Ok(local) => local,
785 Err(msg) => {
786 tracing::error!(
787 "policy: failed to load invalid {PROJECT_PACK_PATH} ({msg}); enforcing deny-all"
788 );
789 return Some(Arc::new(ActivePolicy::deny_all()));
790 }
791 };
792 apply_org_floor(
793 local,
794 crate::core::policy::org::active_resolved_checked(),
795 None,
796 &crate::core::policy::cloud_filters::FilterRules::default(),
797 None,
798 )
799}
800
801fn apply_org_floor(
806 local: Option<ResolvedPolicy>,
807 org: Result<Option<ResolvedPolicy>, String>,
808 horizon: Option<lean_ctx_time::UtcDateTime>,
809 cloud: &crate::core::policy::cloud_filters::FilterRules,
810 cloud_floor: Option<&ResolvedPolicy>,
811) -> Option<Arc<ActivePolicy>> {
812 let effective = match org {
814 Ok(Some(org)) => Some(crate::core::policy::floor::merge_floor(
815 &org,
816 local.as_ref(),
817 )),
818 Ok(None) => local,
819 Err(error) => {
820 tracing::error!("org policy rejected; enforcing deny-all: {error}");
821 return Some(Arc::new(ActivePolicy::deny_all()));
822 }
823 };
824 let effective = match cloud_floor {
825 Some(floor) => Some(crate::core::policy::cloud_floor::apply(
826 floor,
827 effective.as_ref(),
828 )),
829 None => effective,
830 };
831 let effective = match effective {
832 Some(effective) => effective,
833 None if cloud.redaction.is_empty() && cloud.blocked.is_empty() => return None,
834 None => cloud_filters_only(),
836 };
837 Some(Arc::new(
838 ActivePolicy::from_resolved_with_cloud(effective, cloud).until(horizon),
839 ))
840}
841
842fn cloud_filters_only() -> ResolvedPolicy {
844 ResolvedPolicy {
845 name: "cloud-filters".into(),
846 version: "1.0.0".into(),
847 description: "content rules of the installed LeanCTX Cloud filter packs".into(),
848 chain: Vec::new(),
849 default_read_mode: None,
850 allow_tools: None,
851 deny_tools: Vec::new(),
852 max_context_tokens: None,
853 audit_retention_days: None,
854 redaction: std::collections::BTreeMap::new(),
855 filters: crate::core::policy::FilterRules::default(),
856 egress: crate::core::policy::EgressRules::default(),
857 routing: crate::core::policy::RoutingPolicyRules::default(),
858 budgets: crate::core::policy::BudgetRules::default(),
859 }
860}
861
862#[cfg(test)]
865fn load_local_pack() -> Result<Option<ResolvedPolicy>, String> {
866 let path = PathBuf::from(PROJECT_PACK_PATH);
867 load_local_pack_at(&path)
868}
869
870#[cfg(test)]
871fn load_local_pack_at(path: &Path) -> Result<Option<ResolvedPolicy>, String> {
872 match std::fs::symlink_metadata(path) {
873 Ok(_) => {}
874 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
875 Err(error) => return Err(format!("{}: {error}", path.display())),
876 }
877 match parse_file(path).and_then(|p| resolve(&p)) {
878 Ok(resolved) => Ok(Some(resolved)),
879 Err(e) => Err(format!("{}: {e}", path.display())),
880 }
881}
882
883pub fn for_project(project_root: &Path) -> Result<Option<Arc<ActivePolicy>>, String> {
886 refresh::current(project_root.to_path_buf())
887}
888
889#[must_use]
892pub fn active() -> Option<Arc<ActivePolicy>> {
893 active_observed().0
894}
895
896#[must_use]
908pub(crate) fn active_observed() -> (Option<Arc<ActivePolicy>>, Option<super::org::Observation>) {
909 let deny_all = || (Some(Arc::new(ActivePolicy::deny_all())), None);
910 if let Some(view) = current_source_view() {
911 if !view.live.load(Ordering::Acquire) || !view.valid.load(Ordering::Acquire) {
912 return deny_all();
913 }
914 let project = REQUEST_PROJECT
915 .try_with(|slot| slot.borrow().clone())
916 .ok()
917 .flatten();
918 if project.as_ref() != Some(&view.project) || !view.within_horizon() {
919 view.invalidate_if_live();
920 return deny_all();
921 }
922 return (view.policy, view.observation);
923 }
924 #[cfg(any(test, feature = "test-support"))]
925 {
926 let state = test_override()
927 .read()
928 .unwrap_or_else(std::sync::PoisonError::into_inner);
929 if let OverrideState::Fixed(policy) = &*state {
930 return (policy.clone(), None);
931 }
932 }
933 let scoped = REQUEST_PROJECT
934 .try_with(|slot| slot.borrow().clone())
935 .ok()
936 .flatten();
937 match scoped
938 .map_or_else(std::env::current_dir, Ok)
939 .map_err(|_| "policy project root unavailable".into())
940 .and_then(refresh::current_verified)
941 {
942 Ok(verified) => (verified.policy, verified.observation),
943 Err(_) => deny_all(),
944 }
945}
946
947#[cfg(any(test, feature = "test-support"))]
952pub fn with_observed_view_for_test<T>(
953 project: &Path,
954 observation: Option<super::org::Observation>,
955 operation: impl FnOnce() -> T,
956) -> T {
957 let project = canonical_project_root(project).expect("test project root");
958 let role = crate::core::roles::active_role();
959 let verified = refresh::current_verified(project.clone()).expect("test authority");
963 let view = SourceView {
964 project: project.clone(),
965 policy: verified.policy,
966 fingerprint: verified.fingerprint,
967 role_fingerprint: role_fingerprint(&role).expect("test role"),
968 role,
969 lifetime: None,
970 observation,
971 valid: Arc::new(AtomicBool::new(true)),
972 live: Arc::new(AtomicBool::new(true)),
973 };
974 REQUEST_PROJECT.sync_scope(std::cell::RefCell::new(Some(project)), || {
975 SOURCE_VIEW.sync_scope(std::cell::RefCell::new(Some(view)), operation)
976 })
977}
978
979pub(crate) enum HeldObservation {
981 NotHeld,
983 Held(Option<super::org::Observation>),
986}
987
988pub(crate) fn held_observation() -> HeldObservation {
995 let Some(view) = current_source_view() else {
996 return HeldObservation::NotHeld;
997 };
998 let project = REQUEST_PROJECT
999 .try_with(|slot| slot.borrow().clone())
1000 .ok()
1001 .flatten();
1002 if !view.live.load(Ordering::Acquire)
1003 || !view.valid.load(Ordering::Acquire)
1004 || project.as_ref() != Some(&view.project)
1005 || !view.within_horizon()
1006 {
1007 return HeldObservation::NotHeld;
1008 }
1009 HeldObservation::Held(view.observation)
1010}
1011
1012#[must_use]
1014pub fn is_active() -> bool {
1015 active().is_some()
1016}
1017
1018pub fn reload() {
1020 let _ = active();
1021}
1022
1023#[cfg(any(test, feature = "test-support"))]
1024enum OverrideState {
1025 Live,
1026 Fixed(Option<Arc<ActivePolicy>>),
1027}
1028
1029#[cfg(any(test, feature = "test-support"))]
1030fn test_override() -> &'static RwLock<OverrideState> {
1031 static OVERRIDE: OnceLock<RwLock<OverrideState>> = OnceLock::new();
1032 OVERRIDE.get_or_init(|| RwLock::new(OverrideState::Live))
1033}
1034
1035#[cfg(any(test, feature = "test-support"))]
1036fn test_override_lock() -> &'static std::sync::Mutex<()> {
1037 static LOCK: OnceLock<std::sync::Mutex<()>> = OnceLock::new();
1038 LOCK.get_or_init(|| std::sync::Mutex::new(()))
1039}
1040
1041#[cfg(any(test, feature = "test-support"))]
1046pub struct TestOverrideGuard {
1047 _policy: std::sync::MutexGuard<'static, ()>,
1048 _environment: crate::core::data_dir::TestEnvGuard,
1049}
1050
1051#[cfg(any(test, feature = "test-support"))]
1052pub fn lock_test_override() -> TestOverrideGuard {
1053 let environment = crate::core::data_dir::test_env_lock();
1054 let policy = test_override_lock()
1055 .lock()
1056 .unwrap_or_else(std::sync::PoisonError::into_inner);
1057 TestOverrideGuard {
1058 _policy: policy,
1059 _environment: environment,
1060 }
1061}
1062
1063#[cfg(any(test, feature = "test-support"))]
1065pub struct TestPolicyOverride {
1066 previous: OverrideState,
1067 _lock: TestOverrideGuard,
1068}
1069
1070#[cfg(any(test, feature = "test-support"))]
1071impl TestPolicyOverride {
1072 pub fn set(resolved: Option<ResolvedPolicy>) -> Self {
1073 let lock = lock_test_override();
1074 let previous = std::mem::replace(
1075 &mut *test_override()
1076 .write()
1077 .unwrap_or_else(std::sync::PoisonError::into_inner),
1078 OverrideState::Fixed(
1079 resolved.map(|policy| Arc::new(ActivePolicy::from_resolved(policy))),
1080 ),
1081 );
1082 Self {
1083 previous,
1084 _lock: lock,
1085 }
1086 }
1087}
1088
1089#[cfg(any(test, feature = "test-support"))]
1090impl Drop for TestPolicyOverride {
1091 fn drop(&mut self) {
1092 *test_override()
1093 .write()
1094 .unwrap_or_else(std::sync::PoisonError::into_inner) =
1095 std::mem::replace(&mut self.previous, OverrideState::Live);
1096 }
1097}
1098
1099#[cfg(test)]
1100#[path = "runtime/tests.rs"]
1101mod tests;