Skip to main content

lean_ctx_cloud/consent/
optin_key.rs

1// SPDX-License-Identifier: Apache-2.0
2//! The opt-in key (rc4-16, owner decision 24.11.): an Ed25519 key that lives
3//! only in LeanCTX Code (its Keychain) and signs the person's "turn task
4//! pickup on" without a prompt per click.
5//!
6//! - The engine never holds the private half and never signs with it: it
7//!   keeps the public key ([`OPTIN_KEY_FILE`], public part only), checks a
8//!   turn-on the app signed, and forwards it unchanged.
9//! - Scope `optin.v1` only: the signing domain is exactly
10//!   [`lean_ctx_protocol::cloud::optin::OPTIN_SIGNING_DOMAIN`]; a chat post,
11//!   a consent proof or anything else is never signed with it.
12//! - Binding (p37 contract): the key signs [`bind_statement`] itself (proof
13//!   of possession) over this computer's `instance_public_key`, and the bind
14//!   travels as `optin_key` on `POST /v1/device/token` (a first connect, or a
15//!   re-bind through the device flow with the same instance keys). The
16//!   Cloud's 2xx token answer is what makes the key usable: until then it is
17//!   kept here as pending ([`store_pending`]), and [`bound_optin_key`]
18//!   returns a key only once it was accepted ([`mark_accepted`]) and the
19//!   enrolled Cloud announces [`FEATURE_INSTANCE_OPTIN_KEY`].
20//! - Connect (rc4-16): `lean-ctx cloud connect --json --app-keys -` with
21//!   `optin_key` checks the [`OptinKeyOffer`] before anything is sent, sends
22//!   it as [`REQUEST_MEMBER`] on the token request, and keeps it accepted
23//!   ([`store_pending`] then [`mark_accepted`]) after a 2xx answer; a 409
24//!   `optin_key_cleared` calls [`clear_accepted`]. The offer it sends comes
25//!   only from the app on stdin, never rebuilt from `optin_key.json`:
26//!   agents can write that file, and it holds no bind signature.
27//! - Encoding: base64url without padding for the opt-in key and its
28//!   signatures; `key_id = hex(sha256(public key))[..16]`;
29//!   `instance_public_key` exactly as sent in the token request (standard
30//!   base64).
31
32use base64::Engine as _;
33use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64URL;
34use ed25519_dalek::{Signature, Verifier as _, VerifyingKey};
35use serde::{Deserialize, Serialize};
36use serde_json::{Value, json};
37use sha2::Digest as _;
38
39use crate::CloudStore;
40
41/// The opt-in key's public part, in the Cloud config directory.
42pub const OPTIN_KEY_FILE: &str = "optin_key.json";
43/// Domain of the bind statement.
44pub const BIND_DOMAIN: &str = "leanctx.cloud.optin_key_bind.v1\n";
45/// The one scope an opt-in key is bound for.
46pub const SCOPE: &str = "optin.v1";
47/// The one algorithm.
48pub const ALG: &str = "ed25519";
49/// The `GET /v1/capabilities` feature of a Cloud that verifies turn-ons
50/// against the bound opt-in key.
51pub const FEATURE_INSTANCE_OPTIN_KEY: &str = "instance_optin_key";
52
53/// The member of `POST /v1/device/token` that carries the offer.
54pub const REQUEST_MEMBER: &str = "optin_key";
55
56/// The key as the app hands it over.
57#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
58#[serde(deny_unknown_fields)]
59pub struct OptinKeyOffer {
60    pub alg: String,
61    /// base64url, raw 32 bytes.
62    pub public_key: String,
63    pub key_id: String,
64    /// base64url signature of the opt-in key over [`bind_statement`].
65    pub bind_signature: String,
66}
67
68/// The opt-in key kept here, public part only.
69#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
70#[serde(deny_unknown_fields)]
71pub struct BoundOptinKey {
72    pub alg: String,
73    pub key_id: String,
74    pub public_key: String,
75    /// The Cloud took the bind (a 2xx token answer). False while pending.
76    #[serde(default)]
77    pub accepted: bool,
78}
79
80/// `hex(sha256(public key bytes))[..16]`.
81pub fn key_id_of(public_key: &[u8]) -> String {
82    hex::encode(sha2::Sha256::digest(public_key))[..16].to_owned()
83}
84
85/// The bytes the opt-in key signs to bind itself to this computer:
86/// [`BIND_DOMAIN`] ‖ canonical_json({alg, instance_public_key, key_id,
87/// public_key, scope}). `instance_public_key` is the string the token
88/// request carries (standard base64 of the instance key).
89pub fn bind_statement(
90    instance_public_key: &str,
91    key_id: &str,
92    alg: &str,
93    public_key: &str,
94) -> Result<Vec<u8>, String> {
95    lean_ctx_protocol::cloud::signing_input(
96        BIND_DOMAIN,
97        &json!({
98            "alg": alg,
99            "instance_public_key": instance_public_key,
100            "key_id": key_id,
101            "public_key": public_key,
102            "scope": SCOPE,
103        }),
104    )
105    .map_err(|e| e.to_string())
106}
107
108impl BoundOptinKey {
109    fn verifying_key(&self) -> Option<VerifyingKey> {
110        if self.alg != ALG {
111            return None;
112        }
113        let bytes = B64URL.decode(&self.public_key).ok()?;
114        if key_id_of(&bytes) != self.key_id {
115            return None;
116        }
117        VerifyingKey::from_bytes(&<[u8; 32]>::try_from(bytes).ok()?).ok()
118    }
119
120    /// Whether the file is an ed25519 key whose `key_id` matches.
121    pub fn consistent(&self) -> bool {
122        self.verifying_key().is_some()
123    }
124
125    /// Whether `signature` (base64url, 64 bytes) is this key's over `message`.
126    pub fn verifies(&self, message: &[u8], signature: &str) -> bool {
127        let (Some(key), Ok(raw)) = (self.verifying_key(), B64URL.decode(signature)) else {
128            return false;
129        };
130        Signature::from_slice(&raw).is_ok_and(|sig| key.verify(message, &sig).is_ok())
131    }
132
133    /// Whether `signature` is this key's over the turn-on `body` of
134    /// Instance `instance_id` ([`super::person_sign::signing_input`] under
135    /// the opt-in domain).
136    pub fn admits_turn_on(&self, body: &Value, instance_id: &str, signature: &str) -> bool {
137        super::person_sign::signing_input(
138            lean_ctx_protocol::cloud::optin::OPTIN_SIGNING_DOMAIN,
139            body,
140            instance_id,
141        )
142        .is_ok_and(|input| self.verifies(&input, signature))
143    }
144}
145
146impl OptinKeyOffer {
147    /// The checks before a key is kept, as the Cloud makes them: ed25519, a
148    /// 32-byte key, its `key_id`, and the key's own signature over the bind
149    /// statement for `instance_public_key`. A refusal names what is wrong,
150    /// never key material.
151    pub fn check(&self, instance_public_key: &str) -> Result<(), String> {
152        let key = self.public();
153        if self.alg != ALG {
154            return Err("the opt-in key's alg is not ed25519".into());
155        }
156        if !key.consistent() {
157            return Err("the opt-in key's key_id does not match its public key".into());
158        }
159        let statement = bind_statement(
160            instance_public_key,
161            &self.key_id,
162            &self.alg,
163            &self.public_key,
164        )?;
165        if !key.verifies(&statement, &self.bind_signature) {
166            return Err("the opt-in key's bind signature does not verify".into());
167        }
168        Ok(())
169    }
170
171    /// Whether alg, key and `key_id` fit (the bind signature is checked
172    /// against this computer's key by [`Self::check`]).
173    pub fn well_formed(&self) -> bool {
174        self.alg == ALG && self.public().consistent()
175    }
176
177    /// The `optin_key` member of the device-token request.
178    pub fn request_member(&self) -> Value {
179        json!({
180            "alg": self.alg,
181            "public_key": self.public_key,
182            "key_id": self.key_id,
183            "bind_signature": self.bind_signature,
184        })
185    }
186
187    /// The public part this machine keeps, not yet accepted.
188    pub fn public(&self) -> BoundOptinKey {
189        BoundOptinKey {
190            alg: self.alg.clone(),
191            key_id: self.key_id.clone(),
192            public_key: self.public_key.clone(),
193            accepted: false,
194        }
195    }
196}
197
198fn stored(store: &CloudStore) -> Option<BoundOptinKey> {
199    store
200        .read_config::<BoundOptinKey>(OPTIN_KEY_FILE)
201        .ok()
202        .flatten()
203        .filter(BoundOptinKey::consistent)
204}
205
206/// Keep the public part of `offer` until the Cloud takes the bind. The same
207/// key again keeps its acceptance; another key replaces it as pending.
208pub fn store_pending(store: &CloudStore, offer: &OptinKeyOffer) -> Result<(), crate::CloudError> {
209    let accepted = stored(store).is_some_and(|k| k.accepted && k.key_id == offer.key_id);
210    store.write_config(
211        OPTIN_KEY_FILE,
212        &BoundOptinKey {
213            accepted,
214            ..offer.public()
215        },
216    )
217}
218
219/// Record that the Cloud took the bind of `key_id` (a 2xx token answer).
220/// False when the kept key is another one.
221pub fn mark_accepted(store: &CloudStore, key_id: &str) -> Result<bool, crate::CloudError> {
222    match stored(store) {
223        Some(mut key) if key.key_id == key_id => {
224            key.accepted = true;
225            store.write_config(OPTIN_KEY_FILE, &key)?;
226            Ok(true)
227        }
228        _ => Ok(false),
229    }
230}
231
232/// The Cloud no longer holds the key (409 `optin_key_cleared`): back to
233/// pending.
234pub fn clear_accepted(store: &CloudStore) -> Result<(), crate::CloudError> {
235    if let Some(mut key) = stored(store).filter(|k| k.accepted) {
236        key.accepted = false;
237        store.write_config(OPTIN_KEY_FILE, &key)?;
238    }
239    Ok(())
240}
241
242/// The opt-in key kept here, accepted or not.
243pub fn pending_optin_key(store: &CloudStore) -> Option<BoundOptinKey> {
244    stored(store)
245}
246
247/// The opt-in key that can turn task pickup on: kept here, accepted by the
248/// Cloud, and the enrolled Cloud announces [`FEATURE_INSTANCE_OPTIN_KEY`].
249pub fn bound_optin_key(store: &CloudStore) -> Option<BoundOptinKey> {
250    stored(store)
251        .filter(|k| k.accepted && crate::session_ref::announced(store, FEATURE_INSTANCE_OPTIN_KEY))
252}
253
254#[cfg(test)]
255pub mod test_key {
256    //! A fixed opt-in key for tests (the app's key, never the engine's).
257    use super::*;
258    use ed25519_dalek::{Signer as _, SigningKey};
259
260    pub const INSTANCE_ID: &str = "3f1c2b6a-8d4e-4a7b-9c10-5e2f6a7b8c09";
261    /// Standard base64 of 32 bytes, as the token request carries it.
262    pub const INSTANCE_PUBLIC_KEY: &str = "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE=";
263
264    pub fn key() -> SigningKey {
265        SigningKey::from_bytes(&[7u8; 32])
266    }
267
268    pub fn sign(key: &SigningKey, message: &[u8]) -> String {
269        B64URL.encode(key.sign(message).to_bytes())
270    }
271
272    pub fn offer(key: &SigningKey, instance_public_key: &str) -> OptinKeyOffer {
273        let public_key = B64URL.encode(key.verifying_key().to_bytes());
274        let key_id = key_id_of(&key.verifying_key().to_bytes());
275        let statement = bind_statement(instance_public_key, &key_id, ALG, &public_key).unwrap();
276        OptinKeyOffer {
277            alg: ALG.into(),
278            public_key,
279            key_id,
280            bind_signature: sign(key, &statement),
281        }
282    }
283}
284
285#[cfg(test)]
286mod tests {
287    use super::test_key::{INSTANCE_ID, INSTANCE_PUBLIC_KEY, key, offer, sign};
288    use super::*;
289
290    /// The p37 opt-in vector (`contracts/cloud-v2/fixtures/vectors/
291    /// optin.vectors.json`): seed, body, signing input and signature.
292    const VECTOR_SEED: &str = "46da4b21837ca6e42b4e8f26541d12a8152f962c97ee51f52eb4d00b5c2cbc58";
293    const VECTOR_INPUT: &str = "leanctx.cloud.optin.v1\n{\"active\":true,\"daily_budget\":{\"tasks\":3,\"tokens\":1000000},\"instance_id\":\"3f1c2b6a-8d4e-4a7b-9c10-5e2f6a7b8c09\",\"prev_optin_id\":\"opt_7a1d4c2e9b3f4e6a8c5d0f1e2a3b4c5d\",\"schema\":\"leanctx.cloud.instance-optin-on/v1\",\"vaults\":[\"0f3c2b6a8d4e4a7b9c105e2f6a7b8c01\"]}";
294    const VECTOR_SIGNATURE: &str =
295        "tKv5Z23pifLgCDpvE2jqgMR9uih1A-9lukZt8ko_inLa2DqoQ0uqUW0wfJV6B-IuP3QFyRyj66zZdxeFhxuIBQ";
296
297    fn vector_body() -> Value {
298        json!({
299            "schema": "leanctx.cloud.instance-optin-on/v1",
300            "active": true,
301            "prev_optin_id": "opt_7a1d4c2e9b3f4e6a8c5d0f1e2a3b4c5d",
302            "vaults": ["0f3c2b6a8d4e4a7b9c105e2f6a7b8c01"],
303            "daily_budget": {"tasks": 3, "tokens": 1_000_000},
304        })
305    }
306
307    #[test]
308    fn pickup_optin_signing_input_and_signature_match_the_cloud_vector() {
309        let input = super::super::person_sign::signing_input(
310            lean_ctx_protocol::cloud::optin::OPTIN_SIGNING_DOMAIN,
311            &vector_body(),
312            INSTANCE_ID,
313        )
314        .unwrap();
315        assert_eq!(String::from_utf8(input.clone()).unwrap(), VECTOR_INPUT);
316        let seed: [u8; 32] = hex::decode(VECTOR_SEED).unwrap().try_into().unwrap();
317        let key = ed25519_dalek::SigningKey::from_bytes(&seed);
318        assert_eq!(sign(&key, &input), VECTOR_SIGNATURE);
319        let bound = test_key::offer(&key, INSTANCE_PUBLIC_KEY).public();
320        assert!(bound.admits_turn_on(&vector_body(), INSTANCE_ID, VECTOR_SIGNATURE));
321        // Another instance, a changed body or another domain: refused.
322        assert!(!bound.admits_turn_on(
323            &vector_body(),
324            "00000000-0000-4000-8000-000000000000",
325            VECTOR_SIGNATURE
326        ));
327        let mut changed = vector_body();
328        changed["daily_budget"]["tasks"] = json!(4);
329        assert!(!bound.admits_turn_on(&changed, INSTANCE_ID, VECTOR_SIGNATURE));
330    }
331
332    /// The p37 opt-in key vector (`contracts/cloud-v2/fixtures/vectors/
333    /// optin_key.vectors.json`, p37 !307 @8a430385): the bind statement and
334    /// the turn-on signature, byte for byte, both signatures verified.
335    mod optin_key_vector {
336        pub(super) const SEED: &str =
337            "9255f0c0a33e1b276f658b9ddf007e5017482d3b5d29a3c1cb3aae45df460251";
338        pub(super) const PUBLIC_KEY: &str = "h-5BejEvZBRC3aIStZGiozVi4uf7gZ8veK-p7mkpyjU";
339        pub(super) const KEY_ID: &str = "1b20740d444f4fb5";
340        pub(super) const INSTANCE_PUBLIC_KEY: &str = "ioEkWHZo5VtdH2xcZCQff/UUv9C2VZlpZzW7qf3qhNo=";
341        pub(super) const BIND_SIGNATURE: &str = "0cwbxvvScrR7fS3rBT6JmlCmSDpbrBD7xBrkdU4cTG0T6LhkJDp6xTpePzXrSo9NePrFZz4nYV_I6VEC0_AXBQ";
342        pub(super) const OPTIN_SIGNATURE: &str = "TBWmm3lcYfhlZH_gByquAks8MwdiA5UyzoGOvpwUOBaJUKv5t4pc8pswzRJigB4ewgpI5MF8uLjQ4yWwlqK5DA";
343    }
344
345    #[test]
346    fn pickup_optin_key_bind_and_turn_on_match_the_cloud_vector() {
347        use optin_key_vector as v;
348        use sha2::Digest as _;
349        let seed: [u8; 32] = hex::decode(v::SEED).unwrap().try_into().unwrap();
350        let key = ed25519_dalek::SigningKey::from_bytes(&seed);
351        assert_eq!(B64URL.encode(key.verifying_key().to_bytes()), v::PUBLIC_KEY);
352        assert_eq!(key_id_of(&key.verifying_key().to_bytes()), v::KEY_ID);
353        // The test instance key as p37 derives it (standard base64).
354        let instance_seed: [u8; 32] =
355            sha2::Sha256::digest(b"leanctx-cloud test instance key: rc4-67")
356                .as_slice()
357                .try_into()
358                .unwrap();
359        let instance = ed25519_dalek::SigningKey::from_bytes(&instance_seed);
360        assert_eq!(
361            base64::engine::general_purpose::STANDARD.encode(instance.verifying_key().to_bytes()),
362            v::INSTANCE_PUBLIC_KEY
363        );
364        // Bind statement, byte for byte, and its signature.
365        let statement =
366            bind_statement(v::INSTANCE_PUBLIC_KEY, v::KEY_ID, ALG, v::PUBLIC_KEY).unwrap();
367        assert_eq!(
368            String::from_utf8(statement.clone()).unwrap(),
369            format!(
370                "leanctx.cloud.optin_key_bind.v1\n{{\"alg\":\"ed25519\",\"instance_public_key\":\"{}\",\"key_id\":\"{}\",\"public_key\":\"{}\",\"scope\":\"optin.v1\"}}",
371                v::INSTANCE_PUBLIC_KEY,
372                v::KEY_ID,
373                v::PUBLIC_KEY
374            )
375        );
376        assert_eq!(sign(&key, &statement), v::BIND_SIGNATURE);
377        let offer = OptinKeyOffer {
378            alg: ALG.into(),
379            public_key: v::PUBLIC_KEY.into(),
380            key_id: v::KEY_ID.into(),
381            bind_signature: v::BIND_SIGNATURE.into(),
382        };
383        offer.check(v::INSTANCE_PUBLIC_KEY).unwrap();
384        assert!(offer.check(INSTANCE_PUBLIC_KEY).is_err());
385        // The turn-on: same body and instance as the opt-in vector.
386        let input = super::super::person_sign::signing_input(
387            lean_ctx_protocol::cloud::optin::OPTIN_SIGNING_DOMAIN,
388            &vector_body(),
389            INSTANCE_ID,
390        )
391        .unwrap();
392        assert_eq!(String::from_utf8(input.clone()).unwrap(), VECTOR_INPUT);
393        assert_eq!(sign(&key, &input), v::OPTIN_SIGNATURE);
394        let bound = offer.public();
395        assert!(bound.admits_turn_on(&vector_body(), INSTANCE_ID, v::OPTIN_SIGNATURE));
396        assert!(!bound.admits_turn_on(&vector_body(), INSTANCE_ID, VECTOR_SIGNATURE));
397        assert!(!bound.verifies(&statement, v::OPTIN_SIGNATURE));
398    }
399
400    #[test]
401    fn pickup_optin_key_bind_is_signed_by_the_key_over_the_instance_public_key() {
402        let key = key();
403        let good = offer(&key, INSTANCE_PUBLIC_KEY);
404        let statement =
405            bind_statement(INSTANCE_PUBLIC_KEY, &good.key_id, ALG, &good.public_key).unwrap();
406        let text = String::from_utf8(statement).unwrap();
407        assert_eq!(
408            text,
409            format!(
410                "leanctx.cloud.optin_key_bind.v1\n{{\"alg\":\"ed25519\",\"instance_public_key\":\"{INSTANCE_PUBLIC_KEY}\",\"key_id\":\"{}\",\"public_key\":\"{}\",\"scope\":\"optin.v1\"}}",
411                good.key_id, good.public_key
412            )
413        );
414        good.check(INSTANCE_PUBLIC_KEY).unwrap();
415        // Bound over another instance key, or the instance id: refused.
416        assert!(
417            good.check("AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI=")
418                .is_err()
419        );
420        assert!(offer(&key, INSTANCE_ID).check(INSTANCE_PUBLIC_KEY).is_err());
421        let mut alg = good.clone();
422        alg.alg = "p256".into();
423        assert!(alg.check(INSTANCE_PUBLIC_KEY).is_err());
424        let mut id = good.clone();
425        id.key_id = "0000000000000000".into();
426        assert!(id.check(INSTANCE_PUBLIC_KEY).is_err());
427        let mut sig = good;
428        sig.bind_signature = sign(&key, b"something else");
429        assert!(sig.check(INSTANCE_PUBLIC_KEY).is_err());
430    }
431
432    #[test]
433    fn pickup_optin_key_is_usable_only_once_the_cloud_took_and_announced_it() {
434        let dir = tempfile::tempdir().unwrap();
435        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
436        assert!(bound_optin_key(&store).is_none());
437        let good = offer(&key(), INSTANCE_PUBLIC_KEY);
438        store_pending(&store, &good).unwrap();
439        let text = std::fs::read_to_string(dir.path().join("config").join(OPTIN_KEY_FILE)).unwrap();
440        assert!(!text.contains("bind_signature"));
441        assert_eq!(pending_optin_key(&store), Some(good.public()));
442        assert!(bound_optin_key(&store).is_none(), "pending");
443        assert!(!mark_accepted(&store, "0000000000000000").unwrap());
444        assert!(mark_accepted(&store, &good.key_id).unwrap());
445        assert!(bound_optin_key(&store).is_none(), "not announced");
446        let instance: crate::state::InstanceRecord = serde_json::from_value(json!({
447            "instance_id": INSTANCE_ID, "org_id": "org_acme", "org_name": "Platform",
448            "label": "laptop", "url": "https://cloud.example", "org_salt_id": "salt",
449            "enrolled_at": "2026-11-16T12:00:00Z"
450        }))
451        .unwrap();
452        store
453            .write_config(crate::state::INSTANCE_FILE, &instance)
454            .unwrap();
455        crate::session_ref::record(
456            &store,
457            "https://cloud.example",
458            vec![FEATURE_INSTANCE_OPTIN_KEY.into()],
459        )
460        .unwrap();
461        assert!(bound_optin_key(&store).is_some_and(|k| k.accepted));
462        // The same key handed over again stays accepted; another is pending.
463        store_pending(&store, &good).unwrap();
464        assert!(bound_optin_key(&store).is_some());
465        clear_accepted(&store).unwrap();
466        assert!(bound_optin_key(&store).is_none(), "cleared");
467        mark_accepted(&store, &good.key_id).unwrap();
468        let other = offer(
469            &ed25519_dalek::SigningKey::from_bytes(&[8u8; 32]),
470            INSTANCE_PUBLIC_KEY,
471        );
472        store_pending(&store, &other).unwrap();
473        assert!(bound_optin_key(&store).is_none(), "another key");
474    }
475}