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.agent_exchange",
140 "sharing.allowed_vaults",
141 "sharing.consent_required_for",
142 "sharing.cross_team_sharing",
143 "sharing.personal_workspace",
144 "sharing.share_instance_metrics",
147 "sharing.task_claim_min_role",
148];
149
150pub const ADVISORY_MEMBERS: &[&str] = &[
152 "agents.require_approvals",
155 "context.allowed_sources",
156 "context.auto_extraction",
157 "context.extraction_requires_source_anchor",
158 "context.max_source_age_days",
159 "context.ranking_profile",
160 "orchestrator.cross_team_review",
163 "orchestrator.max_sessions_per_vault",
164 "security.confidential_out_of_sharing",
165 "security.external_model_excluded_classes",
166];
167
168#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
170#[serde(rename_all = "snake_case")]
171pub enum PolicyActionV1 {
172 Off,
173 Warn,
174 Redact,
175 Block,
176}
177
178impl PolicyActionV1 {
179 pub fn as_str(self) -> &'static str {
180 match self {
181 Self::Off => "off",
182 Self::Warn => "warn",
183 Self::Redact => "redact",
184 Self::Block => "block",
185 }
186 }
187}
188
189const READ_MODES: &[&str] = &[
190 "auto",
191 "full",
192 "map",
193 "signatures",
194 "diff",
195 "task",
196 "reference",
197 "aggressive",
198 "entropy",
199];
200const DATA_CLASSES: &[&str] = &[
201 "secrets",
202 "pii",
203 "confidential",
204 "customer_data",
205 "source_code",
206];
207const CLAIM_ROLES: &[&str] = &["reader", "contributor", "maintainer", "admin", "owner"];
208pub const PERSONAL_WORKSPACE_MODES: &[&str] = &["allow", "forbid"];
210const CONSENT_ACTIONS: &[&str] = &[
211 "trust_boundary",
212 "permission_expansion",
213 "security_command",
214 "destructive_change",
215 "team_sharing",
216 "external_model",
217];
218
219#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
221pub struct SecurityPolicyV1 {
222 #[serde(default, skip_serializing_if = "Option::is_none")]
223 pub excluded_paths: Option<Vec<String>>,
224 #[serde(default, skip_serializing_if = "Option::is_none")]
225 pub block_secrets: Option<bool>,
226 #[serde(default, skip_serializing_if = "Option::is_none")]
227 pub pii: Option<PolicyActionV1>,
228 #[serde(default, skip_serializing_if = "Option::is_none")]
229 pub classification: Option<PolicyActionV1>,
230 #[serde(default, skip_serializing_if = "Option::is_none")]
231 pub blocked_labels: Option<Vec<String>>,
232 #[serde(default, skip_serializing_if = "Option::is_none")]
233 pub allowed_models: Option<Vec<Vec<String>>>,
234 #[serde(default, skip_serializing_if = "Option::is_none")]
235 pub external_model_excluded_classes: Option<Vec<String>>,
236 #[serde(default, skip_serializing_if = "Option::is_none")]
237 pub confidential_out_of_sharing: Option<bool>,
238 #[serde(default, skip_serializing_if = "Option::is_none")]
241 pub blocked_model_origins: Option<Vec<String>>,
242 #[serde(default, skip_serializing_if = "Option::is_none")]
245 pub blocked_host_countries: Option<Vec<String>>,
246 #[serde(default, skip_serializing_if = "Option::is_none")]
249 pub vendor_direct_cn: Option<bool>,
250 #[serde(default, skip_serializing_if = "Option::is_none")]
253 pub allowed_providers: Option<Vec<String>>,
254 #[serde(default, skip_serializing_if = "Option::is_none")]
257 pub require_proxy: Option<bool>,
258 #[serde(default, skip_serializing_if = "Option::is_none")]
261 pub readable_roots: Option<Vec<String>>,
262 #[serde(default, skip_serializing_if = "Option::is_none")]
265 pub never_send: Option<Vec<String>>,
266 #[serde(flatten)]
268 pub other: BTreeMap<String, Value>,
269}
270
271#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
273pub struct ContextPolicyV1 {
274 #[serde(default, skip_serializing_if = "Option::is_none")]
275 pub max_context_tokens: Option<u64>,
276 #[serde(default, skip_serializing_if = "Option::is_none")]
277 pub injection_filter: Option<PolicyActionV1>,
278 #[serde(default, skip_serializing_if = "Option::is_none")]
279 pub read_mode: Option<String>,
280 #[serde(default, skip_serializing_if = "Option::is_none")]
281 pub ranking_profile: Option<String>,
282 #[serde(default, skip_serializing_if = "Option::is_none")]
283 pub allowed_tools: Option<Vec<String>>,
284 #[serde(default, skip_serializing_if = "Option::is_none")]
285 pub denied_tools: Option<Vec<String>>,
286 #[serde(default, skip_serializing_if = "Option::is_none")]
287 pub allowed_sources: Option<Vec<String>>,
288 #[serde(default, skip_serializing_if = "Option::is_none")]
289 pub max_writes_per_min: Option<u64>,
290 #[serde(default, skip_serializing_if = "Option::is_none")]
291 pub max_cost_cents_per_person_per_day: Option<u64>,
292 #[serde(default, skip_serializing_if = "Option::is_none")]
293 pub max_cost_cents_per_project_per_month: Option<u64>,
294 #[serde(default, skip_serializing_if = "Option::is_none")]
295 pub max_requests_per_minute_per_person: Option<u64>,
296 #[serde(default, skip_serializing_if = "Option::is_none")]
297 pub auto_extraction: Option<bool>,
298 #[serde(default, skip_serializing_if = "Option::is_none")]
299 pub extraction_requires_source_anchor: Option<bool>,
300 #[serde(default, skip_serializing_if = "Option::is_none")]
301 pub max_source_age_days: Option<u64>,
302 #[serde(flatten)]
303 pub other: BTreeMap<String, Value>,
304}
305
306#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
308pub struct SharingPolicyV1 {
309 #[serde(default, skip_serializing_if = "Option::is_none")]
310 pub allowed_vaults: Option<Vec<String>>,
311 #[serde(default, skip_serializing_if = "Option::is_none")]
312 pub cross_team_sharing: Option<bool>,
313 #[serde(default, skip_serializing_if = "Option::is_none")]
314 pub task_claim_min_role: Option<String>,
315 #[serde(default, skip_serializing_if = "Option::is_none")]
316 pub consent_required_for: Option<Vec<String>>,
317 #[serde(default, skip_serializing_if = "Option::is_none")]
322 pub personal_workspace: Option<String>,
323 #[serde(flatten)]
324 pub other: BTreeMap<String, Value>,
325}
326
327#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
330pub struct AgentsPolicyV1 {
331 #[serde(default, skip_serializing_if = "Option::is_none")]
334 pub allowed: Option<Vec<String>>,
335 #[serde(default, skip_serializing_if = "Option::is_none")]
337 pub require_approvals: Option<bool>,
338 #[serde(flatten)]
339 pub other: BTreeMap<String, Value>,
340}
341
342#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
346pub struct OrchestratorPolicyV1 {
347 #[serde(default, skip_serializing_if = "Option::is_none")]
350 pub network: Option<bool>,
351 #[serde(default, skip_serializing_if = "Option::is_none")]
354 pub cross_team_review: Option<bool>,
355 #[serde(default, skip_serializing_if = "Option::is_none")]
358 pub max_sessions_per_vault: Option<u64>,
359 #[serde(flatten)]
360 pub other: BTreeMap<String, Value>,
361}
362
363#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
365pub struct EffectivePolicyV1 {
366 pub schema: String,
367 pub security: SecurityPolicyV1,
368 pub context: ContextPolicyV1,
369 pub sharing: SharingPolicyV1,
370 #[serde(default, skip_serializing_if = "Option::is_none")]
371 pub agents: Option<AgentsPolicyV1>,
372 #[serde(default, skip_serializing_if = "Option::is_none")]
373 pub orchestrator: Option<OrchestratorPolicyV1>,
374 #[serde(flatten)]
378 pub other: BTreeMap<String, Value>,
379}
380
381#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
383#[serde(deny_unknown_fields)]
384pub struct VaultEffectivePolicyV1 {
385 pub vault_id: String,
386 pub effective: EffectivePolicyV1,
387}
388
389#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
392#[serde(deny_unknown_fields)]
393pub struct BundlePolicyV1 {
394 pub effective: EffectivePolicyV1,
395 pub vaults: Vec<VaultEffectivePolicyV1>,
396}
397
398impl BundlePolicyV1 {
399 pub fn for_vault(&self, vault_id: Option<&str>) -> &EffectivePolicyV1 {
401 vault_id
402 .and_then(|id| self.vaults.iter().find(|v| v.vault_id == id))
403 .map_or(&self.effective, |v| &v.effective)
404 }
405}
406
407#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
409#[serde(deny_unknown_fields)]
410pub struct PolicySourceV1 {
411 pub level: String,
412 pub scope: String,
413 pub version: u64,
414 pub digest: String,
415}
416
417#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
419pub struct EffectivePolicyBundleV1 {
420 pub schema: String,
421 pub org_id: String,
422 pub instance_id: String,
423 pub version: u64,
424 pub issued_at: UtcTimestamp,
425 pub not_after: UtcTimestamp,
426 pub sources: Vec<PolicySourceV1>,
427 pub policy: BundlePolicyV1,
428 pub digest: String,
429 pub key_id: String,
430 pub signature: String,
431}
432
433#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
435#[serde(deny_unknown_fields)]
436pub struct PolicyAckRequestV1 {
437 pub version: u64,
438 pub digest: String,
439 #[serde(default, skip_serializing_if = "Vec::is_empty")]
440 pub unenforced: Vec<String>,
441 #[serde(default, skip_serializing_if = "Option::is_none")]
444 pub refused: Option<PolicyAckRefusalV1>,
445}
446
447#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
449#[serde(rename_all = "snake_case")]
450pub enum PolicyRefusalReasonV1 {
451 InvalidBundle,
453 WrongTarget,
455 KeyUnavailable,
457 SignatureInvalid,
458 DigestMismatch,
460 Downgrade,
462 Expired,
464 InstallFailed,
466}
467
468pub const MAX_REFUSAL_DETAIL: usize = 300;
470
471#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
474#[serde(deny_unknown_fields)]
475pub struct PolicyAckRefusalV1 {
476 pub reason_code: PolicyRefusalReasonV1,
477 #[serde(default, skip_serializing_if = "Option::is_none")]
480 pub detail: Option<String>,
481 pub applied_version: Option<u64>,
482 pub applied_digest: Option<String>,
483}
484
485pub fn refusal_detail(line: &str) -> Option<String> {
495 let clean: String = line
496 .chars()
497 .map(|c| if c.is_control() { ' ' } else { c })
498 .collect();
499 let place = |word: &str| {
500 word.contains('/')
501 || word.contains('\\')
502 || word.starts_with('~')
503 || (word.len() > 2
504 && word.as_bytes()[1] == b':'
505 && word.as_bytes()[0].is_ascii_alphabetic())
506 };
507 let mut words: Vec<&str> = Vec::new();
508 let mut run = false;
509 for word in clean.split(' ') {
510 if !run && !place(word) {
511 words.push(word);
512 continue;
513 }
514 run = true;
515 if word.ends_with(':') {
516 words.push("<path>:");
517 run = false;
518 }
519 }
520 if run {
521 words.push("<path>");
522 }
523 let text: String = words.join(" ").chars().take(MAX_REFUSAL_DETAIL).collect();
524 let text = text.trim();
525 (!text.is_empty()).then(|| text.to_string())
526}
527
528impl PolicyAckRequestV1 {
529 pub fn refusal(version: u64, digest: String, refused: PolicyAckRefusalV1) -> Self {
531 Self {
532 version,
533 digest,
534 unenforced: Vec::new(),
535 refused: Some(refused),
536 }
537 }
538}
539
540#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
543pub struct PolicyAckRefusedResponseV1 {
544 pub schema: String,
545 pub version: u64,
546 pub digest: String,
547 pub state: String,
549 pub reason_code: PolicyRefusalReasonV1,
550 pub applied_version: Option<u64>,
551 pub applied_digest: Option<String>,
552 pub refused_at: UtcTimestamp,
553}
554
555impl PolicyAckRefusedResponseV1 {
556 pub fn validate_for(&self, request: &PolicyAckRequestV1) -> Result<(), ValidationError> {
558 require_schema(&self.schema, POLICY_ACK_SCHEMA)?;
559 let Some(refused) = &request.refused else {
560 return Err(ValidationError::new("not a refusal request"));
561 };
562 if self.state != "refused"
563 || self.version != request.version
564 || self.digest != request.digest
565 || self.reason_code != refused.reason_code
566 || self.applied_version != refused.applied_version
567 || self.applied_digest != refused.applied_digest
568 {
569 return Err(ValidationError::new(
570 "the refusal answer names another bundle or reason",
571 ));
572 }
573 Ok(())
574 }
575}
576
577#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
579#[serde(rename_all = "snake_case")]
580pub enum PolicyAckStateV1 {
581 Acked,
582 Outdated,
583}
584
585#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
587pub struct PolicyAckResponseV1 {
588 pub schema: String,
589 pub version: u64,
590 pub digest: String,
591 pub state: PolicyAckStateV1,
592 pub acked_at: UtcTimestamp,
593}
594
595impl PolicyAckResponseV1 {
596 pub fn validate_for(&self, request: &PolicyAckRequestV1) -> Result<(), ValidationError> {
598 require_schema(&self.schema, POLICY_ACK_SCHEMA)?;
599 if self.version != request.version || self.digest != request.digest {
600 return Err(ValidationError::new(
601 "the ack answer names another policy version or digest",
602 ));
603 }
604 Ok(())
605 }
606}
607
608fn hex(bytes: &[u8]) -> String {
609 use std::fmt::Write as _;
610 bytes.iter().fold(String::new(), |mut out, b| {
611 let _ = write!(out, "{b:02x}");
612 out
613 })
614}
615
616pub fn policy_digest(value: &Value) -> Result<String, ValidationError> {
618 Ok(format!(
619 "sha256:{}",
620 hex(&Sha256::digest(canonical_json(value)?))
621 ))
622}
623
624pub fn signing_input_raw(raw: &Value) -> Result<Vec<u8>, ValidationError> {
627 signing_input_without_signature(EFFECTIVE_POLICY_SIGNATURE_DOMAIN, raw)
628}
629
630fn is_lower_hex(value: &str, len: usize) -> bool {
631 value.len() == len
632 && value
633 .bytes()
634 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
635}
636
637pub fn is_country(value: &str) -> bool {
639 value.len() == 2 && value.bytes().all(|b| b.is_ascii_uppercase())
640}
641
642fn validate_digest(value: &str, field: &str) -> Result<(), ValidationError> {
643 match value.strip_prefix("sha256:") {
644 Some(hex) if is_lower_hex(hex, 64) => Ok(()),
645 _ => Err(ValidationError::new(format!(
646 "{field} must be sha256: and 64 lowercase hex characters"
647 ))),
648 }
649}
650
651fn prefixed_hex32(value: &str, prefix: &str) -> bool {
652 value
653 .strip_prefix(prefix)
654 .is_some_and(|rest| is_lower_hex(rest, 32))
655}
656
657fn valid_name(value: &str) -> bool {
658 let bytes = value.as_bytes();
659 !bytes.is_empty()
660 && bytes.len() <= 64
661 && (bytes[0].is_ascii_lowercase() || bytes[0].is_ascii_digit())
662 && bytes.iter().all(|b| {
663 b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'_' | b'.' | b':' | b'-')
664 })
665}
666
667fn valid_pattern(value: &str, max: usize) -> bool {
669 let count = value.chars().count();
670 (1..=max).contains(&count)
671 && !value
672 .chars()
673 .any(|c| matches!(c, '\u{0}'..='\u{1f}' | '\u{7f}'..='\u{9f}'))
674}
675
676fn valid_member_name(name: &str) -> bool {
678 !name.is_empty()
679 && name.len() <= 64
680 && name.bytes().all(|b| b.is_ascii_lowercase() || b == b'_')
681}
682
683fn invalid(field: &str) -> ValidationError {
684 ValidationError::new(format!("invalid_policy: {field}"))
685}
686
687fn check_set(
690 set: Option<&Vec<String>>,
691 field: &str,
692 item_ok: impl Fn(&str) -> bool,
693) -> Result<(), ValidationError> {
694 let Some(set) = set else { return Ok(()) };
695 if set.len() > MAX_SET
696 || !set.windows(2).all(|w| w[0] < w[1])
697 || !set.iter().all(|item| item_ok(item))
698 {
699 return Err(invalid(field));
700 }
701 Ok(())
702}
703
704fn check_range(value: Option<u64>, min: u64, max: u64, field: &str) -> Result<(), ValidationError> {
705 match value {
706 Some(v) if !(min..=max).contains(&v) => Err(invalid(field)),
707 _ => Ok(()),
708 }
709}
710
711fn check_enum(
712 value: Option<&String>,
713 allowed: &[&str],
714 field: &str,
715) -> Result<(), ValidationError> {
716 match value {
717 Some(v) if !allowed.contains(&v.as_str()) => Err(invalid(field)),
718 _ => Ok(()),
719 }
720}
721
722impl EffectivePolicyV1 {
723 pub fn validate(&self) -> Result<(), ValidationError> {
725 require_schema(&self.schema, POLICY_DOCUMENT_SCHEMA)?;
726 let s = &self.security;
727 check_set(s.excluded_paths.as_ref(), "security.excluded_paths", |p| {
728 valid_pattern(p, 256)
729 })?;
730 check_set(
731 s.blocked_labels.as_ref(),
732 "security.blocked_labels",
733 valid_name,
734 )?;
735 check_set(
736 s.external_model_excluded_classes.as_ref(),
737 "security.external_model_excluded_classes",
738 |c| DATA_CLASSES.contains(&c),
739 )?;
740 check_set(
741 s.blocked_model_origins.as_ref(),
742 "security.blocked_model_origins",
743 is_country,
744 )?;
745 check_set(
746 s.blocked_host_countries.as_ref(),
747 "security.blocked_host_countries",
748 is_country,
749 )?;
750 if let Some(groups) = &s.allowed_models {
751 let field = "security.allowed_models";
752 if groups.is_empty()
753 || groups.len() > MAX_MODEL_GROUPS
754 || !groups.windows(2).all(|w| w[0] < w[1])
755 {
756 return Err(invalid(field));
757 }
758 for group in groups {
759 if group.len() > MAX_MODEL_GROUP {
760 return Err(invalid(field));
761 }
762 check_set(Some(group), field, |p| valid_pattern(p, 128))?;
763 }
764 }
765 check_set(
766 s.allowed_providers.as_ref(),
767 "security.allowed_providers",
768 valid_name,
769 )?;
770 check_set(s.readable_roots.as_ref(), "security.readable_roots", |p| {
771 valid_pattern(p, 256)
772 })?;
773 check_set(s.never_send.as_ref(), "security.never_send", |p| {
774 valid_pattern(p, 256)
775 })?;
776 if let Some(agents) = &self.agents {
777 check_set(agents.allowed.as_ref(), "agents.allowed", |a| {
778 a == "*" || valid_name(a)
779 })?;
780 }
781 let c = &self.context;
782 check_range(
783 c.max_context_tokens,
784 1,
785 10_000_000,
786 "context.max_context_tokens",
787 )?;
788 check_enum(c.read_mode.as_ref(), READ_MODES, "context.read_mode")?;
789 if c.ranking_profile.as_deref().is_some_and(|p| !valid_name(p)) {
790 return Err(invalid("context.ranking_profile"));
791 }
792 check_set(
793 c.allowed_tools.as_ref(),
794 "context.allowed_tools",
795 valid_name,
796 )?;
797 check_set(c.denied_tools.as_ref(), "context.denied_tools", valid_name)?;
798 check_set(
799 c.allowed_sources.as_ref(),
800 "context.allowed_sources",
801 valid_name,
802 )?;
803 check_range(
804 c.max_writes_per_min,
805 0,
806 10_000,
807 "context.max_writes_per_min",
808 )?;
809 check_range(
810 c.max_cost_cents_per_person_per_day,
811 0,
812 100_000_000,
813 "context.max_cost_cents_per_person_per_day",
814 )?;
815 check_range(
816 c.max_cost_cents_per_project_per_month,
817 0,
818 100_000_000,
819 "context.max_cost_cents_per_project_per_month",
820 )?;
821 check_range(
822 c.max_requests_per_minute_per_person,
823 1,
824 1_000_000,
825 "context.max_requests_per_minute_per_person",
826 )?;
827 check_range(
828 c.max_source_age_days,
829 1,
830 3650,
831 "context.max_source_age_days",
832 )?;
833 let h = &self.sharing;
834 check_set(h.allowed_vaults.as_ref(), "sharing.allowed_vaults", |v| {
835 is_lower_hex(v, 32)
836 })?;
837 check_enum(
838 h.task_claim_min_role.as_ref(),
839 CLAIM_ROLES,
840 "sharing.task_claim_min_role",
841 )?;
842 check_set(
843 h.consent_required_for.as_ref(),
844 "sharing.consent_required_for",
845 |a| CONSENT_ACTIONS.contains(&a),
846 )?;
847 check_enum(
848 h.personal_workspace.as_ref(),
849 PERSONAL_WORKSPACE_MODES,
850 "sharing.personal_workspace",
851 )?;
852 if let Some(orchestrator) = &self.orchestrator {
853 check_range(
854 orchestrator.max_sessions_per_vault,
855 0,
856 MAX_ORCHESTRATOR_SESSIONS,
857 "orchestrator.max_sessions_per_vault",
858 )?;
859 }
860 let empty = BTreeMap::new();
861 let agents_other = self.agents.as_ref().map_or(&empty, |a| &a.other);
862 let orchestrator_other = self.orchestrator.as_ref().map_or(&empty, |o| &o.other);
863 for (section, other) in [
864 ("security", &s.other),
865 ("context", &c.other),
866 ("sharing", &h.other),
867 ("agents", agents_other),
868 ("orchestrator", orchestrator_other),
869 ] {
870 if let Some(name) = other.keys().find(|k| !valid_member_name(k)) {
871 return Err(invalid(&format!("{section}.{name}")));
872 }
873 }
874 for (section, value) in &self.other {
876 let ok = valid_member_name(section)
877 && value
878 .as_object()
879 .is_some_and(|members| members.keys().all(|k| valid_member_name(k)));
880 if !ok {
881 return Err(invalid(section));
882 }
883 }
884 Ok(())
885 }
886
887 pub fn members(&self) -> BTreeSet<String> {
889 let section = |name: &str, value: Value| -> Vec<String> {
890 value
891 .as_object()
892 .map(|fields| fields.keys().map(|k| format!("{name}.{k}")).collect())
893 .unwrap_or_default()
894 };
895 let mut out = BTreeSet::new();
896 out.extend(section(
897 "security",
898 serde_json::to_value(&self.security).unwrap_or(Value::Null),
899 ));
900 out.extend(section(
901 "context",
902 serde_json::to_value(&self.context).unwrap_or(Value::Null),
903 ));
904 out.extend(section(
905 "sharing",
906 serde_json::to_value(&self.sharing).unwrap_or(Value::Null),
907 ));
908 if let Some(agents) = &self.agents {
909 out.extend(section(
910 "agents",
911 serde_json::to_value(agents).unwrap_or(Value::Null),
912 ));
913 }
914 if let Some(orchestrator) = &self.orchestrator {
915 out.extend(section(
916 "orchestrator",
917 serde_json::to_value(orchestrator).unwrap_or(Value::Null),
918 ));
919 }
920 for (name, value) in &self.other {
921 out.extend(section(name, value.clone()));
922 }
923 out
924 }
925}
926
927pub fn is_engine_member(member: &str) -> bool {
929 ENGINE_MEMBERS.iter().any(|(m, _)| *m == member)
930}
931
932pub fn is_server_member(member: &str) -> bool {
934 SERVER_MEMBERS.contains(&member)
935}
936
937fn set_members(policy: &BundlePolicyV1) -> BTreeSet<String> {
939 let mut all = policy.effective.members();
940 for vault in &policy.vaults {
941 all.extend(vault.effective.members());
942 }
943 all
944}
945
946pub fn unenforced_members(policy: &BundlePolicyV1) -> Vec<String> {
949 set_members(policy)
950 .into_iter()
951 .filter(|m| !is_engine_member(m) && !is_server_member(m))
952 .collect()
953}
954
955pub fn server_members(policy: &BundlePolicyV1) -> Vec<String> {
957 set_members(policy)
958 .into_iter()
959 .filter(|m| is_server_member(m))
960 .collect()
961}
962
963impl EffectivePolicyBundleV1 {
964 pub fn validate(&self) -> Result<(), ValidationError> {
967 require_schema(&self.schema, EFFECTIVE_POLICY_SCHEMA)?;
968 if !prefixed_hex32(&self.org_id, "org_") {
969 return Err(ValidationError::new("org_id must be org_ and 32 hex"));
970 }
971 if !prefixed_hex32(&self.instance_id, "inst_") {
972 return Err(ValidationError::new("instance_id must be inst_ and 32 hex"));
973 }
974 if self.version == 0 {
975 return Err(ValidationError::new("version starts at 1"));
976 }
977 if self.not_after <= self.issued_at {
978 return Err(ValidationError::new("not_after must follow issued_at"));
979 }
980 if self.sources.len() > MAX_POLICY_SOURCES {
981 return Err(ValidationError::new("too many policy sources"));
982 }
983 for source in &self.sources {
984 let scope_ok = prefixed_hex32(&source.scope, "org_")
988 || (source.level == "org" && prefixed_hex32(&source.scope, "orgn_"))
989 || prefixed_hex32(&source.scope, "inst_")
990 || is_lower_hex(&source.scope, 32);
991 if !matches!(
992 source.level.as_str(),
993 "org" | "workspace" | "vault" | "instance"
994 ) || !scope_ok
995 || source.version == 0
996 {
997 return Err(ValidationError::new("a policy source is malformed"));
998 }
999 validate_digest(&source.digest, "sources.digest")?;
1000 }
1001 if self.policy.vaults.len() > MAX_POLICY_VAULTS
1002 || !self
1003 .policy
1004 .vaults
1005 .windows(2)
1006 .all(|w| w[0].vault_id < w[1].vault_id)
1007 {
1008 return Err(ValidationError::new(
1009 "policy.vaults must be at most 32, ascending by vault_id",
1010 ));
1011 }
1012 self.policy.effective.validate()?;
1013 for vault in &self.policy.vaults {
1014 if !is_lower_hex(&vault.vault_id, 32) {
1015 return Err(ValidationError::new("policy.vaults.vault_id is malformed"));
1016 }
1017 vault.effective.validate()?;
1018 }
1019 validate_digest(&self.digest, "digest")?;
1020 if !is_lower_hex(&self.key_id, 16) {
1021 return Err(ValidationError::new("key_id must be 16 lowercase hex"));
1022 }
1023 if !is_lower_hex(&self.signature, 128) {
1024 return Err(ValidationError::new("signature must be 128 lowercase hex"));
1025 }
1026 Ok(())
1027 }
1028
1029 pub fn ack(&self) -> PolicyAckRequestV1 {
1033 let mut unenforced = unenforced_members(&self.policy);
1034 unenforced.truncate(MAX_UNENFORCED);
1035 PolicyAckRequestV1 {
1036 version: self.version,
1037 digest: self.digest.clone(),
1038 unenforced,
1039 refused: None,
1040 }
1041 }
1042}
1043
1044#[cfg(test)]
1045#[path = "effective_policy_tests.rs"]
1046mod tests;