Skip to main content

lean_ctx/core/policy/
cloud_floor.rs

1// SPDX-License-Identifier: Apache-2.0
2//! The Cloud effective policy as a floor of the gateway policy engine
3//! (Release B 3.1.4).
4//!
5//! A verified bundle (the Cloud connector's effective-policy pull) is installed as two files
6//! in `<data_dir>/cloud/policy/effective/`, both 0600 and written atomically:
7//!
8//! - `floor.json` ([`Floor`]): the verified `policy` (default + per vault),
9//!   its version, digest and `not_after`;
10//! - `required.json`: the highest version ever installed. It only grows, and
11//!   it is what makes a missing policy never mean "no rules": while it
12//!   exists, a missing, damaged or older floor fails every policy refresh
13//!   closed instead of dropping the Cloud rules.
14//!
15//! The policy snapshot ([`crate::core::policy::runtime`]) reads both files
16//! and folds the floor *underneath* whatever the engine would enforce
17//! otherwise (local pack, org policy), with [`crate::core::policy::floor::merge_floor`]:
18//! every field merges toward the stricter side, so a local setting can only
19//! tighten the Cloud policy, never loosen it. [`loosened_by_floor`] names the
20//! local settings the floor overrides, for `cloud status`.
21//!
22//! Only the members the schema marks `x-enforcement: engine` are mapped
23//! (their `x-engine` field; `security.readable_roots` and `never_send` are
24//! applied to reads by [`crate::core::policy::cloud_io`] instead);
25//! everything else is reported as unenforced on
26//! the ack. Expiry (`not_after`) does not lift the floor: the last valid
27//! rules keep restricting local work offline; only sensitive operations
28//! fail closed (the connector's sensitive-operation gate).
29
30use std::collections::BTreeMap;
31use std::path::{Path, PathBuf};
32
33use serde::{Deserialize, Serialize};
34
35use crate::core::input_filters::FilterAction;
36use crate::core::policy::{
37    BudgetRules, EgressRules, FilterRules, ResolvedPolicy, RoutingPolicyRules,
38};
39use lean_ctx_protocol::cloud::effective_policy::{BundlePolicyV1, EffectivePolicyV1};
40
41pub const FLOOR_SCHEMA: &str = "leanctx.cloud.policy-floor/v1";
42pub const DIR: &str = "effective";
43pub const FLOOR_FILE: &str = "floor.json";
44pub const REQUIRED_FILE: &str = "required.json";
45/// Name of the resolved Cloud floor (shows in `policy` diagnostics).
46pub const FLOOR_NAME: &str = "cloud-policy";
47
48/// What `floor.json` holds: the verified effective policy, nothing else.
49#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
50#[serde(deny_unknown_fields)]
51pub struct Floor {
52    pub schema: String,
53    pub version: u64,
54    pub digest: String,
55    pub not_after: String,
56    pub policy: BundlePolicyV1,
57}
58
59/// `required.json`: the highest installed version.
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
61#[serde(deny_unknown_fields)]
62pub struct Required {
63    pub version: u64,
64}
65
66/// `<data_dir>/cloud/policy/effective` of this installation.
67pub fn floor_dir() -> Option<PathBuf> {
68    let data = crate::core::paths::data_dir().ok()?;
69    Some(data.join("cloud").join("policy").join(DIR))
70}
71
72/// Whether `target` (canonical) lies in `<data_dir>/cloud/policy`, the files
73/// only the engine's own policy pull writes: agent file tools are refused
74/// there ([`crate::core::pathjail::enforce_writable`]).
75pub fn is_policy_path(target: &Path) -> bool {
76    let Ok(data) = crate::core::paths::data_dir() else {
77        return false;
78    };
79    let dir = data.join("cloud").join("policy");
80    let canonical =
81        crate::core::pathutil::canonicalize_secure(&dir).unwrap_or_else(|_| dir.clone());
82    target.starts_with(&dir) || target.starts_with(&canonical)
83}
84
85/// `floor_dir` below a Cloud store's data directory (`<data_dir>/cloud`).
86pub fn floor_dir_in(cloud_data: &Path) -> PathBuf {
87    cloud_data.join("policy").join(DIR)
88}
89
90/// The installed floor and requirement, checked against each other: `Ok(None)`
91/// only when neither exists (no Cloud policy was ever installed here).
92pub fn check(floor: Option<&str>, required: Option<&str>) -> Result<Option<Floor>, String> {
93    let required = required
94        .map(serde_json::from_str::<Required>)
95        .transpose()
96        .map_err(|_| "the team policy requirement is damaged")?;
97    let floor = match floor {
98        Some(text) => Some(
99            serde_json::from_str::<Floor>(text)
100                .ok()
101                .filter(|f| f.schema == FLOOR_SCHEMA)
102                .filter(|f| {
103                    f.policy.effective.validate().is_ok()
104                        && f.policy
105                            .vaults
106                            .iter()
107                            .all(|v| v.effective.validate().is_ok())
108                })
109                .ok_or("the installed team policy is damaged")?,
110        ),
111        None => None,
112    };
113    match (floor, required) {
114        (None, Some(_)) => Err("the team policy in force is missing".into()),
115        (Some(floor), Some(required)) if floor.version < required.version => Err(format!(
116            "the installed team policy v{} is older than v{} in force",
117            floor.version, required.version
118        )),
119        (floor, _) => Ok(floor),
120    }
121}
122
123/// Read both files of `dir` (absent = `None`).
124pub fn read(dir: &Path) -> Result<(Option<String>, Option<String>), String> {
125    let read = |name: &str| match std::fs::read_to_string(dir.join(name)) {
126        Ok(text) => Ok(Some(text)),
127        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
128        Err(_) => Err(format!("the team policy file {name} is unreadable")),
129    };
130    Ok((read(FLOOR_FILE)?, read(REQUIRED_FILE)?))
131}
132
133/// The vault whose effective policy applies to `project_root`, when the
134/// floor has per-vault entries: the vault this checkout is linked to.
135pub fn vault_for(floor_text: &str, cloud_data: &Path, project_root: &Path) -> Option<String> {
136    let floor: Floor = serde_json::from_str(floor_text).ok()?;
137    if floor.policy.vaults.is_empty() {
138        return None;
139    }
140    let map = crate::core::vault_map::VaultMap::load(cloud_data);
141    let record = map.for_root(&project_root.to_string_lossy())?;
142    floor
143        .policy
144        .vaults
145        .iter()
146        .any(|v| v.vault_id == record.vault_id)
147        .then(|| record.vault_id.clone())
148}
149
150/// The floor for `vault` (or the default) as a resolved policy, or `None`
151/// when no Cloud policy is installed or the verified policy sets no members.
152/// Enrollment metadata alone must not activate protected source/egress mode.
153/// An inconsistent pair is still an error, and the caller fails closed.
154pub fn resolve(
155    floor: Option<&str>,
156    required: Option<&str>,
157    vault: Option<&str>,
158) -> Result<Option<ResolvedPolicy>, String> {
159    Ok(check(floor, required)?.and_then(|floor| {
160        let policy = floor.policy.for_vault(vault);
161        // Inspect the selected wire policy before mapping it: fields enforced
162        // elsewhere and unknown future members must not be mistaken for an
163        // empty policy. Explicit values, even `off` or an empty allowlist,
164        // conservatively keep the floor active.
165        (!policy.members().is_empty()).then(|| to_resolved(policy, floor.version))
166    }))
167}
168
169fn cap_u32(value: Option<u64>) -> Option<u32> {
170    value.map(|v| u32::try_from(v).unwrap_or(u32::MAX))
171}
172
173/// Cents per the schema; the engine counts USD.
174#[allow(clippy::cast_precision_loss)] // ≤ 1e8 cents is exact in f64
175fn usd(cents: Option<u64>) -> Option<f64> {
176    cents.map(|c| c as f64 / 100.0)
177}
178
179/// The `x-engine` mapping of every `engine` member onto the gateway pack.
180pub fn to_resolved(policy: &EffectivePolicyV1, version: u64) -> ResolvedPolicy {
181    let s = &policy.security;
182    let c = &policy.context;
183    // A pack's label list replaces the built-in set; a Cloud list must
184    // only add to it, so the built-in labels stay in force with it.
185    let blocked_labels = s.blocked_labels.as_ref().map_or_else(Vec::new, |labels| {
186        let mut all: Vec<String> = crate::core::input_filters::classification::DEFAULT_LABELS
187            .iter()
188            .map(|l| (*l).to_string())
189            .collect();
190        all.extend(labels.iter().cloned());
191        all
192    });
193    ResolvedPolicy {
194        name: FLOOR_NAME.into(),
195        version: version.to_string(),
196        description: format!("LeanCTX effective policy v{version}"),
197        chain: Vec::new(),
198        default_read_mode: c.read_mode.clone(),
199        allow_tools: c.allowed_tools.clone(),
200        deny_tools: c.denied_tools.clone().unwrap_or_default(),
201        max_context_tokens: cap_u32(c.max_context_tokens),
202        audit_retention_days: None,
203        redaction: BTreeMap::new(),
204        filters: FilterRules {
205            pii: s.pii.map(|a| a.as_str().to_string()),
206            classification: s.classification.map(|a| a.as_str().to_string()),
207            injection: c.injection_filter.map(|a| a.as_str().to_string()),
208            blocked_labels,
209            ..FilterRules::default()
210        },
211        egress: EgressRules {
212            forbidden_patterns: Vec::new(),
213            block_secrets: s.block_secrets,
214            max_writes_per_min: cap_u32(c.max_writes_per_min),
215        },
216        routing: RoutingPolicyRules {
217            allowed_models: Vec::new(),
218            model_ceiling_groups: s.allowed_models.clone().unwrap_or_default(),
219            forbid_downgrade_for: Vec::new(),
220            blocked_model_origins: s.blocked_model_origins.clone().unwrap_or_default(),
221            blocked_host_countries: s.blocked_host_countries.clone().unwrap_or_default(),
222            vendor_direct_cn: s.vendor_direct_cn,
223        },
224        budgets: BudgetRules {
225            max_cost_usd_per_person_per_day: usd(c.max_cost_cents_per_person_per_day),
226            max_cost_usd_per_project_per_month: usd(c.max_cost_cents_per_project_per_month),
227            max_requests_per_minute_per_person: cap_u32(c.max_requests_per_minute_per_person),
228        },
229    }
230}
231
232/// Fold the Cloud floor under `effective` (what the engine enforces without
233/// it). Tighten-only: see [`crate::core::policy::floor::merge_floor`].
234pub fn apply(floor: &ResolvedPolicy, effective: Option<&ResolvedPolicy>) -> ResolvedPolicy {
235    crate::core::policy::floor::merge_floor(floor, effective)
236}
237
238/// The local settings of the project at `project_root` (its
239/// `.lean-ctx/policy.toml`) that the installed Cloud floor overrides.
240pub fn local_overrides(cloud_data: &Path, project_root: &Path) -> Vec<String> {
241    let Ok((Some(text), required)) = read(&floor_dir_in(cloud_data)) else {
242        return Vec::new();
243    };
244    let Ok(Some(floor)) = check(Some(&text), required.as_deref()) else {
245        return Vec::new();
246    };
247    let pack = project_root.join(".lean-ctx").join("policy.toml");
248    let Some(local) = crate::core::policy::parse_file(&pack)
249        .ok()
250        .and_then(|p| crate::core::policy::resolve(&p).ok())
251    else {
252        return Vec::new();
253    };
254    let vault = vault_for(&text, cloud_data, project_root);
255    let cloud = to_resolved(floor.policy.for_vault(vault.as_deref()), floor.version);
256    loosened_by_floor(&cloud, &local)
257}
258
259fn rank(action: Option<&String>) -> Option<u8> {
260    action
261        .and_then(|a| FilterAction::parse(a))
262        .map(FilterAction::rank)
263}
264
265/// The settings of `local` that are looser than the Cloud `floor` and are
266/// therefore ignored, one line each, in a fixed order.
267pub fn loosened_by_floor(floor: &ResolvedPolicy, local: &ResolvedPolicy) -> Vec<String> {
268    let mut out = Vec::new();
269    let mut cap = |field: &str, local: Option<f64>, cloud: Option<f64>| {
270        if let (Some(l), Some(a)) = (local, cloud)
271            && l > a
272        {
273            out.push(format!("{field}: local {l}, LeanCTX {a} applies"));
274        }
275    };
276    let f = |v: Option<u32>| v.map(f64::from);
277    cap(
278        "context.max_context_tokens",
279        f(local.max_context_tokens),
280        f(floor.max_context_tokens),
281    );
282    cap(
283        "egress.max_writes_per_min",
284        f(local.egress.max_writes_per_min),
285        f(floor.egress.max_writes_per_min),
286    );
287    cap(
288        "budgets.max_cost_usd_per_person_per_day",
289        local.budgets.max_cost_usd_per_person_per_day,
290        floor.budgets.max_cost_usd_per_person_per_day,
291    );
292    cap(
293        "budgets.max_cost_usd_per_project_per_month",
294        local.budgets.max_cost_usd_per_project_per_month,
295        floor.budgets.max_cost_usd_per_project_per_month,
296    );
297    cap(
298        "budgets.max_requests_per_minute_per_person",
299        f(local.budgets.max_requests_per_minute_per_person),
300        f(floor.budgets.max_requests_per_minute_per_person),
301    );
302    for (field, l, a) in [
303        ("filters.pii", &local.filters.pii, &floor.filters.pii),
304        (
305            "filters.classification",
306            &local.filters.classification,
307            &floor.filters.classification,
308        ),
309        (
310            "filters.injection",
311            &local.filters.injection,
312            &floor.filters.injection,
313        ),
314    ] {
315        if let (Some(lr), Some(ar)) = (rank(l.as_ref()), rank(a.as_ref()))
316            && lr < ar
317        {
318            out.push(format!(
319                "{field}: local {}, LeanCTX {} applies",
320                l.as_deref().unwrap_or_default(),
321                a.as_deref().unwrap_or_default()
322            ));
323        }
324    }
325    if local.egress.block_secrets == Some(false) && floor.egress.block_secrets == Some(true) {
326        out.push("egress.block_secrets: local false, LeanCTX true applies".into());
327    }
328    if let (Some(l), Some(a)) = (&local.default_read_mode, &floor.default_read_mode)
329        && l != a
330    {
331        out.push(format!(
332            "context.default_read_mode: local {l}, LeanCTX {a} applies"
333        ));
334    }
335    if let Some(local_allow) = &local.allow_tools {
336        let extra: Vec<&str> = local_allow
337            .iter()
338            .filter(|t| {
339                floor.deny_tools.contains(t)
340                    || floor
341                        .allow_tools
342                        .as_ref()
343                        .is_some_and(|allow| !allow.contains(t))
344            })
345            .map(String::as_str)
346            .collect();
347        if !extra.is_empty() {
348            out.push(format!(
349                "context.allow_tools: local allows {}, LeanCTX does not",
350                extra.join(", ")
351            ));
352        }
353    }
354    out
355}
356
357#[cfg(test)]
358mod tests {
359    use super::*;
360    use serde_json::json;
361
362    fn empty_floor() -> serde_json::Value {
363        json!({
364            "schema": FLOOR_SCHEMA, "version": 1,
365            "digest": format!("sha256:{}", "a".repeat(64)),
366            "not_after": "2099-01-01T00:00:00Z",
367            "policy": {"effective": {
368                "schema": "leanctx.cloud.policy/v1",
369                "security": {}, "context": {}, "sharing": {}
370            }, "vaults": []}
371        })
372    }
373
374    #[test]
375    fn empty_floor_is_neutral_only_after_required_policy_validation() {
376        let floor = empty_floor().to_string();
377        let required = r#"{"version":1}"#;
378        assert!(
379            resolve(Some(&floor), Some(required), None)
380                .unwrap()
381                .is_none()
382        );
383        assert!(resolve(None, Some(required), None).is_err());
384        assert!(resolve(Some("damaged"), Some(required), None).is_err());
385        assert!(resolve(Some(&floor), Some(r#"{"version":2}"#), None).is_err());
386    }
387
388    #[test]
389    fn selected_vault_and_unmapped_members_never_count_as_empty() {
390        for (section, member, value) in [
391            ("security", "pii", json!("redact")),
392            ("context", "allowed_tools", json!([])),
393            ("context", "allowed_sources", json!([])),
394            ("security", "future_control", json!(true)),
395        ] {
396            let mut floor = empty_floor();
397            let mut vault_policy = floor["policy"]["effective"].clone();
398            vault_policy[section][member] = value;
399            floor["policy"]["vaults"] = json!([{
400                "vault_id": "restricted", "effective": vault_policy
401            }]);
402            let floor = floor.to_string();
403            assert!(resolve(Some(&floor), None, None).unwrap().is_none());
404            assert!(
405                resolve(Some(&floor), None, Some("restricted"))
406                    .unwrap()
407                    .is_some(),
408                "{section}.{member} must retain the selected vault's policy"
409            );
410        }
411    }
412}