Skip to main content

lean_ctx_cloud/
session_ref.rs

1// SPDX-License-Identifier: Apache-2.0
2//! V9 `session_ref`: the session a write names, and whether the enrolled
3//! Cloud may hear it.
4//!
5//! An older Cloud refuses the closed event envelope and receipt document
6//! with the member, and a refused signed event or receipt batch is moved
7//! to `outbox/failed` for good. So the engine reads `GET /v1/capabilities`
8//! (cached per server in `<config>/capabilities.json`, refreshed with the
9//! instance card) and attaches a session only while that server announces
10//! the `session_ref` feature.
11//!
12//! What leaves is never the session id: it is an HMAC-SHA256 under the
13//! engine-local receipts key (`receipts.hmac-key`, never uploaded), so Cloud
14//! cannot test a guessed id (session ids carry a timestamp and a process id
15//! and are guessable). Events name only sessions this engine generated
16//! ([`lean_ctx::core::session::is_engine_session_id`]); labels such as an
17//! import never become a session.
18//!
19//! The older body field `session_ref` (`ses_` and 24 hex characters) of
20//! drafts, task claims, task proposals and episodes needs no capability:
21//! its shape is unchanged. It is keyed the same way ([`uploaded_ses_ref`]);
22//! when the local key cannot be read or created, the write is not uploaded
23//! at all, so no unsalted digest of a guessable session id leaves the
24//! machine.
25
26use std::path::Path;
27
28use serde::{Deserialize, Serialize};
29
30use crate::CloudError;
31use crate::receipts::ReceiptKey;
32use crate::state::CloudStore;
33use crate::transport::CloudClient;
34
35/// The `features` entry of a Cloud that accepts `session_ref`
36/// (`cloud_wire::engine::FEATURE_SESSION_REF`).
37pub const FEATURE_SESSION_REF: &str = "session_ref";
38
39/// Prefix of the envelope ref: `hs_` and 32 lowercase hex characters, the
40/// first half of the receipt's `hmac-sha256:` value for the same input.
41pub const EVENT_REF_PREFIX: &str = "hs_";
42
43pub(crate) const CAPABILITIES_FILE: &str = "capabilities.json";
44/// Bounds what a cached answer may hold.
45const MAX_FEATURES: usize = 64;
46const MAX_FEATURE_LEN: usize = 64;
47
48#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
49struct Capabilities {
50    /// The origin that answered; a different enrolled server reads none.
51    server: String,
52    features: Vec<String>,
53}
54
55/// The features of a `GET /v1/capabilities` answer, bounded; an answer of
56/// another shape announces nothing.
57fn features_of(answer: &serde_json::Value) -> Vec<String> {
58    if answer["schema"] != "leanctx.cloud.capabilities/v1" {
59        return Vec::new();
60    }
61    answer["features"]
62        .as_array()
63        .into_iter()
64        .flatten()
65        .filter_map(serde_json::Value::as_str)
66        .filter(|f| !f.is_empty() && f.len() <= MAX_FEATURE_LEN)
67        .take(MAX_FEATURES)
68        .map(str::to_string)
69        .collect()
70}
71
72/// Record what `server` announced.
73pub fn record(store: &CloudStore, server: &str, features: Vec<String>) -> Result<(), CloudError> {
74    store.write_config(
75        CAPABILITIES_FILE,
76        &Capabilities {
77            server: server.to_string(),
78            features,
79        },
80    )
81}
82
83/// Ask the enrolled Cloud what it accepts and record it. A Cloud without the
84/// route announces nothing; any other failure keeps the last answer.
85pub fn refresh(store: &CloudStore, server: &str, client: &CloudClient) -> Result<(), CloudError> {
86    record(store, server, announced_by(client.get("/capabilities"))?)
87}
88
89/// The features a capabilities request announced. A 404, whether typed or
90/// a bare status from a proxy in front of a downgraded server, announces
91/// nothing, so the cached capability is cleared.
92fn announced_by(answer: Result<serde_json::Value, CloudError>) -> Result<Vec<String>, CloudError> {
93    match answer {
94        Ok(answer) => Ok(features_of(&answer)),
95        Err(CloudError::NotFound | CloudError::Server { status: 404, .. }) => Ok(Vec::new()),
96        Err(error) => Err(error),
97    }
98}
99
100/// Whether the server this machine is enrolled with announced `feature`
101/// when last asked.
102pub fn announced(store: &CloudStore, feature: &str) -> bool {
103    let Ok(Some(instance)) = store.instance() else {
104        return false;
105    };
106    store
107        .read_config::<Capabilities>(CAPABILITIES_FILE)
108        .ok()
109        .flatten()
110        .is_some_and(|c| c.server == instance.url && c.features.iter().any(|f| f == feature))
111}
112
113/// Keyed session refs, present only while the enrolled Cloud accepts them.
114pub struct SessionRefs(ReceiptKey);
115
116impl SessionRefs {
117    /// `None` when the enrolled Cloud did not announce `session_ref` or the
118    /// local key cannot be read: nothing then carries a session.
119    pub fn for_store(store: &CloudStore) -> Option<Self> {
120        if !announced(store, FEATURE_SESSION_REF) {
121            return None;
122        }
123        ReceiptKey::load_or_create(store.data_dir()).map(Self)
124    }
125
126    #[cfg(test)]
127    pub(crate) fn from_key(key: ReceiptKey) -> Self {
128        Self(key)
129    }
130
131    /// The envelope `session_ref` of the engine session `id`, or `None` when
132    /// `id` is no session this engine generated.
133    pub fn event_ref(&self, id: &str) -> Option<String> {
134        let id = id.trim();
135        lean_ctx::core::session::is_engine_session_id(id)
136            .then(|| format!("{EVENT_REF_PREFIX}{}", &self.0.mac_hex("session", id)[..32]))
137    }
138
139    /// The `ses_` ref an uploaded episode body names session `id` by: the
140    /// contract shape of [`crate::knowledge::draft::session_ref`] (`ses_` and
141    /// 24 hex characters), but keyed under the local receipts key with its
142    /// own label, so the server can neither test a guessed id against it nor
143    /// tie it to the envelope ref of the same event.
144    pub fn episode_ref(&self, id: &str) -> String {
145        keyed_ses_ref(&self.0, id)
146    }
147}
148
149/// HMAC label of every keyed body `ses_` ref. One label for all bodies, so
150/// the drafts, claims, proposals and episode of one session keep naming it
151/// alike (as the unsalted ref did), apart from the envelope `hs_` ref.
152const BODY_REF_LABEL: &str = "session.episode";
153
154fn keyed_ses_ref(key: &ReceiptKey, id: &str) -> String {
155    format!("ses_{}", &key.mac_hex(BODY_REF_LABEL, id.trim())[..24])
156}
157
158/// HMAC label of a queued ref re-keyed at upload: a draft or proposal
159/// queued before the body refs were keyed holds only the unsalted digest
160/// (never the session id), so that digest is keyed instead.
161const LEGACY_REF_LABEL: &str = "session.legacy-ref";
162
163/// Why nothing naming a session is uploaded: the local receipts key cannot
164/// be read or created, and the unsalted digest of a guessable session id
165/// must not stand in for the keyed one.
166pub const NO_SESSION_KEY: &str = "the local receipts key (receipts.hmac-key) cannot be read or \
167     created, so nothing that names a session is uploaded; check the permissions of the Cloud \
168     data directory";
169
170fn local_key(cloud_data: &Path) -> Result<ReceiptKey, CloudError> {
171    ReceiptKey::load_or_create(cloud_data).ok_or_else(|| CloudError::Local(NO_SESSION_KEY.into()))
172}
173
174/// The body `ses_` ref an upload (draft, task claim, task proposal,
175/// episode) names session `id` (or a fixed label such as `cli-import`) by:
176/// keyed under the local receipts key in `cloud_data`
177/// ([`SessionRefs::episode_ref`], no capability needed, the shape is
178/// unchanged). When that key cannot be read or created this is an error
179/// ([`NO_SESSION_KEY`]) and the caller skips the upload: every contract
180/// that carries the field requires it, and the unsalted
181/// [`crate::knowledge::draft::session_ref`] of a guessable id never stands
182/// in. Local-only uses (file names, done markers) keep the unsalted ref.
183pub fn uploaded_ses_ref(cloud_data: &Path, id: &str) -> Result<String, CloudError> {
184    local_key(cloud_data).map(|key| keyed_ses_ref(&key, id))
185}
186
187/// The ref a draft or proposal queued before body refs were keyed is sent
188/// with: its stored unsalted `ses_` digest (the queue never kept the
189/// session id), keyed under the local key with its own label. Errors as
190/// [`uploaded_ses_ref`] does, and the item then stays queued.
191pub fn rekeyed_legacy_ref(cloud_data: &Path, stored: &str) -> Result<String, CloudError> {
192    local_key(cloud_data).map(|key| {
193        format!(
194            "ses_{}",
195            &key.mac_hex(LEGACY_REF_LABEL, stored.trim())[..24]
196        )
197    })
198}
199
200/// Make the receipts key in `cloud_data` impossible to read or create: a
201/// directory sits where the key file belongs.
202#[cfg(test)]
203pub(crate) fn make_keyless(cloud_data: &Path) {
204    std::fs::create_dir_all(cloud_data.join("receipts.hmac-key")).unwrap();
205}
206
207#[cfg(test)]
208mod tests {
209    use super::*;
210    use serde_json::json;
211
212    const ID: &str = "20261116-091500u123456p4242s0";
213
214    fn refs() -> SessionRefs {
215        SessionRefs::from_key(ReceiptKey::from_bytes([7; 32]))
216    }
217
218    #[test]
219    fn an_event_ref_is_keyed_and_names_only_generated_sessions() {
220        let r = refs().event_ref(ID).unwrap();
221        assert!(r.starts_with(EVENT_REF_PREFIX) && r.len() == 35, "{r}");
222        assert!(crate::events::build::valid_session_ref(&r));
223        assert_eq!(refs().event_ref(ID), Some(r.clone()));
224        let other = SessionRefs::from_key(ReceiptKey::from_bytes([8; 32]));
225        assert_ne!(other.event_ref(ID), Some(r));
226        for label in ["import", "cloud-link", "mcp-4242-0001", "", "ses_1"] {
227            assert_eq!(refs().event_ref(label), None, "{label}");
228        }
229    }
230
231    #[test]
232    fn nothing_carries_a_session_unless_the_enrolled_server_announced_it() {
233        let dir = tempfile::tempdir().unwrap();
234        let store = CloudStore::at(dir.path().join("config"), dir.path().join("cloud"));
235        assert!(SessionRefs::for_store(&store).is_none(), "not enrolled");
236        let instance: crate::state::InstanceRecord = serde_json::from_value(json!({
237            "instance_id": "inst_1", "org_id": "org_acme", "org_name": "Platform",
238            "label": "laptop", "url": "https://cloud.example", "org_salt_id": "salt",
239            "enrolled_at": "2026-11-16T12:00:00Z"
240        }))
241        .unwrap();
242        store
243            .write_config(crate::state::INSTANCE_FILE, &instance)
244            .unwrap();
245        assert!(SessionRefs::for_store(&store).is_none(), "never asked");
246        record(&store, "https://cloud.example", vec!["device_setup".into()]).unwrap();
247        assert!(SessionRefs::for_store(&store).is_none(), "an older Cloud");
248        record(
249            &store,
250            "https://other.example",
251            vec![FEATURE_SESSION_REF.into()],
252        )
253        .unwrap();
254        assert!(
255            SessionRefs::for_store(&store).is_none(),
256            "another server's answer"
257        );
258        record(
259            &store,
260            "https://cloud.example",
261            vec![FEATURE_SESSION_REF.into()],
262        )
263        .unwrap();
264        let refs = SessionRefs::for_store(&store).unwrap();
265        assert!(refs.event_ref(ID).is_some());
266    }
267
268    #[test]
269    fn only_a_capabilities_answer_announces_features() {
270        let ok = json!({"schema": "leanctx.cloud.capabilities/v1",
271                        "features": ["device_setup", "session_ref", 3]});
272        assert_eq!(features_of(&ok), ["device_setup", "session_ref"]);
273        assert!(features_of(&json!({"features": ["session_ref"]})).is_empty());
274        let long = json!({"schema": "leanctx.cloud.capabilities/v1",
275                          "features": ["x".repeat(65)]});
276        assert!(features_of(&long).is_empty());
277        // The contract answer of a Cloud with V9 (cloud-v2 fixture).
278        let fixture: serde_json::Value = serde_json::from_str(include_str!(
279            "../../lean-ctx-protocol/tests/fixtures/cloud-v2/routes/capabilities.response.json"
280        ))
281        .unwrap();
282        assert!(
283            features_of(&fixture)
284                .iter()
285                .any(|f| f == FEATURE_SESSION_REF)
286        );
287    }
288
289    #[test]
290    fn an_episode_ref_keeps_the_contract_shape_but_is_keyed_apart() {
291        let r = refs().episode_ref(ID);
292        let unsalted = crate::knowledge::draft::session_ref(ID);
293        assert!(r.starts_with("ses_") && r.len() == unsalted.len(), "{r}");
294        assert!(r[4..].chars().all(|c| c.is_ascii_hexdigit()));
295        assert_ne!(r, unsalted);
296        assert_eq!(refs().episode_ref(ID), r);
297        let event = refs().event_ref(ID).unwrap();
298        assert!(!event.contains(&r[4..]) && !r.contains(&event[3..27]));
299        let other = SessionRefs::from_key(ReceiptKey::from_bytes([8; 32]));
300        assert_ne!(other.episode_ref(ID), r);
301    }
302
303    #[test]
304    fn an_uploaded_body_ref_is_keyed_under_the_local_key_without_a_capability() {
305        let dir = tempfile::tempdir().unwrap();
306        let r = uploaded_ses_ref(dir.path(), ID).unwrap();
307        let unsalted = crate::knowledge::draft::session_ref(ID);
308        assert!(r.starts_with("ses_") && r.len() == unsalted.len(), "{r}");
309        assert!(r[4..].chars().all(|c| c.is_ascii_hexdigit()));
310        assert_ne!(r, unsalted, "never the unsalted digest");
311        assert!(!r.contains(ID));
312        // Stable across calls (the key is kept), the same value an episode
313        // body gets under that key, and another machine's key differs.
314        assert_eq!(uploaded_ses_ref(dir.path(), ID).unwrap(), r);
315        let local = ReceiptKey::load_or_create(dir.path()).unwrap();
316        assert_eq!(SessionRefs::from_key(local).episode_ref(ID), r);
317        let other = tempfile::tempdir().unwrap();
318        assert_ne!(uploaded_ses_ref(other.path(), ID).unwrap(), r);
319    }
320
321    #[test]
322    fn without_a_readable_key_no_ref_is_made_rather_than_the_unsalted_one() {
323        let dir = tempfile::tempdir().unwrap();
324        make_keyless(dir.path());
325        assert!(ReceiptKey::load_or_create(dir.path()).is_none());
326        for id in [ID, "cli-import", "emspace-import"] {
327            let error = uploaded_ses_ref(dir.path(), id).unwrap_err();
328            assert!(error.to_string().contains("receipts.hmac-key"), "{error}");
329            let stored = crate::knowledge::draft::session_ref(id);
330            assert!(rekeyed_legacy_ref(dir.path(), &stored).is_err());
331        }
332    }
333
334    #[test]
335    fn a_queued_legacy_ref_is_keyed_apart_from_a_fresh_one() {
336        let dir = tempfile::tempdir().unwrap();
337        let stored = crate::knowledge::draft::session_ref(ID);
338        let rekeyed = rekeyed_legacy_ref(dir.path(), &stored).unwrap();
339        assert!(rekeyed.starts_with("ses_") && rekeyed.len() == stored.len());
340        assert!(rekeyed[4..].chars().all(|c| c.is_ascii_hexdigit()));
341        assert_ne!(rekeyed, stored, "never the unsalted digest");
342        assert_ne!(rekeyed, uploaded_ses_ref(dir.path(), ID).unwrap());
343        assert_eq!(rekeyed_legacy_ref(dir.path(), &stored).unwrap(), rekeyed);
344        let other = tempfile::tempdir().unwrap();
345        assert_ne!(rekeyed_legacy_ref(other.path(), &stored).unwrap(), rekeyed);
346    }
347
348    #[test]
349    fn a_404_from_a_proxy_clears_the_capability_like_a_missing_route() {
350        for gone in [
351            CloudError::NotFound,
352            CloudError::Server {
353                status: 404,
354                code: "unknown".into(),
355            },
356        ] {
357            assert_eq!(announced_by(Err(gone)).unwrap(), Vec::<String>::new());
358        }
359        let busy = CloudError::Server {
360            status: 503,
361            code: "unknown".into(),
362        };
363        assert!(announced_by(Err(busy)).is_err(), "keeps the last answer");
364        let ok = json!({"schema": "leanctx.cloud.capabilities/v1", "features": ["session_ref"]});
365        assert_eq!(announced_by(Ok(ok)).unwrap(), [FEATURE_SESSION_REF]);
366    }
367
368    #[test]
369    fn the_event_ref_is_the_receipt_hmac_of_the_same_input_cut_to_fit() {
370        let key = ReceiptKey::from_bytes([7; 32]);
371        let full = key.mac_hex("session", ID);
372        assert_eq!(
373            refs().event_ref(ID).unwrap()[EVENT_REF_PREFIX.len()..],
374            full[..32]
375        );
376    }
377}