Skip to main content

lean_ctx_cloud/metrics_v2/
gate.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Whether engine metrics may be collected and sent for the connected
3//! workspace, and which vaults are left out (SPEC §3, owner decisions).
4//!
5//! Every one of these must allow it, else nothing is collected, buffered
6//! or sent and the buffer is dropped (K3):
7//!
8//! 1. `[cloud] metrics_upload` (this engine);
9//! 2. no recorded revocation of this engine (K16);
10//! 3. the lease right `metrics.upload` and the workspace switch
11//!    `org_settings.metrics_upload`;
12//! 4. the policy rule "Share instance metrics"
13//!    (`sharing.share_instance_metrics`) in the verified effective-policy
14//!    bundle: `false` turns it off. No bundle, or an expired, damaged or
15//!    inconsistent one counts as off (fail closed for egress);
16//! 5. the workspace's sharing state (`GET /v1/metrics/sharing`, the
17//!    `sharing` of every ack): `on`. Unknown yet: the plan default, on for
18//!    every plan (owner decision 23.11.: no prompt, the terms cover it). An
19//!    explicit `needs_confirmation` answer from Cloud is still honoured;
20//! 6. no `403` refusal under the policy version or lease in force.
21//!
22//! A vault whose own entry turns the rule off is left out of every slice;
23//! no hour before the state's `since` is built.
24
25use std::collections::BTreeSet;
26use std::path::Path;
27
28use lean_ctx_time::{OffsetDateTime, UtcDateTime};
29use serde::{Deserialize, Serialize};
30
31use crate::config::CloudConfig;
32use crate::effective_floor;
33use crate::state::{CloudStore, InstanceRecord};
34use lean_ctx_protocol::cloud::effective_policy::EffectivePolicyV1;
35use lean_ctx_protocol::cloud::lease::{CloudLeaseV1, CloudPlan, CloudRight};
36use lean_ctx_protocol::cloud::metrics_v2::{
37    PlanDefault, PolicyLevel, SharingStateV2, SharingValue, TimeStamp,
38};
39
40const MEMBER: &str = "share_instance_metrics";
41
42/// Why engine metrics are off.
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
44#[serde(rename_all = "snake_case")]
45pub enum OffReason {
46    /// `[cloud] metrics_upload = false`.
47    Engine,
48    /// The lease does not include `metrics.upload`.
49    Lease,
50    /// The workspace switched metrics upload off.
51    Workspace,
52    /// This engine was revoked.
53    Revoked,
54    /// The policy rule is off.
55    Policy,
56    /// The policy bundle in force expired or is damaged.
57    PolicyUnavailable,
58    /// Personal: the person has not confirmed yet.
59    NotConfirmed,
60}
61
62/// The decision for one pass.
63#[derive(Debug, Clone, PartialEq, Eq)]
64pub enum Sharing {
65    On {
66        /// Vaults whose own policy turns the rule off.
67        vaults_off: BTreeSet<String>,
68        /// Work outside every vault may be sent (Personal workspace only).
69        unattributed: bool,
70        /// Version of the effective policy in force (0 = none).
71        policy_version: u64,
72        /// Start of the sharing period: no hour before it is built.
73        since: Option<UtcDateTime>,
74        /// Who set it: `None` = the plan default.
75        level: Option<PolicyLevel>,
76    },
77    Off {
78        reason: OffReason,
79        level: Option<PolicyLevel>,
80    },
81}
82
83impl Sharing {
84    pub fn is_on(&self) -> bool {
85        matches!(self, Self::On { .. })
86    }
87
88    /// Cloud still waits for the person's confirmation (an explicit
89    /// `needs_confirmation` answer; no plan asks for it by default any more).
90    pub fn waits_for_confirmation(&self) -> bool {
91        matches!(
92            self,
93            Self::Off {
94                reason: OffReason::NotConfirmed,
95                ..
96            }
97        )
98    }
99
100    /// `on (plan default)` or `off (<why>)` as `cloud status` prints it.
101    pub fn describe(&self) -> String {
102        match self {
103            Self::On { level, .. } => match level {
104                Some(level) => format!("on (set by {})", level.label()),
105                None => "on (plan default)".into(),
106            },
107            Self::Off { reason, level } => {
108                let why = match reason {
109                    OffReason::Engine => "this instance, [cloud] metrics_upload = false",
110                    OffReason::Lease => "the lease does not include metrics.upload",
111                    OffReason::Workspace => "switched off by the workspace",
112                    OffReason::Revoked => "this instance was revoked",
113                    OffReason::Policy => "policy",
114                    OffReason::PolicyUnavailable => "policy, no valid bundle in force",
115                    OffReason::NotConfirmed => {
116                        "waiting for your confirmation: run `lean-ctx cloud metrics confirm` in a terminal"
117                    }
118                };
119                match level {
120                    Some(level) => format!("off ({why}, set by {})", level.label()),
121                    None => format!("off ({why})"),
122                }
123            }
124        }
125    }
126
127    /// The SPEC §4 `now:` words.
128    pub fn now_words(&self) -> String {
129        match self {
130            Self::On { level, .. } => format!(
131                "on, set by {}",
132                level.map_or("plan default", PolicyLevel::label)
133            ),
134            Self::Off {
135                reason: OffReason::NotConfirmed,
136                ..
137            } => "waiting for your confirmation, set by plan default".into(),
138            Self::Off { level, .. } => format!(
139                "off, set by {}",
140                level.map_or("this instance", PolicyLevel::label)
141            ),
142        }
143    }
144}
145
146/// Whether the plan waits for the person's confirmation by default: no
147/// plan does (owner decision 23.11.: metrics are on by default, without a
148/// prompt; turning them off stays possible).
149pub fn needs_confirmation(_plan: CloudPlan) -> bool {
150    false
151}
152
153/// The rule's value in one effective policy: `None` = no level sets it.
154/// Read through JSON so it works whether the protocol types name the
155/// member or keep it among the unknown members.
156fn rule(policy: &EffectivePolicyV1) -> Option<bool> {
157    serde_json::to_value(&policy.sharing)
158        .ok()?
159        .get(MEMBER)?
160        .as_bool()
161}
162
163/// The policy part of the decision, from the installed floor under
164/// `cloud_data`: `Err(reason)` when it turns metrics off.
165pub(crate) fn policy(
166    cloud_data: &Path,
167    now: UtcDateTime,
168) -> Result<(BTreeSet<String>, u64), OffReason> {
169    let dir = effective_floor::floor_dir_in(cloud_data);
170    let (floor, required) =
171        effective_floor::read(&dir).map_err(|_| OffReason::PolicyUnavailable)?;
172    let Some(floor) = effective_floor::check(floor.as_deref(), required.as_deref())
173        .map_err(|_| OffReason::PolicyUnavailable)?
174    else {
175        // K2 (L3): no verified bundle installed means no rule to send under.
176        return Err(OffReason::PolicyUnavailable);
177    };
178    let expired =
179        OffsetDateTime::parse_from_rfc3339(&floor.not_after).map_or(true, |t| t.to_utc() <= now);
180    if expired {
181        return Err(OffReason::PolicyUnavailable);
182    }
183    if rule(&floor.policy.effective) == Some(false) {
184        return Err(OffReason::Policy);
185    }
186    let vaults_off = floor
187        .policy
188        .vaults
189        .iter()
190        .filter(|v| rule(&v.effective) == Some(false))
191        .map(|v| v.vault_id.clone())
192        .collect();
193    Ok((vaults_off, floor.version))
194}
195
196/// The decision from the local switches and the last sharing state Cloud
197/// answered (`None`: not asked yet, the plan default applies).
198pub fn decide_with(
199    store: &CloudStore,
200    config: &CloudConfig,
201    instance: &InstanceRecord,
202    lease: &CloudLeaseV1,
203    sharing: Option<&SharingStateV2>,
204    now: UtcDateTime,
205) -> Sharing {
206    let off = |reason, level| Sharing::Off { reason, level };
207    if !config.metrics_upload {
208        return off(OffReason::Engine, Some(PolicyLevel::Instance));
209    }
210    if crate::revoked::recorded(store, instance).is_some() {
211        return off(OffReason::Revoked, None);
212    }
213    if !lease.grants(CloudRight::MetricsUpload) {
214        return off(OffReason::Lease, None);
215    }
216    if !lease.org_allows_metrics_upload() {
217        return off(OffReason::Workspace, None);
218    }
219    // The workspace's answer first: a person who never confirmed is told so.
220    let (since, level) = match sharing {
221        Some(s) => match s.state {
222            SharingValue::On => (
223                s.since.as_ref().map(TimeStamp::at),
224                s.policy.map(|p| p.level),
225            ),
226            SharingValue::Off => {
227                return off(OffReason::Policy, s.policy.map(|p| p.level));
228            }
229            SharingValue::NeedsConfirmation => return off(OffReason::NotConfirmed, None),
230        },
231        None if needs_confirmation(lease.plan) => return off(OffReason::NotConfirmed, None),
232        None => (None, None),
233    };
234    let (vaults_off, policy_version) = match policy(store.data_dir(), now) {
235        Ok(found) => found,
236        Err(OffReason::Policy) => {
237            return off(
238                OffReason::Policy,
239                sharing.and_then(|s| s.policy).map(|p| p.level),
240            );
241        }
242        Err(reason) => return off(reason, None),
243    };
244    let state = super::buffer::State::load(store.data_dir());
245    if let Some((reason, level)) = state.refused(&lease.lease_id, policy_version) {
246        return off(reason, level);
247    }
248    Sharing::On {
249        vaults_off,
250        unattributed: instance.org_kind.as_deref() == Some("personal"),
251        policy_version,
252        since,
253        level,
254    }
255}
256
257/// [`decide_with`] and the sharing state this engine last received.
258pub fn decide(
259    store: &CloudStore,
260    config: &CloudConfig,
261    instance: &InstanceRecord,
262    lease: &CloudLeaseV1,
263    now: UtcDateTime,
264) -> Sharing {
265    let state = super::buffer::State::load(store.data_dir());
266    let sharing = state.sharing.filter(|_| state.org_id == instance.org_id);
267    decide_with(store, config, instance, lease, sharing.as_ref(), now)
268}
269
270/// The sharing state to report when Cloud has not answered one yet.
271pub fn plan_state(plan: CloudPlan) -> SharingStateV2 {
272    let default_on = !needs_confirmation(plan);
273    SharingStateV2 {
274        state: if default_on {
275            SharingValue::On
276        } else {
277            SharingValue::NeedsConfirmation
278        },
279        plan_default: if default_on {
280            PlanDefault::On
281        } else {
282            PlanDefault::Off
283        },
284        policy: None,
285        confirmed_at: None,
286        since: None,
287    }
288}