Skip to main content

lean_ctx_cloud/
policy.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Filter packs from Cloud.
3//!
4//! `GET /v1/policy/bundle` (conditional) → verified here before anything is
5//! kept: filter packs must be signed by an Cloud key of the verified key
6//! set, match their digest and validate completely (every pattern
7//! compiles); all packs together stay within [`CLOUD_MAX_RULES`]. A bundle
8//! that fails any check never replaces the last good one; the refusal is
9//! shown in `cloud status` and `lean-ctx doctor`, and local work goes on
10//! under the last verified bundle.
11//!
12//! Stored in `<data_dir>/cloud/policy/`: the verified bundle, its state,
13//! and `filters/set.json`, the one file the policy snapshot reads to apply
14//! the patterns ([`filter_rules`]).
15
16use std::path::Path;
17
18use base64::Engine as _;
19use base64::engine::general_purpose::STANDARD;
20use ed25519_dalek::{Signature, VerifyingKey};
21use lean_ctx_time::UtcDateTime;
22use serde::{Deserialize, Serialize};
23use serde_json::Value;
24
25use super::CloudError;
26use super::auth::Session;
27use super::lease::verify_keyset;
28use super::state::write_private;
29use lean_ctx_protocol::cloud::lease::CloudKeySetV1;
30use lean_ctx_protocol::cloud::policy::{
31    FilterPackRefV1, FilterPackV1, MAX_POLICY_BUNDLE_BYTES, PolicyBundleV1,
32    filter_pack_signing_input,
33};
34
35pub use lean_ctx::core::policy::cloud_filters::{
36    CLOUD_MAX_RULES, FILTER_SET_SCHEMA, FilterRules, FilterSet, filter_rules, filter_set_path,
37    installed_filter_rules, load_filter_set, required_packs_installed,
38};
39use lean_ctx::core::policy::cloud_filters::{FILTER_SET_FILE, digest_hex};
40
41const STATE_FILE: &str = "state.json";
42const BUNDLE_FILE: &str = "bundle.json";
43
44/// What the last verified bundle established.
45#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
46pub struct PolicyState {
47    pub etag: Option<String>,
48    /// `pack_id → version` of the accepted filter packs.
49    #[serde(default)]
50    pub filter_packs: std::collections::BTreeMap<String, u64>,
51    pub verified_at: Option<String>,
52    /// Why the newest bundle was refused (the last good one stays).
53    pub last_refusal: Option<String>,
54    /// The effective policy in force (2.x, [`super::effective_policy`]).
55    #[serde(default, skip_serializing_if = "Option::is_none")]
56    pub effective: Option<super::effective_policy::EffectiveState>,
57    /// Why the newest effective policy was refused (the last valid stays).
58    #[serde(default, skip_serializing_if = "Option::is_none")]
59    pub effective_refusal: Option<String>,
60    /// That refusal as reported to Cloud (SERVER-B4), once per received
61    /// version and digest.
62    #[serde(default, skip_serializing_if = "Option::is_none")]
63    pub effective_refused: Option<super::effective_policy::RefusalRecord>,
64}
65
66pub fn load_state(data_dir: &Path) -> PolicyState {
67    std::fs::read(data_dir.join("policy").join(STATE_FILE))
68        .ok()
69        .and_then(|b| serde_json::from_slice(&b).ok())
70        .unwrap_or_default()
71}
72
73fn save_state(data_dir: &Path, state: &PolicyState) -> Result<(), CloudError> {
74    let bytes = serde_json::to_vec_pretty(state).map_err(|e| CloudError::Local(e.to_string()))?;
75    write_private(&data_dir.join("policy"), STATE_FILE, &bytes)
76}
77
78/// The last verified bundle, as received.
79pub fn load_bundle(data_dir: &Path) -> Option<Value> {
80    std::fs::read(data_dir.join("policy").join(BUNDLE_FILE))
81        .ok()
82        .and_then(|b| serde_json::from_slice(&b).ok())
83}
84
85fn verify(public: &[u8; 32], message: &[u8], signature: &[u8; 64]) -> bool {
86    VerifyingKey::from_bytes(public).is_ok_and(|key| {
87        key.verify_strict(message, &Signature::from_bytes(signature))
88            .is_ok()
89    })
90}
91
92/// Check one filter pack against the verified Cloud key set; returns the pack.
93fn verify_filter_pack(
94    pack: &FilterPackRefV1,
95    keyset: &CloudKeySetV1,
96) -> Result<FilterPackV1, String> {
97    let id = &pack.pack_id;
98    let statement = STANDARD
99        .decode(&pack.envelope.statement_b64)
100        .map_err(|_| format!("filter pack {id}: statement is not base64"))?;
101    if digest_hex(&statement) != pack.sha256 {
102        return Err(format!("filter pack {id}: digest mismatch"));
103    }
104    let key = keyset
105        .key(&pack.envelope.kid)
106        .ok_or_else(|| format!("filter pack {id}: unknown signing key"))?;
107    let public: [u8; 32] = STANDARD
108        .decode(&key.ed25519_pub)
109        .ok()
110        .and_then(|b| b.try_into().ok())
111        .ok_or("key set key is malformed")?;
112    let signature: [u8; 64] = STANDARD
113        .decode(&pack.envelope.signature)
114        .ok()
115        .and_then(|b| b.try_into().ok())
116        .ok_or_else(|| format!("filter pack {id}: signature is malformed"))?;
117    if !verify(&public, &filter_pack_signing_input(&statement), &signature) {
118        return Err(format!("filter pack {id}: signature does not verify"));
119    }
120    let parsed: FilterPackV1 = serde_json::from_slice(&statement)
121        .map_err(|_| format!("filter pack {id}: statement is not a filter pack"))?;
122    parsed
123        .validate()
124        .map_err(|e| format!("filter pack {id}: {e}"))?;
125    if parsed.pack_id != *id || parsed.version != pack.version {
126        return Err(format!(
127            "filter pack {id}: statement does not match its listing"
128        ));
129    }
130    Ok(parsed)
131}
132
133/// Verify a whole bundle against the key set, and against the last
134/// accepted state (filter pack versions only move forward). Returns the
135/// state it establishes and the verified filter packs. The bundle's TOML
136/// org policy fields are not read.
137pub fn verify_bundle(
138    raw: &Value,
139    keyset: &CloudKeySetV1,
140    previous: &PolicyState,
141    now: UtcDateTime,
142) -> Result<(PolicyState, FilterSet), String> {
143    let bundle: PolicyBundleV1 =
144        serde_json::from_value(raw.clone()).map_err(|e| format!("bundle: {e}"))?;
145    bundle.validate().map_err(|e| format!("bundle: {e}"))?;
146    let mut state = PolicyState {
147        etag: None,
148        verified_at: Some(now.to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true)),
149        effective: previous.effective.clone(),
150        effective_refusal: previous.effective_refusal.clone(),
151        effective_refused: previous.effective_refused.clone(),
152        ..PolicyState::default()
153    };
154    let mut packs = Vec::new();
155    let mut statements = std::collections::BTreeMap::new();
156    let mut labels = std::collections::BTreeSet::new();
157    for pack in &bundle.filter_packs {
158        let verified = verify_filter_pack(pack, keyset)?;
159        statements.insert(pack.pack_id.clone(), pack.envelope.statement_b64.clone());
160        if previous
161            .filter_packs
162            .get(&verified.pack_id)
163            .is_some_and(|accepted| verified.version < *accepted)
164        {
165            return Err(format!(
166                "filter pack {} version {} is older than the accepted one",
167                verified.pack_id, verified.version
168            ));
169        }
170        for pattern in &verified.patterns {
171            if !labels.insert(pattern.rule_label()) {
172                return Err(format!(
173                    "filter pack {}: rule {} repeats across packs",
174                    verified.pack_id,
175                    pattern.rule_label()
176                ));
177            }
178        }
179        state
180            .filter_packs
181            .insert(verified.pack_id.clone(), verified.version);
182        packs.push(verified);
183    }
184    if labels.len() > CLOUD_MAX_RULES {
185        return Err(format!(
186            "the filter packs hold {} patterns; at most {CLOUD_MAX_RULES} are applied as a whole",
187            labels.len()
188        ));
189    }
190    packs.sort_by(|a, b| a.pack_id.cmp(&b.pack_id));
191    Ok((
192        state,
193        FilterSet {
194            schema: FILTER_SET_SCHEMA.into(),
195            packs,
196            statements,
197        },
198    ))
199}
200
201/// What a policy pull did.
202#[derive(Debug, Clone, PartialEq, Eq)]
203pub enum PolicyPull {
204    Unchanged,
205    Accepted(Box<PolicyState>),
206    Refused(String),
207}
208
209/// The `If-None-Match` of the next pull: the kept ETag, if any.
210pub(crate) fn if_none_match(state: &PolicyState) -> Option<&str> {
211    state.etag.as_deref().filter(|etag| !etag.is_empty())
212}
213
214/// The last step of a pull with a full answer, once its effective policy
215/// was received (`effective_taken`, [`super::effective_policy::receive`]):
216/// a refused effective policy keeps no ETag. Cloud tags the bundle it
217/// signed, so a copy refused here (e.g. a signature broken on the way, the
218/// genuine ETag passed through) would otherwise turn every later pull into
219/// a 304 that never fetches the genuine bundle; without a tag the next pull
220/// fetches it in full.
221///
222/// A newer policy in force than `previous` (effective version or digest)
223/// ends every policy hold ([`super::throttle`]):
224/// each was the old policy's answer, and an admin who loosened it expects
225/// the next claim or publish to ask Cloud again. Quota throttles stay.
226pub(crate) fn settle(
227    store: &super::CloudStore,
228    previous: &PolicyState,
229    state: &mut PolicyState,
230    effective_taken: bool,
231) {
232    if !effective_taken {
233        state.etag = None;
234    }
235    let effective = |s: &PolicyState| s.effective.as_ref().map(|e| (e.version, e.digest.clone()));
236    if effective(state).is_some() && effective(state) != effective(previous) {
237        super::throttle::policy_changed(store);
238    }
239}
240
241/// Pull, verify and keep the policy bundle.
242pub fn pull(session: &Session) -> Result<PolicyPull, CloudError> {
243    let data = session.store.data_dir().to_path_buf();
244    let previous = load_state(&data);
245    // `since=0` asks for the whole bundle.
246    let path = "/policy/bundle?since=0";
247    let extra: Vec<(&str, &str)> = if_none_match(&previous)
248        .map(|etag| ("If-None-Match", etag))
249        .into_iter()
250        .collect();
251    let answer =
252        session.with_client(|c| c.send("GET", path, None, &extra, MAX_POLICY_BUNDLE_BYTES))?;
253    let now = session.lease.service_time(UtcDateTime::now()).to_utc();
254    let stamp = now.to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true);
255    if answer.status == 304 {
256        let mut state = previous.clone();
257        // An ack that failed (offline) is sent again.
258        super::effective_policy::on_pull(session, None, &mut state, now);
259        if state != previous {
260            save_state(&data, &state)?;
261        }
262        session.store.record_success("policy", &stamp);
263        return Ok(PolicyPull::Unchanged);
264    }
265    let keys_raw: Value = session
266        .store
267        .read_config(super::state::KEYS_FILE)?
268        .ok_or(CloudError::NotConnected)?;
269    let keyset = verify_keyset(&keys_raw, session.root_key())?;
270    match verify_bundle(&answer.body, &keyset, &previous, now) {
271        Ok((mut state, filters)) => {
272            state.etag = answer.etag;
273            let local = |e: serde_json::Error| CloudError::Local(e.to_string());
274            write_private(
275                &data.join("policy"),
276                BUNDLE_FILE,
277                &serde_json::to_vec_pretty(&answer.body).map_err(local)?,
278            )?;
279            write_private(
280                &data.join("policy").join("filters"),
281                FILTER_SET_FILE,
282                &serde_json::to_vec(&filters).map_err(local)?,
283            )?;
284            let taken =
285                super::effective_policy::on_pull(session, Some(&answer.body), &mut state, now);
286            settle(&session.store, &previous, &mut state, taken);
287            save_state(&data, &state)?;
288            session.store.record_success("policy", &stamp);
289            Ok(PolicyPull::Accepted(Box::new(state)))
290        }
291        Err(reason) => {
292            let mut kept = previous.clone();
293            kept.last_refusal = Some(reason.clone());
294            // The effective policy is verified on its own: a refused
295            // filter pack does not hold back a newer, stricter effective
296            // policy.
297            let taken =
298                super::effective_policy::on_pull(session, Some(&answer.body), &mut kept, now);
299            settle(&session.store, &previous, &mut kept, taken);
300            save_state(&data, &kept)?;
301            session.store.record_error(&format!("policy: {reason}"));
302            Ok(PolicyPull::Refused(reason))
303        }
304    }
305}
306
307const PULLS_FILE: &str = "pulls.json";
308
309/// What started a policy pull.
310#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
311#[serde(rename_all = "snake_case")]
312pub enum PulledVia {
313    /// A bus hint (`policy.advanced`, a reconnect).
314    Nudge,
315    /// The scheduler's periodic pull (the fallback).
316    Poll,
317    /// `lean-ctx cloud sync`.
318    Manual,
319}
320
321/// The last policy pull, and whether Cloud has shown it sends policy
322/// nudges (`<data_dir>/cloud/policy/pulls.json`).
323#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
324#[serde(default)]
325pub struct PullRecord {
326    pub last_pull_at: Option<String>,
327    pub pulled_via: Option<PulledVia>,
328    /// Cloud sent a `policy.advanced` frame or a `hello.ack` with
329    /// `policy_version` at least once: changes arrive at once; until then
330    /// only the periodic pull brings them.
331    pub nudges_seen: bool,
332}
333
334pub fn load_pulls(data_dir: &Path) -> PullRecord {
335    std::fs::read(data_dir.join("policy").join(PULLS_FILE))
336        .ok()
337        .and_then(|b| serde_json::from_slice(&b).ok())
338        .unwrap_or_default()
339}
340
341fn save_pulls(data_dir: &Path, record: &PullRecord) {
342    if let Ok(bytes) = serde_json::to_vec_pretty(record) {
343        let _ = write_private(&data_dir.join("policy"), PULLS_FILE, &bytes);
344    }
345}
346
347/// Note a successful pull started by `via`.
348pub fn note_pull(data_dir: &Path, via: PulledVia) {
349    let mut record = load_pulls(data_dir);
350    record.last_pull_at =
351        Some(UtcDateTime::now().to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true));
352    record.pulled_via = Some(via);
353    save_pulls(data_dir, &record);
354}
355
356/// Note that Cloud sends policy nudges (written once).
357pub fn note_nudges_seen(data_dir: &Path) {
358    let mut record = load_pulls(data_dir);
359    if !record.nudges_seen {
360        record.nudges_seen = true;
361        save_pulls(data_dir, &record);
362    }
363}
364
365#[cfg(test)]
366pub(crate) mod test_support {
367    use super::*;
368    use ed25519_dalek::{Signer as _, SigningKey};
369
370    /// A signed filter pack listing for `pack_id` at `version` with `patterns`.
371    #[allow(clippy::needless_pass_by_value)] // builder: callers hand over fresh JSON
372    pub(crate) fn filter_pack_with(
373        seed: [u8; 32],
374        kid: &str,
375        pack_id: &str,
376        version: u64,
377        patterns: Value,
378    ) -> Value {
379        let statement = serde_json::to_vec(&serde_json::json!({
380            "schema": lean_ctx_protocol::cloud::policy::FILTER_PACK_SCHEMA,
381            "pack_id": pack_id, "version": version, "patterns": patterns,
382        }))
383        .unwrap();
384        let signature = SigningKey::from_bytes(&seed).sign(&filter_pack_signing_input(&statement));
385        serde_json::json!({
386            "pack_id": pack_id, "version": version, "sha256": digest_hex(&statement),
387            "envelope": {"statement_b64": STANDARD.encode(&statement), "kid": kid, "signature": STANDARD.encode(signature.to_bytes())},
388        })
389    }
390
391    pub(crate) fn filter_pack(seed: [u8; 32], kid: &str, pack_id: &str, version: u64) -> Value {
392        filter_pack_with(
393            seed,
394            kid,
395            pack_id,
396            version,
397            serde_json::json!([{"id": "ahv", "kind": "regex", "pattern": "756\\.\\d{4}\\.\\d{4}\\.\\d{2}", "action": "redact"}]),
398        )
399    }
400
401    #[allow(clippy::needless_pass_by_value)] // builder: callers hand over fresh JSON
402    pub(crate) fn bundle(packs: Vec<Value>) -> Value {
403        serde_json::json!({
404            "schema": lean_ctx_protocol::cloud::policy::POLICY_BUNDLE_SCHEMA,
405            "filter_packs": packs,
406        })
407    }
408}
409
410#[cfg(test)]
411#[path = "policy_tests.rs"]
412mod tests;