1use base64::Engine as _;
25use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64URL;
26use serde::{Deserialize, Serialize};
27use serde_json::{Value, json};
28use sha2::{Digest, Sha256};
29
30use super::signing_input;
31use crate::ValidationError;
32
33pub const FEATURE_DEVICE_APP_KEYS: &str = "device_app_keys";
37pub const APP_KEY_BIND_DOMAIN: &str = "leanctx.cloud.app_key_bind.v1\n";
39pub const APP_KEY_ALG: &str = "ed25519";
41pub const MAX_APP_KEYS: usize = 3;
43pub const APP_KEY_ID_LEN: usize = 16;
45pub const APP_KEY_ERROR_CODE: &str = "invalid_field";
47pub const REASON_APP_KEY_NOT_ANNOUNCED: &str = "app_key_not_announced";
49pub const REASON_APP_KEY_BIND_INVALID: &str = "app_key_bind_invalid";
51pub const PAIRING_FAILED_TEXT: &str = "Pairing failed, please start connecting again.";
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
56#[serde(rename_all = "snake_case")]
57pub enum AppKeyKind {
58 Chat,
60 Optin,
62 TaskPropose,
64}
65
66impl AppKeyKind {
67 pub const ALL: [Self; 3] = [Self::Chat, Self::Optin, Self::TaskPropose];
68
69 pub fn as_str(self) -> &'static str {
71 match self {
72 Self::Chat => "chat",
73 Self::Optin => "optin",
74 Self::TaskPropose => "task_propose",
75 }
76 }
77
78 pub fn request_member(self) -> &'static str {
80 match self {
81 Self::Chat => "chat_key",
82 Self::Optin => "optin_key",
83 Self::TaskPropose => "task_propose_key",
84 }
85 }
86
87 pub fn bind_domain(self) -> &'static str {
89 match self {
90 Self::Chat => "leanctx.cloud.chat_key_bind.v1\n",
91 Self::Optin => "leanctx.cloud.optin_key_bind.v1\n",
92 Self::TaskPropose => "leanctx.cloud.task_propose_key_bind.v1\n",
93 }
94 }
95
96 pub fn scope(self) -> &'static str {
98 match self {
99 Self::Chat => "person_publish.v1",
100 Self::Optin => "optin.v1",
101 Self::TaskPropose => "task_propose_person.v1",
102 }
103 }
104
105 pub fn label(self) -> &'static str {
107 match self {
108 Self::Chat => "Chat messages",
109 Self::Optin => "Task pickup",
110 Self::TaskPropose => "Task proposals",
111 }
112 }
113}
114
115#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
117#[serde(deny_unknown_fields)]
118pub struct AppKeyAnnouncementV1 {
119 pub kind: AppKeyKind,
120 pub alg: String,
122 pub key_id: String,
124 pub public_key: String,
126}
127
128#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
130#[serde(deny_unknown_fields)]
131pub struct AppKeyOfferV1 {
132 pub alg: String,
133 pub public_key: String,
135 pub key_id: String,
136 pub bind_signature: String,
138}
139
140pub fn app_key_id(public_key: &[u8]) -> String {
142 let mut id = lower_hex(&Sha256::digest(public_key));
143 id.truncate(APP_KEY_ID_LEN);
144 id
145}
146
147fn lower_hex(bytes: &[u8]) -> String {
148 use std::fmt::Write as _;
149 bytes.iter().fold(String::new(), |mut out, byte| {
150 let _ = write!(out, "{byte:02x}");
151 out
152 })
153}
154
155pub fn decode_b64url_exact(
157 value: &str,
158 len: usize,
159 field: &str,
160) -> Result<Vec<u8>, ValidationError> {
161 let refuse = || {
162 ValidationError::new(format!(
163 "{field} must be base64url without padding of {len} bytes"
164 ))
165 };
166 let bytes = B64URL.decode(value).map_err(|_| refuse())?;
167 if bytes.len() != len || B64URL.encode(&bytes) != value {
168 return Err(refuse());
169 }
170 Ok(bytes)
171}
172
173fn validate_key(
174 alg: &str,
175 key_id: &str,
176 public_key: &str,
177 field: &str,
178) -> Result<(), ValidationError> {
179 if alg != APP_KEY_ALG {
180 return Err(ValidationError::new(format!(
181 "{field}.alg must be {APP_KEY_ALG}"
182 )));
183 }
184 let raw = decode_b64url_exact(public_key, 32, &format!("{field}.public_key"))?;
185 if key_id != app_key_id(&raw) {
186 return Err(ValidationError::new(format!(
187 "{field}.key_id must be hex(sha256(public_key))[..16]"
188 )));
189 }
190 Ok(())
191}
192
193impl AppKeyAnnouncementV1 {
194 pub fn new(kind: AppKeyKind, public_key: &[u8; 32]) -> Self {
196 Self {
197 kind,
198 alg: APP_KEY_ALG.into(),
199 key_id: app_key_id(public_key),
200 public_key: B64URL.encode(public_key),
201 }
202 }
203
204 pub fn validate(&self) -> Result<(), ValidationError> {
205 validate_key(&self.alg, &self.key_id, &self.public_key, "app_keys")
206 }
207}
208
209impl AppKeyOfferV1 {
210 pub fn validate(&self, kind: AppKeyKind) -> Result<(), ValidationError> {
211 let field = kind.request_member();
212 validate_key(&self.alg, &self.key_id, &self.public_key, field)?;
213 decode_b64url_exact(&self.bind_signature, 64, &format!("{field}.bind_signature"))?;
214 Ok(())
215 }
216
217 pub fn matches(&self, announced: &AppKeyAnnouncementV1) -> bool {
219 self.alg == announced.alg
220 && self.key_id == announced.key_id
221 && self.public_key == announced.public_key
222 }
223}
224
225pub fn validate_app_keys(keys: &[AppKeyAnnouncementV1]) -> Result<(), ValidationError> {
229 if keys.len() > MAX_APP_KEYS {
230 return Err(ValidationError::new(format!(
231 "app_keys carries at most {MAX_APP_KEYS} keys"
232 )));
233 }
234 for pair in keys.windows(2) {
235 if pair[0].kind == pair[1].kind {
236 return Err(ValidationError::new("app_keys carries one key per kind"));
237 }
238 if pair[0].kind > pair[1].kind {
239 return Err(ValidationError::new("app_keys must be sorted by kind"));
240 }
241 }
242 keys.iter().try_for_each(AppKeyAnnouncementV1::validate)
243}
244
245pub fn app_key_bind_signing_input(
251 device_code: &str,
252 instance_public_key: &str,
253 keys: &[AppKeyAnnouncementV1],
254) -> Result<Vec<u8>, ValidationError> {
255 signing_input(
256 APP_KEY_BIND_DOMAIN,
257 &app_key_bind_statement(device_code, instance_public_key, keys),
258 )
259}
260
261pub fn app_key_bind_statement(
263 device_code: &str,
264 instance_public_key: &str,
265 keys: &[AppKeyAnnouncementV1],
266) -> Value {
267 let mut keys = keys.iter().collect::<Vec<_>>();
268 keys.sort_by_key(|key| key.kind);
269 json!({
270 "device_code_sha256": lower_hex(&Sha256::digest(device_code.as_bytes())),
271 "instance_public_key": instance_public_key,
272 "keys": keys
273 .iter()
274 .map(|key| json!({"alg": key.alg, "kind": key.kind, "key_id": key.key_id, "public_key": key.public_key}))
275 .collect::<Vec<_>>(),
276 })
277}
278
279pub fn app_key_offer_bind_input(
283 kind: AppKeyKind,
284 instance_public_key: &str,
285 key_id: &str,
286 public_key: &str,
287) -> Result<Vec<u8>, ValidationError> {
288 signing_input(
289 kind.bind_domain(),
290 &json!({
291 "alg": APP_KEY_ALG,
292 "instance_public_key": instance_public_key,
293 "key_id": key_id,
294 "public_key": public_key,
295 "scope": kind.scope(),
296 }),
297 )
298}
299
300pub fn offered_equals_announced(
307 announced: &[AppKeyAnnouncementV1],
308 offered: &[(AppKeyKind, &AppKeyOfferV1)],
309) -> Result<(), &'static str> {
310 for kind in AppKeyKind::ALL {
311 if offered.iter().filter(|(k, _)| *k == kind).count() > 1 {
312 return Err(kind.request_member());
313 }
314 let a = announced.iter().find(|key| key.kind == kind);
315 let o = offered
316 .iter()
317 .find(|(k, _)| *k == kind)
318 .map(|(_, offer)| *offer);
319 match (a, o) {
320 (None, None) => {}
321 (Some(a), Some(o)) if o.matches(a) => {}
322 _ => return Err(kind.request_member()),
323 }
324 }
325 Ok(())
326}
327
328pub fn app_key_refusal_text(reason: Option<&str>) -> Option<&'static str> {
331 match reason? {
332 REASON_APP_KEY_NOT_ANNOUNCED | REASON_APP_KEY_BIND_INVALID => Some(PAIRING_FAILED_TEXT),
333 _ => None,
334 }
335}
336
337#[cfg(test)]
338mod tests {
339 use super::*;
340
341 fn key(byte: u8) -> [u8; 32] {
342 ed25519_dalek::SigningKey::from_bytes(&[byte; 32])
343 .verifying_key()
344 .to_bytes()
345 }
346
347 fn chat_key_where(wanted: impl Fn(&AppKeyAnnouncementV1) -> bool) -> AppKeyAnnouncementV1 {
349 (1..=u8::MAX)
350 .map(|byte| AppKeyAnnouncementV1::new(AppKeyKind::Chat, &key(byte)))
351 .find(wanted)
352 .expect("a test key with the wanted shape")
353 }
354
355 fn three() -> Vec<AppKeyAnnouncementV1> {
356 vec![
357 AppKeyAnnouncementV1::new(AppKeyKind::Chat, &key(1)),
358 AppKeyAnnouncementV1::new(AppKeyKind::Optin, &key(2)),
359 AppKeyAnnouncementV1::new(AppKeyKind::TaskPropose, &key(3)),
360 ]
361 }
362
363 #[test]
364 fn kinds_sort_by_wire_name() {
365 let mut names = AppKeyKind::ALL.map(AppKeyKind::as_str);
366 names.sort_unstable();
367 assert_eq!(names, AppKeyKind::ALL.map(AppKeyKind::as_str));
368 for kind in AppKeyKind::ALL {
369 assert_eq!(serde_json::to_value(kind).unwrap(), kind.as_str());
370 }
371 }
372
373 #[test]
374 fn valid_lists_pass() {
375 validate_app_keys(&[]).unwrap();
376 validate_app_keys(&three()).unwrap();
377 validate_app_keys(&three()[1..]).unwrap();
378 }
379
380 #[test]
381 fn the_validator_refuses_every_malformed_list() {
382 let keys = three();
383 let mut unsorted = keys.clone();
384 unsorted.swap(0, 2);
385 let duplicate = vec![keys[0].clone(), keys[0].clone()];
386 let mut four = keys.clone();
387 four.push(keys[2].clone());
388 let mut alg = keys.clone();
389 alg[0].alg = "ed448".into();
390 let mut padded = keys.clone();
391 padded[0].public_key.push('=');
392 let mut standard = keys.clone();
395 standard[0] = chat_key_where(|a| a.public_key.contains(['-', '_']));
396 standard[0].public_key = standard[0].public_key.replace('-', "+").replace('_', "/");
397 let mut trailing = keys.clone();
400 let last = trailing[0].public_key.pop().unwrap();
401 let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
402 let index = alphabet.find(last).unwrap() | 1;
403 trailing[0]
404 .public_key
405 .push(alphabet.as_bytes()[index] as char);
406 let mut short = keys.clone();
407 short[0].public_key = B64URL.encode([7u8; 31]);
408 let mut id = keys.clone();
409 id[0].key_id = keys[1].key_id.clone();
410 let mut upper = keys.clone();
411 upper[0] = chat_key_where(|a| a.key_id.bytes().any(|b| b.is_ascii_lowercase()));
412 upper[0].key_id = upper[0].key_id.to_ascii_uppercase();
413 for (name, list) in [
414 ("unsorted", unsorted),
415 ("duplicate", duplicate),
416 ("four", four),
417 ("alg", alg),
418 ("padded", padded),
419 ("short", short),
420 ("key_id", id),
421 ("standard", standard),
422 ("trailing_bits", trailing),
423 ("upper", upper),
424 ] {
425 assert!(validate_app_keys(&list).is_err(), "{name} passed");
426 }
427 let unknown = serde_json::json!({"kind": "share", "alg": "ed25519", "key_id": "0", "public_key": "x"});
428 assert!(serde_json::from_value::<AppKeyAnnouncementV1>(unknown).is_err());
429 }
430
431 #[test]
432 fn the_bind_input_is_deterministic_jcs_over_the_sorted_keys() {
433 let keys = three();
434 let mut reversed = keys.clone();
435 reversed.reverse();
436 let ipk = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
437 let one = app_key_bind_signing_input("dc_x", ipk, &keys).unwrap();
438 assert_eq!(
439 one,
440 app_key_bind_signing_input("dc_x", ipk, &reversed).unwrap()
441 );
442 assert_ne!(one, app_key_bind_signing_input("dc_y", ipk, &keys).unwrap());
443 let text = String::from_utf8(one).unwrap();
444 let expected = format!(
445 "leanctx.cloud.app_key_bind.v1\n{{\"device_code_sha256\":\"{}\",\"instance_public_key\":\"{ipk}\",\"keys\":[{}]}}",
446 lower_hex(&Sha256::digest(b"dc_x")),
447 keys.iter()
448 .map(|k| format!(
449 "{{\"alg\":\"ed25519\",\"key_id\":\"{}\",\"kind\":\"{}\",\"public_key\":\"{}\"}}",
450 k.key_id,
451 k.kind.as_str(),
452 k.public_key
453 ))
454 .collect::<Vec<_>>()
455 .join(",")
456 );
457 assert_eq!(text, expected);
458 }
459
460 #[test]
461 fn offered_set_must_equal_the_announced_set() {
462 let keys = three();
463 let offer = |a: &AppKeyAnnouncementV1| AppKeyOfferV1 {
464 alg: a.alg.clone(),
465 public_key: a.public_key.clone(),
466 key_id: a.key_id.clone(),
467 bind_signature: B64URL.encode([0u8; 64]),
468 };
469 let offers = keys.iter().map(offer).collect::<Vec<_>>();
470 let all = keys
471 .iter()
472 .map(|k| k.kind)
473 .zip(offers.iter())
474 .collect::<Vec<_>>();
475 offered_equals_announced(&keys, &all).unwrap();
476 assert_eq!(
477 offered_equals_announced(&keys, &all[..2]),
478 Err("task_propose_key")
479 );
480 assert_eq!(offered_equals_announced(&keys[..1], &all), Err("optin_key"));
481 let other = offer(&AppKeyAnnouncementV1::new(AppKeyKind::Chat, &key(9)));
482 assert_eq!(
483 offered_equals_announced(&keys[..1], &[(AppKeyKind::Chat, &other)]),
484 Err("chat_key")
485 );
486 offered_equals_announced(&[], &[]).unwrap();
487 let twice = [all[0], all[0], all[1], all[2]];
488 assert_eq!(offered_equals_announced(&keys, &twice), Err("chat_key"));
489 }
490
491 #[test]
492 fn both_refusals_read_the_same_and_others_are_left_alone() {
493 assert_eq!(
494 app_key_refusal_text(Some(REASON_APP_KEY_NOT_ANNOUNCED)),
495 Some(PAIRING_FAILED_TEXT)
496 );
497 assert_eq!(
498 app_key_refusal_text(Some(REASON_APP_KEY_BIND_INVALID)),
499 Some(PAIRING_FAILED_TEXT)
500 );
501 assert_eq!(app_key_refusal_text(Some("required")), None);
502 assert_eq!(app_key_refusal_text(None), None);
503 let banned = [
504 "hive",
505 "this mac",
506 "workspace",
507 "engine",
508 "lease",
509 "instance",
510 "weave",
511 "merge queue",
512 "retry",
513 "excl. vat",
514 "leanctx cloud",
515 "queen",
516 "pro",
517 "leanctx app",
518 "instances",
519 ];
520 let words = |text: &str| {
522 let spaced: String = text
523 .to_ascii_lowercase()
524 .chars()
525 .map(|c| if c.is_ascii_alphanumeric() { c } else { ' ' })
526 .collect();
527 format!(
528 " {} ",
529 spaced.split_whitespace().collect::<Vec<_>>().join(" ")
530 )
531 };
532 let clean = |text: &str| {
533 let text = words(text);
534 banned.iter().all(|word| !text.contains(&words(word)))
535 };
536 assert!(clean(PAIRING_FAILED_TEXT));
537 assert!(!clean("Lease expired"), "the check finds a banned word");
538 for kind in AppKeyKind::ALL {
539 assert!(clean(kind.label()), "{}", kind.label());
540 }
541 }
542}