Skip to main content

lean_ctx_cloud/
disconnect.rs

1// SPDX-License-Identifier: Apache-2.0
2//! `lean-ctx cloud disconnect`: Cloud is told first, local data goes after.
3//!
4//! The engine revokes its own instance (`DELETE /v1/instances/{id}`, C0
5//! 2.0: the signed statement with reason `web_revoke`; on 1.x the seat is
6//! freed). Only once Cloud confirmed it, or answered that the instance is
7//! already revoked or unknown, are the credentials and local data removed.
8//! Unreachable, the disconnect stays pending (`disconnect-pending.json`):
9//! nothing is removed and the scheduler retries it instead of syncing
10//! (dogfood 25.10.: the CLI said "removed" while the instance stayed active
11//! in Cloud).
12
13use serde::{Deserialize, Serialize};
14
15use super::CloudError;
16use super::auth::Session;
17use super::config::CloudConfig;
18use super::state::{CloudStore, InstanceRecord};
19
20pub(crate) const PENDING_FILE: &str = "disconnect-pending.json";
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
23struct Pending {
24    keep_local: bool,
25}
26
27/// What Cloud said to the disconnect.
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub enum Told {
30    /// Cloud revoked the instance now.
31    Revoked,
32    /// Cloud already had it revoked or does not know it.
33    AlreadyGone,
34    /// Cloud could not be reached; try again later.
35    Unreachable(CloudError),
36    /// Cloud refused (or no session could be built); nothing was removed.
37    Refused(CloudError),
38}
39
40impl Told {
41    /// Whether the local data may go now.
42    pub fn done(&self) -> bool {
43        matches!(self, Self::Revoked | Self::AlreadyGone)
44    }
45}
46
47/// Classify the answer to the revoke call.
48pub fn classify(answer: Result<(), CloudError>) -> Told {
49    match answer {
50        Ok(()) => Told::Revoked,
51        Err(CloudError::Revoked(_) | CloudError::NotFound) => Told::AlreadyGone,
52        Err(e) if e.is_transient() => Told::Unreachable(e),
53        Err(e) => Told::Refused(e),
54    }
55}
56
57/// Ask Cloud to revoke `instance`.
58pub fn tell_cloud(store: &CloudStore, config: &CloudConfig, instance: &InstanceRecord) -> Told {
59    // A revocation recorded before means Cloud already ended it.
60    if super::revoked::recorded(store, instance).is_some() {
61        return Told::AlreadyGone;
62    }
63    classify(
64        super::root_cert::trust_root(store, config, &instance.url)
65            .and_then(|root| Session::load(store.clone(), root))
66            .and_then(|session| session.delete_instance()),
67    )
68}
69
70/// Remember an unfinished disconnect (with its `--keep-local`).
71pub fn mark_pending(store: &CloudStore, keep_local: bool) -> Result<(), CloudError> {
72    store.write_config(PENDING_FILE, &Pending { keep_local })
73}
74
75/// The pending disconnect's `keep_local`, if one is pending.
76pub fn pending(store: &CloudStore) -> Option<bool> {
77    store
78        .read_config::<Pending>(PENDING_FILE)
79        .ok()
80        .flatten()
81        .map(|p| p.keep_local)
82}
83
84/// The scheduler's retry of a pending disconnect: `Some(line)` when one was
85/// pending (finished, or why not yet).
86pub fn retry_pending(
87    store: &CloudStore,
88    config: &CloudConfig,
89    instance: &InstanceRecord,
90) -> Option<Result<String, CloudError>> {
91    let keep_local = pending(store)?;
92    Some(match tell_cloud(store, config, instance) {
93        Told::Revoked | Told::AlreadyGone => store.forget(keep_local).map(|()| {
94            format!(
95                "disconnected {} (pending disconnect finished)",
96                instance.label
97            )
98        }),
99        Told::Unreachable(e) | Told::Refused(e) => Err(e),
100    })
101}
102
103#[cfg(test)]
104mod tests {
105    use super::*;
106
107    #[test]
108    fn local_data_goes_only_after_cloud_answered() {
109        assert!(classify(Ok(())).done());
110        assert!(classify(Err(CloudError::NotFound)).done());
111        assert!(classify(Err(CloudError::Revoked(crate::Revocation::default()))).done());
112        assert!(matches!(
113            classify(Err(CloudError::Offline("dns".into()))),
114            Told::Unreachable(_)
115        ));
116        assert!(matches!(
117            classify(Err(CloudError::Forbidden)),
118            Told::Refused(_)
119        ));
120    }
121
122    #[test]
123    fn an_unreachable_disconnect_stays_pending_and_keeps_everything() {
124        let dir = tempfile::tempdir().unwrap();
125        let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
126        assert_eq!(pending(&store), None);
127        mark_pending(&store, true).unwrap();
128        assert_eq!(pending(&store), Some(true));
129        // Disconnecting for good removes the marker with the credentials.
130        store.forget(false).unwrap();
131        assert_eq!(pending(&store), None);
132    }
133}