Skip to main content

lean_ctx_cloud/consent/
task_key.rs

1// SPDX-License-Identifier: Apache-2.0
2//! The app's task-propose key (rc4-67): an Ed25519 key that lives only in
3//! LeanCTX Code and signs the person's own task proposals
4//! (`leanctx.cloud.task_propose_person.v1`).
5//!
6//! - The engine never holds the private half and never signs with it: it
7//!   keeps the public key ([`TASK_KEY_FILE`], public part only), prepares the
8//!   exact bytes the app signs ([`person_task_signing_input`]) and checks the
9//!   signature the app made before it relays it.
10//! - Scope `task_propose_person.v1` only: never a consent action, a chat
11//!   post or anything else (the Cloud verifies it against this key only).
12//! - The app binds the key at pairing: the device-token request carries
13//!   [`TaskKeyOffer`] (`task_propose_key`) with `bind_signature`, made by the
14//!   task-propose key itself over [`bind_statement`] (proof of possession).
15//! - Encoding: base64url without padding for the key and signatures;
16//!   `key_id = hex(sha256(public key))[..16]`; `instance_public_key` is
17//!   exactly the string the device-token request sends (standard base64).
18
19use base64::Engine as _;
20use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64URL;
21use ed25519_dalek::{Signature, VerifyingKey};
22use lean_ctx_protocol::cloud::tasks::TaskProposeRequestV1;
23use serde::{Deserialize, Serialize};
24use serde_json::{Value, json};
25use sha2::Digest as _;
26
27use crate::CloudStore;
28
29/// The bound task-propose key's public part, in the Cloud config directory.
30pub const TASK_KEY_FILE: &str = "task_propose_key.json";
31/// Domain of the bind statement.
32pub const BIND_DOMAIN: &str = "leanctx.cloud.task_propose_key_bind.v1\n";
33/// Domain of a person's signed task proposal.
34pub const PERSON_TASK_DOMAIN: &str = "leanctx.cloud.task_propose_person.v1\n";
35/// The one scope a task-propose key is bound for.
36pub const SCOPE: &str = "task_propose_person.v1";
37/// The one algorithm.
38pub const ALG: &str = "ed25519";
39/// The device-token request member.
40pub const REQUEST_MEMBER: &str = "task_propose_key";
41
42/// `task_propose_key` of the device-token request, as the app hands it
43/// over (`lean-ctx cloud connect --json --task-propose-key -`, stdin).
44#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
45#[serde(deny_unknown_fields)]
46pub struct TaskKeyOffer {
47    pub alg: String,
48    /// base64url, raw 32 bytes.
49    pub public_key: String,
50    pub key_id: String,
51    /// base64url signature of the task-propose key over [`bind_statement`].
52    pub bind_signature: String,
53}
54
55/// The bound task-propose key, public part only.
56#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
57#[serde(deny_unknown_fields)]
58pub struct BoundTaskKey {
59    pub alg: String,
60    pub key_id: String,
61    pub public_key: String,
62}
63
64/// `hex(sha256(public key bytes))[..16]`.
65pub fn key_id_of(public_key: &[u8]) -> String {
66    hex::encode(sha2::Sha256::digest(public_key))[..16].to_owned()
67}
68
69/// The bytes the task-propose key signs to bind itself:
70/// [`BIND_DOMAIN`] ‖ canonical_json({alg, instance_public_key, key_id,
71/// public_key, scope}).
72pub fn bind_statement(
73    instance_public_key: &str,
74    key_id: &str,
75    alg: &str,
76    public_key: &str,
77) -> Result<Vec<u8>, String> {
78    lean_ctx_protocol::cloud::signing_input(
79        BIND_DOMAIN,
80        &json!({
81            "alg": alg,
82            "instance_public_key": instance_public_key,
83            "key_id": key_id,
84            "public_key": public_key,
85            "scope": SCOPE,
86        }),
87    )
88    .map_err(|e| e.to_string())
89}
90
91/// `(instance_id, vault_id)` as the Cloud checks a person's proposal
92/// against them: the dashed lowercase UUID of the instance (cloud v2 ids
93/// are always UUIDs) and the vault's 32 lowercase hex. `None` when either
94/// is no such id, `inst_` forms of old enrollments included: a signature
95/// over another spelling would be refused as unproven.
96pub fn canonical_person_ids(instance_id: &str, vault_id: &str) -> Option<(String, String)> {
97    let instance = instance_id.trim().to_ascii_lowercase();
98    let vault = vault_id.trim().to_ascii_lowercase();
99    let lower_hex = |s: &str| {
100        s.bytes()
101            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
102    };
103    let uuid = instance.len() == 36
104        && instance.split('-').map(str::len).eq([8, 4, 4, 4, 12])
105        && instance.split('-').all(lower_hex);
106    (uuid && vault.len() == 32 && lower_hex(&vault)).then_some((instance, vault))
107}
108
109/// The bytes the app signs for a person's proposal `request` (sent as
110/// `POST /v1/vaults/{vault_id}/tasks`): [`PERSON_TASK_DOMAIN`] ‖
111/// canonical_json(the body without `task_signature`, plus `instance_id`
112/// and `vault_id`).
113pub fn person_task_signing_input(
114    request: &TaskProposeRequestV1,
115    instance_id: &str,
116    vault_id: &str,
117) -> Result<Vec<u8>, String> {
118    let Value::Object(mut body) = serde_json::to_value(request).map_err(|e| e.to_string())? else {
119        return Err("a task proposal is an object".into());
120    };
121    body.remove("task_signature");
122    body.insert("instance_id".into(), instance_id.into());
123    body.insert("vault_id".into(), vault_id.into());
124    lean_ctx_protocol::cloud::signing_input(PERSON_TASK_DOMAIN, &Value::Object(body))
125        .map_err(|e| e.to_string())
126}
127
128impl BoundTaskKey {
129    fn verifying_key(&self) -> Option<VerifyingKey> {
130        if self.alg != ALG {
131            return None;
132        }
133        let bytes = B64URL.decode(&self.public_key).ok()?;
134        if key_id_of(&bytes) != self.key_id {
135            return None;
136        }
137        VerifyingKey::from_bytes(&<[u8; 32]>::try_from(bytes).ok()?).ok()
138    }
139
140    /// Whether the file is an ed25519 key whose `key_id` matches.
141    pub fn consistent(&self) -> bool {
142        self.verifying_key().is_some()
143    }
144
145    /// Whether `signature` (base64url, 64 bytes) is this key's over `message`.
146    pub fn verifies(&self, message: &[u8], signature: &str) -> bool {
147        let (Some(key), Ok(raw)) = (self.verifying_key(), B64URL.decode(signature)) else {
148            return false;
149        };
150        Signature::from_slice(&raw).is_ok_and(|sig| key.verify_strict(message, &sig).is_ok())
151    }
152}
153
154impl TaskKeyOffer {
155    /// The offer in `raw` (JSON), checked against `instance_public_key`. A
156    /// refusal names what is wrong, never key material.
157    pub fn parse(raw: &str, instance_public_key: &str) -> Result<Self, String> {
158        let offer: Self = serde_json::from_str(raw.trim())
159            .map_err(|_| "the task key is not {alg, public_key, key_id, bind_signature}")?;
160        offer.check(instance_public_key)?;
161        Ok(offer)
162    }
163
164    /// The offer in `raw` (JSON), its shape only ([`Self::well_formed`]),
165    /// before the instance key is known.
166    pub fn parse_shape(raw: &str) -> Result<Self, String> {
167        let offer: Self = serde_json::from_str(raw.trim())
168            .map_err(|_| "the task key is not {alg, public_key, key_id, bind_signature}")?;
169        if !offer.well_formed() {
170            return Err("the task key is not an ed25519 key with its key_id".into());
171        }
172        Ok(offer)
173    }
174
175    /// ed25519, a 32-byte key, its `key_id`, and a bind signature of the
176    /// key itself that verifies over [`bind_statement`].
177    pub fn check(&self, instance_public_key: &str) -> Result<(), String> {
178        let bound = self.public();
179        if self.alg != ALG {
180            return Err("the task key's alg is not ed25519".into());
181        }
182        if !bound.consistent() {
183            return Err("the task key's key_id does not match its public key".into());
184        }
185        let statement = bind_statement(
186            instance_public_key,
187            &self.key_id,
188            &self.alg,
189            &self.public_key,
190        )?;
191        if !bound.verifies(&statement, &self.bind_signature) {
192            return Err("the task key's bind signature does not verify".into());
193        }
194        Ok(())
195    }
196
197    /// The shape alone (alg, a 32-byte key, its `key_id`).
198    pub fn well_formed(&self) -> bool {
199        self.alg == ALG && self.public().consistent()
200    }
201
202    /// The public part this machine keeps.
203    pub fn public(&self) -> BoundTaskKey {
204        BoundTaskKey {
205            alg: self.alg.clone(),
206            key_id: self.key_id.clone(),
207            public_key: self.public_key.clone(),
208        }
209    }
210
211    /// The `task_propose_key` member of the device-token request.
212    pub fn request_member(&self) -> Value {
213        json!({
214            "alg": self.alg,
215            "public_key": self.public_key,
216            "key_id": self.key_id,
217            "bind_signature": self.bind_signature,
218        })
219    }
220}
221
222/// Keep the public part of `offer` as this machine's task-propose key.
223pub fn store_bound(store: &CloudStore, offer: &TaskKeyOffer) -> Result<(), crate::CloudError> {
224    store.write_config(TASK_KEY_FILE, &offer.public())
225}
226
227/// Forget the bound task-propose key (a pairing without one).
228pub fn remove_bound(store: &CloudStore) -> Result<(), crate::CloudError> {
229    store.remove_config(TASK_KEY_FILE)
230}
231
232/// The bound task-propose key, when its file is consistent.
233pub fn bound_task_key(store: &CloudStore) -> Option<BoundTaskKey> {
234    store
235        .read_config::<BoundTaskKey>(TASK_KEY_FILE)
236        .ok()
237        .flatten()
238        .filter(BoundTaskKey::consistent)
239}
240
241#[cfg(test)]
242pub(crate) mod tests {
243    use super::*;
244    use base64::engine::general_purpose::STANDARD as B64;
245    use ed25519_dalek::{Signer as _, SigningKey};
246
247    /// Test key only (the p37 vector): seed =
248    /// sha256("leanctx-cloud test task-propose key: rc4-67").
249    pub(crate) fn test_key() -> SigningKey {
250        let seed: [u8; 32] =
251            sha2::Sha256::digest(b"leanctx-cloud test task-propose key: rc4-67").into();
252        SigningKey::from_bytes(&seed)
253    }
254
255    /// The vector's `instance_public_key`: standard base64 of the Ed25519
256    /// key of seed sha256("leanctx-cloud test instance key: rc4-67").
257    pub(crate) fn instance_public_key() -> String {
258        let seed: [u8; 32] =
259            sha2::Sha256::digest(b"leanctx-cloud test instance key: rc4-67").into();
260        B64.encode(SigningKey::from_bytes(&seed).verifying_key().to_bytes())
261    }
262
263    pub(crate) fn sign(key: &SigningKey, message: &[u8]) -> String {
264        B64URL.encode(key.sign(message).to_bytes())
265    }
266
267    pub(crate) fn offer(key: &SigningKey, instance_public_key: &str) -> TaskKeyOffer {
268        let public_key = B64URL.encode(key.verifying_key().to_bytes());
269        let key_id = key_id_of(&key.verifying_key().to_bytes());
270        let statement = bind_statement(instance_public_key, &key_id, ALG, &public_key).unwrap();
271        TaskKeyOffer {
272            alg: ALG.into(),
273            bind_signature: sign(key, &statement),
274            public_key,
275            key_id,
276        }
277    }
278
279    // The p37 vector (`task_propose_key.vectors.json`, p37 !298), pinned.
280    const VECTOR_SEED: &str = "575463aa529a2bc97d74cb71d5e3007a81a4606fea13872867c68f480e650cce";
281    const VECTOR_KEY_ID: &str = "affaec5b6c1add96";
282    const VECTOR_BIND_SIGNATURE: &str =
283        "Fgk2EZ-XWttZPolVvHaMIyPqk_EMLScalp8qxUBEeL1wbqs4cvQd5l-HrzdH_uR6-OK9uWV0bjD0K3UnhQI0Cg";
284    const VECTOR_INSTANCE_ID: &str = "3f1c2b6a-8d4e-4a7b-9c10-5e2f6a7b8c09";
285    const VECTOR_VAULT_ID: &str = "9d2e4f6a1b3c4d5e8f7a6b5c4d3e2f1a";
286    const VECTOR_TASK_SIGNATURE: &str =
287        "OGzdIhUg_HO7JT0XJssV-pqSkN2WBu6SL6dGN2fuXzs5fZxT-fF0X865cAoJIWCz_9bzCsJpyeewB4hiiDpqAg";
288    /// The vector's `body` (= `task_propose.person.request.json`).
289    const VECTOR_BODY: &str = r#"{"schema":"leanctx.cloud.task-propose/v1","session_ref":"leanctx-code","title":"Show the retry budget in settings","acceptance":"The settings page names the retry budget and links its fact","origin":{"kind":"person"},"signed_at":"2026-11-24T09:30:00Z","task_signature":"OGzdIhUg_HO7JT0XJssV-pqSkN2WBu6SL6dGN2fuXzs5fZxT-fF0X865cAoJIWCz_9bzCsJpyeewB4hiiDpqAg"}"#;
290    const VECTOR_PROPOSE_INPUT: &str = "leanctx.cloud.task_propose_person.v1\n{\"acceptance\":\"The settings page names the retry budget and links its fact\",\"instance_id\":\"3f1c2b6a-8d4e-4a7b-9c10-5e2f6a7b8c09\",\"origin\":{\"kind\":\"person\"},\"schema\":\"leanctx.cloud.task-propose/v1\",\"session_ref\":\"leanctx-code\",\"signed_at\":\"2026-11-24T09:30:00Z\",\"title\":\"Show the retry budget in settings\",\"vault_id\":\"9d2e4f6a1b3c4d5e8f7a6b5c4d3e2f1a\"}";
291
292    fn vector_bound() -> BoundTaskKey {
293        let key = test_key();
294        BoundTaskKey {
295            alg: ALG.into(),
296            key_id: key_id_of(&key.verifying_key().to_bytes()),
297            public_key: B64URL.encode(key.verifying_key().to_bytes()),
298        }
299    }
300
301    #[test]
302    fn task_key_bind_statement_is_the_p37_vector() {
303        let key = test_key();
304        assert_eq!(hex::encode(key.to_bytes()), VECTOR_SEED);
305        let ipk = instance_public_key();
306        let bound = vector_bound();
307        assert_eq!(bound.key_id, VECTOR_KEY_ID);
308        let statement = bind_statement(&ipk, &bound.key_id, ALG, &bound.public_key).unwrap();
309        let expected = format!(
310            "leanctx.cloud.task_propose_key_bind.v1\n{{\"alg\":\"ed25519\",\"instance_public_key\":\"{ipk}\",\"key_id\":\"{VECTOR_KEY_ID}\",\"public_key\":\"{}\",\"scope\":\"task_propose_person.v1\"}}",
311            bound.public_key
312        );
313        assert_eq!(statement, expected.as_bytes(), "bind bytes");
314        // The vector's bind signature is the task key's own (proof of
315        // possession), not the instance key's.
316        assert!(bound.verifies(&statement, VECTOR_BIND_SIGNATURE));
317        let offer = TaskKeyOffer {
318            alg: ALG.into(),
319            public_key: bound.public_key.clone(),
320            key_id: bound.key_id.clone(),
321            bind_signature: VECTOR_BIND_SIGNATURE.into(),
322        };
323        let raw = serde_json::to_string(&offer.request_member()).unwrap();
324        assert_eq!(TaskKeyOffer::parse(&raw, &ipk).unwrap(), offer);
325        // Ed25519 is deterministic: the test key makes the same signature.
326        assert_eq!(sign(&key, &statement), VECTOR_BIND_SIGNATURE);
327    }
328
329    #[test]
330    fn person_task_signing_input_is_the_p37_vector() {
331        let request: TaskProposeRequestV1 = serde_json::from_str(VECTOR_BODY).unwrap();
332        request.validate().unwrap();
333        let input =
334            person_task_signing_input(&request, VECTOR_INSTANCE_ID, VECTOR_VAULT_ID).unwrap();
335        assert_eq!(input, VECTOR_PROPOSE_INPUT.as_bytes(), "signing bytes");
336        assert!(vector_bound().verifies(&input, VECTOR_TASK_SIGNATURE));
337        // The same body without its signature prepares the same bytes.
338        let mut unsigned = request.clone();
339        unsigned.task_signature = None;
340        assert_eq!(
341            person_task_signing_input(&unsigned, VECTOR_INSTANCE_ID, VECTOR_VAULT_ID).unwrap(),
342            input
343        );
344        // Sent with the signature, the body is the vector's body.
345        let sent: Value = serde_json::to_value(&request).unwrap();
346        assert_eq!(sent, serde_json::from_str::<Value>(VECTOR_BODY).unwrap());
347        // Another vault or instance does not verify.
348        let other =
349            person_task_signing_input(&request, VECTOR_INSTANCE_ID, "0".repeat(32).as_str())
350                .unwrap();
351        assert!(!vector_bound().verifies(&other, VECTOR_TASK_SIGNATURE));
352    }
353
354    #[test]
355    fn task_key_offers_that_do_not_check_out_are_refused() {
356        let ipk = instance_public_key();
357        let good = offer(&test_key(), &ipk);
358        good.check(&ipk).unwrap();
359        let raw = serde_json::to_string(&good.request_member()).unwrap();
360        assert!(
361            TaskKeyOffer::parse(&raw, "AAAA")
362                .unwrap_err()
363                .contains("bind signature")
364        );
365        // A bind signed by another key (e.g. the instance key) is refused.
366        let mut foreign = good.clone();
367        let statement = bind_statement(&ipk, &good.key_id, ALG, &good.public_key).unwrap();
368        foreign.bind_signature = sign(&SigningKey::from_bytes(&[7; 32]), &statement);
369        assert!(foreign.check(&ipk).is_err());
370        let mut wrong_id = good.clone();
371        wrong_id.key_id = "ab".repeat(8);
372        assert!(wrong_id.check(&ipk).unwrap_err().contains("key_id"));
373        assert!(TaskKeyOffer::parse_shape(&serde_json::to_string(&wrong_id).unwrap()).is_err());
374        let mut wrong_alg = good.clone();
375        wrong_alg.alg = "p256_ecdsa_sha256".into();
376        assert!(wrong_alg.check(&ipk).is_err());
377        let extra = r#"{"alg":"ed25519","public_key":"x","key_id":"y","bind_signature":"z","private_key":"k"}"#;
378        assert!(TaskKeyOffer::parse(extra, &ipk).is_err());
379    }
380
381    #[test]
382    fn task_key_store_keeps_only_the_public_part() {
383        let dir = tempfile::tempdir().unwrap();
384        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
385        assert_eq!(bound_task_key(&store), None);
386        let offer = offer(&test_key(), &instance_public_key());
387        store_bound(&store, &offer).unwrap();
388        let text = std::fs::read_to_string(dir.path().join("config").join(TASK_KEY_FILE)).unwrap();
389        assert!(!text.contains("bind_signature"), "{text}");
390        assert_eq!(bound_task_key(&store), Some(offer.public()));
391        remove_bound(&store).unwrap();
392        assert_eq!(bound_task_key(&store), None);
393    }
394}