Skip to main content

lean_ctx_cloud/consent/
chat_key.rs

1// SPDX-License-Identifier: Apache-2.0
2//! The device chat key (rc4-32): an Ed25519 key that lives only in LeanCTX
3//! Code and signs the person's posts (`leanctx.cloud.person_publish.v1`).
4//!
5//! - The engine never holds the private half and never signs with it: it
6//!   keeps the public key ([`CHAT_KEY_FILE`], public part only) and checks
7//!   a signature the app made. No [`super::person_sign::PersonSigner`] is
8//!   ever built from it.
9//! - Scope `person_publish.v1` only: never a consent action (bind check,
10//!   opt-in, task pickup), which keep the presence key.
11//! - The app binds the key at pairing: the device-token request carries
12//!   [`ChatKeyOffer`] with `bind_signature` over [`bind_statement`].
13//! - Encoding: base64url without padding everywhere;
14//!   `key_id = hex(sha256(public key))[..16]`.
15
16use base64::Engine as _;
17use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64URL;
18use ed25519_dalek::{Signature, Verifier as _, VerifyingKey};
19use serde::{Deserialize, Serialize};
20use serde_json::{Value, json};
21use sha2::Digest as _;
22
23use crate::CloudStore;
24
25/// The bound chat key's public part, in the Cloud config directory.
26pub const CHAT_KEY_FILE: &str = "chat_key.json";
27/// Domain of the bind statement.
28pub const BIND_DOMAIN: &str = "leanctx.cloud.chat_key_bind.v1\n";
29/// The one scope a chat key is bound for.
30pub const SCOPE: &str = "person_publish.v1";
31/// The one algorithm.
32pub const ALG: &str = "ed25519";
33
34/// `chat_key` of the device-token request, as the app hands it over
35/// (`lean-ctx cloud connect --json --chat-key -`, stdin).
36#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
37#[serde(deny_unknown_fields)]
38pub struct ChatKeyOffer {
39    pub alg: String,
40    /// base64url, raw 32 bytes.
41    pub public_key: String,
42    pub key_id: String,
43    /// base64url signature of the chat key over [`bind_statement`].
44    pub bind_signature: String,
45}
46
47/// The bound chat key, public part only.
48#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
49#[serde(deny_unknown_fields)]
50pub struct BoundChatKey {
51    pub alg: String,
52    pub key_id: String,
53    pub public_key: String,
54}
55
56/// `hex(sha256(public key bytes))[..16]`.
57pub fn key_id_of(public_key: &[u8]) -> String {
58    hex::encode(sha2::Sha256::digest(public_key))[..16].to_owned()
59}
60
61/// The bytes the chat key signs to bind itself:
62/// [`BIND_DOMAIN`] ‖ canonical_json({instance_public_key, key_id, alg,
63/// public_key, scope}). `instance_public_key` is exactly the string the
64/// device-token request sends.
65pub fn bind_statement(
66    instance_public_key: &str,
67    key_id: &str,
68    alg: &str,
69    public_key: &str,
70) -> Result<Vec<u8>, String> {
71    lean_ctx_protocol::cloud::signing_input(
72        BIND_DOMAIN,
73        &json!({
74            "instance_public_key": instance_public_key,
75            "key_id": key_id,
76            "alg": alg,
77            "public_key": public_key,
78            "scope": SCOPE,
79        }),
80    )
81    .map_err(|e| e.to_string())
82}
83
84impl BoundChatKey {
85    fn verifying_key(&self) -> Option<VerifyingKey> {
86        if self.alg != ALG {
87            return None;
88        }
89        let bytes = B64URL.decode(&self.public_key).ok()?;
90        if key_id_of(&bytes) != self.key_id {
91            return None;
92        }
93        VerifyingKey::from_bytes(&<[u8; 32]>::try_from(bytes).ok()?).ok()
94    }
95
96    /// Whether the file is an ed25519 key whose `key_id` matches.
97    pub fn consistent(&self) -> bool {
98        self.verifying_key().is_some()
99    }
100
101    /// Whether `signature` (base64url, 64 bytes) is this key's over `message`.
102    pub fn verifies(&self, message: &[u8], signature: &str) -> bool {
103        let (Some(key), Ok(raw)) = (self.verifying_key(), B64URL.decode(signature)) else {
104            return false;
105        };
106        Signature::from_slice(&raw).is_ok_and(|sig| key.verify(message, &sig).is_ok())
107    }
108}
109
110impl ChatKeyOffer {
111    /// The offer in `raw` (JSON), checked against `instance_public_key`:
112    /// ed25519, a 32-byte key, its `key_id`, and a bind signature that
113    /// verifies. A refusal names what is wrong, never key material.
114    pub fn parse(raw: &str, instance_public_key: &str) -> Result<Self, String> {
115        let offer: Self = serde_json::from_str(raw.trim())
116            .map_err(|_| "the chat key is not {alg, public_key, key_id, bind_signature}")?;
117        offer.check(instance_public_key)?;
118        Ok(offer)
119    }
120
121    /// The checks of [`Self::parse`].
122    pub fn check(&self, instance_public_key: &str) -> Result<(), String> {
123        let bound = self.public();
124        if self.alg != ALG {
125            return Err("the chat key's alg is not ed25519".into());
126        }
127        if !bound.consistent() {
128            return Err("the chat key's key_id does not match its public key".into());
129        }
130        let statement = bind_statement(
131            instance_public_key,
132            &self.key_id,
133            &self.alg,
134            &self.public_key,
135        )?;
136        if !bound.verifies(&statement, &self.bind_signature) {
137            return Err("the chat key's bind signature does not verify".into());
138        }
139        Ok(())
140    }
141
142    /// The shape alone (alg, a 32-byte key, its `key_id`), before the
143    /// instance key is known; [`Self::check`] adds the bind signature.
144    pub fn well_formed(&self) -> bool {
145        self.alg == ALG && self.public().consistent()
146    }
147
148    /// The public part this machine keeps.
149    pub fn public(&self) -> BoundChatKey {
150        BoundChatKey {
151            alg: self.alg.clone(),
152            key_id: self.key_id.clone(),
153            public_key: self.public_key.clone(),
154        }
155    }
156
157    /// The `chat_key` member of the device-token request.
158    pub fn request_member(&self) -> Value {
159        json!({
160            "alg": self.alg,
161            "public_key": self.public_key,
162            "key_id": self.key_id,
163            "bind_signature": self.bind_signature,
164        })
165    }
166}
167
168/// Keep the public part of `offer` as this machine's chat key.
169pub fn store_bound(store: &CloudStore, offer: &ChatKeyOffer) -> Result<(), crate::CloudError> {
170    store.write_config(CHAT_KEY_FILE, &offer.public())
171}
172
173/// The bound chat key, when its file is consistent.
174pub fn bound_chat_key(store: &CloudStore) -> Option<BoundChatKey> {
175    store
176        .read_config::<BoundChatKey>(CHAT_KEY_FILE)
177        .ok()
178        .flatten()
179        .filter(BoundChatKey::consistent)
180}
181
182/// What the relay checks a prepared, app-signed person post with: the
183/// bound chat key and the Instance id the signature covers.
184#[derive(Debug, Clone, PartialEq, Eq)]
185pub struct ChatKeyCheck {
186    pub key: BoundChatKey,
187    pub instance_id: String,
188}
189
190impl ChatKeyCheck {
191    pub fn load(store: &CloudStore, instance_id: &str) -> Option<Self> {
192        bound_chat_key(store).map(|key| Self {
193            key,
194            instance_id: instance_id.to_owned(),
195        })
196    }
197
198    /// Whether `signature` is the chat key's over `frame` under the person
199    /// publish rule ([`super::person_sign::signing_input`]).
200    pub fn admits(&self, domain: &str, frame: &Value, signature: &str) -> bool {
201        super::person_sign::signing_input(domain, frame, &self.instance_id)
202            .is_ok_and(|input| self.key.verifies(&input, signature))
203    }
204}
205
206#[cfg(test)]
207pub(crate) mod tests {
208    use super::*;
209    use ed25519_dalek::{Signer as _, SigningKey};
210
211    /// Test key only: seed = sha256("leanctx test chat key: rc4-32").
212    pub(crate) fn test_key() -> SigningKey {
213        let seed: [u8; 32] = sha2::Sha256::digest(b"leanctx test chat key: rc4-32").into();
214        SigningKey::from_bytes(&seed)
215    }
216
217    pub(crate) fn sign(key: &SigningKey, message: &[u8]) -> String {
218        B64URL.encode(key.sign(message).to_bytes())
219    }
220
221    pub(crate) const INSTANCE_PUBLIC_KEY: &str = "Vt7FhcqVvGkAq4sRk6m0Kx8wQ2c1mF0lJj3p9aYb5Zs";
222
223    pub(crate) fn offer(key: &SigningKey) -> ChatKeyOffer {
224        offer_for(key, INSTANCE_PUBLIC_KEY)
225    }
226
227    pub(crate) fn offer_for(key: &SigningKey, instance_public_key: &str) -> ChatKeyOffer {
228        let public_key = B64URL.encode(key.verifying_key().to_bytes());
229        let key_id = key_id_of(&key.verifying_key().to_bytes());
230        let statement = bind_statement(instance_public_key, &key_id, ALG, &public_key).unwrap();
231        ChatKeyOffer {
232            alg: ALG.into(),
233            bind_signature: sign(key, &statement),
234            public_key,
235            key_id,
236        }
237    }
238
239    #[test]
240    fn chat_key_bind_statement_is_the_fixed_vector() {
241        let key = test_key();
242        let offer = offer(&key);
243        let statement =
244            bind_statement(INSTANCE_PUBLIC_KEY, &offer.key_id, ALG, &offer.public_key).unwrap();
245        let expected = format!(
246            "leanctx.cloud.chat_key_bind.v1\n{{\"alg\":\"ed25519\",\"instance_public_key\":\"{INSTANCE_PUBLIC_KEY}\",\"key_id\":\"{}\",\"public_key\":\"{}\",\"scope\":\"person_publish.v1\"}}",
247            offer.key_id, offer.public_key
248        );
249        assert_eq!(String::from_utf8(statement).unwrap(), expected);
250        eprintln!(
251            "CHAT_KEY_VECTOR public_key={} key_id={} bind_signature={}",
252            offer.public_key, offer.key_id, offer.bind_signature
253        );
254        assert_eq!(offer.public_key, VECTOR_PUBLIC_KEY);
255        assert_eq!(offer.key_id, VECTOR_KEY_ID);
256        assert_eq!(offer.bind_signature, VECTOR_BIND_SIGNATURE);
257        let raw = serde_json::to_string(&offer.request_member()).unwrap();
258        assert_eq!(
259            ChatKeyOffer::parse(&raw, INSTANCE_PUBLIC_KEY).unwrap(),
260            offer
261        );
262    }
263
264    #[test]
265    fn chat_key_offers_that_do_not_check_out_are_refused() {
266        let good = offer(&test_key());
267        let other_instance = ChatKeyOffer::parse(
268            &serde_json::to_string(&good.request_member()).unwrap(),
269            "AAAA",
270        );
271        assert!(other_instance.unwrap_err().contains("bind signature"));
272        let mut wrong_id = good.clone();
273        wrong_id.key_id = "ab".repeat(8);
274        assert!(
275            wrong_id
276                .check(INSTANCE_PUBLIC_KEY)
277                .unwrap_err()
278                .contains("key_id")
279        );
280        let mut wrong_alg = good.clone();
281        wrong_alg.alg = "p256_ecdsa_sha256".into();
282        assert!(wrong_alg.check(INSTANCE_PUBLIC_KEY).is_err());
283        let extra = r#"{"alg":"ed25519","public_key":"x","key_id":"y","bind_signature":"z","private_key":"k"}"#;
284        assert!(ChatKeyOffer::parse(extra, INSTANCE_PUBLIC_KEY).is_err());
285    }
286
287    #[test]
288    fn chat_key_store_keeps_only_the_public_part() {
289        let dir = tempfile::tempdir().unwrap();
290        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
291        assert_eq!(bound_chat_key(&store), None);
292        let offer = offer(&test_key());
293        store_bound(&store, &offer).unwrap();
294        let text = std::fs::read_to_string(dir.path().join("config").join(CHAT_KEY_FILE)).unwrap();
295        assert!(!text.contains("bind_signature"), "{text}");
296        assert_eq!(bound_chat_key(&store), Some(offer.public()));
297        // The engine still builds no signer: a bound chat key signs nothing here.
298        assert!(super::super::person_sign::person_signer(&store, "x").is_none());
299    }
300
301    /// The vector's values (seed above, [`INSTANCE_PUBLIC_KEY`]).
302    const VECTOR_PUBLIC_KEY: &str = "-uq_H2bZ-l58clOy_DlWn_CAv7D-Kr3pCrtG0SNSvis";
303    const VECTOR_KEY_ID: &str = "b87ae058e7c0c071";
304    const VECTOR_BIND_SIGNATURE: &str =
305        "GEc1nMaKbFix_W43sPHpSnXHDtx-a3JFtXgOHSPI8v8cKqwcmn-8n-QG4C2m5MccM5LUlV8jjvxJ0dyzGXURAA";
306}