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    "sharing.allowed_vaults",
139    "sharing.consent_required_for",
140    "sharing.cross_team_sharing",
141    "sharing.personal_workspace",
142    // Also honoured by the engine's metrics upload (it sends and buffers
143    // nothing when off); Cloud refuses the upload whatever the engine does.
144    "sharing.share_instance_metrics",
145    "sharing.task_claim_min_role",
146];
147
148/// Every member the schema marks `x-enforcement: advisory`.
149pub const ADVISORY_MEMBERS: &[&str] = &[
150    // Desktop pre-checks it at session start; the instance cannot see
151    // whether an agent asks for approval.
152    "agents.require_approvals",
153    "context.allowed_sources",
154    "context.auto_extraction",
155    "context.extraction_requires_source_anchor",
156    "context.max_source_age_days",
157    "context.ranking_profile",
158    // QN2: no Host code path can enforce them (Orchestrator sessions are
159    // started by the app; a review request is not a bus kind).
160    "orchestrator.cross_team_review",
161    "orchestrator.max_sessions_per_vault",
162    "security.confidential_out_of_sharing",
163    "security.external_model_excluded_classes",
164];
165
166/// Filter action, loosest first (`x-merge: rank`).
167#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
168#[serde(rename_all = "snake_case")]
169pub enum PolicyActionV1 {
170    Off,
171    Warn,
172    Redact,
173    Block,
174}
175
176impl PolicyActionV1 {
177    pub fn as_str(self) -> &'static str {
178        match self {
179            Self::Off => "off",
180            Self::Warn => "warn",
181            Self::Redact => "redact",
182            Self::Block => "block",
183        }
184    }
185}
186
187const READ_MODES: &[&str] = &[
188    "auto",
189    "full",
190    "map",
191    "signatures",
192    "diff",
193    "task",
194    "reference",
195    "aggressive",
196    "entropy",
197];
198const DATA_CLASSES: &[&str] = &[
199    "secrets",
200    "pii",
201    "confidential",
202    "customer_data",
203    "source_code",
204];
205const CLAIM_ROLES: &[&str] = &["reader", "contributor", "maintainer", "admin", "owner"];
206/// `sharing.personal_workspace`, loosest first.
207pub const PERSONAL_WORKSPACE_MODES: &[&str] = &["allow", "forbid"];
208const CONSENT_ACTIONS: &[&str] = &[
209    "trust_boundary",
210    "permission_expansion",
211    "security_command",
212    "destructive_change",
213    "team_sharing",
214    "external_model",
215];
216
217/// `security` of an effective policy. Absent member = no level sets it.
218#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
219pub struct SecurityPolicyV1 {
220    #[serde(default, skip_serializing_if = "Option::is_none")]
221    pub excluded_paths: Option<Vec<String>>,
222    #[serde(default, skip_serializing_if = "Option::is_none")]
223    pub block_secrets: Option<bool>,
224    #[serde(default, skip_serializing_if = "Option::is_none")]
225    pub pii: Option<PolicyActionV1>,
226    #[serde(default, skip_serializing_if = "Option::is_none")]
227    pub classification: Option<PolicyActionV1>,
228    #[serde(default, skip_serializing_if = "Option::is_none")]
229    pub blocked_labels: Option<Vec<String>>,
230    #[serde(default, skip_serializing_if = "Option::is_none")]
231    pub allowed_models: Option<Vec<Vec<String>>>,
232    #[serde(default, skip_serializing_if = "Option::is_none")]
233    pub external_model_excluded_classes: Option<Vec<String>>,
234    #[serde(default, skip_serializing_if = "Option::is_none")]
235    pub confidential_out_of_sharing: Option<bool>,
236    /// Countries of origin whose model weights are never used (catalog
237    /// `origin_country`), whatever the host.
238    #[serde(default, skip_serializing_if = "Option::is_none")]
239    pub blocked_model_origins: Option<Vec<String>>,
240    /// Countries where no model request is processed (catalog
241    /// `host_country`, vendors' own APIs included).
242    #[serde(default, skip_serializing_if = "Option::is_none")]
243    pub blocked_host_countries: Option<Vec<String>>,
244    /// `false` forbids the local opt-in to a vendor's own API processed in
245    /// CN (`x-merge: false_wins`).
246    #[serde(default, skip_serializing_if = "Option::is_none")]
247    pub vendor_direct_cn: Option<bool>,
248    /// ent2: upstream providers the proxy may forward to (`anthropic`,
249    /// `openai`, `bedrock`, `local`, …); `x-merge: intersect`.
250    #[serde(default, skip_serializing_if = "Option::is_none")]
251    pub allowed_providers: Option<Vec<String>>,
252    /// ent2: agent model traffic must go through the LeanCTX proxy;
253    /// `x-merge: or`.
254    #[serde(default, skip_serializing_if = "Option::is_none")]
255    pub require_proxy: Option<bool>,
256    /// ent2: path globs (`{project}` and `~` allowed) LeanCTX tools and
257    /// hooked native reads may read; `x-merge: intersect`.
258    #[serde(default, skip_serializing_if = "Option::is_none")]
259    pub readable_roots: Option<Vec<String>>,
260    /// ent2: gitignore globs whose content is never read into context nor
261    /// sent to a model or Cloud; `x-merge: union`.
262    #[serde(default, skip_serializing_if = "Option::is_none")]
263    pub never_send: Option<Vec<String>>,
264    /// Members this crate does not know (reported as unenforced).
265    #[serde(flatten)]
266    pub other: BTreeMap<String, Value>,
267}
268
269/// `context` of an effective policy.
270#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
271pub struct ContextPolicyV1 {
272    #[serde(default, skip_serializing_if = "Option::is_none")]
273    pub max_context_tokens: Option<u64>,
274    #[serde(default, skip_serializing_if = "Option::is_none")]
275    pub injection_filter: Option<PolicyActionV1>,
276    #[serde(default, skip_serializing_if = "Option::is_none")]
277    pub read_mode: Option<String>,
278    #[serde(default, skip_serializing_if = "Option::is_none")]
279    pub ranking_profile: Option<String>,
280    #[serde(default, skip_serializing_if = "Option::is_none")]
281    pub allowed_tools: Option<Vec<String>>,
282    #[serde(default, skip_serializing_if = "Option::is_none")]
283    pub denied_tools: Option<Vec<String>>,
284    #[serde(default, skip_serializing_if = "Option::is_none")]
285    pub allowed_sources: Option<Vec<String>>,
286    #[serde(default, skip_serializing_if = "Option::is_none")]
287    pub max_writes_per_min: Option<u64>,
288    #[serde(default, skip_serializing_if = "Option::is_none")]
289    pub max_cost_cents_per_person_per_day: Option<u64>,
290    #[serde(default, skip_serializing_if = "Option::is_none")]
291    pub max_cost_cents_per_project_per_month: Option<u64>,
292    #[serde(default, skip_serializing_if = "Option::is_none")]
293    pub max_requests_per_minute_per_person: Option<u64>,
294    #[serde(default, skip_serializing_if = "Option::is_none")]
295    pub auto_extraction: Option<bool>,
296    #[serde(default, skip_serializing_if = "Option::is_none")]
297    pub extraction_requires_source_anchor: Option<bool>,
298    #[serde(default, skip_serializing_if = "Option::is_none")]
299    pub max_source_age_days: Option<u64>,
300    #[serde(flatten)]
301    pub other: BTreeMap<String, Value>,
302}
303
304/// `sharing` of an effective policy (enforced by Cloud, not the engine).
305#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
306pub struct SharingPolicyV1 {
307    #[serde(default, skip_serializing_if = "Option::is_none")]
308    pub allowed_vaults: Option<Vec<String>>,
309    #[serde(default, skip_serializing_if = "Option::is_none")]
310    pub cross_team_sharing: Option<bool>,
311    #[serde(default, skip_serializing_if = "Option::is_none")]
312    pub task_claim_min_role: Option<String>,
313    #[serde(default, skip_serializing_if = "Option::is_none")]
314    pub consent_required_for: Option<Vec<String>>,
315    /// `allow` | `forbid` (Cloud C line): `forbid` keeps the team's project
316    /// knowledge out of Personal workspaces (Cloud enforces W11; this engine
317    /// refuses a personal vault for a project it worked on in the team,
318    /// `core::cloud::company_bound`).
319    #[serde(default, skip_serializing_if = "Option::is_none")]
320    pub personal_workspace: Option<String>,
321    #[serde(flatten)]
322    pub other: BTreeMap<String, Value>,
323}
324
325/// `agents` of an effective policy (ent2). Absent when no level sets one of
326/// its members, so a policy without them keeps its digest.
327#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
328pub struct AgentsPolicyV1 {
329    /// Agent ids allowed to run under LeanCTX (`claude-code`, `codex`,
330    /// `acp:<id>`, `*`); `x-merge: intersect`.
331    #[serde(default, skip_serializing_if = "Option::is_none")]
332    pub allowed: Option<Vec<String>>,
333    /// Only agents that ask for approval may run; `x-merge: or`.
334    #[serde(default, skip_serializing_if = "Option::is_none")]
335    pub require_approvals: Option<bool>,
336    #[serde(flatten)]
337    pub other: BTreeMap<String, Value>,
338}
339
340/// `orchestrator` of an effective policy (QN2, the Orchestrator network;
341/// "Queen" in code). Absent when no level sets one of its members, so a
342/// policy without them keeps its digest.
343#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
344pub struct OrchestratorPolicyV1 {
345    /// `false`: the Orchestrator network is off, the Orchestrator stays
346    /// local; `x-merge: false_wins`.
347    #[serde(default, skip_serializing_if = "Option::is_none")]
348    pub network: Option<bool>,
349    /// `false`: no review across another person's host; `x-merge:
350    /// false_wins`.
351    #[serde(default, skip_serializing_if = "Option::is_none")]
352    pub cross_team_review: Option<bool>,
353    /// Sessions an Orchestrator may run at once for the vault on one host,
354    /// 0..=[`MAX_ORCHESTRATOR_SESSIONS`]; `x-merge: min`.
355    #[serde(default, skip_serializing_if = "Option::is_none")]
356    pub max_sessions_per_vault: Option<u64>,
357    #[serde(flatten)]
358    pub other: BTreeMap<String, Value>,
359}
360
361/// The merged policy in normal form (schema `$defs/effective`).
362#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
363pub struct EffectivePolicyV1 {
364    pub schema: String,
365    pub security: SecurityPolicyV1,
366    pub context: ContextPolicyV1,
367    pub sharing: SharingPolicyV1,
368    #[serde(default, skip_serializing_if = "Option::is_none")]
369    pub agents: Option<AgentsPolicyV1>,
370    #[serde(default, skip_serializing_if = "Option::is_none")]
371    pub orchestrator: Option<OrchestratorPolicyV1>,
372    /// Sections this crate does not know: covered by the signature, every
373    /// member reported as unenforced. Accepting them keeps a later section
374    /// from making this engine refuse the whole bundle.
375    #[serde(flatten)]
376    pub other: BTreeMap<String, Value>,
377}
378
379/// The effective policy of one vault with a vault-level document.
380#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
381#[serde(deny_unknown_fields)]
382pub struct VaultEffectivePolicyV1 {
383    pub vault_id: String,
384    pub effective: EffectivePolicyV1,
385}
386
387/// `policy` of a bundle: the default for every vault without an entry, and
388/// the per-vault entries ascending by `vault_id`.
389#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
390#[serde(deny_unknown_fields)]
391pub struct BundlePolicyV1 {
392    pub effective: EffectivePolicyV1,
393    pub vaults: Vec<VaultEffectivePolicyV1>,
394}
395
396impl BundlePolicyV1 {
397    /// The policy that applies to `vault_id` (`None`: no linked vault).
398    pub fn for_vault(&self, vault_id: Option<&str>) -> &EffectivePolicyV1 {
399        vault_id
400            .and_then(|id| self.vaults.iter().find(|v| v.vault_id == id))
401            .map_or(&self.effective, |v| &v.effective)
402    }
403}
404
405/// A document that went into the bundle.
406#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
407#[serde(deny_unknown_fields)]
408pub struct PolicySourceV1 {
409    pub level: String,
410    pub scope: String,
411    pub version: u64,
412    pub digest: String,
413}
414
415/// `effective_policy` of `GET /v1/policy/bundle` (2.x).
416#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
417pub struct EffectivePolicyBundleV1 {
418    pub schema: String,
419    pub org_id: String,
420    pub instance_id: String,
421    pub version: u64,
422    pub issued_at: UtcTimestamp,
423    pub not_after: UtcTimestamp,
424    pub sources: Vec<PolicySourceV1>,
425    pub policy: BundlePolicyV1,
426    pub digest: String,
427    pub key_id: String,
428    pub signature: String,
429}
430
431/// `POST /v1/policy/ack`.
432#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
433#[serde(deny_unknown_fields)]
434pub struct PolicyAckRequestV1 {
435    pub version: u64,
436    pub digest: String,
437    #[serde(default, skip_serializing_if = "Vec::is_empty")]
438    pub unenforced: Vec<String>,
439    /// SERVER-B4: the engine received this bundle (`version`, `digest` as
440    /// received) but refused it; `unenforced` is then empty.
441    #[serde(default, skip_serializing_if = "Option::is_none")]
442    pub refused: Option<PolicyAckRefusalV1>,
443}
444
445/// Why an engine refused a received bundle (C0 `$defs/refusal_reason`).
446#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
447#[serde(rename_all = "snake_case")]
448pub enum PolicyRefusalReasonV1 {
449    /// Does not parse or validate.
450    InvalidBundle,
451    /// Issued for another org or engine.
452    WrongTarget,
453    /// No verified key set v3, or no valid policy key for `key_id`.
454    KeyUnavailable,
455    SignatureInvalid,
456    /// `digest` is not the policy's.
457    DigestMismatch,
458    /// An older version, or the same version with another digest.
459    Downgrade,
460    /// `not_after` already passed.
461    Expired,
462    /// Verified but could not be stored.
463    InstallFailed,
464}
465
466/// Longest `detail` of a refusal.
467pub const MAX_REFUSAL_DETAIL: usize = 300;
468
469/// `refused` of an ack (C0 `$defs/ack_refusal`): the bundle the engine
470/// keeps applying (`applied_*` both `null` when it holds none).
471#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
472#[serde(deny_unknown_fields)]
473pub struct PolicyAckRefusalV1 {
474    pub reason_code: PolicyRefusalReasonV1,
475    /// The engine's diagnostic line, no content: 1..=300 chars, no control
476    /// characters ([`refusal_detail`]).
477    #[serde(default, skip_serializing_if = "Option::is_none")]
478    pub detail: Option<String>,
479    pub applied_version: Option<u64>,
480    pub applied_digest: Option<String>,
481}
482
483/// A diagnostic line as `detail` takes it: control characters become
484/// spaces, every place on the machine (a path, a home folder, a file URL)
485/// becomes `<path>` (K2 M2: the data directory names the user), at most
486/// [`MAX_REFUSAL_DETAIL`] characters, `None` when empty.
487///
488/// A path may hold spaces (`/Users/John Smith/…`), so the whole run is
489/// scrubbed: from the first word that names a place up to and including
490/// the first word that ends with `:` (the `in <dir>: <reason>` shape), or
491/// to the end of the line when no word does.
492pub fn refusal_detail(line: &str) -> Option<String> {
493    let clean: String = line
494        .chars()
495        .map(|c| if c.is_control() { ' ' } else { c })
496        .collect();
497    let place = |word: &str| {
498        word.contains('/')
499            || word.contains('\\')
500            || word.starts_with('~')
501            || (word.len() > 2
502                && word.as_bytes()[1] == b':'
503                && word.as_bytes()[0].is_ascii_alphabetic())
504    };
505    let mut words: Vec<&str> = Vec::new();
506    let mut run = false;
507    for word in clean.split(' ') {
508        if !run && !place(word) {
509            words.push(word);
510            continue;
511        }
512        run = true;
513        if word.ends_with(':') {
514            words.push("<path>:");
515            run = false;
516        }
517    }
518    if run {
519        words.push("<path>");
520    }
521    let text: String = words.join(" ").chars().take(MAX_REFUSAL_DETAIL).collect();
522    let text = text.trim();
523    (!text.is_empty()).then(|| text.to_string())
524}
525
526impl PolicyAckRequestV1 {
527    /// The refusal report of a received bundle.
528    pub fn refusal(version: u64, digest: String, refused: PolicyAckRefusalV1) -> Self {
529        Self {
530            version,
531            digest,
532            unenforced: Vec::new(),
533            refused: Some(refused),
534        }
535    }
536}
537
538/// Answer of `POST /v1/policy/ack` to a refusal (C0
539/// `$defs/ack_refused_response`).
540#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
541pub struct PolicyAckRefusedResponseV1 {
542    pub schema: String,
543    pub version: u64,
544    pub digest: String,
545    /// Always `refused`.
546    pub state: String,
547    pub reason_code: PolicyRefusalReasonV1,
548    pub applied_version: Option<u64>,
549    pub applied_digest: Option<String>,
550    pub refused_at: UtcTimestamp,
551}
552
553impl PolicyAckRefusedResponseV1 {
554    /// The answer records exactly the refusal `request`.
555    pub fn validate_for(&self, request: &PolicyAckRequestV1) -> Result<(), ValidationError> {
556        require_schema(&self.schema, POLICY_ACK_SCHEMA)?;
557        let Some(refused) = &request.refused else {
558            return Err(ValidationError::new("not a refusal request"));
559        };
560        if self.state != "refused"
561            || self.version != request.version
562            || self.digest != request.digest
563            || self.reason_code != refused.reason_code
564            || self.applied_version != refused.applied_version
565            || self.applied_digest != refused.applied_digest
566        {
567            return Err(ValidationError::new(
568                "the refusal answer names another bundle or reason",
569            ));
570        }
571        Ok(())
572    }
573}
574
575/// State of an ack: `outdated` when a newer bundle was issued since.
576#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
577#[serde(rename_all = "snake_case")]
578pub enum PolicyAckStateV1 {
579    Acked,
580    Outdated,
581}
582
583/// Answer of `POST /v1/policy/ack`.
584#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
585pub struct PolicyAckResponseV1 {
586    pub schema: String,
587    pub version: u64,
588    pub digest: String,
589    pub state: PolicyAckStateV1,
590    pub acked_at: UtcTimestamp,
591}
592
593impl PolicyAckResponseV1 {
594    /// The answer acknowledges exactly `request`.
595    pub fn validate_for(&self, request: &PolicyAckRequestV1) -> Result<(), ValidationError> {
596        require_schema(&self.schema, POLICY_ACK_SCHEMA)?;
597        if self.version != request.version || self.digest != request.digest {
598            return Err(ValidationError::new(
599                "the ack answer names another policy version or digest",
600            ));
601        }
602        Ok(())
603    }
604}
605
606fn hex(bytes: &[u8]) -> String {
607    use std::fmt::Write as _;
608    bytes.iter().fold(String::new(), |mut out, b| {
609        let _ = write!(out, "{b:02x}");
610        out
611    })
612}
613
614/// `"sha256:" + hex(sha256(canonical_json(value)))`.
615pub fn policy_digest(value: &Value) -> Result<String, ValidationError> {
616    Ok(format!(
617        "sha256:{}",
618        hex(&Sha256::digest(canonical_json(value)?))
619    ))
620}
621
622/// The exact bytes the `policy` key signs: the raw bundle as received,
623/// without its `signature`.
624pub fn signing_input_raw(raw: &Value) -> Result<Vec<u8>, ValidationError> {
625    signing_input_without_signature(EFFECTIVE_POLICY_SIGNATURE_DOMAIN, raw)
626}
627
628fn is_lower_hex(value: &str, len: usize) -> bool {
629    value.len() == len
630        && value
631            .bytes()
632            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
633}
634
635/// ISO 3166-1 alpha-2: two uppercase ASCII letters (`$defs/country`).
636pub fn is_country(value: &str) -> bool {
637    value.len() == 2 && value.bytes().all(|b| b.is_ascii_uppercase())
638}
639
640fn validate_digest(value: &str, field: &str) -> Result<(), ValidationError> {
641    match value.strip_prefix("sha256:") {
642        Some(hex) if is_lower_hex(hex, 64) => Ok(()),
643        _ => Err(ValidationError::new(format!(
644            "{field} must be sha256: and 64 lowercase hex characters"
645        ))),
646    }
647}
648
649fn prefixed_hex32(value: &str, prefix: &str) -> bool {
650    value
651        .strip_prefix(prefix)
652        .is_some_and(|rest| is_lower_hex(rest, 32))
653}
654
655fn valid_name(value: &str) -> bool {
656    let bytes = value.as_bytes();
657    !bytes.is_empty()
658        && bytes.len() <= 64
659        && (bytes[0].is_ascii_lowercase() || bytes[0].is_ascii_digit())
660        && bytes.iter().all(|b| {
661            b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'_' | b'.' | b':' | b'-')
662        })
663}
664
665/// 1..=`max` characters without C0/C1 control characters or DEL.
666fn valid_pattern(value: &str, max: usize) -> bool {
667    let count = value.chars().count();
668    (1..=max).contains(&count)
669        && !value
670            .chars()
671            .any(|c| matches!(c, '\u{0}'..='\u{1f}' | '\u{7f}'..='\u{9f}'))
672}
673
674/// A member or section name this crate does not know: 1..=64 of `a-z`, `_`.
675fn valid_member_name(name: &str) -> bool {
676    !name.is_empty()
677        && name.len() <= 64
678        && name.bytes().all(|b| b.is_ascii_lowercase() || b == b'_')
679}
680
681fn invalid(field: &str) -> ValidationError {
682    ValidationError::new(format!("invalid_policy: {field}"))
683}
684
685/// A set in normal form: at most [`MAX_SET`] items, strictly ascending
686/// (bytewise; sorted and without repeats), each one valid.
687fn check_set(
688    set: Option<&Vec<String>>,
689    field: &str,
690    item_ok: impl Fn(&str) -> bool,
691) -> Result<(), ValidationError> {
692    let Some(set) = set else { return Ok(()) };
693    if set.len() > MAX_SET
694        || !set.windows(2).all(|w| w[0] < w[1])
695        || !set.iter().all(|item| item_ok(item))
696    {
697        return Err(invalid(field));
698    }
699    Ok(())
700}
701
702fn check_range(value: Option<u64>, min: u64, max: u64, field: &str) -> Result<(), ValidationError> {
703    match value {
704        Some(v) if !(min..=max).contains(&v) => Err(invalid(field)),
705        _ => Ok(()),
706    }
707}
708
709fn check_enum(
710    value: Option<&String>,
711    allowed: &[&str],
712    field: &str,
713) -> Result<(), ValidationError> {
714    match value {
715        Some(v) if !allowed.contains(&v.as_str()) => Err(invalid(field)),
716        _ => Ok(()),
717    }
718}
719
720impl EffectivePolicyV1 {
721    /// Schema, value ranges and normal form of every known member.
722    pub fn validate(&self) -> Result<(), ValidationError> {
723        require_schema(&self.schema, POLICY_DOCUMENT_SCHEMA)?;
724        let s = &self.security;
725        check_set(s.excluded_paths.as_ref(), "security.excluded_paths", |p| {
726            valid_pattern(p, 256)
727        })?;
728        check_set(
729            s.blocked_labels.as_ref(),
730            "security.blocked_labels",
731            valid_name,
732        )?;
733        check_set(
734            s.external_model_excluded_classes.as_ref(),
735            "security.external_model_excluded_classes",
736            |c| DATA_CLASSES.contains(&c),
737        )?;
738        check_set(
739            s.blocked_model_origins.as_ref(),
740            "security.blocked_model_origins",
741            is_country,
742        )?;
743        check_set(
744            s.blocked_host_countries.as_ref(),
745            "security.blocked_host_countries",
746            is_country,
747        )?;
748        if let Some(groups) = &s.allowed_models {
749            let field = "security.allowed_models";
750            if groups.is_empty()
751                || groups.len() > MAX_MODEL_GROUPS
752                || !groups.windows(2).all(|w| w[0] < w[1])
753            {
754                return Err(invalid(field));
755            }
756            for group in groups {
757                if group.len() > MAX_MODEL_GROUP {
758                    return Err(invalid(field));
759                }
760                check_set(Some(group), field, |p| valid_pattern(p, 128))?;
761            }
762        }
763        check_set(
764            s.allowed_providers.as_ref(),
765            "security.allowed_providers",
766            valid_name,
767        )?;
768        check_set(s.readable_roots.as_ref(), "security.readable_roots", |p| {
769            valid_pattern(p, 256)
770        })?;
771        check_set(s.never_send.as_ref(), "security.never_send", |p| {
772            valid_pattern(p, 256)
773        })?;
774        if let Some(agents) = &self.agents {
775            check_set(agents.allowed.as_ref(), "agents.allowed", |a| {
776                a == "*" || valid_name(a)
777            })?;
778        }
779        let c = &self.context;
780        check_range(
781            c.max_context_tokens,
782            1,
783            10_000_000,
784            "context.max_context_tokens",
785        )?;
786        check_enum(c.read_mode.as_ref(), READ_MODES, "context.read_mode")?;
787        if c.ranking_profile.as_deref().is_some_and(|p| !valid_name(p)) {
788            return Err(invalid("context.ranking_profile"));
789        }
790        check_set(
791            c.allowed_tools.as_ref(),
792            "context.allowed_tools",
793            valid_name,
794        )?;
795        check_set(c.denied_tools.as_ref(), "context.denied_tools", valid_name)?;
796        check_set(
797            c.allowed_sources.as_ref(),
798            "context.allowed_sources",
799            valid_name,
800        )?;
801        check_range(
802            c.max_writes_per_min,
803            0,
804            10_000,
805            "context.max_writes_per_min",
806        )?;
807        check_range(
808            c.max_cost_cents_per_person_per_day,
809            0,
810            100_000_000,
811            "context.max_cost_cents_per_person_per_day",
812        )?;
813        check_range(
814            c.max_cost_cents_per_project_per_month,
815            0,
816            100_000_000,
817            "context.max_cost_cents_per_project_per_month",
818        )?;
819        check_range(
820            c.max_requests_per_minute_per_person,
821            1,
822            1_000_000,
823            "context.max_requests_per_minute_per_person",
824        )?;
825        check_range(
826            c.max_source_age_days,
827            1,
828            3650,
829            "context.max_source_age_days",
830        )?;
831        let h = &self.sharing;
832        check_set(h.allowed_vaults.as_ref(), "sharing.allowed_vaults", |v| {
833            is_lower_hex(v, 32)
834        })?;
835        check_enum(
836            h.task_claim_min_role.as_ref(),
837            CLAIM_ROLES,
838            "sharing.task_claim_min_role",
839        )?;
840        check_set(
841            h.consent_required_for.as_ref(),
842            "sharing.consent_required_for",
843            |a| CONSENT_ACTIONS.contains(&a),
844        )?;
845        check_enum(
846            h.personal_workspace.as_ref(),
847            PERSONAL_WORKSPACE_MODES,
848            "sharing.personal_workspace",
849        )?;
850        if let Some(orchestrator) = &self.orchestrator {
851            check_range(
852                orchestrator.max_sessions_per_vault,
853                0,
854                MAX_ORCHESTRATOR_SESSIONS,
855                "orchestrator.max_sessions_per_vault",
856            )?;
857        }
858        let empty = BTreeMap::new();
859        let agents_other = self.agents.as_ref().map_or(&empty, |a| &a.other);
860        let orchestrator_other = self.orchestrator.as_ref().map_or(&empty, |o| &o.other);
861        for (section, other) in [
862            ("security", &s.other),
863            ("context", &c.other),
864            ("sharing", &h.other),
865            ("agents", agents_other),
866            ("orchestrator", orchestrator_other),
867        ] {
868            if let Some(name) = other.keys().find(|k| !valid_member_name(k)) {
869                return Err(invalid(&format!("{section}.{name}")));
870            }
871        }
872        // An unknown section is an object of members like a known one.
873        for (section, value) in &self.other {
874            let ok = valid_member_name(section)
875                && value
876                    .as_object()
877                    .is_some_and(|members| members.keys().all(|k| valid_member_name(k)));
878            if !ok {
879                return Err(invalid(section));
880            }
881        }
882        Ok(())
883    }
884
885    /// Every member this policy sets, as `section.member`, sorted.
886    pub fn members(&self) -> BTreeSet<String> {
887        let section = |name: &str, value: Value| -> Vec<String> {
888            value
889                .as_object()
890                .map(|fields| fields.keys().map(|k| format!("{name}.{k}")).collect())
891                .unwrap_or_default()
892        };
893        let mut out = BTreeSet::new();
894        out.extend(section(
895            "security",
896            serde_json::to_value(&self.security).unwrap_or(Value::Null),
897        ));
898        out.extend(section(
899            "context",
900            serde_json::to_value(&self.context).unwrap_or(Value::Null),
901        ));
902        out.extend(section(
903            "sharing",
904            serde_json::to_value(&self.sharing).unwrap_or(Value::Null),
905        ));
906        if let Some(agents) = &self.agents {
907            out.extend(section(
908                "agents",
909                serde_json::to_value(agents).unwrap_or(Value::Null),
910            ));
911        }
912        if let Some(orchestrator) = &self.orchestrator {
913            out.extend(section(
914                "orchestrator",
915                serde_json::to_value(orchestrator).unwrap_or(Value::Null),
916            ));
917        }
918        for (name, value) in &self.other {
919            out.extend(section(name, value.clone()));
920        }
921        out
922    }
923}
924
925/// Whether the engine enforces `member` (`section.member`).
926pub fn is_engine_member(member: &str) -> bool {
927    ENGINE_MEMBERS.iter().any(|(m, _)| *m == member)
928}
929
930/// Whether Cloud enforces `member` itself (`x-enforcement: server`).
931pub fn is_server_member(member: &str) -> bool {
932    SERVER_MEMBERS.contains(&member)
933}
934
935/// Every member `policy` sets anywhere (default or any vault), sorted.
936fn set_members(policy: &BundlePolicyV1) -> BTreeSet<String> {
937    let mut all = policy.effective.members();
938    for vault in &policy.vaults {
939        all.extend(vault.effective.members());
940    }
941    all
942}
943
944/// The members `policy` sets that neither this engine nor Cloud enforces
945/// (advisory and unknown members), sorted bytewise: what an ack reports.
946pub fn unenforced_members(policy: &BundlePolicyV1) -> Vec<String> {
947    set_members(policy)
948        .into_iter()
949        .filter(|m| !is_engine_member(m) && !is_server_member(m))
950        .collect()
951}
952
953/// The members `policy` sets that Cloud enforces itself, sorted bytewise.
954pub fn server_members(policy: &BundlePolicyV1) -> Vec<String> {
955    set_members(policy)
956        .into_iter()
957        .filter(|m| is_server_member(m))
958        .collect()
959}
960
961impl EffectivePolicyBundleV1 {
962    /// Everything but the signature and the policy digest, which need the
963    /// raw bytes ([`signing_input_raw`], [`policy_digest`]).
964    pub fn validate(&self) -> Result<(), ValidationError> {
965        require_schema(&self.schema, EFFECTIVE_POLICY_SCHEMA)?;
966        if !prefixed_hex32(&self.org_id, "org_") {
967            return Err(ValidationError::new("org_id must be org_ and 32 hex"));
968        }
969        if !prefixed_hex32(&self.instance_id, "inst_") {
970            return Err(ValidationError::new("instance_id must be inst_ and 32 hex"));
971        }
972        if self.version == 0 {
973            return Err(ValidationError::new("version starts at 1"));
974        }
975        if self.not_after <= self.issued_at {
976            return Err(ValidationError::new("not_after must follow issued_at"));
977        }
978        if self.sources.len() > MAX_POLICY_SOURCES {
979            return Err(ValidationError::new("too many policy sources"));
980        }
981        for source in &self.sources {
982            // `orgn_` names an organisation's own org-level document (a
983            // workspace linked to an organisation, C0 `$defs/source`): only
984            // at level `org`.
985            let scope_ok = prefixed_hex32(&source.scope, "org_")
986                || (source.level == "org" && prefixed_hex32(&source.scope, "orgn_"))
987                || prefixed_hex32(&source.scope, "inst_")
988                || is_lower_hex(&source.scope, 32);
989            if !matches!(
990                source.level.as_str(),
991                "org" | "workspace" | "vault" | "instance"
992            ) || !scope_ok
993                || source.version == 0
994            {
995                return Err(ValidationError::new("a policy source is malformed"));
996            }
997            validate_digest(&source.digest, "sources.digest")?;
998        }
999        if self.policy.vaults.len() > MAX_POLICY_VAULTS
1000            || !self
1001                .policy
1002                .vaults
1003                .windows(2)
1004                .all(|w| w[0].vault_id < w[1].vault_id)
1005        {
1006            return Err(ValidationError::new(
1007                "policy.vaults must be at most 32, ascending by vault_id",
1008            ));
1009        }
1010        self.policy.effective.validate()?;
1011        for vault in &self.policy.vaults {
1012            if !is_lower_hex(&vault.vault_id, 32) {
1013                return Err(ValidationError::new("policy.vaults.vault_id is malformed"));
1014            }
1015            vault.effective.validate()?;
1016        }
1017        validate_digest(&self.digest, "digest")?;
1018        if !is_lower_hex(&self.key_id, 16) {
1019            return Err(ValidationError::new("key_id must be 16 lowercase hex"));
1020        }
1021        if !is_lower_hex(&self.signature, 128) {
1022            return Err(ValidationError::new("signature must be 128 lowercase hex"));
1023        }
1024        Ok(())
1025    }
1026
1027    /// The ack for this bundle as applied. The wire carries at most
1028    /// [`MAX_UNENFORCED`] members (the schema bound, more than the contract
1029    /// defines); the full list stays in the engine's own status.
1030    pub fn ack(&self) -> PolicyAckRequestV1 {
1031        let mut unenforced = unenforced_members(&self.policy);
1032        unenforced.truncate(MAX_UNENFORCED);
1033        PolicyAckRequestV1 {
1034            version: self.version,
1035            digest: self.digest.clone(),
1036            unenforced,
1037            refused: None,
1038        }
1039    }
1040}
1041
1042#[cfg(test)]
1043#[path = "effective_policy_tests.rs"]
1044mod tests;