1use 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";
45pub const FLOOR_NAME: &str = "cloud-policy";
47
48#[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
61#[serde(deny_unknown_fields)]
62pub struct Required {
63 pub version: u64,
64}
65
66pub 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
72pub 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
85pub fn floor_dir_in(cloud_data: &Path) -> PathBuf {
87 cloud_data.join("policy").join(DIR)
88}
89
90pub 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
123pub 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
133pub 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
150pub 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 (!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#[allow(clippy::cast_precision_loss)] fn usd(cents: Option<u64>) -> Option<f64> {
176 cents.map(|c| c as f64 / 100.0)
177}
178
179pub fn to_resolved(policy: &EffectivePolicyV1, version: u64) -> ResolvedPolicy {
181 let s = &policy.security;
182 let c = &policy.context;
183 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
232pub fn apply(floor: &ResolvedPolicy, effective: Option<&ResolvedPolicy>) -> ResolvedPolicy {
235 crate::core::policy::floor::merge_floor(floor, effective)
236}
237
238pub 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
265pub 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}