Skip to main content

lean_ctx/core/policy/
mod.rs

1//! Context Policy Packs v1 — Policies-as-Code (GL #489).
2//!
3//! A policy pack is a declarative, versioned governance preset: which tools an
4//! agent may call, the default read mode, redaction patterns for sensitive
5//! data, an audit-retention expectation and a context-budget cap. Packs are
6//! plain TOML, support single inheritance via `extends`, and resolve into one
7//! [`ResolvedPolicy`] a team can review like code.
8//!
9//! v1 ships the **format, validation, resolution, curated built-ins and the
10//! `lean-ctx policy` CLI** (see `cli::policy_cmd`). Runtime enforcement wires
11//! in afterward (deliberately decoupled so this module stays free of hot-path
12//! churn — see the contract `docs/contracts/context-policy-packs-v1.md`).
13//!
14//! Inheritance semantics are security-first and predictable:
15//! - scalars (`default_read_mode`, `max_context_tokens`,
16//!   `audit_retention_days`) — the child **overrides** when set;
17//! - `deny_tools` and `[redaction]` — **accumulate** down the chain
18//!   (restrictions inherited from a parent can never be silently dropped;
19//!   a child may only tighten or re-point a named redaction pattern);
20//! - `allow_tools` — the child **overrides** when set (an allowlist is a
21//!   deliberate posture choice, not an accumulating set).
22
23pub mod audit_filter;
24pub mod builtin;
25pub mod cloud_agents;
26pub mod cloud_filters;
27pub mod cloud_floor;
28pub mod cloud_io;
29pub mod cloud_orchestrator;
30pub mod content;
31pub mod coverage;
32pub mod diagnostics;
33pub mod floor;
34pub mod org;
35pub mod personal_rules;
36pub mod runtime;
37
38use std::collections::{BTreeMap, BTreeSet};
39use std::path::Path;
40
41use serde::{Deserialize, Serialize};
42
43pub mod files;
44
45/// Maximum `extends` chain depth (defense against runaway chains; built-ins
46/// use at most 2).
47const MAX_EXTENDS_DEPTH: usize = 8;
48
49/// Read modes a pack may pin as `default_read_mode` — the documented
50/// `ctx_read` mode vocabulary (range reads like `lines:N-M` are call-site
51/// specific and make no sense as a policy default).
52pub const KNOWN_READ_MODES: &[&str] = &[
53    "auto",
54    "full",
55    "map",
56    "signatures",
57    "diff",
58    "task",
59    "reference",
60    "aggressive",
61    "entropy",
62];
63
64// ── Wire format ──────────────────────────────────────────────────────────────
65
66/// One policy pack as written in TOML. Unknown keys are rejected so a typo
67/// (`alow_tools`) fails validation instead of silently weakening a policy.
68#[derive(Debug, Clone, Serialize, Deserialize)]
69#[serde(deny_unknown_fields)]
70pub struct PolicyPack {
71    /// Stable identifier: lowercase, digits and hyphens (`acme-platform`).
72    pub name: String,
73    /// Semantic version of the pack itself (`1.0.0`).
74    pub version: String,
75    /// One-line human description.
76    pub description: String,
77    /// Optional parent pack (built-in name) this pack inherits from.
78    #[serde(default, skip_serializing_if = "Option::is_none")]
79    pub extends: Option<String>,
80    /// Context-governance expectations.
81    #[serde(default)]
82    pub context: ContextRules,
83    /// Named redaction patterns: name → regex (matched against content before
84    /// it enters the model context).
85    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
86    pub redaction: BTreeMap<String, String>,
87    /// Inbound content filters (PII / classification / prompt-injection) — the
88    /// input side of the Great Filter (GL #675).
89    #[serde(default, skip_serializing_if = "FilterRules::is_empty")]
90    pub filters: FilterRules,
91    /// Egress/output DLP on agent writes & actions (GL #676).
92    #[serde(default, skip_serializing_if = "EgressRules::is_empty")]
93    pub egress: EgressRules,
94    /// Gateway routing governance: model allowlist + downgrade exemptions
95    /// (enterprise#25). Enforced by the org gateway under a signed policy.
96    #[serde(default, skip_serializing_if = "RoutingPolicyRules::is_empty")]
97    pub routing: RoutingPolicyRules,
98    /// Hard org spend caps per person/project (enterprise#25).
99    #[serde(default, skip_serializing_if = "BudgetRules::is_empty")]
100    pub budgets: BudgetRules,
101}
102
103/// The `[context]` section of a pack. All fields optional — only what a pack
104/// states is constrained; everything else stays at engine defaults.
105#[derive(Debug, Clone, Default, Serialize, Deserialize)]
106#[serde(deny_unknown_fields)]
107pub struct ContextRules {
108    /// Default `ctx_read` mode the policy expects (see [`KNOWN_READ_MODES`]).
109    #[serde(default, skip_serializing_if = "Option::is_none")]
110    pub default_read_mode: Option<String>,
111    /// Allowlist of tool names; when set, only these may be called.
112    #[serde(default, skip_serializing_if = "Option::is_none")]
113    pub allow_tools: Option<Vec<String>>,
114    /// Denylist of tool names; always additive down the `extends` chain.
115    #[serde(default, skip_serializing_if = "Vec::is_empty")]
116    pub deny_tools: Vec<String>,
117    /// Upper bound on tokens a single context assembly may spend.
118    #[serde(default, skip_serializing_if = "Option::is_none")]
119    pub max_context_tokens: Option<u32>,
120    /// Audit-retention expectation in days (governance intent; the hosted
121    /// plane enforces its own plan window — see org-audit-log-v1).
122    #[serde(default, skip_serializing_if = "Option::is_none")]
123    pub audit_retention_days: Option<u32>,
124}
125
126/// The `[filters]` section — inbound content detectors (GL #675). Each action
127/// is one of `off` / `warn` / `redact` / `block` (absent ⇒ `off`). Compiled
128/// into a [`crate::core::input_filters::FilterConfig`] at load time and run on
129/// tool output before it reaches the agent.
130#[derive(Debug, Clone, Default, Serialize, Deserialize)]
131#[serde(deny_unknown_fields)]
132pub struct FilterRules {
133    /// PII detection (email, phone, payment cards).
134    #[serde(default, skip_serializing_if = "Option::is_none")]
135    pub pii: Option<String>,
136    /// Data-classification marking gate (confidential/secret banners).
137    #[serde(default, skip_serializing_if = "Option::is_none")]
138    pub classification: Option<String>,
139    /// Prompt-injection detection (OWASP LLM01) on inbound content.
140    #[serde(default, skip_serializing_if = "Option::is_none")]
141    pub injection: Option<String>,
142    /// Classification labels that gate; overrides the built-in default set.
143    /// Accumulates down the `extends` chain (a child may add, never drop).
144    #[serde(default, skip_serializing_if = "Vec::is_empty")]
145    pub blocked_labels: Vec<String>,
146    /// Named inbound block patterns. Evaluated on original content before any
147    /// masking; inherited and organizational restrictions accumulate.
148    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
149    pub blocked_patterns: BTreeMap<String, String>,
150    /// Ownership of locally published personal rules; never infer ownership from
151    /// a prefix used by an existing hand-authored policy.
152    #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
153    pub managed_personal_rules: BTreeSet<String>,
154}
155
156impl FilterRules {
157    /// True when no filter is configured (all actions absent, no labels).
158    #[must_use]
159    pub fn is_empty(&self) -> bool {
160        self.pii.is_none()
161            && self.classification.is_none()
162            && self.injection.is_none()
163            && self.blocked_labels.is_empty()
164            && self.blocked_patterns.is_empty()
165            && self.managed_personal_rules.is_empty()
166    }
167}
168
169/// Same-name restrictions retain both patterns. Bounds are checked again when
170/// compiling the resolved policy; oversized composition denies all access.
171pub(super) fn merge_block_patterns(
172    target: &mut BTreeMap<String, String>,
173    incoming: &BTreeMap<String, String>,
174) {
175    for (name, pattern) in incoming {
176        match target.get_mut(name) {
177            Some(previous) if previous != pattern => {
178                *previous = format!("(?:{previous})|(?:{pattern})");
179            }
180            Some(_) => {}
181            None => {
182                target.insert(name.clone(), pattern.clone());
183            }
184        }
185    }
186}
187
188/// The `[egress]` section — output/DLP enforcement on agent writes & actions
189/// (GL #676). Gates `ctx_edit` writes and `ctx_shell` actions before they
190/// execute. Compiled into a `crate::core::egress::EgressConfig` at load time.
191#[derive(Debug, Clone, Default, Serialize, Deserialize)]
192#[serde(deny_unknown_fields)]
193pub struct EgressRules {
194    /// Regexes that block a write/action when matched (e.g. a prod-DB DSN).
195    /// Accumulates down the `extends` chain.
196    #[serde(default, skip_serializing_if = "Vec::is_empty")]
197    pub forbidden_patterns: Vec<String>,
198    /// Block writes/actions carrying detected secrets or PII.
199    #[serde(default, skip_serializing_if = "Option::is_none")]
200    pub block_secrets: Option<bool>,
201    /// Rate limit: max agent write/action tool calls per 60 s.
202    #[serde(default, skip_serializing_if = "Option::is_none")]
203    pub max_writes_per_min: Option<u32>,
204}
205
206impl EgressRules {
207    /// True when no egress rule is configured.
208    #[must_use]
209    pub fn is_empty(&self) -> bool {
210        self.forbidden_patterns.is_empty()
211            && self.block_secrets.is_none()
212            && self.max_writes_per_min.is_none()
213    }
214}
215
216/// The `[routing]` section — org gateway routing governance (enterprise#25,
217/// Doc 08 §4.3). Enforced in the gateway forward path when this pack arrives
218/// via a signed, trusted, `enforced = true` [`org::OrgPolicyV1`].
219#[derive(Debug, Clone, Default, Serialize, Deserialize)]
220#[serde(deny_unknown_fields)]
221pub struct RoutingPolicyRules {
222    /// Model allowlist patterns (`"claude-*"`, `"gpt-4o-mini"`). A request for
223    /// a model matching none of them is refused org-wide. Empty = no
224    /// restriction. Accumulates down the `extends` chain (union — the floor
225    /// merge then intersects org vs. local, see `floor`).
226    #[serde(default, skip_serializing_if = "Vec::is_empty")]
227    pub allowed_models: Vec<String>,
228    /// Additional conjunctive ceilings. Every group must match; an empty
229    /// group denies every model. Preserves glob intersections without turning
230    /// a disjoint intersection into the unrestricted empty primary list.
231    #[serde(default, skip_serializing_if = "Vec::is_empty")]
232    pub model_ceiling_groups: Vec<Vec<String>>,
233    /// Projects whose requests the router must never downgrade to a cheaper
234    /// tier (`["security", "prod"]`). Accumulates down the chain.
235    #[serde(default, skip_serializing_if = "Vec::is_empty")]
236    pub forbid_downgrade_for: Vec<String>,
237    /// Countries of origin (ISO 3166-1 alpha-2, the model catalog's
238    /// `origin_country`) whose model weights are never used, whatever the
239    /// host (mz14). Accumulates (union) down the chain and across the floor.
240    #[serde(default, skip_serializing_if = "Vec::is_empty")]
241    pub blocked_model_origins: Vec<String>,
242    /// Countries where no model request is processed: a catalog host's
243    /// `host_country`, and a vendor's own API (`[[direct]]`). Union.
244    #[serde(default, skip_serializing_if = "Vec::is_empty")]
245    pub blocked_host_countries: Vec<String>,
246    /// `Some(false)` voids the local `[proxy] allow_vendor_direct_cn` opt-in.
247    /// `false` wins over `true` in every merge; `true` grants nothing by
248    /// itself (the opt-in stays local).
249    #[serde(default, skip_serializing_if = "Option::is_none")]
250    pub vendor_direct_cn: Option<bool>,
251}
252
253impl RoutingPolicyRules {
254    /// True when no routing governance is configured.
255    #[must_use]
256    pub fn is_empty(&self) -> bool {
257        self.allowed_models.is_empty()
258            && self.model_ceiling_groups.is_empty()
259            && self.forbid_downgrade_for.is_empty()
260            && self.blocked_model_origins.is_empty()
261            && self.blocked_host_countries.is_empty()
262            && self.vendor_direct_cn.is_none()
263    }
264
265    /// Whether `country` is a blocked model origin.
266    #[must_use]
267    pub fn origin_blocked(&self, country: &str) -> bool {
268        self.blocked_model_origins.iter().any(|c| c == country)
269    }
270
271    /// Whether `country` is a blocked host country.
272    #[must_use]
273    pub fn host_blocked(&self, country: &str) -> bool {
274        self.blocked_host_countries.iter().any(|c| c == country)
275    }
276
277    /// Apply all inherited ceilings to one explicitly selected model.
278    #[must_use]
279    pub fn model_allowed(&self, model: &str) -> bool {
280        model_allowed_by_ceilings(&self.allowed_models, &self.model_ceiling_groups, model)
281    }
282}
283
284/// Keep the first occurrence of every exact conjunction, including deny-all
285/// empty groups. Reapplying a floor must not multiply identical checks.
286fn unique_model_ceilings<'a>(groups: impl Iterator<Item = &'a Vec<String>>) -> Vec<Vec<String>> {
287    let mut seen = std::collections::BTreeSet::new();
288    groups
289        .filter(|group| seen.insert(*group))
290        .cloned()
291        .collect()
292}
293
294pub fn model_allowed_by_ceilings(primary: &[String], groups: &[Vec<String>], model: &str) -> bool {
295    let matches = |patterns: &[String]| {
296        patterns
297            .iter()
298            .any(|pattern| model_pattern_matches(pattern, model))
299    };
300    (primary.is_empty() || matches(primary)) && groups.iter().all(|group| matches(group))
301}
302
303/// Glob-lite matching shared by project admission and the gateway.
304pub fn model_pattern_matches(pattern: &str, model: &str) -> bool {
305    let pattern = pattern.trim().as_bytes();
306    let model = model.trim().as_bytes();
307    // Dynamic programming avoids exponential wildcard backtracking.
308    let mut matched = vec![false; model.len() + 1];
309    matched[0] = true;
310    for &byte in pattern {
311        if byte == b'*' {
312            for index in 1..=model.len() {
313                matched[index] |= matched[index - 1];
314            }
315        } else {
316            for index in (1..=model.len()).rev() {
317                matched[index] = matched[index - 1] && model[index - 1] == byte;
318            }
319            matched[0] = false;
320        }
321    }
322    matched[model.len()]
323}
324
325/// The `[budgets]` section — hard org spend caps (enterprise#25, Doc 08 §4.3).
326/// USD amounts against the measured `cost_usd` of the usage meter; breaching a
327/// cap makes the gateway refuse further requests (429) until the window rolls.
328#[derive(Debug, Clone, Default, Serialize, Deserialize)]
329#[serde(deny_unknown_fields)]
330pub struct BudgetRules {
331    /// Max measured spend per person per UTC day.
332    #[serde(default, skip_serializing_if = "Option::is_none")]
333    pub max_cost_usd_per_person_per_day: Option<f64>,
334    /// Max measured spend per project per UTC month.
335    #[serde(default, skip_serializing_if = "Option::is_none")]
336    pub max_cost_usd_per_project_per_month: Option<f64>,
337    /// Max accepted requests per person per UTC minute (enterprise#66) —
338    /// protects shared upstreams from a single runaway agent. Counted per
339    /// gateway process; multi-replica deployments multiply accordingly.
340    #[serde(default, skip_serializing_if = "Option::is_none")]
341    pub max_requests_per_minute_per_person: Option<u32>,
342}
343
344impl BudgetRules {
345    /// True when no cap is configured.
346    #[must_use]
347    pub fn is_empty(&self) -> bool {
348        self.max_cost_usd_per_person_per_day.is_none()
349            && self.max_cost_usd_per_project_per_month.is_none()
350            && self.max_requests_per_minute_per_person.is_none()
351    }
352}
353
354// ── Resolved view ────────────────────────────────────────────────────────────
355
356/// A pack with its full `extends` chain folded in — what enforcement and
357/// `policy show` consume.
358#[derive(Debug, Clone, Serialize)]
359pub struct ResolvedPolicy {
360    pub name: String,
361    pub version: String,
362    pub description: String,
363    /// Inheritance chain, base-most first (`["baseline", "strict-redaction"]`
364    /// for a pack extending `strict-redaction`). Empty for root packs.
365    pub chain: Vec<String>,
366    pub default_read_mode: Option<String>,
367    pub allow_tools: Option<Vec<String>>,
368    pub deny_tools: Vec<String>,
369    pub max_context_tokens: Option<u32>,
370    pub audit_retention_days: Option<u32>,
371    pub redaction: BTreeMap<String, String>,
372    /// Folded inbound-filter actions + label set (GL #675).
373    #[serde(default, skip_serializing_if = "FilterRules::is_empty")]
374    pub filters: FilterRules,
375    /// Folded egress/output DLP rules (GL #676).
376    #[serde(default, skip_serializing_if = "EgressRules::is_empty")]
377    pub egress: EgressRules,
378    /// Folded gateway routing governance (enterprise#25).
379    #[serde(default, skip_serializing_if = "RoutingPolicyRules::is_empty")]
380    pub routing: RoutingPolicyRules,
381    /// Folded org spend caps (enterprise#25).
382    #[serde(default, skip_serializing_if = "BudgetRules::is_empty")]
383    pub budgets: BudgetRules,
384}
385
386// ── Errors ───────────────────────────────────────────────────────────────────
387
388/// Why a pack failed to parse, validate or resolve. Rendered verbatim by the
389/// CLI, so every variant names the offending field and value.
390#[derive(Debug, Clone, PartialEq, Eq)]
391pub enum PolicyError {
392    Toml(String),
393    InvalidName(String),
394    InvalidVersion(String),
395    EmptyDescription,
396    UnknownReadMode(String),
397    BadRegex { pattern_name: String, error: String },
398    ZeroMaxTokens,
399    AllowDenyOverlap(Vec<String>),
400    UnknownParent(String),
401    ExtendsCycle(Vec<String>),
402    ExtendsTooDeep(usize),
403    UnknownFilterAction { field: String, value: String },
404    InvalidBudget { field: String, value: String },
405    EmptyModelPattern,
406    InvalidCountry { field: String, value: String },
407}
408
409/// `false` wins: a `false` anywhere stays `false`; otherwise any `true`.
410#[must_use]
411pub fn false_wins(a: Option<bool>, b: Option<bool>) -> Option<bool> {
412    match (a, b) {
413        (Some(false), _) | (_, Some(false)) => Some(false),
414        (Some(true), _) | (_, Some(true)) => Some(true),
415        (None, None) => None,
416    }
417}
418
419impl std::fmt::Display for PolicyError {
420    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
421        match self {
422            PolicyError::Toml(e) => write!(f, "not valid pack TOML: {e}"),
423            PolicyError::InvalidName(n) => write!(
424                f,
425                "invalid pack name '{n}' (use lowercase letters, digits and hyphens)"
426            ),
427            PolicyError::InvalidVersion(v) => {
428                write!(f, "invalid version '{v}' (expected MAJOR.MINOR.PATCH)")
429            }
430            PolicyError::EmptyDescription => write!(f, "description must not be empty"),
431            PolicyError::UnknownReadMode(m) => write!(
432                f,
433                "unknown default_read_mode '{m}' (one of: {})",
434                KNOWN_READ_MODES.join(", ")
435            ),
436            PolicyError::BadRegex {
437                pattern_name,
438                error,
439            } => write!(
440                f,
441                "redaction pattern '{pattern_name}' is not a valid regex: {error}"
442            ),
443            PolicyError::ZeroMaxTokens => write!(f, "max_context_tokens must be greater than 0"),
444            PolicyError::AllowDenyOverlap(tools) => write!(
445                f,
446                "tools listed in both allow_tools and deny_tools: {}",
447                tools.join(", ")
448            ),
449            PolicyError::UnknownParent(p) => match builtin::paid_tier(p) {
450                Some(_) => write!(f, "extends {}", builtin::unknown_pack_hint(p)),
451                None => write!(
452                    f,
453                    "extends '{p}' does not name a known pack (built-ins: {})",
454                    builtin::names().join(", ")
455                ),
456            },
457            PolicyError::ExtendsCycle(chain) => {
458                write!(f, "extends cycle: {}", chain.join(" -> "))
459            }
460            PolicyError::ExtendsTooDeep(d) => write!(
461                f,
462                "extends chain deeper than {MAX_EXTENDS_DEPTH} (found {d}) — flatten the hierarchy"
463            ),
464            PolicyError::UnknownFilterAction { field, value } => write!(
465                f,
466                "filters.{field} '{value}' is not a valid action (one of: off, warn, redact, block)"
467            ),
468            PolicyError::InvalidBudget { field, value } => write!(
469                f,
470                "budgets.{field} must be a positive, finite USD amount (got {value})"
471            ),
472            PolicyError::EmptyModelPattern => {
473                write!(f, "routing.allowed_models must not contain empty patterns")
474            }
475            PolicyError::InvalidCountry { field, value } => write!(
476                f,
477                "routing.{field} '{value}' is not an ISO 3166-1 alpha-2 country code (e.g. \"CN\")"
478            ),
479        }
480    }
481}
482
483impl std::error::Error for PolicyError {}
484
485// ── Parse + validate ─────────────────────────────────────────────────────────
486
487/// Parse one pack from TOML text (no I/O) and validate it standalone.
488/// `extends` is checked against the built-ins during [`resolve`].
489pub fn parse(toml_text: &str) -> Result<PolicyPack, PolicyError> {
490    let pack: PolicyPack =
491        toml::from_str(toml_text).map_err(|e| PolicyError::Toml(e.to_string()))?;
492    validate(&pack)?;
493    Ok(pack)
494}
495
496/// Parse a pack from a file path. Read errors surface as [`PolicyError::Toml`]
497/// with the OS message — the CLI shows them verbatim.
498pub fn parse_file(path: &Path) -> Result<PolicyPack, PolicyError> {
499    let text = files::read(path, true)
500        .map_err(PolicyError::Toml)?
501        .ok_or_else(|| PolicyError::Toml("policy input is missing".into()))?;
502    parse(&text)
503}
504
505/// Field-level validation of a single (unresolved) pack.
506/// Label prefix of the rules a Cloud filter pack adds.
507pub(crate) const CLOUD_LABEL_PREFIX: &str = "cloud:";
508
509/// Whether `label` is a Cloud filter-pack label.
510pub(crate) fn is_cloud_label(label: &str) -> bool {
511    label.starts_with(CLOUD_LABEL_PREFIX)
512}
513
514pub fn validate(pack: &PolicyPack) -> Result<(), PolicyError> {
515    if pack.name.is_empty()
516        || !pack
517            .name
518            .bytes()
519            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
520        || pack.name.starts_with('-')
521        || pack.name.ends_with('-')
522    {
523        return Err(PolicyError::InvalidName(pack.name.clone()));
524    }
525    if !valid_semver(&pack.version) {
526        return Err(PolicyError::InvalidVersion(pack.version.clone()));
527    }
528    if pack.description.trim().is_empty() {
529        return Err(PolicyError::EmptyDescription);
530    }
531    if let Some(mode) = pack.context.default_read_mode.as_deref()
532        && !KNOWN_READ_MODES.contains(&mode)
533    {
534        return Err(PolicyError::UnknownReadMode(mode.to_string()));
535    }
536    if let Some(max) = pack.context.max_context_tokens
537        && max == 0
538    {
539        return Err(PolicyError::ZeroMaxTokens);
540    }
541    if let Some(allow) = &pack.context.allow_tools {
542        let deny: BTreeSet<&str> = pack.context.deny_tools.iter().map(String::as_str).collect();
543        let overlap: Vec<String> = allow
544            .iter()
545            .filter(|t| deny.contains(t.as_str()))
546            .cloned()
547            .collect();
548        if !overlap.is_empty() {
549            return Err(PolicyError::AllowDenyOverlap(overlap));
550        }
551    }
552    if pack.redaction.len() + pack.filters.blocked_patterns.len() > content::MAX_REDACTION_RULES
553        || pack.egress.forbidden_patterns.len() > content::MAX_REDACTION_RULES
554        || pack.filters.managed_personal_rules.len() > 32
555    {
556        return Err(PolicyError::BadRegex {
557            pattern_name: "policy".into(),
558            error: "too many policy patterns".into(),
559        });
560    }
561    // `cloud:` labels belong to the Cloud filter packs; a pack using one
562    // could shadow or be shadowed by a Cloud rule.
563    if pack
564        .redaction
565        .keys()
566        .chain(pack.filters.blocked_patterns.keys())
567        .any(|label| is_cloud_label(label))
568    {
569        return Err(PolicyError::BadRegex {
570            pattern_name: "policy".into(),
571            error: format!(
572                "rule labels starting with `{CLOUD_LABEL_PREFIX}` or `cloud:` are reserved for Cloud filter packs"
573            ),
574        });
575    }
576    if pack.filters.managed_personal_rules.iter().any(|name| {
577        !name.starts_with("personal_")
578            || name.len() <= 9
579            || name.len() > content::MAX_RULE_LABEL_BYTES
580            || !name
581                .bytes()
582                .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"_-".contains(&b))
583            || (!pack.redaction.contains_key(name)
584                && !pack.filters.blocked_patterns.contains_key(name))
585    }) {
586        return Err(PolicyError::BadRegex {
587            pattern_name: "policy".into(),
588            error: "invalid personal rule ownership".into(),
589        });
590    }
591    for (name, pattern) in pack.redaction.iter().chain(&pack.filters.blocked_patterns) {
592        if name.is_empty()
593            || name.len() > content::MAX_RULE_LABEL_BYTES
594            || name.chars().any(char::is_control)
595            || pattern.len() > content::MAX_RULE_PATTERN_BYTES
596        {
597            return Err(PolicyError::BadRegex {
598                pattern_name: "redaction".into(),
599                error: "policy pattern bounds exceeded".into(),
600            });
601        }
602        if let Err(e) = regex::RegexBuilder::new(pattern)
603            .size_limit(1024 * 1024)
604            .dfa_size_limit(1024 * 1024)
605            .build()
606        {
607            return Err(PolicyError::BadRegex {
608                pattern_name: name.clone(),
609                error: e.to_string(),
610            });
611        }
612    }
613    validate_filter_action("pii", pack.filters.pii.as_deref())?;
614    validate_filter_action("classification", pack.filters.classification.as_deref())?;
615    validate_filter_action("injection", pack.filters.injection.as_deref())?;
616    for pattern in &pack.egress.forbidden_patterns {
617        if pattern.len() > content::MAX_RULE_PATTERN_BYTES {
618            return Err(PolicyError::BadRegex {
619                pattern_name: "egress.forbidden_patterns".into(),
620                error: "policy pattern bounds exceeded".into(),
621            });
622        }
623        if let Err(e) = regex::RegexBuilder::new(pattern)
624            .size_limit(1024 * 1024)
625            .dfa_size_limit(1024 * 1024)
626            .build()
627        {
628            return Err(PolicyError::BadRegex {
629                pattern_name: format!("egress.forbidden_patterns: {pattern}"),
630                error: e.to_string(),
631            });
632        }
633    }
634    if pack
635        .routing
636        .allowed_models
637        .iter()
638        .chain(pack.routing.model_ceiling_groups.iter().flatten())
639        .any(|p| p.trim().is_empty())
640    {
641        return Err(PolicyError::EmptyModelPattern);
642    }
643    for (field, countries) in [
644        ("blocked_model_origins", &pack.routing.blocked_model_origins),
645        (
646            "blocked_host_countries",
647            &pack.routing.blocked_host_countries,
648        ),
649    ] {
650        if let Some(bad) = countries
651            .iter()
652            .find(|c| !lean_ctx_protocol::cloud::effective_policy::is_country(c))
653        {
654            return Err(PolicyError::InvalidCountry {
655                field: field.into(),
656                value: bad.clone(),
657            });
658        }
659    }
660    validate_budget(
661        "max_cost_usd_per_person_per_day",
662        pack.budgets.max_cost_usd_per_person_per_day,
663    )?;
664    validate_budget(
665        "max_cost_usd_per_project_per_month",
666        pack.budgets.max_cost_usd_per_project_per_month,
667    )?;
668    Ok(())
669}
670
671/// A budget cap must be a positive, finite USD amount.
672fn validate_budget(field: &str, value: Option<f64>) -> Result<(), PolicyError> {
673    if let Some(v) = value
674        && !(v.is_finite() && v > 0.0)
675    {
676        return Err(PolicyError::InvalidBudget {
677            field: field.to_string(),
678            value: v.to_string(),
679        });
680    }
681    Ok(())
682}
683
684/// Reject a `[filters]` action that is not a known token.
685fn validate_filter_action(field: &str, value: Option<&str>) -> Result<(), PolicyError> {
686    if let Some(v) = value
687        && crate::core::input_filters::FilterAction::parse(v).is_none()
688    {
689        return Err(PolicyError::UnknownFilterAction {
690            field: field.to_string(),
691            value: v.to_string(),
692        });
693    }
694    Ok(())
695}
696
697/// `MAJOR.MINOR.PATCH`, digits only — packs don't need pre-release tags.
698fn valid_semver(v: &str) -> bool {
699    let parts: Vec<&str> = v.split('.').collect();
700    parts.len() == 3
701        && parts
702            .iter()
703            .all(|p| !p.is_empty() && p.len() <= 6 && p.bytes().all(|b| b.is_ascii_digit()))
704}
705
706// ── Resolve (extends) ────────────────────────────────────────────────────────
707
708/// Fold a pack's `extends` chain (against the built-ins) into one
709/// [`ResolvedPolicy`]. See the module docs for the inheritance semantics.
710pub fn resolve(pack: &PolicyPack) -> Result<ResolvedPolicy, PolicyError> {
711    // Walk to the root, collecting the chain (child first).
712    let mut lineage: Vec<PolicyPack> = vec![pack.clone()];
713    let mut seen: Vec<String> = vec![pack.name.clone()];
714    let mut next_parent = pack.extends.clone();
715    while let Some(parent_name) = next_parent.take() {
716        if seen.contains(&parent_name) {
717            seen.push(parent_name);
718            return Err(PolicyError::ExtendsCycle(seen));
719        }
720        if lineage.len() >= MAX_EXTENDS_DEPTH {
721            return Err(PolicyError::ExtendsTooDeep(lineage.len() + 1));
722        }
723        let parent =
724            builtin::get(&parent_name).ok_or(PolicyError::UnknownParent(parent_name.clone()))?;
725        seen.push(parent_name);
726        next_parent.clone_from(&parent.extends);
727        lineage.push(parent);
728    }
729
730    // Fold base-most first so children override scalars and accumulate
731    // restrictions on top.
732    let mut resolved = ResolvedPolicy {
733        name: pack.name.clone(),
734        version: pack.version.clone(),
735        description: pack.description.clone(),
736        chain: seen.iter().skip(1).rev().cloned().collect(),
737        default_read_mode: None,
738        allow_tools: None,
739        deny_tools: Vec::new(),
740        max_context_tokens: None,
741        audit_retention_days: None,
742        redaction: BTreeMap::new(),
743        filters: FilterRules::default(),
744        egress: EgressRules::default(),
745        routing: RoutingPolicyRules::default(),
746        budgets: BudgetRules::default(),
747    };
748    for layer in lineage.iter().rev() {
749        if let Some(mode) = &layer.context.default_read_mode {
750            resolved.default_read_mode = Some(mode.clone());
751        }
752        if let Some(allow) = &layer.context.allow_tools {
753            resolved.allow_tools = Some(allow.clone());
754        }
755        for tool in &layer.context.deny_tools {
756            if !resolved.deny_tools.contains(tool) {
757                resolved.deny_tools.push(tool.clone());
758            }
759        }
760        if let Some(max) = layer.context.max_context_tokens {
761            resolved.max_context_tokens = Some(max);
762        }
763        if let Some(days) = layer.context.audit_retention_days {
764            resolved.audit_retention_days = Some(days);
765        }
766        for (name, pattern) in &layer.redaction {
767            resolved.redaction.insert(name.clone(), pattern.clone());
768        }
769        // Filter actions override (child wins); labels accumulate.
770        if let Some(v) = &layer.filters.pii {
771            resolved.filters.pii = Some(v.clone());
772        }
773        if let Some(v) = &layer.filters.classification {
774            resolved.filters.classification = Some(v.clone());
775        }
776        if let Some(v) = &layer.filters.injection {
777            resolved.filters.injection = Some(v.clone());
778        }
779        for label in &layer.filters.blocked_labels {
780            if !resolved.filters.blocked_labels.contains(label) {
781                resolved.filters.blocked_labels.push(label.clone());
782            }
783        }
784        merge_block_patterns(
785            &mut resolved.filters.blocked_patterns,
786            &layer.filters.blocked_patterns,
787        );
788        resolved
789            .filters
790            .managed_personal_rules
791            .clone_from(&layer.filters.managed_personal_rules);
792        // Egress: forbidden patterns accumulate; scalars override (child wins).
793        for pattern in &layer.egress.forbidden_patterns {
794            if !resolved.egress.forbidden_patterns.contains(pattern) {
795                resolved.egress.forbidden_patterns.push(pattern.clone());
796            }
797        }
798        if let Some(v) = layer.egress.block_secrets {
799            resolved.egress.block_secrets = Some(v);
800        }
801        if let Some(v) = layer.egress.max_writes_per_min {
802            resolved.egress.max_writes_per_min = Some(v);
803        }
804        // Routing governance: restriction lists accumulate down the chain.
805        for pattern in &layer.routing.allowed_models {
806            if !resolved.routing.allowed_models.contains(pattern) {
807                resolved.routing.allowed_models.push(pattern.clone());
808            }
809        }
810        resolved.routing.model_ceiling_groups = unique_model_ceilings(
811            resolved
812                .routing
813                .model_ceiling_groups
814                .iter()
815                .chain(layer.routing.model_ceiling_groups.iter()),
816        );
817        for project in &layer.routing.forbid_downgrade_for {
818            if !resolved.routing.forbid_downgrade_for.contains(project) {
819                resolved.routing.forbid_downgrade_for.push(project.clone());
820            }
821        }
822        for country in &layer.routing.blocked_model_origins {
823            if !resolved.routing.blocked_model_origins.contains(country) {
824                resolved.routing.blocked_model_origins.push(country.clone());
825            }
826        }
827        for country in &layer.routing.blocked_host_countries {
828            if !resolved.routing.blocked_host_countries.contains(country) {
829                resolved
830                    .routing
831                    .blocked_host_countries
832                    .push(country.clone());
833            }
834        }
835        resolved.routing.vendor_direct_cn = false_wins(
836            resolved.routing.vendor_direct_cn,
837            layer.routing.vendor_direct_cn,
838        );
839        // Budgets: scalar caps override (child wins) — the floor merge takes
840        // the stricter side across org vs. local separately.
841        if let Some(v) = layer.budgets.max_cost_usd_per_person_per_day {
842            resolved.budgets.max_cost_usd_per_person_per_day = Some(v);
843        }
844        if let Some(v) = layer.budgets.max_cost_usd_per_project_per_month {
845            resolved.budgets.max_cost_usd_per_project_per_month = Some(v);
846        }
847    }
848
849    // A resolved allowlist must not collide with accumulated denies.
850    if let Some(allow) = &resolved.allow_tools {
851        let overlap: Vec<String> = allow
852            .iter()
853            .filter(|t| resolved.deny_tools.contains(*t))
854            .cloned()
855            .collect();
856        if !overlap.is_empty() {
857            return Err(PolicyError::AllowDenyOverlap(overlap));
858        }
859    }
860    Ok(resolved)
861}
862
863/// Parse + validate + resolve in one step — the common CLI path.
864pub fn load(toml_text: &str) -> Result<ResolvedPolicy, PolicyError> {
865    resolve(&parse(toml_text)?)
866}
867
868#[cfg(test)]
869mod tests {
870    use super::*;
871
872    fn minimal(name: &str, extends: Option<&str>) -> PolicyPack {
873        PolicyPack {
874            name: name.to_string(),
875            version: "1.0.0".to_string(),
876            description: "test pack".to_string(),
877            extends: extends.map(str::to_string),
878            context: ContextRules::default(),
879            redaction: BTreeMap::new(),
880            filters: FilterRules::default(),
881            egress: EgressRules::default(),
882            routing: RoutingPolicyRules::default(),
883            budgets: BudgetRules::default(),
884        }
885    }
886
887    #[test]
888    fn parses_a_full_pack() {
889        let pack = parse(
890            r#"
891name = "acme-internal"
892version = "2.1.0"
893description = "ACME internal baseline"
894extends = "strict-redaction"
895
896[context]
897default_read_mode = "map"
898deny_tools = ["ctx_url_read"]
899max_context_tokens = 12000
900audit_retention_days = 365
901
902[redaction]
903employee_id = 'EMP-\d{6}'
904"#,
905        )
906        .expect("parses");
907        assert_eq!(pack.name, "acme-internal");
908        assert_eq!(pack.extends.as_deref(), Some("strict-redaction"));
909        assert_eq!(pack.context.deny_tools, vec!["ctx_url_read"]);
910        assert!(pack.redaction.contains_key("employee_id"));
911    }
912
913    #[test]
914    fn parses_gateway_governance_sections() {
915        // enterprise#25: [routing] + [budgets] ride inside the same signed pack.
916        let resolved = load(
917            r#"
918name = "acme-gateway"
919version = "1.0.0"
920description = "org gateway governance"
921
922[routing]
923allowed_models = ["claude-*", "gpt-4o-mini"]
924forbid_downgrade_for = ["prod"]
925
926[budgets]
927max_cost_usd_per_person_per_day = 50.0
928max_cost_usd_per_project_per_month = 20000.0
929"#,
930        )
931        .expect("resolves");
932        assert_eq!(
933            resolved.routing.allowed_models,
934            vec!["claude-*".to_string(), "gpt-4o-mini".to_string()]
935        );
936        assert_eq!(resolved.routing.forbid_downgrade_for, vec!["prod"]);
937        assert_eq!(resolved.budgets.max_cost_usd_per_person_per_day, Some(50.0));
938        assert_eq!(
939            resolved.budgets.max_cost_usd_per_project_per_month,
940            Some(20000.0)
941        );
942    }
943
944    #[test]
945    fn rejects_invalid_budget_and_empty_model_pattern() {
946        let neg = parse(
947            r#"
948name = "bad-budget"
949version = "1.0.0"
950description = "x"
951
952[budgets]
953max_cost_usd_per_person_per_day = -5.0
954"#,
955        );
956        assert!(matches!(neg, Err(PolicyError::InvalidBudget { .. })));
957
958        let empty = parse(
959            r#"
960name = "bad-pattern"
961version = "1.0.0"
962description = "x"
963
964[routing]
965allowed_models = ["claude-*", " "]
966"#,
967        );
968        assert_eq!(empty.unwrap_err(), PolicyError::EmptyModelPattern);
969    }
970
971    #[test]
972    fn unknown_keys_are_rejected() {
973        let err = parse(
974            r#"
975name = "typo"
976version = "1.0.0"
977description = "x"
978
979[context]
980alow_tools = ["ctx_read"]
981"#,
982        )
983        .unwrap_err();
984        assert!(matches!(err, PolicyError::Toml(_)), "{err}");
985    }
986
987    #[test]
988    fn validation_catches_each_field() {
989        let mut p = minimal("Bad Name", None);
990        assert!(matches!(validate(&p), Err(PolicyError::InvalidName(_))));
991
992        p = minimal("ok", None);
993        p.version = "1.0".into();
994        assert!(matches!(validate(&p), Err(PolicyError::InvalidVersion(_))));
995
996        p = minimal("ok", None);
997        p.description = "  ".into();
998        assert!(matches!(validate(&p), Err(PolicyError::EmptyDescription)));
999
1000        p = minimal("ok", None);
1001        p.context.default_read_mode = Some("lines:1-5".into());
1002        assert!(matches!(validate(&p), Err(PolicyError::UnknownReadMode(_))));
1003
1004        p = minimal("ok", None);
1005        p.context.max_context_tokens = Some(0);
1006        assert!(matches!(validate(&p), Err(PolicyError::ZeroMaxTokens)));
1007
1008        p = minimal("ok", None);
1009        p.redaction.insert("broken".into(), "(unclosed".into());
1010        assert!(matches!(validate(&p), Err(PolicyError::BadRegex { .. })));
1011
1012        p = minimal("ok", None);
1013        p.context.allow_tools = Some(vec!["ctx_read".into()]);
1014        p.context.deny_tools = vec!["ctx_read".into()];
1015        assert!(matches!(
1016            validate(&p),
1017            Err(PolicyError::AllowDenyOverlap(_))
1018        ));
1019    }
1020
1021    #[test]
1022    fn resolve_overrides_scalars_and_accumulates_denies() {
1023        let mut child = minimal("child", Some("strict-redaction"));
1024        child.context.default_read_mode = Some("signatures".into());
1025        child.context.deny_tools = vec!["ctx_url_read".into(), "ctx_shell".into()];
1026        child
1027            .redaction
1028            .insert("employee_id".into(), r"EMP-\d{4}".into());
1029        let r = resolve(&child).expect("resolves");
1030
1031        // Scalar overridden by the child.
1032        assert_eq!(r.default_read_mode.as_deref(), Some("signatures"));
1033        // The child's denies apply.
1034        assert!(r.deny_tools.contains(&"ctx_url_read".to_string()));
1035        assert!(r.deny_tools.contains(&"ctx_shell".to_string()));
1036        // Redaction accumulated from the whole chain (baseline + strict + child).
1037        assert!(r.redaction.contains_key("employee_id"));
1038        assert!(r.redaction.contains_key("private_key"));
1039        // Chain is base-most first and excludes the pack itself.
1040        assert_eq!(r.chain, vec!["baseline", "strict-redaction"]);
1041    }
1042
1043    #[test]
1044    fn resolve_rejects_unknown_parent_and_cycle() {
1045        let p = minimal("orphan", Some("no-such-pack"));
1046        assert!(matches!(resolve(&p), Err(PolicyError::UnknownParent(_))));
1047
1048        // A former built-in that moved to a paid tier says so.
1049        let p = minimal("regulated", Some("healthcare"));
1050        let err = resolve(&p).expect_err("not bundled");
1051        assert!(err.to_string().contains("LeanCTX"), "{err}");
1052
1053        // Self-reference is the minimal cycle reachable without registering
1054        // custom packs (built-ins are acyclic by construction + test below).
1055        let p = minimal("loop", Some("loop"));
1056        assert!(matches!(resolve(&p), Err(PolicyError::ExtendsCycle(_))));
1057    }
1058
1059    #[test]
1060    fn child_redaction_overrides_same_named_parent_pattern() {
1061        let mut child = minimal("child", Some("baseline"));
1062        child
1063            .redaction
1064            .insert("private_key".into(), "MY-OWN-KEY-\\d+".into());
1065        let r = resolve(&child).expect("resolves");
1066        assert_eq!(r.redaction.get("private_key").unwrap(), "MY-OWN-KEY-\\d+");
1067    }
1068}