Skip to main content

lean_ctx_protocol/cloud/
effective_policy.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Unified Control: the signed effective policy of one engine (Release B,
4//! C0 2.x `schemas/policy.schema.json`).
5//!
6//! `GET /v1/policy/bundle` with `Cloud-Protocol: 2.x` keeps every 1.x member
7//! and adds `effective_policy` ([`EffectivePolicyBundleV1`], or `null` when
8//! the server has no lease signing key). Cloud merges the policy hierarchy
9//! (org → workspace → vault → engine) itself; the engine never merges, it
10//! verifies and applies the result:
11//!
12//! - signature: Ed25519 by a key-set v3 key of purpose `policy` over
13//!   [`EFFECTIVE_POLICY_SIGNATURE_DOMAIN`] ‖ canonical_json(bundle without
14//!   `signature`), 128 lowercase hex characters;
15//! - `digest` = `"sha256:" + hex(sha256(canonical_json(policy)))`
16//!   ([`policy_digest`]), the value the engine acks;
17//! - every member carries `x-enforcement`: `engine` members map onto the
18//!   gateway policy pack ([`ENGINE_MEMBERS`]), `server` members are enforced
19//!   by Cloud itself at the point their `x-server` names (`403 policy_denied
20//!   {member, level}`, [`SERVER_MEMBERS`]), `advisory` members are
21//!   distributed and shown only. The ack's `unenforced` reports what is
22//!   enforced nowhere: every member it received that this engine does not
23//!   enforce and Cloud does not enforce either ([`unenforced_members`]:
24//!   advisory members and members this engine does not know yet), never
25//!   pretending to enforce them. Server members are left out: Cloud
26//!   enforces them whatever the engine does ([`server_members`], shown
27//!   apart in status).
28//!
29//! The bundle, the effective policy and its sections accept unknown members
30//! and unknown sections (they are covered by the signature and reported as
31//! unenforced); a known member with a value outside the contract refuses the
32//! whole bundle, so the engine keeps its last valid one.
33//!
34//! ent2 (rules for agents and models) adds the optional `agents` section and
35//! the `security` members `allowed_providers`, `require_proxy`,
36//! `readable_roots` and `never_send`. This engine enforces `readable_roots`
37//! and `never_send` (ent2-3: `io_boundary` and the native hooks),
38//! `agents.allowed` (ent2-2: the MCP server refuses a client whose agent is
39//! not listed) and `allowed_providers` (ent2-4: the proxy refuses a request
40//! whose serving provider is not listed) and `require_proxy` (N1: the MCP
41//! server refuses a client whose model traffic is not routed through the
42//! LeanCTX proxy).
43//!
44//! QN2 adds the optional `orchestrator` section ([`OrchestratorPolicyV1`]).
45//! This engine enforces `orchestrator.network` (off: no Orchestrator kind is
46//! posted or relayed for the vault). It validates `cross_team_review` and
47//! `max_sessions_per_vault` but has no code path that could enforce them
48//! (Orchestrator sessions are started by the app, and a review request is
49//! not a bus kind). The C0 schema marks both `x-enforcement: advisory`, so
50//! they are [`ADVISORY_MEMBERS`] and the ack reports them as unenforced.
51
52use 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";
64/// Domain of the effective-policy signature (key-set v3 purpose `policy`).
65pub const EFFECTIVE_POLICY_SIGNATURE_DOMAIN: &str = "leanctx.cloud.effective-policy.v1\n";
66/// Largest number of `sources` and per-vault entries of one bundle.
67pub const MAX_POLICY_SOURCES: usize = 35;
68pub const MAX_POLICY_VAULTS: usize = 32;
69/// Largest `unenforced` list of an ack.
70pub const MAX_UNENFORCED: usize = 64;
71/// Error code of an ack for a version/digest this engine was not issued.
72pub const POLICY_MISMATCH: &str = "policy_mismatch";
73
74/// Bound of every set member of an effective section.
75const MAX_SET: usize = 256;
76const MAX_MODEL_GROUPS: usize = 16;
77const MAX_MODEL_GROUP: usize = 32;
78
79/// `section.member` → the gateway policy pack field that enforces it, for
80/// every member the schema marks `x-enforcement: engine` (its `x-engine`).
81pub 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
122/// `section.member` → its `x-instance` gateway pack field, for every member
123/// the schema marks `x-enforcement: instance` that this engine validates but
124/// does not enforce yet. The ack reports them as unenforced; each one moves
125/// into [`ENGINE_MEMBERS`] with its enforcement.
126///
127/// Empty: the `security` origin members (mz6/mz14) are enforced (proxy
128/// origin gate, Cloud floor) and listed in [`ENGINE_MEMBERS`].
129pub const PLANNED_ENGINE_MEMBERS: &[(&str, &str)] = &[];
130
131/// Largest `orchestrator.max_sessions_per_vault` (QN2).
132pub const MAX_ORCHESTRATOR_SESSIONS: u64 = 1000;
133
134/// Every member the schema marks `x-enforcement: server`: Cloud enforces it
135/// (its `x-server` point), this engine does not.
136pub const SERVER_MEMBERS: &[&str] = &[
137    "security.excluded_paths",
138    // C0 sync 2026-11-24: Cloud refuses a bus message of a kind outside it.
139    "sharing.agent_exchange",
140    "sharing.allowed_vaults",
141    "sharing.consent_required_for",
142    "sharing.cross_team_sharing",
143    "sharing.personal_workspace",
144    // Also honoured by the engine's metrics upload (it sends and buffers
145    // nothing when off); Cloud refuses the upload whatever the engine does.
146    "sharing.share_instance_metrics",
147    "sharing.task_claim_min_role",
148];
149
150/// Every member the schema marks `x-enforcement: advisory`.
151pub const ADVISORY_MEMBERS: &[&str] = &[
152    // Desktop pre-checks it at session start; the instance cannot see
153    // whether an agent asks for approval.
154    "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    // QN2: no Host code path can enforce them (Orchestrator sessions are
161    // started by the app; a review request is not a bus kind).
162    "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/// Filter action, loosest first (`x-merge: rank`).
169#[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"];
208/// `sharing.personal_workspace`, loosest first.
209pub 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/// `security` of an effective policy. Absent member = no level sets it.
220#[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    /// Countries of origin whose model weights are never used (catalog
239    /// `origin_country`), whatever the host.
240    #[serde(default, skip_serializing_if = "Option::is_none")]
241    pub blocked_model_origins: Option<Vec<String>>,
242    /// Countries where no model request is processed (catalog
243    /// `host_country`, vendors' own APIs included).
244    #[serde(default, skip_serializing_if = "Option::is_none")]
245    pub blocked_host_countries: Option<Vec<String>>,
246    /// `false` forbids the local opt-in to a vendor's own API processed in
247    /// CN (`x-merge: false_wins`).
248    #[serde(default, skip_serializing_if = "Option::is_none")]
249    pub vendor_direct_cn: Option<bool>,
250    /// ent2: upstream providers the proxy may forward to (`anthropic`,
251    /// `openai`, `bedrock`, `local`, …); `x-merge: intersect`.
252    #[serde(default, skip_serializing_if = "Option::is_none")]
253    pub allowed_providers: Option<Vec<String>>,
254    /// ent2: agent model traffic must go through the LeanCTX proxy;
255    /// `x-merge: or`.
256    #[serde(default, skip_serializing_if = "Option::is_none")]
257    pub require_proxy: Option<bool>,
258    /// ent2: path globs (`{project}` and `~` allowed) LeanCTX tools and
259    /// hooked native reads may read; `x-merge: intersect`.
260    #[serde(default, skip_serializing_if = "Option::is_none")]
261    pub readable_roots: Option<Vec<String>>,
262    /// ent2: gitignore globs whose content is never read into context nor
263    /// sent to a model or Cloud; `x-merge: union`.
264    #[serde(default, skip_serializing_if = "Option::is_none")]
265    pub never_send: Option<Vec<String>>,
266    /// Members this crate does not know (reported as unenforced).
267    #[serde(flatten)]
268    pub other: BTreeMap<String, Value>,
269}
270
271/// `context` of an effective policy.
272#[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/// `sharing` of an effective policy (enforced by Cloud, not the engine).
307#[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    /// `allow` | `forbid` (Cloud C line): `forbid` keeps the team's project
318    /// knowledge out of Personal workspaces (Cloud enforces W11; this engine
319    /// refuses a personal vault for a project it worked on in the team,
320    /// `core::cloud::company_bound`).
321    #[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/// `agents` of an effective policy (ent2). Absent when no level sets one of
328/// its members, so a policy without them keeps its digest.
329#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
330pub struct AgentsPolicyV1 {
331    /// Agent ids allowed to run under LeanCTX (`claude-code`, `codex`,
332    /// `acp:<id>`, `*`); `x-merge: intersect`.
333    #[serde(default, skip_serializing_if = "Option::is_none")]
334    pub allowed: Option<Vec<String>>,
335    /// Only agents that ask for approval may run; `x-merge: or`.
336    #[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/// `orchestrator` of an effective policy (QN2, the Orchestrator network;
343/// "Queen" in code). Absent when no level sets one of its members, so a
344/// policy without them keeps its digest.
345#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
346pub struct OrchestratorPolicyV1 {
347    /// `false`: the Orchestrator network is off, the Orchestrator stays
348    /// local; `x-merge: false_wins`.
349    #[serde(default, skip_serializing_if = "Option::is_none")]
350    pub network: Option<bool>,
351    /// `false`: no review across another person's host; `x-merge:
352    /// false_wins`.
353    #[serde(default, skip_serializing_if = "Option::is_none")]
354    pub cross_team_review: Option<bool>,
355    /// Sessions an Orchestrator may run at once for the vault on one host,
356    /// 0..=[`MAX_ORCHESTRATOR_SESSIONS`]; `x-merge: min`.
357    #[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/// The merged policy in normal form (schema `$defs/effective`).
364#[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    /// Sections this crate does not know: covered by the signature, every
375    /// member reported as unenforced. Accepting them keeps a later section
376    /// from making this engine refuse the whole bundle.
377    #[serde(flatten)]
378    pub other: BTreeMap<String, Value>,
379}
380
381/// The effective policy of one vault with a vault-level document.
382#[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/// `policy` of a bundle: the default for every vault without an entry, and
390/// the per-vault entries ascending by `vault_id`.
391#[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    /// The policy that applies to `vault_id` (`None`: no linked vault).
400    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/// A document that went into the bundle.
408#[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/// `effective_policy` of `GET /v1/policy/bundle` (2.x).
418#[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/// `POST /v1/policy/ack`.
434#[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    /// SERVER-B4: the engine received this bundle (`version`, `digest` as
442    /// received) but refused it; `unenforced` is then empty.
443    #[serde(default, skip_serializing_if = "Option::is_none")]
444    pub refused: Option<PolicyAckRefusalV1>,
445}
446
447/// Why an engine refused a received bundle (C0 `$defs/refusal_reason`).
448#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
449#[serde(rename_all = "snake_case")]
450pub enum PolicyRefusalReasonV1 {
451    /// Does not parse or validate.
452    InvalidBundle,
453    /// Issued for another org or engine.
454    WrongTarget,
455    /// No verified key set v3, or no valid policy key for `key_id`.
456    KeyUnavailable,
457    SignatureInvalid,
458    /// `digest` is not the policy's.
459    DigestMismatch,
460    /// An older version, or the same version with another digest.
461    Downgrade,
462    /// `not_after` already passed.
463    Expired,
464    /// Verified but could not be stored.
465    InstallFailed,
466}
467
468/// Longest `detail` of a refusal.
469pub const MAX_REFUSAL_DETAIL: usize = 300;
470
471/// `refused` of an ack (C0 `$defs/ack_refusal`): the bundle the engine
472/// keeps applying (`applied_*` both `null` when it holds none).
473#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
474#[serde(deny_unknown_fields)]
475pub struct PolicyAckRefusalV1 {
476    pub reason_code: PolicyRefusalReasonV1,
477    /// The engine's diagnostic line, no content: 1..=300 chars, no control
478    /// characters ([`refusal_detail`]).
479    #[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
485/// A diagnostic line as `detail` takes it: control characters become
486/// spaces, every place on the machine (a path, a home folder, a file URL)
487/// becomes `<path>` (K2 M2: the data directory names the user), at most
488/// [`MAX_REFUSAL_DETAIL`] characters, `None` when empty.
489///
490/// A path may hold spaces (`/Users/John Smith/…`), so the whole run is
491/// scrubbed: from the first word that names a place up to and including
492/// the first word that ends with `:` (the `in <dir>: <reason>` shape), or
493/// to the end of the line when no word does.
494pub 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    /// The refusal report of a received bundle.
530    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/// Answer of `POST /v1/policy/ack` to a refusal (C0
541/// `$defs/ack_refused_response`).
542#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
543pub struct PolicyAckRefusedResponseV1 {
544    pub schema: String,
545    pub version: u64,
546    pub digest: String,
547    /// Always `refused`.
548    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    /// The answer records exactly the refusal `request`.
557    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/// State of an ack: `outdated` when a newer bundle was issued since.
578#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
579#[serde(rename_all = "snake_case")]
580pub enum PolicyAckStateV1 {
581    Acked,
582    Outdated,
583}
584
585/// Answer of `POST /v1/policy/ack`.
586#[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    /// The answer acknowledges exactly `request`.
597    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
616/// `"sha256:" + hex(sha256(canonical_json(value)))`.
617pub fn policy_digest(value: &Value) -> Result<String, ValidationError> {
618    Ok(format!(
619        "sha256:{}",
620        hex(&Sha256::digest(canonical_json(value)?))
621    ))
622}
623
624/// The exact bytes the `policy` key signs: the raw bundle as received,
625/// without its `signature`.
626pub 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
637/// ISO 3166-1 alpha-2: two uppercase ASCII letters (`$defs/country`).
638pub 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
667/// 1..=`max` characters without C0/C1 control characters or DEL.
668fn 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
676/// A member or section name this crate does not know: 1..=64 of `a-z`, `_`.
677fn 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
687/// A set in normal form: at most [`MAX_SET`] items, strictly ascending
688/// (bytewise; sorted and without repeats), each one valid.
689fn 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    /// Schema, value ranges and normal form of every known member.
724    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        // An unknown section is an object of members like a known one.
875        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    /// Every member this policy sets, as `section.member`, sorted.
888    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
927/// Whether the engine enforces `member` (`section.member`).
928pub fn is_engine_member(member: &str) -> bool {
929    ENGINE_MEMBERS.iter().any(|(m, _)| *m == member)
930}
931
932/// Whether Cloud enforces `member` itself (`x-enforcement: server`).
933pub fn is_server_member(member: &str) -> bool {
934    SERVER_MEMBERS.contains(&member)
935}
936
937/// Every member `policy` sets anywhere (default or any vault), sorted.
938fn 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
946/// The members `policy` sets that neither this engine nor Cloud enforces
947/// (advisory and unknown members), sorted bytewise: what an ack reports.
948pub 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
955/// The members `policy` sets that Cloud enforces itself, sorted bytewise.
956pub 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    /// Everything but the signature and the policy digest, which need the
965    /// raw bytes ([`signing_input_raw`], [`policy_digest`]).
966    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            // `orgn_` names an organisation's own org-level document (a
985            // workspace linked to an organisation, C0 `$defs/source`): only
986            // at level `org`.
987            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    /// The ack for this bundle as applied. The wire carries at most
1030    /// [`MAX_UNENFORCED`] members (the schema bound, more than the contract
1031    /// defines); the full list stays in the engine's own status.
1032    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;