Skip to main content

lean_ctx_cloud/
effective_policy.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Unified Control on the engine (Release B 3.1.4, 3.1.6): receive, verify,
3//! apply and acknowledge the signed effective policy a 2.x Cloud adds to
4//! `GET /v1/policy/bundle` (`effective_policy`).
5//!
6//! - Verification ([`verify`]): the bundle names this engine's org and
7//!   instance; its key is a key-set v3 key of purpose `policy` that was
8//!   valid when the bundle arrived; the signature covers the raw bundle; the
9//!   digest is the policy's own; the version only grows — a lower version,
10//!   or the same version with another digest, is a downgrade and refused.
11//! - A refused bundle (or one dropped to `null` once a policy is in force)
12//!   never replaces the last valid one. That one stays installed
13//!   ([`super::effective_floor`]) and keeps restricting local work, also
14//!   offline and after `not_after`.
15//! - After installing, the engine acks `{version, digest, unenforced}`
16//!   (`POST /v1/policy/ack`); `unenforced` lists every member it received
17//!   but does not enforce. A failed ack is retried on the next pull.
18//! - Sensitive operations (team sharing, a new trust boundary, rights
19//!   expansion: the consent kinds of [`sensitive_kind`]) fail closed when
20//!   the policy's authorisation has expired or the policy in force is
21//!   missing or damaged ([`sensitive_gate`]).
22//! - Agents never change it: only the scheduler/`cloud sync` pull writes
23//!   these files, no MCP tool reaches them, and a local pack can only
24//!   tighten the floor. Cloud enforces on paths through LeanCTX only.
25//!
26//! A 1.x Cloud (prod until the cutover) sends no `effective_policy`; then
27//! nothing here runs and the 1.x policy path is unchanged.
28
29use std::path::Path;
30
31use ed25519_dalek::Signature;
32use lean_ctx_time::{OffsetDateTime, UtcDateTime};
33use serde::{Deserialize, Serialize};
34use serde_json::Value;
35
36use super::CloudError;
37use super::effective_floor::{
38    FLOOR_FILE, FLOOR_SCHEMA, Floor, REQUIRED_FILE, Required, floor_dir_in,
39};
40use super::keyset_v3::{KeySetV3, Purpose};
41use super::policy::PolicyState;
42use super::state::write_private;
43use lean_ctx_protocol::cloud::effective_policy::{
44    EffectivePolicyBundleV1, POLICY_MISMATCH, PolicyAckRefusalV1, PolicyAckRefusedResponseV1,
45    PolicyAckRequestV1, PolicyAckResponseV1, PolicyAckStateV1, PolicyRefusalReasonV1,
46    policy_digest, refusal_detail, signing_input_raw, unenforced_members,
47};
48use lean_ctx_protocol::cloud::lease::CloudLeaseV1;
49
50/// What the engine keeps of the effective policy in force (in the policy
51/// state, `<data_dir>/cloud/policy/state.json`).
52#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
53pub struct EffectiveState {
54    pub version: u64,
55    pub digest: String,
56    pub issued_at: String,
57    pub not_after: String,
58    pub key_id: String,
59    /// Members received that neither this engine nor Cloud enforces
60    /// (default and every vault), sorted: what the ack reports.
61    pub unenforced: Vec<String>,
62    /// Members received that Cloud enforces itself (`x-enforcement:
63    /// server`), sorted; shown in status, never acked as unenforced.
64    #[serde(default, skip_serializing_if = "Vec::is_empty")]
65    pub by_cloud: Vec<String>,
66    #[serde(default, skip_serializing_if = "Option::is_none")]
67    pub ack: Option<AckRecord>,
68    /// Why the last ack of this version failed (retried on the next pull).
69    #[serde(default, skip_serializing_if = "Option::is_none")]
70    pub ack_error: Option<String>,
71}
72
73/// The answer to an ack of this version.
74#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
75pub struct AckRecord {
76    pub version: u64,
77    pub digest: String,
78    /// `acked` or `outdated`.
79    pub state: String,
80    pub acked_at: String,
81}
82
83/// The verdict on a received bundle.
84#[derive(Debug, Clone, PartialEq)]
85pub enum Verdict {
86    /// The version and digest already in force.
87    Same,
88    /// A newer, verified bundle.
89    New(Box<EffectivePolicyBundleV1>),
90}
91
92fn hex_signature(text: &str) -> Option<Signature> {
93    let mut bytes = [0u8; 64];
94    hex::decode_to_slice(text, &mut bytes).ok()?;
95    Some(Signature::from_bytes(&bytes))
96}
97
98/// Verify `raw` (the `effective_policy` object as received) for this
99/// engine. `received_at` is the service time in ms.
100pub fn verify(
101    raw: &Value,
102    keyset: &KeySetV3,
103    lease: &CloudLeaseV1,
104    previous: Option<&EffectiveState>,
105    received_at: u64,
106) -> Result<Verdict, String> {
107    verify_coded(raw, keyset, lease, previous, received_at).map_err(|(_, why)| why)
108}
109
110/// [`verify`] with the contract's reason code of a refusal (SERVER-B4).
111fn verify_coded(
112    raw: &Value,
113    keyset: &KeySetV3,
114    lease: &CloudLeaseV1,
115    previous: Option<&EffectiveState>,
116    received_at: u64,
117) -> Result<Verdict, (PolicyRefusalReasonV1, String)> {
118    use PolicyRefusalReasonV1 as R;
119    let invalid = |e: &dyn std::fmt::Display| (R::InvalidBundle, format!("effective policy: {e}"));
120    let bundle: EffectivePolicyBundleV1 =
121        serde_json::from_value(raw.clone()).map_err(|e| invalid(&e))?;
122    bundle.validate().map_err(|e| invalid(&e))?;
123    if bundle.org_id != lease.org_id || bundle.instance_id != lease.instance_id {
124        return Err((
125            R::WrongTarget,
126            "the effective policy was issued for another workspace or instance".into(),
127        ));
128    }
129    let key = keyset
130        .key_for(&bundle.key_id, Purpose::Policy, received_at)
131        .map_err(|r| (R::KeyUnavailable, format!("effective policy: {r}")))?;
132    let input = signing_input_raw(raw).map_err(|e| invalid(&e))?;
133    let verified = hex_signature(&bundle.signature)
134        .is_some_and(|signature| key.verify_strict(&input, &signature).is_ok());
135    if !verified {
136        return Err((
137            R::SignatureInvalid,
138            "the effective policy signature does not verify".into(),
139        ));
140    }
141    if policy_digest(&raw["policy"]).ok().as_deref() != Some(bundle.digest.as_str()) {
142        return Err((
143            R::DigestMismatch,
144            "the effective policy digest is not the digest of its policy".into(),
145        ));
146    }
147    if let Some(previous) = previous {
148        match bundle.version.cmp(&previous.version) {
149            std::cmp::Ordering::Less => {
150                return Err((
151                    R::Downgrade,
152                    format!(
153                        "effective policy v{} is older than v{} in force (downgrade refused)",
154                        bundle.version, previous.version
155                    ),
156                ));
157            }
158            std::cmp::Ordering::Equal if bundle.digest != previous.digest => {
159                return Err((
160                    R::Downgrade,
161                    format!(
162                        "effective policy v{} was accepted with another digest (downgrade refused)",
163                        bundle.version
164                    ),
165                ));
166            }
167            std::cmp::Ordering::Equal => return Ok(Verdict::Same),
168            std::cmp::Ordering::Greater => {}
169        }
170    }
171    Ok(Verdict::New(Box::new(bundle)))
172}
173
174/// Install a verified bundle under `cloud_data`: the floor first, then the
175/// requirement (a crash in between leaves an older requirement, which the
176/// newer floor satisfies).
177pub fn install(
178    cloud_data: &Path,
179    bundle: &EffectivePolicyBundleV1,
180) -> Result<EffectiveState, CloudError> {
181    let dir = floor_dir_in(cloud_data);
182    let floor = Floor {
183        schema: FLOOR_SCHEMA.into(),
184        version: bundle.version,
185        digest: bundle.digest.clone(),
186        not_after: bundle.not_after.as_str().to_string(),
187        policy: bundle.policy.clone(),
188    };
189    let local = |e: serde_json::Error| CloudError::Local(e.to_string());
190    write_private(
191        &dir,
192        FLOOR_FILE,
193        &serde_json::to_vec_pretty(&floor).map_err(local)?,
194    )?;
195    write_private(
196        &dir,
197        REQUIRED_FILE,
198        &serde_json::to_vec(&Required {
199            version: bundle.version,
200        })
201        .map_err(local)?,
202    )?;
203    Ok(EffectiveState {
204        version: bundle.version,
205        digest: bundle.digest.clone(),
206        issued_at: bundle.issued_at.as_str().to_string(),
207        not_after: bundle.not_after.as_str().to_string(),
208        key_id: bundle.key_id.clone(),
209        unenforced: unenforced_members(&bundle.policy),
210        by_cloud: lean_ctx_protocol::cloud::effective_policy::server_members(&bundle.policy),
211        ack: None,
212        ack_error: None,
213    })
214}
215
216/// Take the `effective_policy` of a pulled bundle response into `state`
217/// (which starts as the previous state's copy): verify, install, record.
218/// Never fails the pull; a refusal is recorded and the last valid policy
219/// stays. `false` when the response's effective policy was not taken
220/// (refused, or dropped while one is in force): the pull then keeps no
221/// ETag of it, so the next pull fetches the bundle in full.
222pub fn receive(
223    cloud_data: &Path,
224    response: &Value,
225    keyset: Option<&KeySetV3>,
226    lease: &CloudLeaseV1,
227    state: &mut PolicyState,
228    received_at: u64,
229) -> bool {
230    let raw = response.get("effective_policy").unwrap_or(&Value::Null);
231    if raw.is_null() {
232        state.effective_refusal = state.effective.as_ref().map(|e| {
233            format!(
234                "The Cloud sent no effective policy; v{} stays in force",
235                e.version
236            )
237        });
238        return state.effective_refusal.is_none();
239    }
240    let verdict = match keyset {
241        None => Err((
242            PolicyRefusalReasonV1::KeyUnavailable,
243            "no verified key set v3 to check the effective policy with".to_string(),
244        )),
245        Some(keyset) => verify_coded(raw, keyset, lease, state.effective.as_ref(), received_at),
246    };
247    let refused = match verdict {
248        Ok(Verdict::Same) => None,
249        Ok(Verdict::New(bundle)) => match install(cloud_data, &bundle) {
250            Ok(installed) => {
251                state.effective = Some(installed);
252                None
253            }
254            Err(error) => Some((
255                PolicyRefusalReasonV1::InstallFailed,
256                format!("install the effective policy: {error}"),
257            )),
258        },
259        Err(refused) => Some(refused),
260    };
261    match refused {
262        None => {
263            state.effective_refusal = None;
264            state.effective_refused = None;
265            true
266        }
267        Some((code, why)) => {
268            let fresh = RefusalRecord::of(raw, code, &why, state.effective.as_ref());
269            state.effective_refused = match (state.effective_refused.take(), fresh) {
270                // The same bundle again: it is reported once.
271                (Some(known), Some(fresh))
272                    if known.version == fresh.version && known.digest == fresh.digest =>
273                {
274                    Some(known)
275                }
276                (_, fresh) => fresh,
277            };
278            state.effective_refusal = Some(why);
279            false
280        }
281    }
282}
283
284/// A refused bundle as Cloud hears of it (SERVER-B4 `refused`): once per
285/// received version and digest, with the bundle the engine keeps.
286#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
287pub struct RefusalRecord {
288    /// `version` and `digest` of the bundle as received.
289    pub version: u64,
290    pub digest: String,
291    pub refused: PolicyAckRefusalV1,
292    /// `refused_at` of Cloud' answer, once reported.
293    #[serde(default, skip_serializing_if = "Option::is_none")]
294    pub reported_at: Option<String>,
295    /// Why the last report failed (retried on the next pull).
296    #[serde(default, skip_serializing_if = "Option::is_none")]
297    pub report_error: Option<String>,
298}
299
300impl RefusalRecord {
301    /// `None` when the received object names no usable version and digest
302    /// (nothing Cloud could match it to).
303    fn of(
304        raw: &Value,
305        code: PolicyRefusalReasonV1,
306        why: &str,
307        applied: Option<&EffectiveState>,
308    ) -> Option<Self> {
309        let version = raw["version"].as_u64().filter(|v| *v >= 1)?;
310        let digest = raw["digest"].as_str().filter(|d| {
311            d.strip_prefix("sha256:").is_some_and(|h| {
312                h.len() == 64
313                    && h.bytes()
314                        .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
315            })
316        })?;
317        // The bundle in force itself (only its key set is missing now):
318        // nothing was refused that Cloud does not already see applied.
319        if applied.is_some_and(|e| e.version == version && e.digest == digest) {
320            return None;
321        }
322        Some(Self {
323            version,
324            digest: digest.to_string(),
325            refused: PolicyAckRefusalV1 {
326                reason_code: code,
327                detail: refusal_detail(why),
328                applied_version: applied.map(|e| e.version),
329                applied_digest: applied.map(|e| e.digest.clone()),
330            },
331            reported_at: None,
332            report_error: None,
333        })
334    }
335}
336
337/// Tell Cloud once that this engine refused the bundle `record` names
338/// (again after a failure). Only a 2.x Cloud sends effective policies, so
339/// only one ever gets a refusal.
340pub fn report_refusal_with(client: &super::transport::CloudClient, record: &mut RefusalRecord) {
341    if record.reported_at.is_some() {
342        return;
343    }
344    let request = PolicyAckRequestV1::refusal(
345        record.version,
346        record.digest.clone(),
347        record.refused.clone(),
348    );
349    let body = match serde_json::to_value(&request) {
350        Ok(body) => body,
351        Err(error) => {
352            record.report_error = Some(error.to_string());
353            return;
354        }
355    };
356    let answer = client.post("/policy/ack", &body).and_then(|answer| {
357        let answer: PolicyAckRefusedResponseV1 = serde_json::from_value(answer)
358            .map_err(|e| CloudError::Protocol(format!("policy refusal: {e}")))?;
359        answer
360            .validate_for(&request)
361            .map_err(|e| CloudError::Protocol(format!("policy refusal: {e}")))?;
362        Ok(answer)
363    });
364    match answer {
365        Ok(answer) => {
366            record.reported_at = Some(answer.refused_at.as_str().to_string());
367            record.report_error = None;
368        }
369        Err(CloudError::Server { status: 409, .. }) => {
370            record.report_error = Some(format!(
371                "{POLICY_MISMATCH}: the Cloud did not issue v{} with this digest to this instance",
372                record.version
373            ));
374        }
375        Err(error) => record.report_error = Some(error.to_string()),
376    }
377}
378
379/// Ack the installed version once (again after a failure, or once a newer
380/// version is in force). Only after [`install`]: the ack says "applied".
381pub fn ack_with(client: &super::transport::CloudClient, state: &mut EffectiveState) {
382    if state
383        .ack
384        .as_ref()
385        .is_some_and(|a| a.version == state.version && a.digest == state.digest)
386    {
387        return;
388    }
389    // A state written by an older build may still list server members.
390    let mut unenforced: Vec<String> = state
391        .unenforced
392        .iter()
393        .filter(|m| !lean_ctx_protocol::cloud::effective_policy::is_server_member(m))
394        .cloned()
395        .collect();
396    unenforced.truncate(lean_ctx_protocol::cloud::effective_policy::MAX_UNENFORCED);
397    let request = PolicyAckRequestV1 {
398        version: state.version,
399        digest: state.digest.clone(),
400        unenforced,
401        refused: None,
402    };
403    let body = match serde_json::to_value(&request) {
404        Ok(body) => body,
405        Err(error) => {
406            state.ack_error = Some(error.to_string());
407            return;
408        }
409    };
410    let answer = client.post("/policy/ack", &body).and_then(|answer| {
411        let answer: PolicyAckResponseV1 = serde_json::from_value(answer)
412            .map_err(|e| CloudError::Protocol(format!("policy ack: {e}")))?;
413        answer
414            .validate_for(&request)
415            .map_err(|e| CloudError::Protocol(format!("policy ack: {e}")))?;
416        Ok(answer)
417    });
418    match answer {
419        Ok(answer) => {
420            state.ack = Some(AckRecord {
421                version: answer.version,
422                digest: answer.digest,
423                state: match answer.state {
424                    PolicyAckStateV1::Acked => "acked".into(),
425                    PolicyAckStateV1::Outdated => "outdated".into(),
426                },
427                acked_at: answer.acked_at.as_str().to_string(),
428            });
429            state.ack_error = None;
430        }
431        // `policy_mismatch` is the one 409 of this route (C0).
432        Err(CloudError::Server { status: 409, .. }) => {
433            state.ack_error = Some(format!(
434                "{POLICY_MISMATCH}: the Cloud did not issue v{} with this digest to this instance",
435                state.version
436            ));
437        }
438        Err(error) => state.ack_error = Some(error.to_string()),
439    }
440}
441
442/// One pull's effective-policy work (`None` body: 304, only the ack retry).
443/// `false` when the body's effective policy was not taken ([`receive`]).
444pub(crate) fn on_pull(
445    session: &super::auth::Session,
446    body: Option<&Value>,
447    state: &mut PolicyState,
448    now: UtcDateTime,
449) -> bool {
450    let mut taken = true;
451    if let Some(body) = body {
452        let present = body
453            .get("effective_policy")
454            .is_some_and(|raw| !raw.is_null());
455        if !present && state.effective.is_none() {
456            return true;
457        }
458        let keyset = if present {
459            // A signing key the stored set does not know yet (a rotation):
460            // fetch the current set once.
461            let key_id = body["effective_policy"]["key_id"]
462                .as_str()
463                .unwrap_or_default();
464            super::keyset_v3::load(&session.store, session.root_key())
465                .filter(|set| set.keys.iter().any(|k| k.key_id == key_id))
466                .or_else(|| super::keyset_v3::refresh(session).ok())
467        } else {
468            None
469        };
470        let received_at = u64::try_from(now.timestamp_millis()).unwrap_or(0);
471        taken = receive(
472            session.store.data_dir(),
473            body,
474            keyset.as_ref(),
475            &session.lease.lease,
476            state,
477            received_at,
478        );
479    }
480    super::company_bound::on_policy(&session.store, &session.instance);
481    if let Some(effective) = state.effective.as_mut()
482        && let Ok(client) = session.client()
483    {
484        ack_with(&client, effective);
485    }
486    if let Some(record) = state.effective_refused.as_mut()
487        && record.reported_at.is_none()
488        && let Ok(client) = session.client()
489    {
490        report_refusal_with(&client, record);
491    }
492    taken
493}
494
495/// Consent kinds that are sensitive operations: they open a new trust
496/// boundary, share with a team or the public, or expand rights.
497pub fn sensitive_kind(kind: super::consent::Kind) -> bool {
498    use super::consent::Kind;
499    matches!(kind, Kind::LinkVault)
500}
501
502/// `now` is at or past `not_after` (an unreadable instant counts as past).
503fn expired_at(not_after: &str, now: UtcDateTime) -> bool {
504    !OffsetDateTime::parse_from_rfc3339(not_after).is_ok_and(|until| now < until.to_utc())
505}
506
507/// Whether a sensitive operation may go on under the Cloud policy in
508/// `cloud_data`: never once an installed policy's authorisation expired
509/// (`now ≥ not_after`), nor while the policy in force is missing or
510/// damaged. Without any installed Cloud policy (1.x, or never sent) there
511/// is nothing to check.
512pub fn sensitive_gate(cloud_data: &Path, now: UtcDateTime) -> Result<(), String> {
513    let (floor, required) = super::effective_floor::read(&floor_dir_in(cloud_data))?;
514    let Some(floor) = super::effective_floor::check(floor.as_deref(), required.as_deref())? else {
515        return Ok(());
516    };
517    let expired = expired_at(&floor.not_after, now);
518    if expired {
519        return Err(format!(
520            "the Cloud policy v{} expired at {}; sensitive operations stay refused until this instance reaches the Cloud again (`lean-ctx cloud sync`)",
521            floor.version, floor.not_after
522        ));
523    }
524    Ok(())
525}
526
527/// `cloud status` lines of the effective policy, deterministic in `state`,
528/// `now` and the installed files; with `project_root`, also the local
529/// settings there that the Cloud policy overrides.
530pub fn status_lines(
531    cloud_data: &Path,
532    state: &PolicyState,
533    now: UtcDateTime,
534    project_root: Option<&Path>,
535) -> Vec<String> {
536    let mut lines = Vec::new();
537    let installed = super::effective_floor::read(&floor_dir_in(cloud_data))
538        .and_then(|(f, r)| super::effective_floor::check(f.as_deref(), r.as_deref()));
539    match (&state.effective, &installed) {
540        (_, Err(problem)) => lines.push(format!(
541            "Policy:       {problem}; every tool is refused until the next pull installs it"
542        )),
543        (Some(e), Ok(_)) => {
544            let expired = expired_at(&e.not_after, now);
545            lines.push(format!(
546                "Policy:       v{} {} ({}), {} {}",
547                e.version,
548                e.digest.get(..19).unwrap_or(&e.digest),
549                if expired { "EXPIRED" } else { "valid" },
550                if expired {
551                    "its rules still apply; sensitive operations refused since"
552                } else {
553                    "applied until"
554                },
555                e.not_after
556            ));
557            lines.push(match (&e.ack, &e.ack_error) {
558                (Some(a), _) if a.version == e.version && a.digest == e.digest => {
559                    format!("Policy ack:   {} at {}", a.state, a.acked_at)
560                }
561                (_, Some(error)) => {
562                    format!("Policy ack:   not yet ({error}); retried on the next pull")
563                }
564                _ => "Policy ack:   pending".to_string(),
565            });
566            // Status says what Cloud enforces itself and what nobody does.
567            // (A state of an older build lists server members as unenforced.)
568            let (mut by_cloud, nowhere): (Vec<&str>, Vec<&str>) = e
569                .unenforced
570                .iter()
571                .map(String::as_str)
572                .partition(|m| lean_ctx_protocol::cloud::effective_policy::is_server_member(m));
573            by_cloud.extend(e.by_cloud.iter().map(String::as_str));
574            by_cloud.sort_unstable();
575            by_cloud.dedup();
576            if !by_cloud.is_empty() {
577                lines.push(format!(
578                    "By Cloud:     {} (the Cloud refuses, this instance does not check)",
579                    by_cloud.join(", ")
580                ));
581            }
582            lines.push(if nowhere.is_empty() {
583                "Unenforced:   none".to_string()
584            } else {
585                format!("Unenforced:   {}", nowhere.join(", "))
586            });
587        }
588        (None, Ok(Some(_))) => {
589            lines.push("Policy:       installed, state lost; applied until the next pull".into());
590        }
591        (None, Ok(None)) => {}
592    }
593    if let Some(refusal) = &state.effective_refusal {
594        lines.push(format!(
595            "Policy refused: {refusal} (the last valid policy stays)"
596        ));
597    }
598    if let Some(root) = project_root {
599        for line in super::effective_floor::local_overrides(cloud_data, root) {
600            lines.push(format!(
601                "Ignored:      {line} (local settings only tighten)"
602            ));
603        }
604    }
605    lines
606}
607
608#[cfg(test)]
609#[path = "effective_policy_tests.rs"]
610mod tests;