1pub(crate) mod marker;
9pub mod model;
10pub mod store;
11pub mod trust;
12
13use std::path::PathBuf;
14
15pub use model::{OrgPolicyV1, OrgVerifyResult};
16pub use trust::{TrustStore, TrustedKey};
17
18use crate::core::policy::ResolvedPolicy;
19
20#[must_use]
21pub fn org_key_id(org: &str) -> String {
22 let safe: String = org
23 .chars()
24 .map(|c| {
25 if c.is_ascii_alphanumeric() || c == '-' {
26 c.to_ascii_lowercase()
27 } else {
28 '-'
29 }
30 })
31 .collect();
32 format!("org-{safe}")
33}
34
35#[must_use]
42pub fn active_resolved() -> Option<ResolvedPolicy> {
43 let artifact = store::load_active()?;
44
45 let result = artifact.verify();
46 if !result.signature_valid {
47 tracing::warn!(
48 "org policy: signature invalid ({}), ignoring",
49 result.error.as_deref().unwrap_or("unknown")
50 );
51 return None;
52 }
53
54 let signer = artifact.signer_public_key.as_deref()?;
55 if !trust::is_trusted(signer) {
56 tracing::debug!("org policy: signer not trust-pinned, ignoring (fail-open)");
57 return None;
58 }
59
60 if !artifact.enforced {
61 tracing::debug!("org policy: admin did not set enforced=true, skipping");
62 return None;
63 }
64
65 match artifact.resolved() {
66 Ok(resolved) => Some(resolved),
67 Err(e) => {
68 tracing::warn!("org policy: failed to resolve pack: {e}");
69 None
70 }
71 }
72}
73
74pub fn active_resolved_checked() -> Result<Option<ResolvedPolicy>, String> {
83 AuthoritySnapshot::capture()?.resolve()
84}
85
86pub struct AuthoritySnapshot {
95 fingerprint: blake3::Hash,
96 before_marker: blake3::Hasher,
98 policy: Option<String>,
99 trust: Option<String>,
100 marker: Option<String>,
101}
102
103impl AuthoritySnapshot {
104 pub fn capture() -> Result<Self, String> {
107 let (policy_path, policy_required) = store::selected_source()?;
108 let mut hash = blake3::Hasher::new();
109 let mut read =
112 |path: PathBuf, required: bool, artifact: bool| -> Result<Option<String>, String> {
113 let path_bytes = path.as_os_str().as_encoded_bytes();
114 hash.update(&(path_bytes.len() as u64).to_le_bytes());
115 hash.update(path_bytes);
116 let text = if artifact {
117 crate::core::policy::files::read_org_artifact(&path, required, false)?
118 } else {
119 crate::core::policy::files::read(&path, required)?
120 };
121 hash_text(&mut hash, text.as_deref());
122 Ok(text)
123 };
124 let policy = read(policy_path, policy_required, true)?;
125 let trust = read(trust::trust_path_read_only()?, false, false)?;
126 let marker_path = marker::marker_path_read_only()?;
129 let path_bytes = marker_path.as_os_str().as_encoded_bytes();
130 hash.update(&(path_bytes.len() as u64).to_le_bytes());
131 hash.update(path_bytes);
132 let marker = crate::core::policy::files::read(&marker_path, false)?;
133 let before_marker = hash.clone();
134 hash_text(&mut hash, marker.as_deref());
135 Ok(Self {
136 fingerprint: hash.finalize(),
137 before_marker,
138 policy,
139 trust,
140 marker,
141 })
142 }
143
144 #[cfg(any(test, feature = "enterprise"))]
145 pub fn fingerprint(&self) -> blake3::Hash {
146 self.fingerprint
147 }
148
149 fn required(&self) -> Result<bool, String> {
152 Ok(self
153 .marker
154 .as_deref()
155 .map(marker::parse)
156 .transpose()?
157 .is_some_and(|marker| marker.is_required()))
158 }
159
160 pub fn resolve(&self) -> Result<Option<ResolvedPolicy>, String> {
166 self.resolve_observed().map(|(floor, _)| floor)
167 }
168
169 pub(crate) fn resolve_observed(
175 &self,
176 ) -> Result<(Option<ResolvedPolicy>, Option<Observation>), String> {
177 let required = self.required()?;
178 let Some(policy) = self.policy.as_deref() else {
179 if required {
180 return Err("required organization policy is missing".into());
181 }
182 return Ok((None, None));
183 };
184 if is_v2(policy) {
187 let verified = verify_v2(
188 policy,
189 self.trust.as_deref(),
190 self.marker.as_deref(),
191 std::time::Instant::now() + RESOLVE_DEADLINE,
192 )?;
193 let mut expected = self.before_marker.clone();
199 hash_text(&mut expected, Some(&verified.marker));
200 if Self::capture()?.fingerprint != expected.finalize() {
201 return Err("organization authority changed during verification".into());
202 }
203 verified.lifetime.check()?;
205 return Ok((verified.floor, Some(verified.observation)));
206 }
207 if policy.len() as u64 > crate::core::policy::files::MAX_BYTES {
209 return Err("policy input exceeds byte limit".into());
210 }
211 if required {
212 return Err("required organization policy is not verifiable".into());
213 }
214 let artifact = OrgPolicyV1::from_json(policy)?;
215 let trust: TrustStore = match self.trust.as_deref() {
216 Some(text) => {
217 toml::from_str(text).map_err(|_| "org trust input is invalid".to_string())?
218 }
219 None => TrustStore::default(),
220 };
221 resolve_checked(&artifact, &trust).map(|floor| (floor, None))
222 }
223}
224
225fn hash_text(hash: &mut blake3::Hasher, text: Option<&str>) {
226 match text {
227 Some(text) => {
228 hash.update(&[1]);
229 hash.update(&(text.len() as u64).to_le_bytes());
230 hash.update(text.as_bytes());
231 }
232 None => {
233 hash.update(&[0]);
234 }
235 }
236}
237
238pub(crate) fn is_v2(text: &str) -> bool {
243 let Ok(value) = serde_json::from_str::<serde_json::Value>(text) else {
244 return false;
245 };
246 let schema = value
247 .get("schema")
248 .or_else(|| value.get("statement").and_then(|s| s.get("schema")))
249 .and_then(serde_json::Value::as_str);
250 schema == Some(lean_ctx_protocol::org_policy_verifier::ORG_POLICY_V2_ARTIFACT_SCHEMA_ID)
251}
252
253pub(crate) fn verify_v2(
271 artifact: &str,
272 trust: Option<&str>,
273 marker_text: Option<&str>,
274 deadline: std::time::Instant,
275) -> Result<VerifiedV2, String> {
276 use crate::core::intelligence_runtime::org_policy_verifier::{Accepted, Snapshot, verify};
277 use lean_ctx_protocol::org_policy_verifier::{
278 OrgRequiredMarkerEntryV1, OrgRequiredMarkerStateV1,
279 };
280
281 let marker_text =
282 marker_text.ok_or("organization policy has no recorded requirement to verify against")?;
283 let stored = marker::parse(marker_text)?;
284 let accepted = verify(
285 &Snapshot {
286 organization: &stored.organization_id,
287 artifact: artifact.as_bytes(),
288 trust: trust.map(str::as_bytes),
289 marker: Some(marker_text.as_bytes()),
290 },
291 deadline,
292 )
293 .map_err(|_| "organization policy could not be verified")?;
294 let (state, sequence, pack, observed, statement) = match accepted {
297 Accepted::Enforce {
298 pack_toml,
299 policy_digest,
300 sequence,
301 valid_until,
302 } => {
303 let statement = policy_digest.as_str().to_owned();
304 (
305 OrgRequiredMarkerStateV1::Required { policy_digest },
306 sequence,
307 Some((pack_toml, valid_until)),
308 ObservedState::Required,
309 statement,
310 )
311 }
312 Accepted::NotRequired {
313 unpin_digest,
314 sequence,
315 } => {
316 let statement = unpin_digest.as_str().to_owned();
317 (
318 OrgRequiredMarkerStateV1::Unpinned { unpin_digest },
319 sequence,
320 None,
321 ObservedState::Unpinned,
322 statement,
323 )
324 }
325 };
326 let recorded_at = lean_ctx_protocol::TeamTimestampV1::new(
327 lean_ctx_time::UtcDateTime::now()
328 .to_rfc3339_opts(lean_ctx_time::SecondsFormat::Nanos, true),
329 )
330 .map_err(|_| "organization policy decision could not be dated")?;
331 let (_, marker) = marker::advance_within(
332 &stored.organization_id,
333 OrgRequiredMarkerEntryV1 {
334 sequence,
335 recorded_at,
336 state,
337 },
338 marker::Predecessor::Stored(marker_text),
339 deadline,
340 )
341 .map_err(|_| "organization policy decision could not be recorded")?;
342 let (floor, horizon) = match pack {
343 Some((pack_toml, valid_until)) => {
344 let floor = crate::core::policy::parse(&pack_toml)
345 .and_then(|pack| crate::core::policy::resolve(&pack))
346 .map_err(|_| "verified organization policy is invalid")?;
347 let horizon = lean_ctx_time::OffsetDateTime::parse_from_rfc3339(valid_until.as_str())
349 .map_err(|_| "verified organization policy has expired")?
350 .to_utc();
351 (Some(floor), Some(horizon))
352 }
353 None => (None, None),
354 };
355 let lifetime = Lifetime { horizon, deadline };
356 lifetime.check()?;
358 Ok(VerifiedV2 {
359 floor,
360 marker,
361 lifetime,
362 observation: Observation {
366 state: observed,
367 statement,
368 policy_version: sequence,
369 valid_until: horizon,
370 },
371 })
372}
373
374pub(crate) struct VerifiedV2 {
379 pub(crate) floor: Option<ResolvedPolicy>,
380 pub(crate) marker: String,
381 pub(crate) lifetime: Lifetime,
382 pub(crate) observation: Observation,
383}
384
385#[derive(Debug, Clone, Copy, PartialEq, Eq)]
387pub(crate) enum ObservedState {
388 Required,
390 Unpinned,
394}
395
396#[derive(Debug, Clone, PartialEq, Eq)]
406pub struct Observation {
407 state: ObservedState,
408 statement: String,
410 policy_version: u64,
411 valid_until: Option<lean_ctx_time::UtcDateTime>,
414}
415
416impl Observation {
417 #[cfg(any(test, feature = "test-support"))]
420 pub fn unpinned_for_test(policy_version: u64, fill: char) -> Self {
421 Self {
422 state: ObservedState::Unpinned,
423 statement: format!("sha256:{}", fill.to_string().repeat(64)),
424 policy_version,
425 valid_until: None,
426 }
427 }
428
429 pub(crate) fn state(&self) -> ObservedState {
430 self.state
431 }
432
433 pub(crate) fn statement(&self) -> &str {
434 &self.statement
435 }
436
437 pub fn policy_version(&self) -> u64 {
438 self.policy_version
439 }
440
441 pub(crate) fn valid_until(&self) -> Option<lean_ctx_time::UtcDateTime> {
442 self.valid_until
443 }
444}
445
446#[derive(Debug, Clone, Copy)]
452pub(crate) struct Lifetime {
453 horizon: Option<lean_ctx_time::UtcDateTime>,
454 deadline: std::time::Instant,
455}
456
457impl Lifetime {
458 #[cfg(any(test, feature = "test-support"))]
461 pub(crate) fn for_test(
462 horizon: Option<lean_ctx_time::UtcDateTime>,
463 deadline: std::time::Instant,
464 ) -> Self {
465 Self { horizon, deadline }
466 }
467
468 pub(crate) fn restored(horizon: Option<lean_ctx_time::UtcDateTime>) -> Self {
473 Self {
474 horizon,
475 deadline: std::time::Instant::now(),
476 }
477 }
478
479 pub(crate) fn horizon(&self) -> Option<lean_ctx_time::UtcDateTime> {
482 self.horizon
483 }
484
485 pub(crate) fn check(&self) -> Result<(), String> {
487 self.check_horizon()?;
488 if std::time::Instant::now() >= self.deadline {
489 return Err("organization policy verification deadline exceeded".into());
490 }
491 Ok(())
492 }
493
494 pub(crate) fn check_horizon(&self) -> Result<(), String> {
497 if self
498 .horizon
499 .is_some_and(|horizon| lean_ctx_time::UtcDateTime::now() >= horizon)
500 {
501 return Err("verified organization policy has expired".into());
502 }
503 Ok(())
504 }
505}
506
507const RESOLVE_DEADLINE: std::time::Duration = std::time::Duration::from_secs(5);
510
511pub(crate) fn resolve_checked(
512 artifact: &OrgPolicyV1,
513 trusted: &TrustStore,
514) -> Result<Option<ResolvedPolicy>, String> {
515 if !artifact.verify().signature_valid {
516 return Err("org policy signature invalid".into());
517 }
518 let signer = artifact
519 .signer_public_key
520 .as_deref()
521 .ok_or_else(|| "org policy signer missing".to_string())?;
522 if !trusted
523 .keys
524 .iter()
525 .any(|key| key.public_key == signer && key.org == artifact.org)
526 {
527 return Err("org policy signer is not pinned for this organization".into());
528 }
529 let resolved = artifact.resolved().map_err(|error| error.to_string())?;
530 Ok(artifact.enforced.then_some(resolved))
531}
532
533#[derive(Debug, Default, PartialEq, Eq)]
535pub struct Uninstalled {
536 pub artifact: bool,
538 pub org: Option<String>,
540 pub unpinned: Vec<String>,
542 pub remaining: Vec<TrustedKey>,
546}
547
548pub fn uninstall() -> Result<Uninstalled, String> {
555 let path = store::installed_path()?;
556 let mut outcome = Uninstalled::default();
557 if path.exists() {
558 outcome.org = store::read(&path).ok().map(|artifact| artifact.org);
562 outcome.artifact = store::uninstall()?;
563 }
564 if let Some(org) = &outcome.org {
565 outcome.unpinned = trust::remove_org(org)?;
566 }
567 outcome.remaining = trust::load()?.keys;
568 Ok(outcome)
569}
570
571#[cfg(test)]
574mod authority_tests {
575 use super::*;
576 use lean_ctx_protocol::org_policy_verifier::{
577 OrgRequiredMarkerEntryV1, OrgRequiredMarkerStateV1,
578 };
579 use lean_ctx_protocol::{RecordDigest, TeamId, TeamTimestampV1};
580
581 const PACK: &str = "name = \"floor\"\nversion = \"1.0.0\"\ndescription = \"test\"\n[context]\ndeny_tools = [\"ctx_shell\"]\n";
582
583 fn install_policy() -> OrgPolicyV1 {
585 let key = ed25519_dalek::SigningKey::from_bytes(&[23; 32]);
586 let mut artifact = OrgPolicyV1::build("acme", "1", true, PACK).unwrap();
587 artifact.sign_with_key(&key);
588 store::install(&artifact).unwrap();
589 artifact
590 }
591
592 fn pin(org: &str, artifact: &OrgPolicyV1) {
593 trust::pin(org, artifact.signer_public_key.as_deref().unwrap()).unwrap();
594 }
595
596 fn require(sequence: u64) {
597 let entry = OrgRequiredMarkerEntryV1 {
598 sequence,
599 recorded_at: TeamTimestampV1::new("2026-10-10T09:00:00Z").unwrap(),
600 state: OrgRequiredMarkerStateV1::Required {
601 policy_digest: RecordDigest::new(format!("sha256:{}", "a".repeat(64))).unwrap(),
602 },
603 };
604 let path = marker::marker_path_read_only().unwrap();
607 let stored = crate::core::policy::files::read(&path, false).unwrap();
608 let predecessor = stored.as_deref().map_or(
609 marker::Predecessor::NeverStored,
610 marker::Predecessor::Stored,
611 );
612 marker::advance(&TeamId::new("acme").unwrap(), entry, predecessor).unwrap();
613 }
614
615 #[test]
616 fn status_reports_a_key_pinned_for_another_organization_as_not_applied() {
617 let _data = crate::core::data_dir::isolated_data_dir();
618 let artifact = install_policy();
619 pin("other", &artifact);
620
621 let status = status();
622 assert!(status.present && status.signature_valid);
623 assert!(!status.trusted, "the key is pinned, but not for this org");
624 assert!(!status.applied);
625 assert!(
626 active_resolved_checked().is_err(),
627 "enforcement refuses the same state"
628 );
629
630 pin("acme", &artifact);
631 assert!(!self::status().trusted);
633
634 let key = artifact.signer_public_key.as_deref().unwrap();
638 assert!(trust::is_trusted(key), "the key alone is pinned");
639 assert!(!trust::is_trusted_for("acme", key));
640 assert!(trust::is_trusted_for("other", key));
641 assert_eq!(trust::pinned_organization(key).as_deref(), Some("other"));
642 assert_eq!(
643 trust::pin_for("acme", key).unwrap(),
644 trust::PinOutcome::PinnedForAnother("other".into())
645 );
646 assert_eq!(
647 trust::pin_for("other", key).unwrap(),
648 trust::PinOutcome::AlreadyPinned
649 );
650 assert!(!trust::is_trusted_for("acme", key), "nothing was moved");
651 assert_eq!(trust::trusted_keys().len(), 1);
652 }
653
654 #[test]
658 fn status_creates_nothing_and_reports_a_missing_explicit_source() {
659 let data = crate::core::data_dir::isolated_data_dir();
660 let observed = || {
661 [
662 store::selected_source().unwrap().0,
663 trust::trust_path_read_only().unwrap(),
664 marker::marker_path_read_only().unwrap(),
665 ]
666 .map(|path| {
667 (
668 path.exists(),
669 path.parent().is_some_and(std::path::Path::exists),
670 )
671 })
672 };
673 let before = observed();
674 let status = status();
675 assert!(!status.present && status.resolve_error.is_none());
676 assert_eq!(status.recorded, RecordedRequirement::Absent);
677 assert_eq!(observed(), before, "the status left a trace on disk");
678
679 let missing = data.path().join("does-not-exist.json");
680 crate::test_env::set_var("LEANCTX_ORG_POLICY", &missing);
681 let status = self::status();
682 crate::test_env::remove_var("LEANCTX_ORG_POLICY");
683 assert!(
684 status.resolve_error.is_some(),
685 "an explicit source that is missing is not 'nothing installed'"
686 );
687 assert!(!missing.exists());
688 }
689
690 #[test]
691 fn status_and_enforcement_agree_for_a_correctly_pinned_policy() {
692 let _data = crate::core::data_dir::isolated_data_dir();
693 let artifact = install_policy();
694 pin("acme", &artifact);
695
696 let status = status();
697 assert!(status.trusted && status.applied && status.resolve_error.is_none());
698 assert!(active_resolved_checked().unwrap().is_some());
699 }
700
701 #[test]
702 fn a_recorded_requirement_or_a_damaged_marker_is_never_reported_as_applied() {
703 let _data = crate::core::data_dir::isolated_data_dir();
704 let artifact = install_policy();
705 pin("acme", &artifact);
706 require(1);
707
708 let status = status();
709 assert!(status.present && status.trusted);
710 assert!(!status.applied, "a version-one policy does not satisfy it");
711 assert!(status.resolve_error.is_some());
712 assert!(active_resolved_checked().is_err());
713
714 store::uninstall().unwrap();
716 let status = self::status();
717 assert!(!status.present && !status.applied);
718 assert!(status.resolve_error.is_some());
719 assert!(active_resolved_checked().is_err());
720
721 std::fs::write(marker::marker_path_read_only().unwrap(), b"{}").unwrap();
723 assert!(self::status().resolve_error.is_some());
724 assert!(active_resolved_checked().is_err());
725 store::install(&artifact).unwrap();
726 let status = self::status();
727 assert!(!status.applied && status.resolve_error.is_some());
728 assert!(AuthoritySnapshot::capture().unwrap().resolve().is_err());
729 }
730
731 #[test]
735 fn the_stored_record_is_read_as_recorded_absent_or_unavailable() {
736 let _data = crate::core::data_dir::isolated_data_dir();
737 assert_eq!(recorded_requirement(), RecordedRequirement::Absent);
738 assert_eq!(status().recorded, RecordedRequirement::Absent);
739
740 require(3);
741 match recorded_requirement() {
742 RecordedRequirement::Recorded {
743 organization,
744 required: true,
745 sequence: 3,
746 entries: 1,
747 ..
748 } => assert_eq!(organization, "acme"),
749 other => panic!("not the recorded requirement: {other:?}"),
750 }
751
752 let path = marker::marker_path_read_only().unwrap();
753 let stored = crate::core::policy::files::read(&path, false)
754 .unwrap()
755 .unwrap();
756 marker::advance(
757 &TeamId::new("acme").unwrap(),
758 OrgRequiredMarkerEntryV1 {
759 sequence: 4,
760 recorded_at: TeamTimestampV1::new("2026-10-11T09:00:00Z").unwrap(),
761 state: OrgRequiredMarkerStateV1::Unpinned {
762 unpin_digest: RecordDigest::new(format!("sha256:{}", "b".repeat(64))).unwrap(),
763 },
764 },
765 marker::Predecessor::Stored(&stored),
766 )
767 .unwrap();
768 let status = status();
769 assert!(!status.present && status.source.is_none());
770 assert!(
771 status.resolve_error.is_none(),
772 "a lifted requirement refuses nothing"
773 );
774 match status.recorded {
775 RecordedRequirement::Recorded {
776 required: false,
777 sequence: 4,
778 entries: 2,
779 statement,
780 ..
781 } => assert_eq!(statement, format!("sha256:{}", "b".repeat(64))),
782 other => panic!("the unpin is not on record: {other:?}"),
783 }
784
785 std::fs::write(&path, b"{}").unwrap();
786 assert!(matches!(
787 recorded_requirement(),
788 RecordedRequirement::Unavailable(_)
789 ));
790 }
791
792 #[test]
793 fn a_capture_resolves_its_own_bytes_whatever_changes_afterwards() {
794 let _data = crate::core::data_dir::isolated_data_dir();
795 let artifact = install_policy();
796 pin("acme", &artifact);
797
798 let enforced = AuthoritySnapshot::capture().unwrap();
799 store::uninstall().unwrap();
802 trust::remove(artifact.signer_public_key.as_deref().unwrap()).unwrap();
803 require(1);
804 assert!(
805 enforced.resolve().unwrap().is_some(),
806 "the capture answers for the bytes it holds"
807 );
808
809 let now = AuthoritySnapshot::capture().unwrap();
810 assert_ne!(now.fingerprint(), enforced.fingerprint());
811 assert!(now.resolve().is_err(), "required, and nothing installed");
812
813 let before = AuthoritySnapshot::capture().unwrap().fingerprint();
815 store::install(&artifact).unwrap();
816 let with_policy = AuthoritySnapshot::capture().unwrap().fingerprint();
817 pin("acme", &artifact);
818 let with_trust = AuthoritySnapshot::capture().unwrap().fingerprint();
819 require(2);
820 let with_marker = AuthoritySnapshot::capture().unwrap().fingerprint();
821 assert!(before != with_policy && with_policy != with_trust && with_trust != with_marker);
822 }
823
824 #[test]
825 fn an_unreadable_explicit_source_refuses_instead_of_resolving_to_no_policy() {
826 let data = crate::core::data_dir::isolated_data_dir();
827 let missing = data.path().join("does-not-exist.json");
828 crate::test_env::set_var("LEANCTX_ORG_POLICY", &missing);
829 let captured = AuthoritySnapshot::capture();
830 crate::test_env::remove_var("LEANCTX_ORG_POLICY");
831 assert!(captured.is_err(), "an explicit source that is absent");
832 }
833}
834
835#[cfg(test)]
836mod checked_tests {
837 use super::*;
838
839 fn fixture(enforced: bool) -> (OrgPolicyV1, TrustStore) {
840 let key = ed25519_dalek::SigningKey::from_bytes(&[19; 32]);
841 let mut artifact = OrgPolicyV1::build(
842 "acme", "1", enforced,
843 "name = \"floor\"\nversion = \"1.0.0\"\ndescription = \"test\"\n[context]\ndeny_tools = [\"ctx_shell\"]\n",
844 ).unwrap();
845 artifact.sign_with_key(&key);
846 let trusted = TrustStore {
847 keys: vec![TrustedKey {
848 org: "acme".into(),
849 public_key: artifact.signer_public_key.clone().unwrap(),
850 added_at: "2026-09-09T00:00:00Z".into(),
851 }],
852 };
853 (artifact, trusted)
854 }
855
856 #[test]
857 fn checked_resolution_requires_valid_signature_and_org_pin() {
858 let (mut artifact, mut trusted) = fixture(true);
859 assert!(resolve_checked(&artifact, &trusted).unwrap().is_some());
860 assert!(resolve_checked(&artifact, &TrustStore::default()).is_err());
861 trusted.keys[0].org = "other".into();
862 assert!(resolve_checked(&artifact, &trusted).is_err());
863 trusted.keys[0].org = "acme".into();
864 artifact.enforced = false;
865 assert!(resolve_checked(&artifact, &trusted).is_err());
866 }
867
868 #[test]
869 fn checked_resolution_allows_only_trusted_signed_disable() {
870 let (artifact, trusted) = fixture(false);
871 assert!(resolve_checked(&artifact, &trusted).unwrap().is_none());
872 assert!(resolve_checked(&artifact, &TrustStore::default()).is_err());
873 }
874}
875
876#[derive(Debug, Clone, Default, PartialEq, Eq)]
883pub enum RecordedRequirement {
884 #[default]
886 Absent,
887 Unavailable(String),
890 Recorded {
892 organization: String,
893 required: bool,
896 sequence: u64,
898 statement: String,
900 recorded_at: String,
901 entries: usize,
903 },
904}
905
906#[must_use]
908pub fn recorded_requirement() -> RecordedRequirement {
909 use lean_ctx_protocol::org_policy_verifier::OrgRequiredMarkerStateV1;
910
911 let text = match marker::marker_path_read_only()
912 .and_then(|path| crate::core::policy::files::read(&path, false))
913 {
914 Ok(Some(text)) => text,
915 Ok(None) => return RecordedRequirement::Absent,
916 Err(error) => return RecordedRequirement::Unavailable(error),
917 };
918 let stored = match marker::parse(&text) {
919 Ok(stored) => stored,
920 Err(error) => return RecordedRequirement::Unavailable(error),
921 };
922 let current = stored.current();
923 let (required, statement) = match ¤t.state {
924 OrgRequiredMarkerStateV1::Required { policy_digest } => (true, policy_digest.as_str()),
925 OrgRequiredMarkerStateV1::Unpinned { unpin_digest } => (false, unpin_digest.as_str()),
926 };
927 RecordedRequirement::Recorded {
928 organization: stored.organization_id.as_str().to_owned(),
929 required,
930 sequence: current.sequence,
931 statement: statement.to_owned(),
932 recorded_at: current.recorded_at.as_str().to_owned(),
933 entries: stored.entries.len(),
934 }
935}
936
937#[derive(Debug, Clone, Default)]
938pub struct OrgStatus {
939 pub recorded: RecordedRequirement,
941 pub present: bool,
942 pub source: Option<PathBuf>,
943 pub org: Option<String>,
944 pub policy_version: Option<String>,
945 pub enforced: bool,
946 pub issued_at: Option<String>,
947 pub signer_public_key: Option<String>,
948 pub signature_valid: bool,
949 pub trusted: bool,
950 pub applied: bool,
951 pub resolve_error: Option<String>,
952 pub pinned_anchors: usize,
953 pub floor_preview: Option<ResolvedPolicy>,
957}
958
959#[must_use]
960pub fn status() -> OrgStatus {
961 let recorded = recorded_requirement();
967 let required = match &recorded {
970 RecordedRequirement::Absent => Ok(false),
971 RecordedRequirement::Recorded { required, .. } => Ok(*required),
972 RecordedRequirement::Unavailable(error) => Err(error.clone()),
973 };
974 let (anchors, trust_error) = match trust::load_read_only() {
977 Ok(store) => (store.keys, None),
978 Err(error) => (Vec::new(), Some(error)),
979 };
980 let pinned_anchors = anchors.len();
981 let (source, text) = match store::selected_source() {
985 Ok((path, explicit)) => {
986 match crate::core::policy::files::read_org_artifact(&path, explicit, false) {
987 Ok(text) => (text.as_ref().map(|_| path), text),
988 Err(error) => {
989 return OrgStatus {
990 recorded,
991 present: true,
992 source: Some(path),
993 resolve_error: Some(error),
994 pinned_anchors,
995 ..Default::default()
996 };
997 }
998 }
999 }
1000 Err(error) => {
1001 return OrgStatus {
1002 recorded,
1003 resolve_error: Some(error),
1004 pinned_anchors,
1005 ..Default::default()
1006 };
1007 }
1008 };
1009 let artifact = text
1010 .as_deref()
1011 .filter(|text| text.len() as u64 <= crate::core::policy::files::MAX_BYTES)
1012 .and_then(|text| OrgPolicyV1::from_json(text).ok());
1013 let Some(artifact) = artifact else {
1014 let resolve_error = match required {
1018 Ok(true) => Some(
1019 "an organization policy is required on this endpoint, but none that can be \
1020 verified is installed"
1021 .to_string(),
1022 ),
1023 Ok(false) => source
1024 .as_ref()
1025 .map(|_| {
1026 "the installed organization policy is not a version-one artifact; it needs \
1027 a verifier"
1028 .to_string()
1029 })
1030 .or(trust_error),
1031 Err(error) => Some(error),
1032 };
1033 return OrgStatus {
1034 recorded,
1035 present: source.is_some(),
1037 source,
1038 resolve_error,
1039 pinned_anchors,
1040 ..Default::default()
1041 };
1042 };
1043 let verify = artifact.verify();
1044 let signer_key = artifact.signer_public_key.clone();
1045 let trusted = signer_key.as_deref().is_some_and(|signer| {
1049 anchors
1050 .iter()
1051 .any(|key| key.public_key == signer && key.org == artifact.org)
1052 });
1053 let resolve_result = artifact.resolved();
1054 let authority_error = match required {
1058 Ok(true) => Some(
1059 "an organization policy is required on this endpoint; the installed version-one \
1060 policy does not satisfy it"
1061 .to_string(),
1062 ),
1063 Ok(false) => trust_error,
1064 Err(error) => Some(error),
1065 };
1066 let applied = authority_error.is_none()
1067 && trusted
1068 && verify.signature_valid
1069 && artifact.enforced
1070 && resolve_result.is_ok();
1071
1072 OrgStatus {
1073 recorded,
1074 present: true,
1075 source,
1076 org: Some(artifact.org.clone()),
1077 policy_version: Some(artifact.policy_version.clone()),
1078 enforced: artifact.enforced,
1079 issued_at: Some(artifact.issued_at.clone()),
1080 signer_public_key: signer_key,
1081 signature_valid: verify.signature_valid,
1082 trusted,
1083 applied,
1084 floor_preview: resolve_result.as_ref().ok().cloned(),
1087 resolve_error: authority_error.or_else(|| resolve_result.err().map(|e| e.to_string())),
1088 pinned_anchors,
1089 }
1090}