1use std::collections::{BTreeMap, BTreeSet};
53
54use serde::{Deserialize, Serialize};
55use serde_json::Value;
56use sha2::{Digest, Sha256};
57
58use super::{canonical_json, require_schema, signing_input_without_signature};
59use crate::{UtcTimestamp, ValidationError};
60
61pub const EFFECTIVE_POLICY_SCHEMA: &str = "leanctx.cloud.effective-policy/v1";
62pub const POLICY_DOCUMENT_SCHEMA: &str = "leanctx.cloud.policy/v1";
63pub const POLICY_ACK_SCHEMA: &str = "leanctx.cloud.policy-ack/v1";
64pub const EFFECTIVE_POLICY_SIGNATURE_DOMAIN: &str = "leanctx.cloud.effective-policy.v1\n";
66pub const MAX_POLICY_SOURCES: usize = 35;
68pub const MAX_POLICY_VAULTS: usize = 32;
69pub const MAX_UNENFORCED: usize = 64;
71pub const POLICY_MISMATCH: &str = "policy_mismatch";
73
74const MAX_SET: usize = 256;
76const MAX_MODEL_GROUPS: usize = 16;
77const MAX_MODEL_GROUP: usize = 32;
78
79pub const ENGINE_MEMBERS: &[(&str, &str)] = &[
82 ("agents.allowed", "agents.allowed_agents"),
83 ("context.allowed_tools", "context.allow_tools"),
84 ("context.denied_tools", "context.deny_tools"),
85 ("context.injection_filter", "filters.injection"),
86 ("context.max_context_tokens", "context.max_context_tokens"),
87 (
88 "context.max_cost_cents_per_person_per_day",
89 "budgets.max_cost_usd_per_person_per_day",
90 ),
91 (
92 "context.max_cost_cents_per_project_per_month",
93 "budgets.max_cost_usd_per_project_per_month",
94 ),
95 (
96 "context.max_requests_per_minute_per_person",
97 "budgets.max_requests_per_minute_per_person",
98 ),
99 ("context.max_writes_per_min", "egress.max_writes_per_min"),
100 ("context.read_mode", "context.default_read_mode"),
101 ("orchestrator.network", "orchestrator.network"),
102 ("security.allowed_models", "routing.model_ceiling_groups"),
103 ("security.allowed_providers", "routing.allowed_providers"),
104 ("security.block_secrets", "egress.block_secrets"),
105 (
106 "security.blocked_host_countries",
107 "routing.blocked_host_countries",
108 ),
109 ("security.blocked_labels", "filters.blocked_labels"),
110 (
111 "security.blocked_model_origins",
112 "routing.blocked_model_origins",
113 ),
114 ("security.classification", "filters.classification"),
115 ("security.never_send", "io.never_send"),
116 ("security.pii", "filters.pii"),
117 ("security.readable_roots", "io.readable_roots"),
118 ("security.require_proxy", "routing.require_proxy"),
119 ("security.vendor_direct_cn", "routing.vendor_direct_cn"),
120];
121
122pub const PLANNED_ENGINE_MEMBERS: &[(&str, &str)] = &[];
130
131pub const MAX_ORCHESTRATOR_SESSIONS: u64 = 1000;
133
134pub const SERVER_MEMBERS: &[&str] = &[
137 "security.excluded_paths",
138 "sharing.allowed_vaults",
139 "sharing.consent_required_for",
140 "sharing.cross_team_sharing",
141 "sharing.personal_workspace",
142 "sharing.share_instance_metrics",
145 "sharing.task_claim_min_role",
146];
147
148pub const ADVISORY_MEMBERS: &[&str] = &[
150 "agents.require_approvals",
153 "context.allowed_sources",
154 "context.auto_extraction",
155 "context.extraction_requires_source_anchor",
156 "context.max_source_age_days",
157 "context.ranking_profile",
158 "orchestrator.cross_team_review",
161 "orchestrator.max_sessions_per_vault",
162 "security.confidential_out_of_sharing",
163 "security.external_model_excluded_classes",
164];
165
166#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
168#[serde(rename_all = "snake_case")]
169pub enum PolicyActionV1 {
170 Off,
171 Warn,
172 Redact,
173 Block,
174}
175
176impl PolicyActionV1 {
177 pub fn as_str(self) -> &'static str {
178 match self {
179 Self::Off => "off",
180 Self::Warn => "warn",
181 Self::Redact => "redact",
182 Self::Block => "block",
183 }
184 }
185}
186
187const READ_MODES: &[&str] = &[
188 "auto",
189 "full",
190 "map",
191 "signatures",
192 "diff",
193 "task",
194 "reference",
195 "aggressive",
196 "entropy",
197];
198const DATA_CLASSES: &[&str] = &[
199 "secrets",
200 "pii",
201 "confidential",
202 "customer_data",
203 "source_code",
204];
205const CLAIM_ROLES: &[&str] = &["reader", "contributor", "maintainer", "admin", "owner"];
206pub const PERSONAL_WORKSPACE_MODES: &[&str] = &["allow", "forbid"];
208const CONSENT_ACTIONS: &[&str] = &[
209 "trust_boundary",
210 "permission_expansion",
211 "security_command",
212 "destructive_change",
213 "team_sharing",
214 "external_model",
215];
216
217#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
219pub struct SecurityPolicyV1 {
220 #[serde(default, skip_serializing_if = "Option::is_none")]
221 pub excluded_paths: Option<Vec<String>>,
222 #[serde(default, skip_serializing_if = "Option::is_none")]
223 pub block_secrets: Option<bool>,
224 #[serde(default, skip_serializing_if = "Option::is_none")]
225 pub pii: Option<PolicyActionV1>,
226 #[serde(default, skip_serializing_if = "Option::is_none")]
227 pub classification: Option<PolicyActionV1>,
228 #[serde(default, skip_serializing_if = "Option::is_none")]
229 pub blocked_labels: Option<Vec<String>>,
230 #[serde(default, skip_serializing_if = "Option::is_none")]
231 pub allowed_models: Option<Vec<Vec<String>>>,
232 #[serde(default, skip_serializing_if = "Option::is_none")]
233 pub external_model_excluded_classes: Option<Vec<String>>,
234 #[serde(default, skip_serializing_if = "Option::is_none")]
235 pub confidential_out_of_sharing: Option<bool>,
236 #[serde(default, skip_serializing_if = "Option::is_none")]
239 pub blocked_model_origins: Option<Vec<String>>,
240 #[serde(default, skip_serializing_if = "Option::is_none")]
243 pub blocked_host_countries: Option<Vec<String>>,
244 #[serde(default, skip_serializing_if = "Option::is_none")]
247 pub vendor_direct_cn: Option<bool>,
248 #[serde(default, skip_serializing_if = "Option::is_none")]
251 pub allowed_providers: Option<Vec<String>>,
252 #[serde(default, skip_serializing_if = "Option::is_none")]
255 pub require_proxy: Option<bool>,
256 #[serde(default, skip_serializing_if = "Option::is_none")]
259 pub readable_roots: Option<Vec<String>>,
260 #[serde(default, skip_serializing_if = "Option::is_none")]
263 pub never_send: Option<Vec<String>>,
264 #[serde(flatten)]
266 pub other: BTreeMap<String, Value>,
267}
268
269#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
271pub struct ContextPolicyV1 {
272 #[serde(default, skip_serializing_if = "Option::is_none")]
273 pub max_context_tokens: Option<u64>,
274 #[serde(default, skip_serializing_if = "Option::is_none")]
275 pub injection_filter: Option<PolicyActionV1>,
276 #[serde(default, skip_serializing_if = "Option::is_none")]
277 pub read_mode: Option<String>,
278 #[serde(default, skip_serializing_if = "Option::is_none")]
279 pub ranking_profile: Option<String>,
280 #[serde(default, skip_serializing_if = "Option::is_none")]
281 pub allowed_tools: Option<Vec<String>>,
282 #[serde(default, skip_serializing_if = "Option::is_none")]
283 pub denied_tools: Option<Vec<String>>,
284 #[serde(default, skip_serializing_if = "Option::is_none")]
285 pub allowed_sources: Option<Vec<String>>,
286 #[serde(default, skip_serializing_if = "Option::is_none")]
287 pub max_writes_per_min: Option<u64>,
288 #[serde(default, skip_serializing_if = "Option::is_none")]
289 pub max_cost_cents_per_person_per_day: Option<u64>,
290 #[serde(default, skip_serializing_if = "Option::is_none")]
291 pub max_cost_cents_per_project_per_month: Option<u64>,
292 #[serde(default, skip_serializing_if = "Option::is_none")]
293 pub max_requests_per_minute_per_person: Option<u64>,
294 #[serde(default, skip_serializing_if = "Option::is_none")]
295 pub auto_extraction: Option<bool>,
296 #[serde(default, skip_serializing_if = "Option::is_none")]
297 pub extraction_requires_source_anchor: Option<bool>,
298 #[serde(default, skip_serializing_if = "Option::is_none")]
299 pub max_source_age_days: Option<u64>,
300 #[serde(flatten)]
301 pub other: BTreeMap<String, Value>,
302}
303
304#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
306pub struct SharingPolicyV1 {
307 #[serde(default, skip_serializing_if = "Option::is_none")]
308 pub allowed_vaults: Option<Vec<String>>,
309 #[serde(default, skip_serializing_if = "Option::is_none")]
310 pub cross_team_sharing: Option<bool>,
311 #[serde(default, skip_serializing_if = "Option::is_none")]
312 pub task_claim_min_role: Option<String>,
313 #[serde(default, skip_serializing_if = "Option::is_none")]
314 pub consent_required_for: Option<Vec<String>>,
315 #[serde(default, skip_serializing_if = "Option::is_none")]
320 pub personal_workspace: Option<String>,
321 #[serde(flatten)]
322 pub other: BTreeMap<String, Value>,
323}
324
325#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
328pub struct AgentsPolicyV1 {
329 #[serde(default, skip_serializing_if = "Option::is_none")]
332 pub allowed: Option<Vec<String>>,
333 #[serde(default, skip_serializing_if = "Option::is_none")]
335 pub require_approvals: Option<bool>,
336 #[serde(flatten)]
337 pub other: BTreeMap<String, Value>,
338}
339
340#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
344pub struct OrchestratorPolicyV1 {
345 #[serde(default, skip_serializing_if = "Option::is_none")]
348 pub network: Option<bool>,
349 #[serde(default, skip_serializing_if = "Option::is_none")]
352 pub cross_team_review: Option<bool>,
353 #[serde(default, skip_serializing_if = "Option::is_none")]
356 pub max_sessions_per_vault: Option<u64>,
357 #[serde(flatten)]
358 pub other: BTreeMap<String, Value>,
359}
360
361#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
363pub struct EffectivePolicyV1 {
364 pub schema: String,
365 pub security: SecurityPolicyV1,
366 pub context: ContextPolicyV1,
367 pub sharing: SharingPolicyV1,
368 #[serde(default, skip_serializing_if = "Option::is_none")]
369 pub agents: Option<AgentsPolicyV1>,
370 #[serde(default, skip_serializing_if = "Option::is_none")]
371 pub orchestrator: Option<OrchestratorPolicyV1>,
372 #[serde(flatten)]
376 pub other: BTreeMap<String, Value>,
377}
378
379#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
381#[serde(deny_unknown_fields)]
382pub struct VaultEffectivePolicyV1 {
383 pub vault_id: String,
384 pub effective: EffectivePolicyV1,
385}
386
387#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
390#[serde(deny_unknown_fields)]
391pub struct BundlePolicyV1 {
392 pub effective: EffectivePolicyV1,
393 pub vaults: Vec<VaultEffectivePolicyV1>,
394}
395
396impl BundlePolicyV1 {
397 pub fn for_vault(&self, vault_id: Option<&str>) -> &EffectivePolicyV1 {
399 vault_id
400 .and_then(|id| self.vaults.iter().find(|v| v.vault_id == id))
401 .map_or(&self.effective, |v| &v.effective)
402 }
403}
404
405#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
407#[serde(deny_unknown_fields)]
408pub struct PolicySourceV1 {
409 pub level: String,
410 pub scope: String,
411 pub version: u64,
412 pub digest: String,
413}
414
415#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
417pub struct EffectivePolicyBundleV1 {
418 pub schema: String,
419 pub org_id: String,
420 pub instance_id: String,
421 pub version: u64,
422 pub issued_at: UtcTimestamp,
423 pub not_after: UtcTimestamp,
424 pub sources: Vec<PolicySourceV1>,
425 pub policy: BundlePolicyV1,
426 pub digest: String,
427 pub key_id: String,
428 pub signature: String,
429}
430
431#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
433#[serde(deny_unknown_fields)]
434pub struct PolicyAckRequestV1 {
435 pub version: u64,
436 pub digest: String,
437 #[serde(default, skip_serializing_if = "Vec::is_empty")]
438 pub unenforced: Vec<String>,
439 #[serde(default, skip_serializing_if = "Option::is_none")]
442 pub refused: Option<PolicyAckRefusalV1>,
443}
444
445#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
447#[serde(rename_all = "snake_case")]
448pub enum PolicyRefusalReasonV1 {
449 InvalidBundle,
451 WrongTarget,
453 KeyUnavailable,
455 SignatureInvalid,
456 DigestMismatch,
458 Downgrade,
460 Expired,
462 InstallFailed,
464}
465
466pub const MAX_REFUSAL_DETAIL: usize = 300;
468
469#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
472#[serde(deny_unknown_fields)]
473pub struct PolicyAckRefusalV1 {
474 pub reason_code: PolicyRefusalReasonV1,
475 #[serde(default, skip_serializing_if = "Option::is_none")]
478 pub detail: Option<String>,
479 pub applied_version: Option<u64>,
480 pub applied_digest: Option<String>,
481}
482
483pub fn refusal_detail(line: &str) -> Option<String> {
493 let clean: String = line
494 .chars()
495 .map(|c| if c.is_control() { ' ' } else { c })
496 .collect();
497 let place = |word: &str| {
498 word.contains('/')
499 || word.contains('\\')
500 || word.starts_with('~')
501 || (word.len() > 2
502 && word.as_bytes()[1] == b':'
503 && word.as_bytes()[0].is_ascii_alphabetic())
504 };
505 let mut words: Vec<&str> = Vec::new();
506 let mut run = false;
507 for word in clean.split(' ') {
508 if !run && !place(word) {
509 words.push(word);
510 continue;
511 }
512 run = true;
513 if word.ends_with(':') {
514 words.push("<path>:");
515 run = false;
516 }
517 }
518 if run {
519 words.push("<path>");
520 }
521 let text: String = words.join(" ").chars().take(MAX_REFUSAL_DETAIL).collect();
522 let text = text.trim();
523 (!text.is_empty()).then(|| text.to_string())
524}
525
526impl PolicyAckRequestV1 {
527 pub fn refusal(version: u64, digest: String, refused: PolicyAckRefusalV1) -> Self {
529 Self {
530 version,
531 digest,
532 unenforced: Vec::new(),
533 refused: Some(refused),
534 }
535 }
536}
537
538#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
541pub struct PolicyAckRefusedResponseV1 {
542 pub schema: String,
543 pub version: u64,
544 pub digest: String,
545 pub state: String,
547 pub reason_code: PolicyRefusalReasonV1,
548 pub applied_version: Option<u64>,
549 pub applied_digest: Option<String>,
550 pub refused_at: UtcTimestamp,
551}
552
553impl PolicyAckRefusedResponseV1 {
554 pub fn validate_for(&self, request: &PolicyAckRequestV1) -> Result<(), ValidationError> {
556 require_schema(&self.schema, POLICY_ACK_SCHEMA)?;
557 let Some(refused) = &request.refused else {
558 return Err(ValidationError::new("not a refusal request"));
559 };
560 if self.state != "refused"
561 || self.version != request.version
562 || self.digest != request.digest
563 || self.reason_code != refused.reason_code
564 || self.applied_version != refused.applied_version
565 || self.applied_digest != refused.applied_digest
566 {
567 return Err(ValidationError::new(
568 "the refusal answer names another bundle or reason",
569 ));
570 }
571 Ok(())
572 }
573}
574
575#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
577#[serde(rename_all = "snake_case")]
578pub enum PolicyAckStateV1 {
579 Acked,
580 Outdated,
581}
582
583#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
585pub struct PolicyAckResponseV1 {
586 pub schema: String,
587 pub version: u64,
588 pub digest: String,
589 pub state: PolicyAckStateV1,
590 pub acked_at: UtcTimestamp,
591}
592
593impl PolicyAckResponseV1 {
594 pub fn validate_for(&self, request: &PolicyAckRequestV1) -> Result<(), ValidationError> {
596 require_schema(&self.schema, POLICY_ACK_SCHEMA)?;
597 if self.version != request.version || self.digest != request.digest {
598 return Err(ValidationError::new(
599 "the ack answer names another policy version or digest",
600 ));
601 }
602 Ok(())
603 }
604}
605
606fn hex(bytes: &[u8]) -> String {
607 use std::fmt::Write as _;
608 bytes.iter().fold(String::new(), |mut out, b| {
609 let _ = write!(out, "{b:02x}");
610 out
611 })
612}
613
614pub fn policy_digest(value: &Value) -> Result<String, ValidationError> {
616 Ok(format!(
617 "sha256:{}",
618 hex(&Sha256::digest(canonical_json(value)?))
619 ))
620}
621
622pub fn signing_input_raw(raw: &Value) -> Result<Vec<u8>, ValidationError> {
625 signing_input_without_signature(EFFECTIVE_POLICY_SIGNATURE_DOMAIN, raw)
626}
627
628fn is_lower_hex(value: &str, len: usize) -> bool {
629 value.len() == len
630 && value
631 .bytes()
632 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
633}
634
635pub fn is_country(value: &str) -> bool {
637 value.len() == 2 && value.bytes().all(|b| b.is_ascii_uppercase())
638}
639
640fn validate_digest(value: &str, field: &str) -> Result<(), ValidationError> {
641 match value.strip_prefix("sha256:") {
642 Some(hex) if is_lower_hex(hex, 64) => Ok(()),
643 _ => Err(ValidationError::new(format!(
644 "{field} must be sha256: and 64 lowercase hex characters"
645 ))),
646 }
647}
648
649fn prefixed_hex32(value: &str, prefix: &str) -> bool {
650 value
651 .strip_prefix(prefix)
652 .is_some_and(|rest| is_lower_hex(rest, 32))
653}
654
655fn valid_name(value: &str) -> bool {
656 let bytes = value.as_bytes();
657 !bytes.is_empty()
658 && bytes.len() <= 64
659 && (bytes[0].is_ascii_lowercase() || bytes[0].is_ascii_digit())
660 && bytes.iter().all(|b| {
661 b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'_' | b'.' | b':' | b'-')
662 })
663}
664
665fn valid_pattern(value: &str, max: usize) -> bool {
667 let count = value.chars().count();
668 (1..=max).contains(&count)
669 && !value
670 .chars()
671 .any(|c| matches!(c, '\u{0}'..='\u{1f}' | '\u{7f}'..='\u{9f}'))
672}
673
674fn valid_member_name(name: &str) -> bool {
676 !name.is_empty()
677 && name.len() <= 64
678 && name.bytes().all(|b| b.is_ascii_lowercase() || b == b'_')
679}
680
681fn invalid(field: &str) -> ValidationError {
682 ValidationError::new(format!("invalid_policy: {field}"))
683}
684
685fn check_set(
688 set: Option<&Vec<String>>,
689 field: &str,
690 item_ok: impl Fn(&str) -> bool,
691) -> Result<(), ValidationError> {
692 let Some(set) = set else { return Ok(()) };
693 if set.len() > MAX_SET
694 || !set.windows(2).all(|w| w[0] < w[1])
695 || !set.iter().all(|item| item_ok(item))
696 {
697 return Err(invalid(field));
698 }
699 Ok(())
700}
701
702fn check_range(value: Option<u64>, min: u64, max: u64, field: &str) -> Result<(), ValidationError> {
703 match value {
704 Some(v) if !(min..=max).contains(&v) => Err(invalid(field)),
705 _ => Ok(()),
706 }
707}
708
709fn check_enum(
710 value: Option<&String>,
711 allowed: &[&str],
712 field: &str,
713) -> Result<(), ValidationError> {
714 match value {
715 Some(v) if !allowed.contains(&v.as_str()) => Err(invalid(field)),
716 _ => Ok(()),
717 }
718}
719
720impl EffectivePolicyV1 {
721 pub fn validate(&self) -> Result<(), ValidationError> {
723 require_schema(&self.schema, POLICY_DOCUMENT_SCHEMA)?;
724 let s = &self.security;
725 check_set(s.excluded_paths.as_ref(), "security.excluded_paths", |p| {
726 valid_pattern(p, 256)
727 })?;
728 check_set(
729 s.blocked_labels.as_ref(),
730 "security.blocked_labels",
731 valid_name,
732 )?;
733 check_set(
734 s.external_model_excluded_classes.as_ref(),
735 "security.external_model_excluded_classes",
736 |c| DATA_CLASSES.contains(&c),
737 )?;
738 check_set(
739 s.blocked_model_origins.as_ref(),
740 "security.blocked_model_origins",
741 is_country,
742 )?;
743 check_set(
744 s.blocked_host_countries.as_ref(),
745 "security.blocked_host_countries",
746 is_country,
747 )?;
748 if let Some(groups) = &s.allowed_models {
749 let field = "security.allowed_models";
750 if groups.is_empty()
751 || groups.len() > MAX_MODEL_GROUPS
752 || !groups.windows(2).all(|w| w[0] < w[1])
753 {
754 return Err(invalid(field));
755 }
756 for group in groups {
757 if group.len() > MAX_MODEL_GROUP {
758 return Err(invalid(field));
759 }
760 check_set(Some(group), field, |p| valid_pattern(p, 128))?;
761 }
762 }
763 check_set(
764 s.allowed_providers.as_ref(),
765 "security.allowed_providers",
766 valid_name,
767 )?;
768 check_set(s.readable_roots.as_ref(), "security.readable_roots", |p| {
769 valid_pattern(p, 256)
770 })?;
771 check_set(s.never_send.as_ref(), "security.never_send", |p| {
772 valid_pattern(p, 256)
773 })?;
774 if let Some(agents) = &self.agents {
775 check_set(agents.allowed.as_ref(), "agents.allowed", |a| {
776 a == "*" || valid_name(a)
777 })?;
778 }
779 let c = &self.context;
780 check_range(
781 c.max_context_tokens,
782 1,
783 10_000_000,
784 "context.max_context_tokens",
785 )?;
786 check_enum(c.read_mode.as_ref(), READ_MODES, "context.read_mode")?;
787 if c.ranking_profile.as_deref().is_some_and(|p| !valid_name(p)) {
788 return Err(invalid("context.ranking_profile"));
789 }
790 check_set(
791 c.allowed_tools.as_ref(),
792 "context.allowed_tools",
793 valid_name,
794 )?;
795 check_set(c.denied_tools.as_ref(), "context.denied_tools", valid_name)?;
796 check_set(
797 c.allowed_sources.as_ref(),
798 "context.allowed_sources",
799 valid_name,
800 )?;
801 check_range(
802 c.max_writes_per_min,
803 0,
804 10_000,
805 "context.max_writes_per_min",
806 )?;
807 check_range(
808 c.max_cost_cents_per_person_per_day,
809 0,
810 100_000_000,
811 "context.max_cost_cents_per_person_per_day",
812 )?;
813 check_range(
814 c.max_cost_cents_per_project_per_month,
815 0,
816 100_000_000,
817 "context.max_cost_cents_per_project_per_month",
818 )?;
819 check_range(
820 c.max_requests_per_minute_per_person,
821 1,
822 1_000_000,
823 "context.max_requests_per_minute_per_person",
824 )?;
825 check_range(
826 c.max_source_age_days,
827 1,
828 3650,
829 "context.max_source_age_days",
830 )?;
831 let h = &self.sharing;
832 check_set(h.allowed_vaults.as_ref(), "sharing.allowed_vaults", |v| {
833 is_lower_hex(v, 32)
834 })?;
835 check_enum(
836 h.task_claim_min_role.as_ref(),
837 CLAIM_ROLES,
838 "sharing.task_claim_min_role",
839 )?;
840 check_set(
841 h.consent_required_for.as_ref(),
842 "sharing.consent_required_for",
843 |a| CONSENT_ACTIONS.contains(&a),
844 )?;
845 check_enum(
846 h.personal_workspace.as_ref(),
847 PERSONAL_WORKSPACE_MODES,
848 "sharing.personal_workspace",
849 )?;
850 if let Some(orchestrator) = &self.orchestrator {
851 check_range(
852 orchestrator.max_sessions_per_vault,
853 0,
854 MAX_ORCHESTRATOR_SESSIONS,
855 "orchestrator.max_sessions_per_vault",
856 )?;
857 }
858 let empty = BTreeMap::new();
859 let agents_other = self.agents.as_ref().map_or(&empty, |a| &a.other);
860 let orchestrator_other = self.orchestrator.as_ref().map_or(&empty, |o| &o.other);
861 for (section, other) in [
862 ("security", &s.other),
863 ("context", &c.other),
864 ("sharing", &h.other),
865 ("agents", agents_other),
866 ("orchestrator", orchestrator_other),
867 ] {
868 if let Some(name) = other.keys().find(|k| !valid_member_name(k)) {
869 return Err(invalid(&format!("{section}.{name}")));
870 }
871 }
872 for (section, value) in &self.other {
874 let ok = valid_member_name(section)
875 && value
876 .as_object()
877 .is_some_and(|members| members.keys().all(|k| valid_member_name(k)));
878 if !ok {
879 return Err(invalid(section));
880 }
881 }
882 Ok(())
883 }
884
885 pub fn members(&self) -> BTreeSet<String> {
887 let section = |name: &str, value: Value| -> Vec<String> {
888 value
889 .as_object()
890 .map(|fields| fields.keys().map(|k| format!("{name}.{k}")).collect())
891 .unwrap_or_default()
892 };
893 let mut out = BTreeSet::new();
894 out.extend(section(
895 "security",
896 serde_json::to_value(&self.security).unwrap_or(Value::Null),
897 ));
898 out.extend(section(
899 "context",
900 serde_json::to_value(&self.context).unwrap_or(Value::Null),
901 ));
902 out.extend(section(
903 "sharing",
904 serde_json::to_value(&self.sharing).unwrap_or(Value::Null),
905 ));
906 if let Some(agents) = &self.agents {
907 out.extend(section(
908 "agents",
909 serde_json::to_value(agents).unwrap_or(Value::Null),
910 ));
911 }
912 if let Some(orchestrator) = &self.orchestrator {
913 out.extend(section(
914 "orchestrator",
915 serde_json::to_value(orchestrator).unwrap_or(Value::Null),
916 ));
917 }
918 for (name, value) in &self.other {
919 out.extend(section(name, value.clone()));
920 }
921 out
922 }
923}
924
925pub fn is_engine_member(member: &str) -> bool {
927 ENGINE_MEMBERS.iter().any(|(m, _)| *m == member)
928}
929
930pub fn is_server_member(member: &str) -> bool {
932 SERVER_MEMBERS.contains(&member)
933}
934
935fn set_members(policy: &BundlePolicyV1) -> BTreeSet<String> {
937 let mut all = policy.effective.members();
938 for vault in &policy.vaults {
939 all.extend(vault.effective.members());
940 }
941 all
942}
943
944pub fn unenforced_members(policy: &BundlePolicyV1) -> Vec<String> {
947 set_members(policy)
948 .into_iter()
949 .filter(|m| !is_engine_member(m) && !is_server_member(m))
950 .collect()
951}
952
953pub fn server_members(policy: &BundlePolicyV1) -> Vec<String> {
955 set_members(policy)
956 .into_iter()
957 .filter(|m| is_server_member(m))
958 .collect()
959}
960
961impl EffectivePolicyBundleV1 {
962 pub fn validate(&self) -> Result<(), ValidationError> {
965 require_schema(&self.schema, EFFECTIVE_POLICY_SCHEMA)?;
966 if !prefixed_hex32(&self.org_id, "org_") {
967 return Err(ValidationError::new("org_id must be org_ and 32 hex"));
968 }
969 if !prefixed_hex32(&self.instance_id, "inst_") {
970 return Err(ValidationError::new("instance_id must be inst_ and 32 hex"));
971 }
972 if self.version == 0 {
973 return Err(ValidationError::new("version starts at 1"));
974 }
975 if self.not_after <= self.issued_at {
976 return Err(ValidationError::new("not_after must follow issued_at"));
977 }
978 if self.sources.len() > MAX_POLICY_SOURCES {
979 return Err(ValidationError::new("too many policy sources"));
980 }
981 for source in &self.sources {
982 let scope_ok = prefixed_hex32(&source.scope, "org_")
986 || (source.level == "org" && prefixed_hex32(&source.scope, "orgn_"))
987 || prefixed_hex32(&source.scope, "inst_")
988 || is_lower_hex(&source.scope, 32);
989 if !matches!(
990 source.level.as_str(),
991 "org" | "workspace" | "vault" | "instance"
992 ) || !scope_ok
993 || source.version == 0
994 {
995 return Err(ValidationError::new("a policy source is malformed"));
996 }
997 validate_digest(&source.digest, "sources.digest")?;
998 }
999 if self.policy.vaults.len() > MAX_POLICY_VAULTS
1000 || !self
1001 .policy
1002 .vaults
1003 .windows(2)
1004 .all(|w| w[0].vault_id < w[1].vault_id)
1005 {
1006 return Err(ValidationError::new(
1007 "policy.vaults must be at most 32, ascending by vault_id",
1008 ));
1009 }
1010 self.policy.effective.validate()?;
1011 for vault in &self.policy.vaults {
1012 if !is_lower_hex(&vault.vault_id, 32) {
1013 return Err(ValidationError::new("policy.vaults.vault_id is malformed"));
1014 }
1015 vault.effective.validate()?;
1016 }
1017 validate_digest(&self.digest, "digest")?;
1018 if !is_lower_hex(&self.key_id, 16) {
1019 return Err(ValidationError::new("key_id must be 16 lowercase hex"));
1020 }
1021 if !is_lower_hex(&self.signature, 128) {
1022 return Err(ValidationError::new("signature must be 128 lowercase hex"));
1023 }
1024 Ok(())
1025 }
1026
1027 pub fn ack(&self) -> PolicyAckRequestV1 {
1031 let mut unenforced = unenforced_members(&self.policy);
1032 unenforced.truncate(MAX_UNENFORCED);
1033 PolicyAckRequestV1 {
1034 version: self.version,
1035 digest: self.digest.clone(),
1036 unenforced,
1037 refused: None,
1038 }
1039 }
1040}
1041
1042#[cfg(test)]
1043#[path = "effective_policy_tests.rs"]
1044mod tests;