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