Skip to main content

lean_ctx_cloud/
auth.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Enrollment (device flow), access tokens and lease renewal.
3//!
4//! The instance's Ed25519 key is its only long-lived secret: every access
5//! token is minted from a fresh signed assertion and cached until shortly
6//! before it expires. Nothing here runs inside a tool call.
7
8use std::time::Duration;
9
10use lean_ctx_time::UtcDateTime;
11use serde_json::{Value, json};
12
13use super::CloudError;
14use super::consent::chat_key::ChatKeyOffer;
15use super::consent::optin_key::{self, OptinKeyOffer};
16use super::consent::task_key::{self, TaskKeyOffer};
17use super::instance_key::InstanceKeys;
18use super::lease::{VerifiedLease, load_lease, store_lease, verify_keyset, verify_lease};
19use super::state::{CloudStore, INSTANCE_FILE, InstanceRecord, TOKEN_FILE, TokenRecord};
20use super::transport::CloudClient;
21use lean_ctx_protocol::cloud::app_keys::{
22    AppKeyAnnouncementV1, AppKeyKind, PAIRING_FAILED_TEXT, app_key_bind_signing_input,
23    validate_app_keys,
24};
25use lean_ctx_protocol::cloud::enroll::{
26    AccessTokenV1, DEVICE_SETUP_REQUEST_SCHEMA, DEVICE_TOKEN_REQUEST_SCHEMA, DeviceCodeRequestV1,
27    DeviceCodeV1, DeviceSetupProjectV1, DeviceSetupRequestV1, EngineOs, EnrollmentV1,
28    MAX_INSTANCE_LABEL_CHARS, TOKEN_REQUEST_SCHEMA, TrialPlan, token_assertion_input,
29};
30use lean_ctx_protocol::cloud::lease::CloudLeaseEnvelopeV1;
31
32/// Tokens are refreshed this long before they expire.
33const TOKEN_REFRESH_MARGIN_SECONDS: i64 = 120;
34
35pub fn engine_os() -> EngineOs {
36    if cfg!(target_os = "macos") {
37        EngineOs::Macos
38    } else if cfg!(target_os = "linux") {
39        EngineOs::Linux
40    } else if cfg!(windows) {
41        EngineOs::Windows
42    } else {
43        EngineOs::Other
44    }
45}
46
47fn stamp(time: UtcDateTime) -> String {
48    time.to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true)
49}
50
51fn protocol(what: &str) -> impl Fn(lean_ctx_protocol::ValidationError) -> CloudError + '_ {
52    move |e| CloudError::Protocol(format!("{what}: {e}"))
53}
54
55fn decode<T: serde::de::DeserializeOwned>(value: Value, what: &str) -> Result<T, CloudError> {
56    serde_json::from_value(value).map_err(|e| CloudError::Protocol(format!("{what}: {e}")))
57}
58
59/// Step 1: ask Cloud for a device code; `label` is the user's `--label`, if
60/// any (the approval page shows it, Cloud task #11).
61pub fn start_device_flow(
62    client: &CloudClient,
63    label: Option<&str>,
64) -> Result<DeviceCodeV1, CloudError> {
65    start_device_flow_for(client, label, None)
66}
67
68/// Step 1 for `cloud connect [--trial]`: `trial` names the plan whose
69/// one-step trial the browser starts (`None`: a plain sign-in, whose
70/// request is exactly the one older Clouds know).
71pub fn start_device_flow_for(
72    client: &CloudClient,
73    label: Option<&str>,
74    trial: Option<TrialPlan>,
75) -> Result<DeviceCodeV1, CloudError> {
76    start_device_flow_with(client, label, trial, AppKeyOffers::default())
77}
78
79/// [`start_device_flow_for`] that announces the keys LeanCTX Code offers
80/// (f3129 S2, app-key-bind-v1 §2): `app_keys` in `POST /v1/device/code`,
81/// sorted by kind, absent when nothing is offered (the request is then
82/// byte-identical to the plain one). A Cloud whose code answer does not
83/// list `device_app_keys` binds no key: the pairing stops here, before the
84/// browser opens or anything is polled (fail closed, §1).
85pub fn start_device_flow_with(
86    client: &CloudClient,
87    label: Option<&str>,
88    trial: Option<TrialPlan>,
89    offers: AppKeyOffers<'_>,
90) -> Result<DeviceCodeV1, CloudError> {
91    let announced = offers.announcements();
92    let mut plain =
93        DeviceCodeRequestV1::new(env!("CARGO_PKG_VERSION"), engine_os()).with_trial(trial);
94    if !announced.is_empty() {
95        validate_app_keys(&announced).map_err(|e| CloudError::Config(e.to_string()))?;
96        plain = plain.with_app_keys(announced.clone());
97    }
98    // The approval page names the machine from this label (rc3-5); one Cloud
99    // would refuse (400) is trimmed and cut, else dropped: never fatal.
100    let label = label.map(|l| {
101        let cut: String = l.trim().chars().take(MAX_INSTANCE_LABEL_CHARS).collect();
102        cut.trim_end().to_string()
103    });
104    let named = plain.clone().with_label(label);
105    let request = if named.validate().is_ok() {
106        named
107    } else {
108        plain
109    };
110    request
111        .validate()
112        .map_err(protocol("device code request"))?;
113    let body = serde_json::to_value(&request).map_err(|e| CloudError::Protocol(e.to_string()))?;
114    let answer = client.post("/device/code", &body).map_err(|error| {
115        // An older Cloud's 400 on a trial with keys names the trial first.
116        let error = trial_refusal(error, trial.is_some(), client.origin());
117        app_keys_refusal(error, !announced.is_empty()).with_origin(client.origin())
118    })?;
119    let code: DeviceCodeV1 = decode(answer, "device code")?;
120    code.validate().map_err(protocol("device code"))?;
121    offers.require_capability(&code)?;
122    // A Cloud that took the request but does not echo the trial would let
123    // the person sign in without one: refused the same way as a 400.
124    if let Some(plan) = trial
125        && !code.starts_trial(plan)
126    {
127        return Err(CloudError::TrialUnsupported {
128            origin: client.origin().trim_end_matches('/').to_string(),
129        });
130    }
131    Ok(code)
132}
133
134/// A trial request an older Cloud refused for its unknown members (`400
135/// invalid_request`) is [`CloudError::TrialUnsupported`]: it is never sent
136/// again without them, so nobody signs in thinking a trial started.
137pub fn trial_refusal(error: CloudError, trial: bool, origin: &str) -> CloudError {
138    match error {
139        CloudError::Server { status: 400, code } if trial && code == "invalid_request" => {
140            CloudError::TrialUnsupported {
141                origin: origin.trim_end_matches('/').to_string(),
142            }
143        }
144        other => other,
145    }
146}
147
148/// The words for a Cloud that cannot bind the keys of LeanCTX Code in the
149/// pairing (its code answer lacks `device_app_keys`, or it refused the
150/// announced `app_keys`): nothing was paired (app-key-bind-v1 §1).
151pub const APP_KEYS_UNSUPPORTED: &str = "This Cloud cannot pair the keys of LeanCTX Code yet, \
152     so nothing was paired. Connect again later, or connect without LeanCTX Code.";
153
154/// A device-code request announcing app keys that an older Cloud refused for
155/// its unknown member (`400 invalid_request`) is [`APP_KEYS_UNSUPPORTED`]:
156/// never sent again without them, so no key is offered unannounced. A newer
157/// Cloud that refuses the announcement itself (`400 invalid_field`, field
158/// `app_keys`) reads [`APP_KEY_PAIRING_FAILED`]: nothing was paired.
159fn app_keys_refusal(error: CloudError, announced: bool) -> CloudError {
160    match error {
161        CloudError::Server { status: 400, code } if announced && code == "invalid_request" => {
162            CloudError::Config(APP_KEYS_UNSUPPORTED.into())
163        }
164        CloudError::Server { status: 400, code }
165            if announced && code == super::error::APP_KEYS_INVALID =>
166        {
167            CloudError::Config(APP_KEY_PAIRING_FAILED.into())
168        }
169        other => other,
170    }
171}
172
173/// The project an engine names at connect (C0 2.1 device setup): the
174/// checkout's folder name and the remote it sees, plus what it shares.
175#[derive(Debug, Clone, PartialEq, Eq)]
176pub struct SetupAnnouncement {
177    pub project: Option<(String, Option<String>)>,
178    pub shares: Vec<String>,
179}
180
181/// Step 1b (C0 2.1): name the project and what this machine shares, so the
182/// approval page asks "Share this project" too. Only when the Cloud offers
183/// it; `false` when it did not take it (the terminal then asks, as before).
184pub fn announce_setup(
185    client: &CloudClient,
186    code: &DeviceCodeV1,
187    setup: &SetupAnnouncement,
188) -> bool {
189    if !code.offers_device_setup() {
190        return false;
191    }
192    let request = DeviceSetupRequestV1 {
193        schema: DEVICE_SETUP_REQUEST_SCHEMA.into(),
194        device_code: code.device_code.clone(),
195        project: setup
196            .project
197            .clone()
198            .map(|(name, remote)| DeviceSetupProjectV1 { name, remote }),
199        shares: setup.shares.clone(),
200    };
201    let Ok(body) = serde_json::to_value(&request) else {
202        return false;
203    };
204    match client.post("/device/setup", &body) {
205        Ok(_) => true,
206        Err(error) => {
207            tracing::info!("cloud device setup: {error}");
208            false
209        }
210    }
211}
212
213/// What the device approval answered beyond the enrollment: the page's
214/// answer to "Share this project" (C0 2.1). `None`: the page did not ask
215/// (no setup, or an older Cloud); `Some(None)`: an older page approved it.
216pub type SharingAnswer = Option<Option<bool>>;
217
218/// Step 2: poll until the user approved (or the code expired), then verify
219/// and persist the enrollment. `sleep` is injectable for tests.
220pub fn finish_device_flow(
221    store: &CloudStore,
222    client: &CloudClient,
223    code: &DeviceCodeV1,
224    label: &str,
225    root: &[u8; 32],
226    sleep: &dyn Fn(Duration),
227) -> Result<(InstanceRecord, SharingAnswer), CloudError> {
228    finish_device_flow_with(
229        store,
230        client,
231        code,
232        label,
233        root,
234        sleep,
235        AppKeyOffers::default(),
236    )
237}
238
239/// The keys LeanCTX Code may hand over with a pairing: its chat key
240/// (rc4-32), its task-propose key (rc4-67) and its opt-in key (rc4-16), any
241/// of them or none ([`Default`]).
242#[derive(Debug, Clone, Copy, Default)]
243pub struct AppKeyOffers<'a> {
244    pub chat: Option<&'a ChatKeyOffer>,
245    pub task: Option<&'a TaskKeyOffer>,
246    pub optin: Option<&'a OptinKeyOffer>,
247}
248
249impl AppKeyOffers<'_> {
250    /// Whether no key is offered (the plain pairing).
251    pub fn is_empty(self) -> bool {
252        self.chat.is_none() && self.task.is_none() && self.optin.is_none()
253    }
254
255    /// The `app_keys` of `POST /v1/device/code` (f3129 S2): one entry per
256    /// offered kind, sorted by kind; empty when nothing is offered.
257    pub fn announcements(self) -> Vec<AppKeyAnnouncementV1> {
258        let entry = |kind, alg: &str, key_id: &str, public_key: &str| AppKeyAnnouncementV1 {
259            kind,
260            alg: alg.to_owned(),
261            key_id: key_id.to_owned(),
262            public_key: public_key.to_owned(),
263        };
264        let mut keys = Vec::new();
265        if let Some(o) = self.chat {
266            keys.push(entry(AppKeyKind::Chat, &o.alg, &o.key_id, &o.public_key));
267        }
268        if let Some(o) = self.optin {
269            keys.push(entry(AppKeyKind::Optin, &o.alg, &o.key_id, &o.public_key));
270        }
271        if let Some(o) = self.task {
272            keys.push(entry(
273                AppKeyKind::TaskPropose,
274                &o.alg,
275                &o.key_id,
276                &o.public_key,
277            ));
278        }
279        keys.sort_by_key(|key| key.kind);
280        keys
281    }
282
283    /// The announcement goes with the device-code request, before its
284    /// answer; the offers and their bind signature go out only when that
285    /// answer lists `device_app_keys` (app-key-bind-v1 §1). Otherwise
286    /// nothing is bound and the pairing stops before anything is polled.
287    pub fn require_capability(self, code: &DeviceCodeV1) -> Result<(), CloudError> {
288        if self.is_empty() || code.offers_app_keys() {
289            Ok(())
290        } else {
291            Err(CloudError::Config(APP_KEYS_UNSUPPORTED.into()))
292        }
293    }
294
295    /// `app_keys_bind_signature` (f3129 S3): the instance key's Ed25519
296    /// signature, base64url without padding, over the bind statement of
297    /// `device_code`, the `instance_public_key` the request sends and the
298    /// announced keys (exactly the offered ones). `None` when nothing is
299    /// offered.
300    fn bind_signature(
301        self,
302        keys: &InstanceKeys,
303        device_code: &str,
304    ) -> Result<Option<String>, CloudError> {
305        use base64::Engine as _;
306        use ed25519_dalek::Signer as _;
307        if self.is_empty() {
308            return Ok(None);
309        }
310        let input =
311            app_key_bind_signing_input(device_code, &keys.public_key_b64(), &self.announcements())
312                .map_err(|e| CloudError::Config(e.to_string()))?;
313        let signature = keys.signing_key().sign(&input).to_bytes();
314        Ok(Some(
315            base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(signature),
316        ))
317    }
318
319    /// Each offer must bind to exactly the `instance_public_key` the request
320    /// sends; a bad one stops the pairing before anything is sent.
321    fn check(self, keys: &InstanceKeys) -> Result<(), CloudError> {
322        check_chat_key(keys, self.chat)?;
323        check_task_key(keys, self.task)?;
324        check_optin_key(keys, self.optin)
325    }
326
327    /// The offers' bind check against this computer's instance keys (made here if
328    /// there are none yet, as the pairing would), for the connect to run
329    /// before it contacts the Cloud at all: a bind that does not verify
330    /// stops the connect before the device code is fetched or the browser
331    /// opened (§46.3 point 1, §28a). Loads nothing when no key is offered.
332    pub fn verify(self, store: &CloudStore) -> Result<(), CloudError> {
333        if self.is_empty() {
334            return Ok(());
335        }
336        self.check(&InstanceKeys::load_or_create(store)?)
337    }
338
339    /// Keep the public part of each accepted key. A kind not offered is
340    /// forgotten only on a new enrollment (a key bound to an earlier
341    /// enrollment is never kept); a re-pair of the same instance (`Rebind`)
342    /// keeps it, because the Cloud keeps that kind bound (bd 40011 M2).
343    fn keep(self, store: &CloudStore, pairing: Pairing) -> Result<(), CloudError> {
344        keep_chat_key(store, self.chat, pairing)?;
345        keep_task_key(store, self.task, pairing)?;
346        keep_optin_key(store, self.optin, pairing)
347    }
348
349    /// The Cloud's refusal of an offered key in plain words (the task key's
350    /// and the chat key's codes are distinct); `chat_advice` names the next
351    /// step for a refused chat key.
352    fn refusal(self, error: CloudError, chat_advice: &str) -> CloudError {
353        let offered = !self.is_empty();
354        let error = not_announced_refusal(error, offered);
355        let error = task_key_refusal(error, self.task.is_some());
356        let error = optin_key_refusal(error, self.optin.is_some());
357        chat_key_refusal(error, self.chat.is_some(), chat_advice)
358    }
359}
360
361/// [`finish_device_flow`] that also binds the keys LeanCTX Code offers
362/// (chat key rc4-32, task-propose key rc4-67): each offer is checked against
363/// this machine's public key before anything is sent, and its public part is
364/// kept once the pairing is accepted. A pairing without one forgets a key of
365/// that kind bound earlier.
366pub fn finish_device_flow_with(
367    store: &CloudStore,
368    client: &CloudClient,
369    code: &DeviceCodeV1,
370    label: &str,
371    root: &[u8; 32],
372    sleep: &dyn Fn(Duration),
373    offers: AppKeyOffers<'_>,
374) -> Result<(InstanceRecord, SharingAnswer), CloudError> {
375    finish_device_flow_at(
376        store,
377        client,
378        code,
379        label,
380        root,
381        sleep,
382        offers,
383        UtcDateTime::now,
384    )
385}
386
387/// [`finish_device_flow_with`] with an injectable clock (`now` verifies the
388/// lease).
389#[allow(clippy::too_many_arguments)]
390fn finish_device_flow_at(
391    store: &CloudStore,
392    client: &CloudClient,
393    code: &DeviceCodeV1,
394    label: &str,
395    root: &[u8; 32],
396    sleep: &dyn Fn(Duration),
397    offers: AppKeyOffers<'_>,
398    now: impl Fn() -> UtcDateTime,
399) -> Result<(InstanceRecord, SharingAnswer), CloudError> {
400    poll_device_flow(store, client, code, label, root, sleep, offers, now).map_err(|e| {
401        forget_cleared_optin_key(store, offers.optin, &e);
402        offers.refusal(e, CHAT_KEY_REFUSED)
403    })
404}
405
406/// The Cloud removed the offered opt-in key (`optin_key_cleared`): the key
407/// kept here, if it is that one, is pending again, so `cloud.pickup` stops
408/// reporting `worker_on` (§46.3). A failure to write is logged, never
409/// hides the refusal.
410fn forget_cleared_optin_key(store: &CloudStore, offer: Option<&OptinKeyOffer>, error: &CloudError) {
411    let cleared = matches!(error, CloudError::Server { code, .. }
412        if code == super::error::OPTIN_KEY_CLEARED);
413    let Some(offer) = offer.filter(|_| cleared) else {
414        return;
415    };
416    if optin_key::pending_optin_key(store).is_some_and(|k| k.key_id == offer.key_id)
417        && let Err(e) = optin_key::clear_accepted(store)
418    {
419        tracing::warn!("cloud connect: opt-in key back to pending: {e}");
420    }
421}
422
423/// The words for a pairing whose task key LeanCTX Code offered was refused.
424pub const TASK_KEY_REFUSED: &str =
425    "The task key of LeanCTX Code was not accepted. Pair this computer again from LeanCTX Code.";
426/// The words for a pairing while another task key is bound.
427pub const TASK_KEY_ALREADY_BOUND: &str = "This computer has another task key already. \
428     Remove it on the web, then pair this computer again from LeanCTX Code.";
429/// The words for a pairing with a task key removed on the web.
430pub const TASK_KEY_WAS_REMOVED: &str = "This task key was removed on the web. \
431     LeanCTX Code makes a new one when you pair this computer again.";
432
433/// The words for a pairing whose opt-in key LeanCTX Code offered was
434/// refused (rc4-16).
435pub const OPTIN_KEY_REFUSED: &str =
436    "The opt-in key of LeanCTX Code was not accepted. Pair this computer again from LeanCTX Code.";
437/// The words for a pairing while another opt-in key is bound (§46.4).
438pub const OPTIN_KEY_ALREADY_BOUND: &str = "Another opt-in key is bound to this computer; \
439     remove it on the computer's page, then pair again.";
440/// The words for a pairing with an opt-in key removed on the web (§46.4).
441pub const OPTIN_KEY_WAS_REMOVED: &str =
442    "This opt-in key was removed; LeanCTX Code makes a new one and pairs again.";
443
444/// The words for a pairing with an opt-in key of a computer connected with
445/// an enrollment token (`400 token_enrollment`, §46.2).
446pub const OPTIN_KEY_TOKEN_ENROLLMENT: &str = "This computer was connected with an enrollment \
447     token; pairing the opt-in key needs a connect from LeanCTX Code.";
448
449/// The words for a pairing whose offered keys the Cloud refused as not the
450/// announced set or with a bind signature that does not verify (f3129
451/// `app_key_not_announced` / `app_key_bind_invalid`, app-key-bind-v1 §11).
452pub const APP_KEY_PAIRING_FAILED: &str = PAIRING_FAILED_TEXT;
453
454fn not_announced_refusal(error: CloudError, offered: bool) -> CloudError {
455    match error {
456        CloudError::Server { code, .. }
457            if offered
458                && (code == super::error::APP_KEY_NOT_ANNOUNCED
459                    || code == super::error::APP_KEY_BIND_INVALID) =>
460        {
461            CloudError::DeviceFlow(APP_KEY_PAIRING_FAILED.into())
462        }
463        other => other,
464    }
465}
466
467fn task_key_refusal(error: CloudError, offered: bool) -> CloudError {
468    use super::error::{TASK_KEY_BOUND, TASK_KEY_CLEARED, TASK_KEY_INVALID};
469    match error {
470        CloudError::Server { code, .. } if offered && code == TASK_KEY_INVALID => {
471            CloudError::DeviceFlow(TASK_KEY_REFUSED.into())
472        }
473        CloudError::Server { code, .. } if offered && code == TASK_KEY_BOUND => {
474            CloudError::DeviceFlow(TASK_KEY_ALREADY_BOUND.into())
475        }
476        CloudError::Server { code, .. } if offered && code == TASK_KEY_CLEARED => {
477            CloudError::DeviceFlow(TASK_KEY_WAS_REMOVED.into())
478        }
479        other => other,
480    }
481}
482
483fn optin_key_refusal(error: CloudError, offered: bool) -> CloudError {
484    use super::error::{OPTIN_KEY_BOUND, OPTIN_KEY_CLEARED, OPTIN_KEY_INVALID};
485    match error {
486        CloudError::Server { code, .. } if offered && code == OPTIN_KEY_INVALID => {
487            CloudError::DeviceFlow(OPTIN_KEY_REFUSED.into())
488        }
489        CloudError::Server { code, .. } if offered && code == OPTIN_KEY_BOUND => {
490            CloudError::DeviceFlow(OPTIN_KEY_ALREADY_BOUND.into())
491        }
492        CloudError::Server { code, .. } if offered && code == OPTIN_KEY_CLEARED => {
493            CloudError::DeviceFlow(OPTIN_KEY_WAS_REMOVED.into())
494        }
495        CloudError::Server { status: 400, code } if offered && code == "token_enrollment" => {
496            CloudError::DeviceFlow(OPTIN_KEY_TOKEN_ENROLLMENT.into())
497        }
498        other => other,
499    }
500}
501
502/// The local error for LeanCTX Cloud's `400 invalid_field` on a pairing
503/// that carried a chat key (rc4-32): the bind did not verify there.
504pub const CHAT_KEY_REFUSED: &str = "LeanCTX Cloud refused the chat key of LeanCTX Code \
505     (invalid_field chat_key). Pair this computer again from LeanCTX Code.";
506
507fn chat_key_refusal(error: CloudError, offered: bool, advice: &str) -> CloudError {
508    match error {
509        CloudError::Server { status: 400, code }
510            if offered && (code == "invalid_field" || code == "unknown") =>
511        {
512            CloudError::DeviceFlow(advice.into())
513        }
514        other => other,
515    }
516}
517
518/// The instance this computer holds before a pairing, as far as "the same
519/// instance" goes: its id, team and Cloud, the fields [`repair_chat_key_at`]
520/// checks (its Cloud by the client it is sent with).
521#[derive(Debug, Clone, PartialEq, Eq)]
522struct HeldInstance {
523    instance_id: String,
524    org_id: String,
525    url: String,
526}
527
528impl HeldInstance {
529    /// The instance held now; an unreadable record counts as none (a new
530    /// enrollment, which forgets keys not offered: fail closed).
531    fn read(store: &CloudStore) -> Option<Self> {
532        store.instance().ok().flatten().map(|record| Self {
533            instance_id: record.instance_id,
534            org_id: record.org_id,
535            url: record.url,
536        })
537    }
538
539    fn is(&self, record: &InstanceRecord) -> bool {
540        self.instance_id == record.instance_id
541            && self.org_id == record.org_id
542            && self.url == record.url
543    }
544}
545
546/// The device flow with an injectable clock (`now` verifies the lease).
547#[allow(clippy::too_many_arguments)]
548fn poll_device_flow(
549    store: &CloudStore,
550    client: &CloudClient,
551    code: &DeviceCodeV1,
552    label: &str,
553    root: &[u8; 32],
554    sleep: &dyn Fn(Duration),
555    offers: AppKeyOffers<'_>,
556    now: impl Fn() -> UtcDateTime,
557) -> Result<(InstanceRecord, SharingAnswer), CloudError> {
558    let keys = InstanceKeys::load_or_create(store)?;
559    offers.check(&keys)?;
560    offers.require_capability(code)?;
561    let request = device_token_request(&keys, &code.device_code, label, offers)?;
562    let body = poll_device_token(client, code, &request, sleep)?;
563    // Read before the enrollment is accepted: that overwrites the record.
564    let before = HeldInstance::read(store);
565    let enrolled = accept_enrollment(store, client, body, label, root, now())?;
566    offers.keep(store, Pairing::of(before.as_ref(), &enrolled.0))?;
567    Ok(enrolled)
568}
569
570/// Poll `POST /v1/device/token` with `request` until the person approved
571/// (the answer's body), refused, or the code expired.
572fn poll_device_token(
573    client: &CloudClient,
574    code: &DeviceCodeV1,
575    request: &Value,
576    sleep: &dyn Fn(Duration),
577) -> Result<Value, CloudError> {
578    let expires_in = u64::from(code.expires_in);
579    let deadline = std::time::Instant::now() + Duration::from_secs(expires_in);
580    let mut poll = DevicePoll::new(code.interval);
581    // Seconds slept so far: the deadline also holds when `sleep` does not
582    // pass real time (tests), and never later than the wall clock's.
583    let mut slept = 0u64;
584    let mut wait = poll.interval;
585    loop {
586        let left = expires_in.saturating_sub(slept);
587        let pause = wait.min(left.max(1));
588        sleep(Duration::from_secs(pause));
589        slept = slept.saturating_add(pause);
590        match client.post("/device/token", request) {
591            Ok(body) => return Ok(body),
592            // A plans page named as a path is shown on this Cloud's origin.
593            Err(error) => {
594                wait = poll
595                    .next_wait(error)
596                    .map_err(|e| e.with_origin(client.origin()))?;
597            }
598        }
599        if std::time::Instant::now() >= deadline || slept >= expires_in {
600            return Err(CloudError::DeviceFlow(super::error::CODE_EXPIRED.into()));
601        }
602    }
603}
604
605/// The longest pause between two device-token polls after transient
606/// failures without a `Retry-After` (seconds).
607const DEVICE_POLL_BACKOFF_CAP_S: u64 = 60;
608
609/// The pacing of the device-token polls (RFC 8628 §3.5): `authorization_pending`
610/// keeps the interval, `slow_down` raises it by 5 s for good, a transient
611/// failure (offline, timeout, 429, 5xx) waits its `Retry-After` or backs off
612/// exponentially; every other answer (`access_denied`, `expired_token`,
613/// `invalid_grant`, …) ends the flow.
614#[derive(Debug)]
615struct DevicePoll {
616    interval: u64,
617    /// Transient failures in a row.
618    failures: u32,
619}
620
621impl DevicePoll {
622    fn new(interval: u32) -> Self {
623        Self {
624            interval: u64::from(interval.max(1)),
625            failures: 0,
626        }
627    }
628
629    /// Seconds to wait before the next poll after `error`, or the error
630    /// that ends the flow.
631    fn next_wait(&mut self, error: CloudError) -> Result<u64, CloudError> {
632        match &error {
633            CloudError::Server { status: 400, code } if code == "authorization_pending" => {
634                self.failures = 0;
635                Ok(self.interval)
636            }
637            CloudError::Server { status: 400, code } if code == "slow_down" => {
638                self.failures = 0;
639                self.interval = self.interval.saturating_add(5);
640                Ok(self.interval)
641            }
642            transient if transient.is_transient() => {
643                self.failures = self.failures.saturating_add(1);
644                let backoff = self
645                    .interval
646                    .saturating_mul(1u64 << self.failures.min(6))
647                    .min(DEVICE_POLL_BACKOFF_CAP_S.max(self.interval));
648                let asked = transient.retry_after_at(UtcDateTime::now()).unwrap_or(0);
649                tracing::info!("cloud device token: {transient}; polling again");
650                Ok(backoff.max(asked).max(self.interval))
651            }
652            _ => Err(error),
653        }
654    }
655}
656
657/// The `POST /v1/device/token` body: the device code and this instance's
658/// public keys, plus the offered app keys with the instance key's
659/// `app_keys_bind_signature` over them (f3129 S3): no offer goes out
660/// unsigned.
661fn device_token_request(
662    keys: &InstanceKeys,
663    device_code: &str,
664    label: &str,
665    offers: AppKeyOffers<'_>,
666) -> Result<Value, CloudError> {
667    let mut request = json!({
668        "schema": DEVICE_TOKEN_REQUEST_SCHEMA,
669        "device_code": device_code,
670        "instance_public_key": keys.public_key_b64(),
671        "instance_kx_public_key": keys.kx_public_key_b64(),
672        "instance_label": label,
673        "instance_version": env!("CARGO_PKG_VERSION"),
674        "os": engine_os(),
675    });
676    // rc4-32, rc4-67: each only when LeanCTX Code hands one over; absent
677    // otherwise, so an older Cloud that refuses unknown members serves every
678    // plain pairing.
679    if let Some(offer) = offers.chat {
680        request["chat_key"] = offer.request_member();
681    }
682    if let Some(offer) = offers.task {
683        request[task_key::REQUEST_MEMBER] = offer.request_member();
684    }
685    if let Some(offer) = offers.optin {
686        request[optin_key::REQUEST_MEMBER] = offer.request_member();
687    }
688    if let Some(signature) = offers.bind_signature(keys, device_code)? {
689        request["app_keys_bind_signature"] = Value::String(signature);
690    }
691    Ok(request)
692}
693
694/// The task key offer must bind to exactly the `instance_public_key` this
695/// request sends; a bad one stops the pairing before anything is sent.
696fn check_task_key(keys: &InstanceKeys, offer: Option<&TaskKeyOffer>) -> Result<(), CloudError> {
697    match offer {
698        Some(offer) => offer
699            .check(&keys.public_key_b64())
700            .map_err(CloudError::Config),
701        None => Ok(()),
702    }
703}
704
705/// The opt-in key offer must bind to exactly the `instance_public_key` this
706/// request sends (its own signature over the bind, §46.3); a bad one stops
707/// the pairing before anything is sent.
708fn check_optin_key(keys: &InstanceKeys, offer: Option<&OptinKeyOffer>) -> Result<(), CloudError> {
709    match offer {
710        Some(offer) => offer
711            .check(&keys.public_key_b64())
712            .map_err(CloudError::Config),
713        None => Ok(()),
714    }
715}
716
717/// The chat key offer must bind to exactly the `instance_public_key` this
718/// request sends; a bad one stops the pairing before anything is sent.
719fn check_chat_key(keys: &InstanceKeys, chat_key: Option<&ChatKeyOffer>) -> Result<(), CloudError> {
720    match chat_key {
721        Some(offer) => offer
722            .check(&keys.public_key_b64())
723            .map_err(CloudError::Config),
724        None => Ok(()),
725    }
726}
727
728/// Whether a pairing enrolled a new instance or re-paired the one this
729/// computer already had (the same id, team and Cloud: [`HeldInstance`]).
730#[derive(Debug, Clone, Copy, PartialEq, Eq)]
731enum Pairing {
732    New,
733    Rebind,
734}
735
736impl Pairing {
737    /// `before` is the instance held before the pairing (`None`: none, or
738    /// an unreadable record).
739    fn of(before: Option<&HeldInstance>, after: &InstanceRecord) -> Self {
740        if before.is_some_and(|held| held.is(after)) {
741            Pairing::Rebind
742        } else {
743            Pairing::New
744        }
745    }
746}
747
748/// Keep the public part of an accepted task key (never private material).
749/// A new enrollment replaces it: the new offer, or none at all (a key bound
750/// to an earlier enrollment is never kept). A rebind without an offer keeps
751/// the bound key.
752fn keep_task_key(
753    store: &CloudStore,
754    offer: Option<&TaskKeyOffer>,
755    pairing: Pairing,
756) -> Result<(), CloudError> {
757    match (offer, pairing) {
758        (Some(offer), _) => task_key::store_bound(store, offer),
759        (None, Pairing::New) => task_key::remove_bound(store),
760        (None, Pairing::Rebind) => Ok(()),
761    }
762}
763
764/// Keep the public part of an accepted opt-in key (rc4-16), marked accepted:
765/// the Cloud's 2xx token answer took it, so `cloud.pickup` reports
766/// `worker_on` once the Cloud announces `instance_optin_key`. A new
767/// enrollment without an offer puts a kept key back to pending (a key bound
768/// to an earlier enrollment is never usable; the app pairs it again); a
769/// rebind without an offer keeps it as it is.
770fn keep_optin_key(
771    store: &CloudStore,
772    offer: Option<&OptinKeyOffer>,
773    pairing: Pairing,
774) -> Result<(), CloudError> {
775    match (offer, pairing) {
776        (Some(offer), _) => {
777            optin_key::store_pending(store, offer)?;
778            optin_key::mark_accepted(store, &offer.key_id).map(|_| ())
779        }
780        (None, Pairing::New) => optin_key::clear_accepted(store),
781        (None, Pairing::Rebind) => Ok(()),
782    }
783}
784
785/// Keep the public part of an accepted chat key (never private material).
786/// A new enrollment replaces the bound chat key: the new offer, or none at
787/// all (a key bound to an earlier enrollment is never kept). The re-pair of
788/// a connected computer ([`repair_chat_key`]) stores its offer the same way.
789/// A rebind without an offer keeps the bound key.
790fn keep_chat_key(
791    store: &CloudStore,
792    chat_key: Option<&ChatKeyOffer>,
793    pairing: Pairing,
794) -> Result<(), CloudError> {
795    match (chat_key, pairing) {
796        (Some(offer), _) => crate::consent::chat_key::store_bound(store, offer),
797        (None, Pairing::New) => store.remove_config(crate::consent::chat_key::CHAT_KEY_FILE),
798        (None, Pairing::Rebind) => Ok(()),
799    }
800}
801
802/// Verify and persist the enrollment Cloud answered at `/device/token`.
803fn accept_enrollment(
804    store: &CloudStore,
805    client: &CloudClient,
806    body: Value,
807    label: &str,
808    root: &[u8; 32],
809    local_now: UtcDateTime,
810) -> Result<(InstanceRecord, SharingAnswer), CloudError> {
811    let keys_raw = body["keys"].clone();
812    let sharing: SharingAnswer = body
813        .get("sharing")
814        .filter(|s| s.is_object())
815        .map(|s| s["share"].as_bool());
816    decode::<EnrollmentV1>(body, "enrollment")
817        .and_then(|enrollment| {
818            complete_enrollment(
819                store,
820                client.origin(),
821                &enrollment,
822                &keys_raw,
823                root,
824                label,
825                local_now,
826            )
827        })
828        .map(|instance| (instance, sharing))
829        .map_err(|error| unenrolled(store, label, error))
830}
831
832/// What a chat key re-pair of a connected computer did (rc4-32, p37
833/// §3.18.1): its `reason` in `cloud connect --json`.
834#[derive(Debug, Clone, Copy, PartialEq, Eq)]
835pub enum ChatKeyRepair {
836    /// A chat key is bound now (none was, or LeanCTX Code made a new one).
837    Bound,
838    /// LeanCTX Cloud already had this chat key for this computer.
839    Unchanged,
840}
841
842impl ChatKeyRepair {
843    /// The `reason` LeanCTX Code branches on.
844    #[must_use]
845    pub fn reason(self) -> &'static str {
846        match self {
847            Self::Bound => "bound",
848            Self::Unchanged => "unchanged",
849        }
850    }
851}
852
853/// Another chat key is bound to this computer (`409 invalid_state`, reason
854/// `chat_key_bound`).
855pub const CHAT_KEY_BOUND: &str = "Another chat key is bound to this computer; remove it on the computer's page, then pair again.";
856
857/// The offered chat key was removed (`409`, reason `chat_key_cleared`).
858pub const CHAT_KEY_CLEARED: &str =
859    "This chat key was removed; LeanCTX Code makes a new one and pairs again.";
860
861/// A computer connected with an enrollment token (`400 token_enrollment`).
862pub const CHAT_KEY_TOKEN_ENROLLMENT: &str = "This computer was connected with an enrollment token; pairing the chat key needs a connect from LeanCTX Code.";
863
864/// The answers of a chat key re-pair that name why it was refused, kept by
865/// `CloudError::from_response` as `Server { code }` (this protocol
866/// version does not name them).
867pub const CHAT_KEY_REPAIR_REASONS: &[&str] =
868    &["chat_key_bound", "chat_key_cleared", "token_enrollment"];
869
870/// A refused chat key re-pair: its `reason` (absent for `token_enrollment`,
871/// for `invalid_field chat_key` and for an app-key refusal, whose event
872/// `code` is `app_key_not_announced`) and fixed text; `None` for
873/// any other error.
874#[must_use]
875pub fn chat_key_repair_refusal(error: &CloudError) -> Option<(Option<&'static str>, &'static str)> {
876    match error {
877        CloudError::Server { status: 409, code } if code == "chat_key_bound" => {
878            Some((Some("chat_key_bound"), CHAT_KEY_BOUND))
879        }
880        CloudError::Server { status: 409, code } if code == "chat_key_cleared" => {
881            Some((Some("chat_key_cleared"), CHAT_KEY_CLEARED))
882        }
883        CloudError::Server { status: 400, code } if code == "token_enrollment" => {
884            Some((None, CHAT_KEY_TOKEN_ENROLLMENT))
885        }
886        CloudError::DeviceFlow(why) if why == CHAT_KEY_REFUSED => Some((None, CHAT_KEY_REFUSED)),
887        CloudError::DeviceFlow(why) | CloudError::Config(why) if why == APP_KEY_PAIRING_FAILED => {
888            Some((None, APP_KEY_PAIRING_FAILED))
889        }
890        CloudError::Config(why) if why == APP_KEYS_UNSUPPORTED => {
891            Some((None, APP_KEYS_UNSUPPORTED))
892        }
893        _ => None,
894    }
895}
896
897/// Pair LeanCTX Code's chat key with this ALREADY connected computer
898/// (p37 §3.18.1): the normal device flow (`code` from
899/// [`start_device_flow_for`], the person approves in the browser) with the
900/// existing instance keys plus `chat_key`, and no `replaces`. LeanCTX Cloud
901/// keeps the instance, its keys, vault links and workers; locally the
902/// enrollment record, vault links and the worker state stay as they are:
903/// only the lease (and the cached session token) the answer renews and the
904/// bound chat key change.
905pub fn repair_chat_key(
906    store: &CloudStore,
907    client: &CloudClient,
908    code: &DeviceCodeV1,
909    root: &[u8; 32],
910    sleep: &dyn Fn(Duration),
911    chat_key: &ChatKeyOffer,
912) -> Result<ChatKeyRepair, CloudError> {
913    repair_chat_key_at(store, client, code, root, sleep, chat_key, UtcDateTime::now)
914}
915
916fn repair_chat_key_at(
917    store: &CloudStore,
918    client: &CloudClient,
919    code: &DeviceCodeV1,
920    root: &[u8; 32],
921    sleep: &dyn Fn(Duration),
922    chat_key: &ChatKeyOffer,
923    now: impl Fn() -> UtcDateTime,
924) -> Result<ChatKeyRepair, CloudError> {
925    let instance = store.instance()?.ok_or(CloudError::NotConnected)?;
926    // The keys this computer is connected with; never new ones.
927    let keys = InstanceKeys::load(store)?;
928    check_chat_key(&keys, Some(chat_key))?;
929    let offers = AppKeyOffers {
930        chat: Some(chat_key),
931        ..AppKeyOffers::default()
932    };
933    offers.require_capability(code)?;
934    let request = device_token_request(&keys, &code.device_code, &instance.label, offers)?;
935    let body = poll_device_token(client, code, &request, sleep).map_err(|e| {
936        // f3129 §11: a refused announced set or bind signature reads
937        // "Pairing failed", not its bare 400.
938        let e = not_announced_refusal(e, true);
939        chat_key_refusal(e, true, CHAT_KEY_REFUSED)
940    })?;
941    let keys_raw = body["keys"].clone();
942    let enrollment = decode::<EnrollmentV1>(body, "enrollment")?;
943    enrollment.validate().map_err(protocol("enrollment"))?;
944    if enrollment.instance_id != instance.instance_id || enrollment.org.id != instance.org_id {
945        return Err(CloudError::Protocol(
946            "the chat key pairing answered for another computer".into(),
947        ));
948    }
949    let local_now = now();
950    let keyset = verify_keyset(&keys_raw, root)?;
951    let verified = verify_lease(
952        &enrollment.lease,
953        &keyset,
954        &instance.instance_id,
955        local_now,
956        None,
957    )?;
958    if verified.lease.org_id != instance.org_id {
959        return Err(CloudError::Protocol(
960            "the lease is for another organization".into(),
961        ));
962    }
963    store_lease(store, &verified, &keys_raw, local_now)?;
964    // A session token of the earlier lease is fetched again.
965    store.remove_config(TOKEN_FILE)?;
966    let before = crate::consent::chat_key::bound_chat_key(store);
967    keep_chat_key(store, Some(chat_key), Pairing::Rebind)?;
968    Ok(match before {
969        Some(bound) if bound.key_id == chat_key.key_id => ChatKeyRepair::Unchanged,
970        _ => ChatKeyRepair::Bound,
971    })
972}
973
974/// The plaintext prefix of a pre-issued Host enrollment token.
975pub const ENROLLMENT_TOKEN_PREFIX: &str = "het_";
976
977/// Why a Cloud refused an enrollment token, in the words a person acts on.
978pub const ENROLLMENT_TOKEN_UNUSABLE: &str =
979    "the enrollment token is unknown, expired, revoked or used up; ask a team admin for a new one";
980
981/// A pre-issued Host enrollment token (`het_` and 64 hex digits) that a
982/// team admin handed out, e.g. through MDM. It enrolls this machine without
983/// a browser approval. The value is wiped on drop and never printed: its
984/// `Debug` shows the prefix only, and no error names it.
985pub struct EnrollmentToken(zeroize::Zeroizing<String>);
986
987impl EnrollmentToken {
988    /// Check the format before anything is sent: surrounding whitespace
989    /// (a trailing newline from stdin) is dropped, everything else must be
990    /// `het_` and exactly 64 hex digits.
991    pub fn parse(raw: &str) -> Result<Self, CloudError> {
992        let value = raw.trim();
993        let well_formed = value
994            .strip_prefix(ENROLLMENT_TOKEN_PREFIX)
995            .is_some_and(|hex| hex.len() == 64 && hex.bytes().all(|b| b.is_ascii_hexdigit()));
996        if !well_formed {
997            return Err(CloudError::Config(
998                "the enrollment token is malformed: it is `het_` followed by 64 hex digits, as the team's Hosts page issued it".into(),
999            ));
1000        }
1001        Ok(Self(zeroize::Zeroizing::new(value.to_string())))
1002    }
1003
1004    fn expose(&self) -> &str {
1005        &self.0
1006    }
1007}
1008
1009impl std::fmt::Debug for EnrollmentToken {
1010    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1011        write!(f, "EnrollmentToken({ENROLLMENT_TOKEN_PREFIX}…)")
1012    }
1013}
1014
1015/// Enroll this machine with a pre-issued enrollment token (no browser):
1016/// one `POST /v1/device/token` with the token as `device_code`, then the
1017/// enrollment is verified and persisted exactly as after a device approval.
1018pub fn enroll_with_token(
1019    store: &CloudStore,
1020    client: &CloudClient,
1021    token: &EnrollmentToken,
1022    label: &str,
1023    root: &[u8; 32],
1024) -> Result<(InstanceRecord, SharingAnswer), CloudError> {
1025    enroll_with_token_chat(store, client, token, label, root, None)
1026}
1027
1028/// An enrollment token has no device code to sign the app keys over (f3129
1029/// S3), so it binds none: a chat key with a token is refused before
1030/// anything is sent, like the task and opt-in keys.
1031pub const CHAT_KEY_WITH_TOKEN: &str = "The chat key of LeanCTX Code goes with a pairing \
1032     approved in the browser, not with an enrollment token; nothing was sent.";
1033
1034/// [`enroll_with_token`] as LeanCTX Code calls it: a chat key offer is
1035/// refused (`config`) before the Cloud is contacted ([`CHAT_KEY_WITH_TOKEN`]).
1036pub fn enroll_with_token_chat(
1037    store: &CloudStore,
1038    client: &CloudClient,
1039    token: &EnrollmentToken,
1040    label: &str,
1041    root: &[u8; 32],
1042    chat_key: Option<&ChatKeyOffer>,
1043) -> Result<(InstanceRecord, SharingAnswer), CloudError> {
1044    if chat_key.is_some() {
1045        return Err(CloudError::Config(CHAT_KEY_WITH_TOKEN.into()));
1046    }
1047    enroll_with_token_at(
1048        store,
1049        client,
1050        token,
1051        label,
1052        root,
1053        lean_ctx_time::UtcDateTime::now,
1054    )
1055}
1056
1057fn enroll_with_token_at(
1058    store: &CloudStore,
1059    client: &CloudClient,
1060    token: &EnrollmentToken,
1061    label: &str,
1062    root: &[u8; 32],
1063    now: impl Fn() -> UtcDateTime,
1064) -> Result<(InstanceRecord, SharingAnswer), CloudError> {
1065    let keys = InstanceKeys::load_or_create(store)?;
1066    // A token pairing offers no app key: nobody approved this computer's
1067    // keys as the person, and there is no device code to sign them over.
1068    let offers = AppKeyOffers::default();
1069    let request = device_token_request(&keys, token.expose(), label, offers)?;
1070    match client.post("/device/token", &request) {
1071        Ok(body) => {
1072            let enrolled = accept_enrollment(store, client, body, label, root, now())?;
1073            // A token pairing drops a stored key (local-read-v1 §28a): the
1074            // person did not approve this pairing's keys.
1075            offers.keep(store, Pairing::New)?;
1076            Ok(enrolled)
1077        }
1078        Err(error) => Err(token_refusal(error)),
1079    }
1080}
1081
1082/// An enrollment token's refusal: Cloud answers `expired_token` for an
1083/// unknown, expired, revoked or used-up token (mapped to the device
1084/// code's wording by the transport), named here for a token.
1085fn token_refusal(error: CloudError) -> CloudError {
1086    match error {
1087        CloudError::DeviceFlow(why) if why == super::error::CODE_EXPIRED => {
1088            CloudError::DeviceFlow(ENROLLMENT_TOKEN_UNUSABLE.into())
1089        }
1090        CloudError::Server { status: 400, code } if code == "expired_token" => {
1091            CloudError::DeviceFlow(ENROLLMENT_TOKEN_UNUSABLE.into())
1092        }
1093        other => other,
1094    }
1095}
1096
1097/// Cloud enrolled the instance key, but this engine refused the answer
1098/// (Cloud task #1): the key is spent, since Cloud now knows it and refuses
1099/// it a second time ("instance key is already enrolled"). A machine without
1100/// an enrollment of its own drops it with whatever the refused answer left,
1101/// so the next connect starts from a fresh key, and the error says so.
1102fn unenrolled(store: &CloudStore, label: &str, error: CloudError) -> CloudError {
1103    if !matches!(store.instance(), Ok(None)) {
1104        return error;
1105    }
1106    let next = match store.forget(true) {
1107        Ok(()) => format!(
1108            "Its unused instance key was removed: fix the cause and run `lean-ctx cloud connect` again. LeanCTX Cloud may list an instance \"{label}\" that never connected; remove it there."
1109        ),
1110        Err(e) => format!(
1111            "Its unused instance key could not be removed ({e}); run `lean-ctx cloud disconnect` before connecting again."
1112        ),
1113    };
1114    match error {
1115        CloudError::Protocol(m) => CloudError::Protocol(format!("{m}. {next}")),
1116        CloudError::Config(m) => CloudError::Config(format!("{m}. {next}")),
1117        other => other,
1118    }
1119}
1120
1121/// Verify an enrollment answer against the root key and persist it.
1122pub fn complete_enrollment(
1123    store: &CloudStore,
1124    origin: &str,
1125    enrollment: &EnrollmentV1,
1126    keys_raw: &Value,
1127    root: &[u8; 32],
1128    label: &str,
1129    local_now: UtcDateTime,
1130) -> Result<InstanceRecord, CloudError> {
1131    enrollment.validate().map_err(protocol("enrollment"))?;
1132    let keyset = verify_keyset(keys_raw, root)?;
1133    let verified = verify_lease(
1134        &enrollment.lease,
1135        &keyset,
1136        &enrollment.instance_id,
1137        local_now,
1138        None,
1139    )?;
1140    if verified.lease.org_id != enrollment.org.id {
1141        return Err(CloudError::Protocol(
1142            "the lease is for another workspace".into(),
1143        ));
1144    }
1145    // `cloud.org` / `cloud.url` of a managed machine: refused before anything
1146    // of this enrollment is stored.
1147    if let Some(refusal) = super::config::managed_enrollment_refusal(&enrollment.org.id, origin) {
1148        return Err(refusal);
1149    }
1150    store_lease(store, &verified, keys_raw, local_now)?;
1151    let record = InstanceRecord {
1152        instance_id: enrollment.instance_id.clone(),
1153        org_id: enrollment.org.id.clone(),
1154        org_name: enrollment.org.name.clone(),
1155        org_kind: enrollment.org.kind.clone(),
1156        company_name: enrollment.org.company.as_ref().map(|c| c.name.clone()),
1157        // rc4-1: the name chosen on the approval page wins over the one sent.
1158        label: enrollment.chosen_label().unwrap_or(label).to_string(),
1159        url: origin.to_string(),
1160        org_salt_id: enrollment.org_salt_id.clone(),
1161        web_url: enrollment
1162            .web_url
1163            .as_deref()
1164            .and_then(|url| super::config::normalize_origin(url).ok()),
1165        enrolled_at: stamp(local_now),
1166    };
1167    // Local Cloud data of another server or team goes before anything of
1168    // this enrolment reads it (3.12.8 account scope).
1169    store.scope_to_enrollment(&record)?;
1170    super::worker::prepare_enrollment(store)?;
1171    store.write_config(INSTANCE_FILE, &record)?;
1172    // A new enrolment starts a new sharing period (Cloud' `since`): an
1173    // earlier engine-side off no longer bounds it (K2 review 3, NEW-1).
1174    super::metrics_v2::buffer::clear_local_on_since(store.data_dir());
1175    store.remove_config(TOKEN_FILE)?;
1176    store.record_success("enroll", &stamp(verified.service_time(local_now).to_utc()));
1177    Ok(record)
1178}
1179
1180/// A connected instance: its record, verified lease and keys.
1181pub struct Session {
1182    pub store: CloudStore,
1183    pub instance: InstanceRecord,
1184    pub lease: VerifiedLease,
1185    root: [u8; 32],
1186}
1187
1188impl Session {
1189    /// Load and re-verify the local enrollment. `root` is the root key of the
1190    /// origin the instance is enrolled with.
1191    pub fn load(store: CloudStore, root: [u8; 32]) -> Result<Self, CloudError> {
1192        // Scoped: local data of another account is gone before a session
1193        // reads or sends any of it (3.12.8 account scope).
1194        let instance = store.instance()?.ok_or(CloudError::NotConnected)?;
1195        // A revoked instance fails closed here, before any Cloud call.
1196        if let Some(revoked) = super::revoked::recorded(&store, &instance) {
1197            return Err(revoked);
1198        }
1199        // An enrollment from before the machine was managed, with another
1200        // org or Cloud, is not used.
1201        if let Some(refusal) =
1202            super::config::managed_enrollment_refusal(&instance.org_id, &instance.url)
1203        {
1204            return Err(refusal);
1205        }
1206        let lease = load_lease(&store, &root, &instance.instance_id)?;
1207        super::root_cert::check_lease_org(&store, &instance.url, &lease.lease)?;
1208        Ok(Self {
1209            store,
1210            instance,
1211            lease,
1212            root,
1213        })
1214    }
1215
1216    /// The root key the enrollment was verified with.
1217    pub fn root_key(&self) -> &[u8; 32] {
1218        &self.root
1219    }
1220
1221    fn service_now(&self) -> UtcDateTime {
1222        self.lease.service_time(UtcDateTime::now()).to_utc()
1223    }
1224
1225    /// The current access token (minted when needed), for transports that
1226    /// authenticate outside [`CloudClient`] (the bus WebSocket upgrade).
1227    /// `force` mints a new one.
1228    pub fn bearer_token(&self, force: bool) -> Result<zeroize::Zeroizing<String>, CloudError> {
1229        self.access_token(force).map(zeroize::Zeroizing::new)
1230    }
1231
1232    /// An authenticated client, minting an access token when needed.
1233    pub fn client(&self) -> Result<CloudClient, CloudError> {
1234        let token = self.access_token(false)?;
1235        Ok(CloudClient::new(&self.instance.url)?.with_token(&self.instance.instance_id, &token))
1236    }
1237
1238    /// Run `call` with an authenticated client; on 401 mint a new token once.
1239    pub fn with_client<T>(
1240        &self,
1241        call: impl Fn(&CloudClient) -> Result<T, CloudError>,
1242    ) -> Result<T, CloudError> {
1243        let result = match call(&self.client()?) {
1244            Err(CloudError::Unauthorized) => {
1245                let token = self.access_token(true)?;
1246                let client = CloudClient::new(&self.instance.url)?
1247                    .with_token(&self.instance.instance_id, &token);
1248                call(&client)
1249            }
1250            other => other,
1251        };
1252        result.map_err(|e| self.noted(e))
1253    }
1254
1255    /// A revocation answer is recorded (the engine then fails closed) and
1256    /// named with this workspace; a used-up quota holds the paths it counts
1257    /// (`throttle`); a feature's `plan_required` names the lease's plan;
1258    /// any other error passes unchanged.
1259    pub(crate) fn noted(&self, error: CloudError) -> CloudError {
1260        let error = super::revoked::note(&self.store, &self.instance, error)
1261            .with_plan(self.lease.lease.plan);
1262        super::throttle::note_on(&self.store, None, error, lean_ctx_time::UtcDateTime::now())
1263    }
1264
1265    /// An authenticated client for one call that must end by `deadline`,
1266    /// minting the token (if needed) inside the same budget and without the
1267    /// 401 retry of [`Self::with_client`] (C5c, rule 3 exception).
1268    pub fn bounded_client(&self, deadline: std::time::Instant) -> Result<CloudClient, CloudError> {
1269        let left = |what: &str| {
1270            deadline
1271                .checked_duration_since(std::time::Instant::now())
1272                .filter(|d| !d.is_zero())
1273                .ok_or_else(|| CloudError::Offline(format!("{what}: time budget used up")))
1274        };
1275        let mint = CloudClient::bounded(&self.instance.url, left("token")?)?;
1276        let token = self.access_token_via(false, &mint)?;
1277        Ok(CloudClient::bounded(&self.instance.url, left("request")?)?
1278            .with_token(&self.instance.instance_id, &token))
1279    }
1280
1281    /// The token is minted in C0 2.0 like every other request.
1282    fn access_token(&self, force: bool) -> Result<String, CloudError> {
1283        self.access_token_via(force, &CloudClient::new(&self.instance.url)?)
1284    }
1285
1286    fn access_token_via(&self, force: bool, client: &CloudClient) -> Result<String, CloudError> {
1287        let now = self.service_now().timestamp();
1288        if !force
1289            && let Some(cached) = self.store.read_config::<TokenRecord>(TOKEN_FILE)?
1290            && cached.expires_at - TOKEN_REFRESH_MARGIN_SECONDS > now
1291        {
1292            return Ok(cached.access_token);
1293        }
1294        // A 429 of the mint holds every process of this machine (they share
1295        // the instance key and the server's budget, which counts refused
1296        // attempts too): nothing is sent until it ends, a forced or manual
1297        // mint neither.
1298        if let Some(held) = super::throttle::token_hold(&self.store, UtcDateTime::now()) {
1299            return Err(held);
1300        }
1301        let keys = InstanceKeys::load(&self.store)?;
1302        let mut nonce_bytes = [0u8; 18];
1303        getrandom::fill(&mut nonce_bytes).map_err(|e| CloudError::Local(format!("random: {e}")))?;
1304        use base64::Engine as _;
1305        let nonce = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(nonce_bytes);
1306        let assertion = keys.sign_b64(&token_assertion_input(
1307            &self.instance.instance_id,
1308            now,
1309            &nonce,
1310        ));
1311        let request = json!({
1312            "schema": TOKEN_REQUEST_SCHEMA, "iat": now, "nonce": nonce, "assertion": assertion,
1313        });
1314        let path = format!("/instances/{}/token", self.instance.instance_id);
1315        let answer = client.post(&path, &request).map_err(|e| {
1316            super::throttle::note_token_limit(&self.store, self.noted(e), UtcDateTime::now())
1317        })?;
1318        let token: AccessTokenV1 = decode(answer, "access token")?;
1319        token.validate().map_err(protocol("access token"))?;
1320        super::throttle::token_minted(&self.store);
1321        self.store.write_config(
1322            TOKEN_FILE,
1323            &TokenRecord {
1324                access_token: token.access_token.clone(),
1325                expires_at: now + i64::from(token.expires_in),
1326            },
1327        )?;
1328        self.store
1329            .record_success("token", &stamp(self.service_now()));
1330        Ok(token.access_token)
1331    }
1332
1333    /// Renew the lease and persist it; returns the new lease. Asked in C0
1334    /// 2.0 like the enrollment whose lease it replaces, and checked against
1335    /// the key set that holds its `kid` (which also feeds the runtime lease):
1336    /// the stored one, else key set v3, by which a C0 2.x Cloud signs leases
1337    /// once it serves v3, fetched once when it is not stored yet. The key
1338    /// set the lease verified with is stored with it, so every later load
1339    /// re-verifies it the same way.
1340    pub fn renew(&mut self) -> Result<&VerifiedLease, CloudError> {
1341        let path = format!("/instances/{}/lease/renew", self.instance.instance_id);
1342        let body = self.with_client(|client| client.post(&path, &json!({})))?;
1343        let local_now = UtcDateTime::now();
1344        let envelope: CloudLeaseEnvelopeV1 = decode(body, "lease")?;
1345        let stored: Value = self
1346            .store
1347            .read_config(super::state::KEYS_FILE)?
1348            .ok_or(CloudError::NotConnected)?;
1349        let pick = |session: &Self| {
1350            super::lease::renewal_key_set(
1351                &stored,
1352                super::keyset_v3::stored_raw(&session.store).as_ref(),
1353                &session.root,
1354                &envelope.kid,
1355            )
1356        };
1357        let keys_raw = if let Some(raw) = pick(self) {
1358            raw
1359        } else {
1360            super::keyset_v3::refresh(self)?;
1361            pick(self).ok_or_else(|| {
1362                CloudError::Protocol(format!(
1363                    "the renewed lease names key {}, which no verified key set holds",
1364                    envelope.kid
1365                ))
1366            })?
1367        };
1368        let keyset = verify_keyset(&keys_raw, &self.root)?;
1369        let verified = verify_lease(
1370            &envelope,
1371            &keyset,
1372            &self.instance.instance_id,
1373            local_now,
1374            None,
1375        )?;
1376        store_lease(&self.store, &verified, &keys_raw, local_now)?;
1377        self.store
1378            .record_success("lease", &stamp(verified.service_time(local_now).to_utc()));
1379        self.store.record_renew_error(None);
1380        self.lease = verified;
1381        Ok(&self.lease)
1382    }
1383
1384    /// Free the seat in Cloud.
1385    pub fn delete_instance(&self) -> Result<(), CloudError> {
1386        let path = format!("/instances/{}", self.instance.instance_id);
1387        self.with_client(|client| client.delete(&path))
1388    }
1389}
1390
1391/// A session loaded from the enrollment fixture (key set v1) in a fresh
1392/// store, for tests of passes that take a [`Session`] but must send
1393/// nothing. Its origin is never contacted by such a test.
1394#[cfg(test)]
1395pub(crate) fn fixture_session() -> (tempfile::TempDir, Session) {
1396    fixture_session_at("https://cloud.leanctx.com")
1397}
1398
1399/// [`fixture_session`] enrolled with `origin` (a loopback Cloud of a test).
1400#[cfg(test)]
1401pub(crate) fn fixture_session_at(origin: &str) -> (tempfile::TempDir, Session) {
1402    let path = concat!(
1403        env!("CARGO_MANIFEST_DIR"),
1404        "/../lean-ctx-protocol/tests/fixtures/cloud/enrollment.response.json"
1405    );
1406    let raw: Value = serde_json::from_slice(&std::fs::read(path).expect("fixture")).expect("json");
1407    let root = ed25519_dalek::SigningKey::from_bytes(&[0x52; 32])
1408        .verifying_key()
1409        .to_bytes();
1410    let dir = tempfile::tempdir().expect("tempdir");
1411    let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
1412    let enrollment: EnrollmentV1 = decode(raw.clone(), "enrollment").expect("enrollment");
1413    complete_enrollment(
1414        &store,
1415        origin,
1416        &enrollment,
1417        &raw["keys"],
1418        &root,
1419        "studio-mac",
1420        lean_ctx_time::OffsetDateTime::parse_from_rfc3339("2026-10-20T12:00:00Z")
1421            .expect("time")
1422            .to_utc(),
1423    )
1424    .expect("enrolled");
1425    let session = Session::load(store, root).expect("session");
1426    (dir, session)
1427}
1428
1429#[cfg(test)]
1430mod tests {
1431    use super::*;
1432
1433    /// rc3-5: the approval page names the machine from `/device/code`; a
1434    /// label Cloud would refuse is trimmed, cut or dropped, never a 400.
1435    #[test]
1436    fn the_device_code_request_names_the_machine() {
1437        let long = "m".repeat(MAX_INSTANCE_LABEL_CHARS + 9);
1438        for (label, sent) in [
1439            ("  build-host  ", Some("build-host".to_string())),
1440            (long.as_str(), Some("m".repeat(MAX_INSTANCE_LABEL_CHARS))),
1441            ("bad\u{7}label", None),
1442            ("   ", None),
1443        ] {
1444            let (origin, recorded) = fake_cloud((200, fixture("cloud/device_code.response.json")));
1445            let client = CloudClient::new(&origin).unwrap();
1446            start_device_flow(&client, Some(label)).expect("login still starts");
1447            let body = recorded.lock().unwrap()[0].1.clone();
1448            assert_eq!(recorded.lock().unwrap()[0].0, "/v1/device/code");
1449            assert_eq!(body.get("instance_label").cloned(), sent.map(Value::from));
1450        }
1451    }
1452
1453    /// An older Cloud refuses the trial members (`deny_unknown_fields`):
1454    /// `trial_unsupported`, never a silent sign-in; a sign-in's own 400 and
1455    /// every other trial refusal stay what they were.
1456    #[test]
1457    fn trial_request_refused_as_unknown_is_trial_unsupported() {
1458        let refused = || CloudError::Server {
1459            status: 400,
1460            code: "invalid_request".into(),
1461        };
1462        let mapped = trial_refusal(refused(), true, "https://cloud.leanctx.com/");
1463        assert_eq!(
1464            mapped,
1465            CloudError::TrialUnsupported {
1466                origin: "https://cloud.leanctx.com".into()
1467            }
1468        );
1469        assert_eq!(mapped.event_code(), "trial_unsupported");
1470        assert_eq!(
1471            mapped.to_string(),
1472            "LeanCTX does not offer the one-step trial here yet. Start the trial on https://cloud.leanctx.com, or sign in with `lean-ctx cloud connect`"
1473        );
1474        // Printed by the terminal and by LeanCTX Code alike.
1475        assert!(!mapped.to_string().contains("app"));
1476        assert_eq!(
1477            trial_refusal(refused(), false, "https://cloud.leanctx.com"),
1478            refused()
1479        );
1480        let offline = CloudError::Offline("reset".into());
1481        assert_eq!(
1482            trial_refusal(offline.clone(), true, "https://cloud.leanctx.com"),
1483            offline
1484        );
1485    }
1486
1487    fn fixture(path: &str) -> Value {
1488        let path = format!(
1489            "{}/crates/lean-ctx-protocol/tests/fixtures/{path}",
1490            concat!(env!("CARGO_MANIFEST_DIR"), "/../..")
1491        );
1492        serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
1493    }
1494
1495    fn at(t: &str) -> UtcDateTime {
1496        lean_ctx_time::OffsetDateTime::parse_from_rfc3339(t)
1497            .unwrap()
1498            .to_utc()
1499    }
1500
1501    /// Enroll `raw` in a fresh store; the directory lives as long as the
1502    /// returned guard.
1503    fn enroll(
1504        raw: &Value,
1505        root: &[u8; 32],
1506    ) -> Result<(tempfile::TempDir, CloudStore, InstanceRecord), CloudError> {
1507        let dir = tempfile::tempdir().unwrap();
1508        let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
1509        let enrollment: EnrollmentV1 = decode(raw.clone(), "enrollment")?;
1510        let record = complete_enrollment(
1511            &store,
1512            "https://cloud.leanctx.com",
1513            &enrollment,
1514            &raw["keys"],
1515            root,
1516            "studio-mac",
1517            at("2026-10-20T12:00:00Z"),
1518        )?;
1519        let lease = load_lease(&store, root, &record.instance_id)?;
1520        assert_eq!(lease.envelope.kid, enrollment.lease.kid);
1521        Ok((dir, store, record))
1522    }
1523
1524    /// rc4-274: in a single-dir layout (a legacy `~/.lean-ctx`, a custom
1525    /// `LEAN_CTX_DATA_DIR`) `<config>/cloud` is `<data>/cloud`. The account
1526    /// scope of the enrolment removes only the data there: the instance key
1527    /// made before the approval, the lease and the key set stay, so the
1528    /// approved connect is connected.
1529    #[test]
1530    fn enrolling_in_a_single_dir_layout_keeps_the_keys_and_the_lease() {
1531        let raw = fixture("cloud/enrollment.response.json");
1532        let root = ed25519_dalek::SigningKey::from_bytes(&[0x52; 32])
1533            .verifying_key()
1534            .to_bytes();
1535        let dir = tempfile::tempdir().unwrap();
1536        let cloud = dir.path().join("cloud");
1537        let store = CloudStore::at(&cloud, &cloud);
1538        let keys = crate::instance_key::InstanceKeys::load_or_create(&store).unwrap();
1539        // Data an older version left without a stamp: another account's.
1540        std::fs::write(cloud.join("projects.json"), b"{\"projects\":{}}").unwrap();
1541        let enrollment: EnrollmentV1 = decode(raw.clone(), "enrollment").unwrap();
1542        let record = complete_enrollment(
1543            &store,
1544            "https://cloud.leanctx.com",
1545            &enrollment,
1546            &raw["keys"],
1547            &root,
1548            "studio-mac",
1549            at("2026-10-20T12:00:00Z"),
1550        )
1551        .unwrap();
1552
1553        assert!(!cloud.join("projects.json").exists(), "the data goes");
1554        let kept = crate::instance_key::InstanceKeys::load(&store).unwrap();
1555        assert_eq!(kept.public_key_b64(), keys.public_key_b64());
1556        assert_eq!(kept.kx_public_key_b64(), keys.kx_public_key_b64());
1557        load_lease(&store, &root, &record.instance_id).unwrap();
1558        assert_eq!(store.instance().unwrap(), Some(record));
1559        assert!(Session::load(store, root).is_ok(), "connected");
1560    }
1561
1562    /// Below Cloud-Protocol 2.1: key set v1, the lease signed by its `kid`.
1563    #[test]
1564    fn an_enrollment_with_key_set_v1_is_verified_and_kept() {
1565        use ed25519_dalek::SigningKey;
1566        let raw = fixture("cloud/enrollment.response.json");
1567        let root = SigningKey::from_bytes(&[0x52; 32])
1568            .verifying_key()
1569            .to_bytes();
1570        let (_dir, _store, record) = enroll(&raw, &root).unwrap();
1571        assert_eq!(record.org_id, "org_acme");
1572        let refused = enroll(&raw, &[7; 32]).expect_err("another root");
1573        assert!(
1574            refused
1575                .to_string()
1576                .contains(super::super::lease::ROOT_MISMATCH)
1577        );
1578    }
1579
1580    /// Cloud-Protocol 2.1 (`routes/enrollment.for_2x.response.json`): key set
1581    /// v3, verified as every v3 set, and the lease signed by the key of
1582    /// purpose `policy` its `kid` names.
1583    #[test]
1584    fn an_enrollment_with_key_set_v3_is_verified_with_its_policy_key() {
1585        let raw = fixture("cloud-v2/routes/enrollment.for_2x.response.json");
1586        let mut root = [0u8; 32];
1587        hex::decode_to_slice(
1588            fixture("cloud-v2/vectors/signing.vectors.json")["keys"]["root_new"]["public_key_hex"]
1589                .as_str()
1590                .unwrap(),
1591            &mut root,
1592        )
1593        .unwrap();
1594        let (_dir, store, record) = enroll(&raw, &root).unwrap();
1595        assert_eq!(record.org_id, "org_acme");
1596        assert_eq!(raw["lease"]["kid"], "552e43422b3589fa");
1597        let kept: Value = store
1598            .read_config(super::super::state::KEYS_FILE)
1599            .unwrap()
1600            .unwrap();
1601        assert_eq!(kept, raw["keys"], "the v3 set is kept as received");
1602        // Another root, or a lease kid of a key that signs no leases: refused.
1603        assert!(enroll(&raw, &[7; 32]).is_err());
1604        let mut event_kid = raw;
1605        event_kid["lease"]["kid"] = "4fc7bebc302357bd".into();
1606        assert!(enroll(&event_kid, &root).is_err());
1607    }
1608
1609    const TOKEN: &str = "het_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
1610
1611    #[test]
1612    fn an_enrollment_token_is_checked_before_anything_is_sent() {
1613        let token = EnrollmentToken::parse(&format!("  {TOKEN}\r\n")).unwrap();
1614        assert_eq!(
1615            token.expose(),
1616            TOKEN,
1617            "a trailing newline from stdin is dropped"
1618        );
1619        assert!(
1620            EnrollmentToken::parse(&TOKEN.to_ascii_uppercase().replace("HET_", "het_")).is_ok()
1621        );
1622        let short = &TOKEN[..TOKEN.len() - 1];
1623        let not_hex = format!("{}g", &TOKEN[..TOKEN.len() - 1]);
1624        let device_code = TOKEN.replace("het_", "hdc_");
1625        let inner_space = format!("{} {}", &TOKEN[..20], &TOKEN[20..]);
1626        for bad in [
1627            "",
1628            "het_",
1629            short,
1630            &not_hex,
1631            &device_code,
1632            &inner_space,
1633            &format!("{TOKEN}0"),
1634        ] {
1635            let error = EnrollmentToken::parse(bad).expect_err(bad).to_string();
1636            assert!(error.contains("malformed"), "{error}");
1637            assert!(
1638                bad.len() < 8 || !error.contains(bad),
1639                "the value is never echoed: {error}"
1640            );
1641        }
1642        assert_eq!(format!("{token:?}"), "EnrollmentToken(het_…)");
1643    }
1644
1645    type Recorded = std::sync::Arc<std::sync::Mutex<Vec<(String, Value)>>>;
1646
1647    /// A one-route Cloud on 127.0.0.1 that answers every request with
1648    /// `answer` and records what it was sent.
1649    #[allow(clippy::needless_pass_by_value)] // callers hand over a fresh `json!`
1650    fn fake_cloud(answer: (u16, Value)) -> (String, Recorded) {
1651        let (status, body) = answer;
1652        let raw = raw_answer(
1653            status,
1654            "Content-Type: application/json\r\n",
1655            &body.to_string(),
1656        );
1657        scripted_cloud(vec![raw])
1658    }
1659
1660    /// A raw HTTP answer: status, extra header lines and body.
1661    fn raw_answer(status: u16, headers: &str, body: &str) -> String {
1662        format!(
1663            "HTTP/1.1 {status} X\r\n{headers}Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
1664            body.len()
1665        )
1666    }
1667
1668    /// A Cloud on 127.0.0.1 that answers the n-th request with the n-th raw
1669    /// HTTP answer (the last one repeats) and records what it was sent.
1670    fn scripted_cloud(answers: Vec<String>) -> (String, Recorded) {
1671        use std::io::{BufRead as _, Read as _, Write as _};
1672        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1673        let origin = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());
1674        let recorded: Recorded = std::sync::Arc::default();
1675        let seen = std::sync::Arc::clone(&recorded);
1676        std::thread::spawn(move || {
1677            for stream in listener.incoming().flatten() {
1678                let mut writer = stream.try_clone().unwrap();
1679                let mut reader = std::io::BufReader::new(stream);
1680                let mut line = String::new();
1681                if reader.read_line(&mut line).unwrap_or(0) == 0 {
1682                    continue;
1683                }
1684                let path = line
1685                    .split_whitespace()
1686                    .nth(1)
1687                    .unwrap_or_default()
1688                    .to_owned();
1689                let mut length = 0;
1690                loop {
1691                    let mut header = String::new();
1692                    reader.read_line(&mut header).unwrap();
1693                    let header = header.trim_end();
1694                    if header.is_empty() {
1695                        break;
1696                    }
1697                    if let Some((name, value)) = header.split_once(':')
1698                        && name.eq_ignore_ascii_case("content-length")
1699                    {
1700                        length = value.trim().parse().unwrap();
1701                    }
1702                }
1703                let mut body = vec![0; length];
1704                reader.read_exact(&mut body).unwrap();
1705                let body = serde_json::from_slice(&body).unwrap_or(Value::Null);
1706                let n = {
1707                    let mut seen = seen.lock().unwrap();
1708                    seen.push((path, body));
1709                    seen.len() - 1
1710                };
1711                let raw = &answers[n.min(answers.len() - 1)];
1712                let _ = writer.write_all(raw.as_bytes());
1713            }
1714        });
1715        (origin, recorded)
1716    }
1717
1718    fn device_code(interval: u32, expires_in: u32) -> DeviceCodeV1 {
1719        DeviceCodeV1 {
1720            schema: lean_ctx_protocol::cloud::enroll::DEVICE_CODE_SCHEMA.into(),
1721            device_code: "hdc_test".into(),
1722            user_code: "WDJB-MJHT".into(),
1723            verification_uri: "https://cloud.example.com/device".into(),
1724            verification_uri_complete: "https://cloud.example.com/device?c=WDJB-MJHT".into(),
1725            interval,
1726            expires_in,
1727            features: Vec::new(),
1728            intent: None,
1729            plan: None,
1730        }
1731    }
1732
1733    const EDGE_502: &str = "<html><body><h1>502 Bad Gateway</h1></body></html>";
1734
1735    /// Review fix: an edge error page (502/503 HTML, 429 with only a
1736    /// `Retry-After` header) or a refused connection does not end the
1737    /// device flow; the poll waits (`Retry-After`, else backoff) and goes
1738    /// on, `slow_down` raises the interval, `access_denied` ends it.
1739    #[test]
1740    fn the_device_flow_rides_out_transient_failures_until_a_final_answer() {
1741        let json = "Content-Type: application/json\r\n";
1742        let html = "Content-Type: text/html\r\n";
1743        let (origin, recorded) = scripted_cloud(vec![
1744            raw_answer(502, html, EDGE_502),
1745            raw_answer(
1746                429,
1747                &format!("{html}Retry-After: 30\r\n"),
1748                "Too Many Requests",
1749            ),
1750            raw_answer(503, html, ""),
1751            raw_answer(
1752                400,
1753                json,
1754                r#"{"error":{"code":"authorization_pending","message":"x"}}"#,
1755            ),
1756            raw_answer(400, json, r#"{"error":{"code":"slow_down","message":"x"}}"#),
1757            raw_answer(
1758                400,
1759                json,
1760                r#"{"error":{"code":"access_denied","message":"x"}}"#,
1761            ),
1762        ]);
1763        let dir = tempfile::tempdir().unwrap();
1764        let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
1765        let client = CloudClient::new(&origin).unwrap();
1766        let sleeps = std::cell::RefCell::new(Vec::new());
1767        let error = finish_device_flow(
1768            &store,
1769            &client,
1770            &device_code(2, 600),
1771            "studio-mac",
1772            &[7; 32],
1773            &|d| sleeps.borrow_mut().push(d.as_secs()),
1774        )
1775        .expect_err("denied");
1776        assert!(matches!(error, CloudError::DeviceFlow(_)), "{error:?}");
1777        assert!(error.to_string().contains("Not mine"), "{error}");
1778        assert_eq!(recorded.lock().unwrap().len(), 6);
1779        // interval 2; 502 → 4 (backoff); 429 → its Retry-After 30; 503 →
1780        // 16 (third failure in a row); pending → 2; slow_down → 2 + 5.
1781        assert_eq!(sleeps.into_inner(), vec![2, 4, 30, 16, 2, 7]);
1782        assert!(store.instance().unwrap().is_none(), "nothing enrolled");
1783    }
1784
1785    #[test]
1786    fn transient_failures_end_the_device_flow_only_at_its_deadline() {
1787        let (origin, recorded) = scripted_cloud(vec![raw_answer(
1788            503,
1789            "Content-Type: text/html\r\n",
1790            EDGE_502,
1791        )]);
1792        let dir = tempfile::tempdir().unwrap();
1793        let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
1794        let client = CloudClient::new(&origin).unwrap();
1795        let sleeps = std::cell::RefCell::new(Vec::new());
1796        let error = finish_device_flow(
1797            &store,
1798            &client,
1799            &device_code(5, 120),
1800            "studio-mac",
1801            &[7; 32],
1802            &|d| sleeps.borrow_mut().push(d.as_secs()),
1803        )
1804        .expect_err("expired");
1805        assert_eq!(
1806            error,
1807            CloudError::DeviceFlow(super::super::error::CODE_EXPIRED.into())
1808        );
1809        let sleeps = sleeps.into_inner();
1810        assert_eq!(sleeps.iter().sum::<u64>(), 120, "{sleeps:?}");
1811        assert!(sleeps.iter().all(|s| *s <= DEVICE_POLL_BACKOFF_CAP_S));
1812        assert_eq!(recorded.lock().unwrap().len(), sleeps.len());
1813    }
1814
1815    #[test]
1816    fn device_poll_pacing_keeps_final_refusals_fatal() {
1817        let mut poll = DevicePoll::new(0);
1818        assert_eq!(poll.interval, 1, "an interval of 0 polls each second");
1819        for fatal in [
1820            CloudError::DeviceFlow(super::super::error::CODE_EXPIRED.into()),
1821            CloudError::Server {
1822                status: 400,
1823                code: "unknown".into(),
1824            },
1825            CloudError::Unauthorized,
1826            CloudError::Server {
1827                status: 413,
1828                code: "payload_too_large".into(),
1829            },
1830        ] {
1831            assert_eq!(poll.next_wait(fatal.clone()), Err(fatal));
1832        }
1833        let offline = CloudError::Offline("timeout".into());
1834        assert_eq!(poll.next_wait(offline.clone()), Ok(2));
1835        assert_eq!(poll.next_wait(offline.clone()), Ok(4));
1836        for _ in 0..10 {
1837            assert!(poll.next_wait(offline.clone()).unwrap() <= DEVICE_POLL_BACKOFF_CAP_S);
1838        }
1839        let limited = CloudError::RateLimited {
1840            retry_after: Some(90),
1841        };
1842        assert_eq!(poll.next_wait(limited), Ok(90), "Retry-After wins");
1843    }
1844
1845    #[test]
1846    fn an_enrollment_token_enrolls_in_one_request_without_a_browser() {
1847        use ed25519_dalek::SigningKey;
1848        let raw = fixture("cloud/enrollment.response.json");
1849        let root = SigningKey::from_bytes(&[0x52; 32])
1850            .verifying_key()
1851            .to_bytes();
1852        let (origin, recorded) = fake_cloud((200, raw));
1853        let dir = tempfile::tempdir().unwrap();
1854        let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
1855        let client = CloudClient::new(&origin).unwrap();
1856        let token = EnrollmentToken::parse(TOKEN).unwrap();
1857        let (record, sharing) =
1858            enroll_with_token_at(&store, &client, &token, "ci-runner-7", &root, || {
1859                at("2026-10-20T12:00:00Z")
1860            })
1861            .unwrap();
1862        assert_eq!(record.org_id, "org_acme");
1863        assert_eq!(record.label, "ci-runner-7");
1864        assert_eq!(sharing, None, "no approval page asked anything");
1865        assert_eq!(
1866            store.instance().unwrap().unwrap().instance_id,
1867            record.instance_id
1868        );
1869        let sent = recorded.lock().unwrap().clone();
1870        assert_eq!(sent.len(), 1, "one request, no device code, no polling");
1871        let (path, body) = &sent[0];
1872        assert_eq!(path, "/v1/device/token");
1873        assert_eq!(body["schema"], DEVICE_TOKEN_REQUEST_SCHEMA);
1874        assert_eq!(body["device_code"], TOKEN);
1875        assert_eq!(body["instance_label"], "ci-runner-7");
1876        let keys = InstanceKeys::load(&store).unwrap();
1877        assert_eq!(body["instance_public_key"], keys.public_key_b64());
1878        assert_eq!(body["instance_kx_public_key"], keys.kx_public_key_b64());
1879        assert_eq!(body["instance_version"], env!("CARGO_PKG_VERSION"));
1880    }
1881
1882    /// rc4-1: the name typed on the approval page (`instance_label` in the
1883    /// enrollment answer) becomes this computer's name; an unusable one is
1884    /// ignored and the sent name stays.
1885    #[test]
1886    fn the_name_chosen_on_the_approval_page_names_this_computer() {
1887        use ed25519_dalek::SigningKey;
1888        let root = SigningKey::from_bytes(&[0x52; 32])
1889            .verifying_key()
1890            .to_bytes();
1891        let enroll = |answer_label: Option<&str>| {
1892            let mut raw = fixture("cloud/enrollment.response.json");
1893            if let Some(label) = answer_label {
1894                raw["instance_label"] = json!(label);
1895            }
1896            let (origin, _) = fake_cloud((200, raw));
1897            let dir = tempfile::tempdir().unwrap();
1898            let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
1899            let client = CloudClient::new(&origin).unwrap();
1900            let token = EnrollmentToken::parse(TOKEN).unwrap();
1901            let (record, _) =
1902                enroll_with_token_at(&store, &client, &token, "host-7", &root, || {
1903                    at("2026-10-20T12:00:00Z")
1904                })
1905                .unwrap();
1906            let stored = store.instance().unwrap().unwrap().label;
1907            assert_eq!(stored, record.label, "the stored record names it too");
1908            stored
1909        };
1910        assert_eq!(enroll(Some("Ada's laptop")), "Ada's laptop");
1911        assert_eq!(enroll(Some(" Ada")), "host-7", "no space at the start");
1912        assert_eq!(
1913            enroll(Some("Ada\u{a0}")),
1914            "host-7",
1915            "no no-break space at the end"
1916        );
1917        assert_eq!(enroll(None), "host-7", "an older Cloud keeps today's name");
1918        assert_eq!(enroll(Some(" ")), "host-7");
1919        assert_eq!(enroll(Some("bad\u{1b}[31m")), "host-7");
1920        assert_eq!(enroll(Some(&"x".repeat(65))), "host-7");
1921    }
1922
1923    #[test]
1924    fn a_refused_enrollment_token_says_why_without_naming_it() {
1925        let refusal = json!({"error": {"code": "expired_token", "message":
1926            "Unknown, expired, revoked or used-up enrollment token; ask a team admin for a new one."}});
1927        let (origin, recorded) = fake_cloud((400, refusal));
1928        let dir = tempfile::tempdir().unwrap();
1929        let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
1930        let client = CloudClient::new(&origin).unwrap();
1931        let token = EnrollmentToken::parse(TOKEN).unwrap();
1932        let error = enroll_with_token(&store, &client, &token, "ci", &[7; 32])
1933            .expect_err("refused")
1934            .to_string();
1935        assert!(error.contains(ENROLLMENT_TOKEN_UNUSABLE), "{error}");
1936        assert!(!error.contains(&TOKEN[4..]), "{error}");
1937        assert!(store.instance().unwrap().is_none(), "nothing enrolled");
1938        assert_eq!(recorded.lock().unwrap().len(), 1);
1939        // The transport's code-expired wording and a bare code map the same.
1940        for raw in [
1941            CloudError::DeviceFlow(super::super::error::CODE_EXPIRED.into()),
1942            CloudError::Server {
1943                status: 400,
1944                code: "expired_token".into(),
1945            },
1946        ] {
1947            assert!(
1948                token_refusal(raw)
1949                    .to_string()
1950                    .contains(ENROLLMENT_TOKEN_UNUSABLE)
1951            );
1952        }
1953    }
1954
1955    /// Cloud contact findings A: a `429 rate_limited` of the token mint
1956    /// holds every process sharing `throttles.json` until `Retry-After`;
1957    /// none of them (a forced mint, a manual sync's, neither) calls the
1958    /// cloud again before it ends.
1959    #[test]
1960    fn a_token_mint_429_holds_every_session_sharing_the_store() {
1961        let limited = json!({"error": {"code": "rate_limited",
1962            "message": "Too many requests.", "retry_after_s": 420}});
1963        let (origin, recorded) = fake_cloud((429, limited));
1964        let (dir, mut first) = fixture_session();
1965        first.instance.url.clone_from(&origin);
1966        // The fixture enrolls without an instance key; a mint signs with one.
1967        InstanceKeys::load_or_create(&first.store).expect("instance key");
1968        let error = first.client().map(|_| ()).expect_err("limited");
1969        assert!(
1970            matches!(
1971                error,
1972                CloudError::RateLimited {
1973                    retry_after: Some(420)
1974                }
1975            ),
1976            "{error:?}"
1977        );
1978        assert_eq!(recorded.lock().unwrap().len(), 1, "one mint sent");
1979
1980        // Another process: its own Session on the same store.
1981        let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
1982        let mut second = Session::load(store, *first.root_key()).unwrap();
1983        second.instance.url.clone_from(&origin);
1984        for attempt in [
1985            second.client().map(|_| ()),
1986            second.bearer_token(true).map(|_| ()),
1987            first.bearer_token(true).map(|_| ()),
1988        ] {
1989            match attempt.expect_err("held") {
1990                CloudError::RateLimited {
1991                    retry_after: Some(left),
1992                } => assert!((400..=420).contains(&left), "{left}"),
1993                other => panic!("{other:?}"),
1994            }
1995        }
1996        assert_eq!(
1997            recorded.lock().unwrap().len(),
1998            1,
1999            "no HTTP call before retry_after"
2000        );
2001        let held = super::super::throttle::status_lines(&second.store, UtcDateTime::now());
2002        assert_eq!(held.len(), 1, "{held:?}");
2003        assert!(held[0].contains("token until"), "{held:?}");
2004    }
2005}
2006
2007#[cfg(test)]
2008mod task_key_tests {
2009    use super::*;
2010    use crate::consent::task_key::tests::{instance_public_key, offer, test_key};
2011
2012    /// rc4-67: the offer binds to the `instance_public_key` the request
2013    /// sends, travels as `task_propose_key`, and only its public part stays.
2014    #[test]
2015    fn a_task_key_offer_binds_to_the_instance_public_key_the_request_sends() {
2016        let dir = tempfile::tempdir().unwrap();
2017        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
2018        let keys = InstanceKeys::load_or_create(&store).unwrap();
2019        let plain = device_token_request(&keys, "dc", "label", AppKeyOffers::default()).unwrap();
2020        assert!(plain.get("task_propose_key").is_none());
2021        // Bound to another instance key: refused before anything is sent.
2022        let foreign = offer(&test_key(), &instance_public_key());
2023        assert!(check_task_key(&keys, Some(&foreign)).is_err());
2024        let good = offer(&test_key(), &keys.public_key_b64());
2025        check_task_key(&keys, Some(&good)).unwrap();
2026        let offers = AppKeyOffers {
2027            task: Some(&good),
2028            ..AppKeyOffers::default()
2029        };
2030        let request = device_token_request(&keys, "dc", "label", offers).unwrap();
2031        assert_eq!(request["task_propose_key"], good.request_member());
2032        assert!(request.get("chat_key").is_none());
2033        keep_task_key(&store, Some(&good), Pairing::New).unwrap();
2034        assert_eq!(task_key::bound_task_key(&store), Some(good.public()));
2035        keep_task_key(&store, None, Pairing::New).unwrap();
2036        assert_eq!(task_key::bound_task_key(&store), None);
2037    }
2038
2039    /// The Cloud's pairing refusals of a task key become plain words; the
2040    /// same codes without an offer stay as they are.
2041    #[test]
2042    fn task_key_pairing_refusals_are_plain_words() {
2043        let refusal = |status: u16, body: Value| CloudError::from_response(status, &body);
2044        let invalid = refusal(
2045            400,
2046            json!({"error": {"code": "invalid_field", "field": "task_propose_key",
2047                "reason": "token_enrollment", "message": "x"}}),
2048        );
2049        let bound = refusal(
2050            409,
2051            json!({"error": {"code": "invalid_state", "reason": "task_propose_key_bound",
2052                "message": "x"}}),
2053        );
2054        let cleared = refusal(
2055            409,
2056            json!({"error": {"code": "invalid_state", "reason": "task_propose_key_cleared",
2057                "message": "x"}}),
2058        );
2059        for (error, words, code) in [
2060            (
2061                invalid.clone(),
2062                TASK_KEY_REFUSED,
2063                crate::error::TASK_KEY_INVALID,
2064            ),
2065            (bound, TASK_KEY_ALREADY_BOUND, crate::error::TASK_KEY_BOUND),
2066            (
2067                cleared,
2068                TASK_KEY_WAS_REMOVED,
2069                crate::error::TASK_KEY_CLEARED,
2070            ),
2071        ] {
2072            let refused = task_key_refusal(error, true);
2073            // The `connect --json` error event keeps the reason as its code.
2074            assert_eq!(refused.event_code(), code);
2075            match refused {
2076                CloudError::DeviceFlow(text) => assert_eq!(text, words),
2077                other => panic!("{other:?}"),
2078            }
2079        }
2080        assert!(matches!(
2081            task_key_refusal(invalid, false),
2082            CloudError::Server { status: 400, .. }
2083        ));
2084    }
2085
2086    /// rc4-32 + rc4-67: LeanCTX Code may offer its chat key and its task key
2087    /// in one pairing; each is checked, both travel in the one request, both
2088    /// are kept, and each refusal keeps its own words.
2089    #[test]
2090    fn a_pairing_carries_a_chat_key_and_a_task_key_together() {
2091        use crate::consent::chat_key::tests as chat;
2092        let dir = tempfile::tempdir().unwrap();
2093        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
2094        let keys = InstanceKeys::load_or_create(&store).unwrap();
2095        let chat_offer = chat::offer_for(&chat::test_key(), &keys.public_key_b64());
2096        let task_offer = offer(&test_key(), &keys.public_key_b64());
2097        let both = AppKeyOffers {
2098            chat: Some(&chat_offer),
2099            task: Some(&task_offer),
2100            optin: None,
2101        };
2102        both.check(&keys).unwrap();
2103        // One foreign offer stops the pairing, whichever it is.
2104        let foreign_task = offer(&test_key(), &instance_public_key());
2105        let bad_task = AppKeyOffers {
2106            task: Some(&foreign_task),
2107            ..both
2108        };
2109        assert!(bad_task.check(&keys).is_err());
2110        let foreign_chat = chat::offer(&chat::test_key());
2111        let bad_chat = AppKeyOffers {
2112            chat: Some(&foreign_chat),
2113            ..both
2114        };
2115        assert!(bad_chat.check(&keys).is_err());
2116        let request = device_token_request(&keys, "dc", "label", both).unwrap();
2117        assert_eq!(request["chat_key"], chat_offer.request_member());
2118        assert_eq!(
2119            request[task_key::REQUEST_MEMBER],
2120            task_offer.request_member()
2121        );
2122        both.keep(&store, Pairing::New).unwrap();
2123        assert_eq!(
2124            crate::consent::chat_key::bound_chat_key(&store),
2125            Some(chat_offer.public())
2126        );
2127        assert_eq!(task_key::bound_task_key(&store), Some(task_offer.public()));
2128        // Each kind's refusal maps to its own words.
2129        let task_refused = CloudError::from_response(
2130            409,
2131            &json!({"error": {"code": "invalid_state", "reason": "task_propose_key_bound",
2132                "message": "x"}}),
2133        );
2134        assert!(matches!(
2135            both.refusal(task_refused, CHAT_KEY_REFUSED),
2136            CloudError::DeviceFlow(text) if text == TASK_KEY_ALREADY_BOUND
2137        ));
2138        let chat_refused = CloudError::Server {
2139            status: 400,
2140            code: "invalid_field".into(),
2141        };
2142        assert!(matches!(
2143            both.refusal(chat_refused, CHAT_KEY_REFUSED),
2144            CloudError::DeviceFlow(text) if text == CHAT_KEY_REFUSED
2145        ));
2146        // bd 40011 S1: a Cloud that needs the keys announced (f3129) is
2147        // named as "update lean-ctx", even when it names the task key field.
2148        let not_announced = CloudError::from_response(
2149            400,
2150            &json!({"error": {"code": "invalid_field", "field": "task_propose_key",
2151                "reason": "app_key_not_announced", "message": "x"}}),
2152        );
2153        assert!(matches!(
2154            both.refusal(not_announced, CHAT_KEY_REFUSED),
2155            CloudError::DeviceFlow(text) if text == APP_KEY_PAIRING_FAILED
2156        ));
2157        // bd 40011 M2: a rebind of the same instance offering only a new
2158        // task key keeps the bound chat key (the Cloud keeps it bound).
2159        let task_only = AppKeyOffers {
2160            chat: None,
2161            task: Some(&task_offer),
2162            optin: None,
2163        };
2164        task_only.keep(&store, Pairing::Rebind).unwrap();
2165        assert_eq!(
2166            crate::consent::chat_key::bound_chat_key(&store),
2167            Some(chat_offer.public())
2168        );
2169        assert_eq!(task_key::bound_task_key(&store), Some(task_offer.public()));
2170        // A rebind without offers keeps both.
2171        AppKeyOffers::default()
2172            .keep(&store, Pairing::Rebind)
2173            .unwrap();
2174        assert_eq!(
2175            crate::consent::chat_key::bound_chat_key(&store),
2176            Some(chat_offer.public())
2177        );
2178        assert_eq!(task_key::bound_task_key(&store), Some(task_offer.public()));
2179        // A new enrollment without offers forgets both.
2180        AppKeyOffers::default().keep(&store, Pairing::New).unwrap();
2181        assert_eq!(crate::consent::chat_key::bound_chat_key(&store), None);
2182        assert_eq!(task_key::bound_task_key(&store), None);
2183    }
2184}
2185
2186#[cfg(test)]
2187mod optin_key_tests {
2188    use super::*;
2189    use crate::consent::optin_key::test_key::{INSTANCE_PUBLIC_KEY, key, offer};
2190
2191    fn store() -> (tempfile::TempDir, CloudStore, InstanceKeys) {
2192        let dir = tempfile::tempdir().unwrap();
2193        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
2194        let keys = InstanceKeys::load_or_create(&store).unwrap();
2195        (dir, store, keys)
2196    }
2197
2198    /// rc4-16: the opt-in key binds to the `instance_public_key` the request
2199    /// sends (a foreign or broken bind stops the pairing before anything is
2200    /// sent) and travels as `optin_key` beside the other offers.
2201    #[test]
2202    fn an_optin_key_offer_is_checked_then_sent_as_optin_key() {
2203        let (_dir, _store, keys) = store();
2204        let plain = device_token_request(&keys, "dc", "label", AppKeyOffers::default()).unwrap();
2205        assert!(plain.get("optin_key").is_none());
2206        let foreign = offer(&key(), INSTANCE_PUBLIC_KEY);
2207        let refused = AppKeyOffers {
2208            optin: Some(&foreign),
2209            ..AppKeyOffers::default()
2210        };
2211        assert!(matches!(refused.check(&keys), Err(CloudError::Config(_))));
2212        let mut forged = offer(&key(), &keys.public_key_b64());
2213        forged.bind_signature = foreign.bind_signature.clone();
2214        assert!(check_optin_key(&keys, Some(&forged)).is_err());
2215        let good = offer(&key(), &keys.public_key_b64());
2216        let offers = AppKeyOffers {
2217            optin: Some(&good),
2218            ..AppKeyOffers::default()
2219        };
2220        offers.check(&keys).unwrap();
2221        let request = device_token_request(&keys, "dc", "label", offers).unwrap();
2222        assert_eq!(request["optin_key"], good.request_member());
2223        assert_eq!(
2224            serde_json::from_value::<OptinKeyOffer>(request["optin_key"].clone()).unwrap(),
2225            good
2226        );
2227        assert!(request.get("chat_key").is_none());
2228        assert!(request.get("task_propose_key").is_none());
2229    }
2230
2231    /// rc4-16: an accepted pairing keeps the offered key accepted (pending
2232    /// before); a new enrollment without it puts it back to pending, a
2233    /// rebind without it keeps it.
2234    #[test]
2235    fn a_paired_optin_key_is_kept_accepted_until_a_new_enrollment() {
2236        let (_dir, store, keys) = store();
2237        let good = offer(&key(), &keys.public_key_b64());
2238        // Handed over by `cloud.pickup.key` first: pending.
2239        optin_key::store_pending(&store, &good).unwrap();
2240        assert!(!optin_key::pending_optin_key(&store).unwrap().accepted);
2241        let offers = AppKeyOffers {
2242            optin: Some(&good),
2243            ..AppKeyOffers::default()
2244        };
2245        offers.keep(&store, Pairing::New).unwrap();
2246        let kept = optin_key::pending_optin_key(&store).unwrap();
2247        assert!(kept.accepted);
2248        assert_eq!(kept.key_id, good.key_id);
2249        AppKeyOffers::default()
2250            .keep(&store, Pairing::Rebind)
2251            .unwrap();
2252        assert!(optin_key::pending_optin_key(&store).unwrap().accepted);
2253        AppKeyOffers::default().keep(&store, Pairing::New).unwrap();
2254        let pending = optin_key::pending_optin_key(&store).unwrap();
2255        assert!(
2256            !pending.accepted,
2257            "a key of an earlier enrollment is not usable"
2258        );
2259        assert!(optin_key::bound_optin_key(&store).is_none());
2260    }
2261
2262    /// The Cloud's pairing refusals of an opt-in key become the §46.4 texts
2263    /// with their own codes; `optin_key_cleared` puts the kept key back to
2264    /// pending.
2265    #[test]
2266    fn optin_key_pairing_refusals_keep_their_reasons() {
2267        let refusal = |status: u16, body: Value| CloudError::from_response(status, &body);
2268        let invalid = refusal(
2269            400,
2270            json!({"error": {"code": "invalid_field", "field": "optin_key.bind_signature",
2271                "message": "x"}}),
2272        );
2273        let bound = refusal(
2274            409,
2275            json!({"error": {"code": "conflict", "reason": "optin_key_bound", "message": "x"}}),
2276        );
2277        let cleared = refusal(
2278            409,
2279            json!({"error": {"code": "optin_key_cleared", "message": "x"}}),
2280        );
2281        let foreign = offer(&key(), INSTANCE_PUBLIC_KEY);
2282        let offered = AppKeyOffers {
2283            optin: Some(&foreign),
2284            ..AppKeyOffers::default()
2285        };
2286        for (error, words, code) in [
2287            (invalid.clone(), OPTIN_KEY_REFUSED, "optin_key_invalid"),
2288            (bound, OPTIN_KEY_ALREADY_BOUND, "optin_key_bound"),
2289            (cleared.clone(), OPTIN_KEY_WAS_REMOVED, "optin_key_cleared"),
2290        ] {
2291            let refused = offered.refusal(error, CHAT_KEY_REFUSED);
2292            assert_eq!(refused.event_code(), code);
2293            match refused {
2294                CloudError::DeviceFlow(text) => assert_eq!(text, words),
2295                other => panic!("{other:?}"),
2296            }
2297        }
2298        assert!(matches!(
2299            AppKeyOffers::default().refusal(invalid, CHAT_KEY_REFUSED),
2300            CloudError::Server { status: 400, .. }
2301        ));
2302        // A cleared key that is the one kept here is pending again.
2303        let (_dir, store, keys) = store();
2304        let good = offer(&key(), &keys.public_key_b64());
2305        keep_optin_key(&store, Some(&good), Pairing::New).unwrap();
2306        let mut other = offer(&key(), &keys.public_key_b64());
2307        other.key_id = "0000000000000000".into();
2308        forget_cleared_optin_key(&store, Some(&other), &cleared);
2309        assert!(
2310            optin_key::pending_optin_key(&store).unwrap().accepted,
2311            "another key's removal keeps this one"
2312        );
2313        forget_cleared_optin_key(&store, Some(&good), &CloudError::Unauthorized);
2314        assert!(optin_key::pending_optin_key(&store).unwrap().accepted);
2315        forget_cleared_optin_key(&store, Some(&good), &cleared);
2316        assert!(!optin_key::pending_optin_key(&store).unwrap().accepted);
2317    }
2318}
2319
2320#[cfg(test)]
2321mod chat_key_tests {
2322    use super::*;
2323    use crate::consent::chat_key::tests::{offer, offer_for, test_key};
2324
2325    #[test]
2326    fn a_chat_key_offer_binds_to_the_instance_public_key_the_request_sends() {
2327        let dir = tempfile::tempdir().unwrap();
2328        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
2329        let keys = InstanceKeys::load_or_create(&store).unwrap();
2330        let plain = device_token_request(&keys, "dc", "label", AppKeyOffers::default()).unwrap();
2331        assert!(plain.get("chat_key").is_none());
2332        // Bound to another instance key: refused before anything is sent.
2333        assert!(check_chat_key(&keys, Some(&offer(&test_key()))).is_err());
2334        let good = offer_for(&test_key(), &keys.public_key_b64());
2335        check_chat_key(&keys, Some(&good)).unwrap();
2336        let offers = AppKeyOffers {
2337            chat: Some(&good),
2338            ..AppKeyOffers::default()
2339        };
2340        let request = device_token_request(&keys, "dc", "label", offers).unwrap();
2341        assert_eq!(request["chat_key"], good.request_member());
2342        assert!(request.get("task_propose_key").is_none());
2343        keep_chat_key(&store, Some(&good), Pairing::New).unwrap();
2344        assert_eq!(
2345            crate::consent::chat_key::bound_chat_key(&store),
2346            Some(good.public())
2347        );
2348    }
2349
2350    fn fixture_answer() -> (Value, [u8; 32]) {
2351        let path = concat!(
2352            env!("CARGO_MANIFEST_DIR"),
2353            "/../lean-ctx-protocol/tests/fixtures/cloud/enrollment.response.json"
2354        );
2355        let raw: Value = serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
2356        let root = ed25519_dalek::SigningKey::from_bytes(&[0x52; 32])
2357            .verifying_key()
2358            .to_bytes();
2359        (raw, root)
2360    }
2361
2362    fn fixture_now() -> UtcDateTime {
2363        lean_ctx_time::OffsetDateTime::parse_from_rfc3339("2026-10-20T12:00:00Z")
2364            .unwrap()
2365            .to_utc()
2366    }
2367
2368    fn code() -> DeviceCodeV1 {
2369        DeviceCodeV1 {
2370            schema: lean_ctx_protocol::cloud::enroll::DEVICE_CODE_SCHEMA.into(),
2371            device_code: "hdc_repair".into(),
2372            user_code: "WDJB-MJHT".into(),
2373            verification_uri: "https://cloud.example.com/device".into(),
2374            verification_uri_complete: "https://cloud.example.com/device?c=WDJB-MJHT".into(),
2375            interval: 1,
2376            expires_in: 60,
2377            features: vec![lean_ctx_protocol::cloud::app_keys::FEATURE_DEVICE_APP_KEYS.into()],
2378            intent: None,
2379            plan: None,
2380        }
2381    }
2382
2383    /// One-answer Cloud on 127.0.0.1 recording each request body.
2384    fn one_answer_cloud(
2385        status: u16,
2386        body: &Value,
2387    ) -> (String, std::sync::Arc<std::sync::Mutex<Vec<Value>>>) {
2388        use std::io::{BufRead as _, Read as _, Write as _};
2389        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
2390        let origin = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());
2391        let seen: std::sync::Arc<std::sync::Mutex<Vec<Value>>> = std::sync::Arc::default();
2392        let record = std::sync::Arc::clone(&seen);
2393        let text = body.to_string();
2394        let raw = format!(
2395            "HTTP/1.1 {status} X\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{text}",
2396            text.len()
2397        );
2398        std::thread::spawn(move || {
2399            for stream in listener.incoming().flatten() {
2400                let mut writer = stream.try_clone().unwrap();
2401                let mut reader = std::io::BufReader::new(stream);
2402                let mut line = String::new();
2403                if reader.read_line(&mut line).unwrap_or(0) == 0 {
2404                    continue;
2405                }
2406                let mut length = 0;
2407                loop {
2408                    let mut header = String::new();
2409                    reader.read_line(&mut header).unwrap();
2410                    let header = header.trim_end();
2411                    if header.is_empty() {
2412                        break;
2413                    }
2414                    if let Some((name, value)) = header.split_once(':')
2415                        && name.eq_ignore_ascii_case("content-length")
2416                    {
2417                        length = value.trim().parse().unwrap();
2418                    }
2419                }
2420                let mut body = vec![0; length];
2421                reader.read_exact(&mut body).unwrap();
2422                record
2423                    .lock()
2424                    .unwrap()
2425                    .push(serde_json::from_slice(&body).unwrap_or(Value::Null));
2426                let _ = writer.write_all(raw.as_bytes());
2427            }
2428        });
2429        (origin, seen)
2430    }
2431
2432    /// A connected computer, its instance keys made.
2433    fn connected(origin: &str) -> (tempfile::TempDir, CloudStore, InstanceKeys) {
2434        let (dir, session) = fixture_session_at(origin);
2435        let store = session.store;
2436        let keys = InstanceKeys::load_or_create(&store).unwrap();
2437        (dir, store, keys)
2438    }
2439
2440    /// rc4-32 re-pair: the device flow of a connected computer sends its
2441    /// existing instance key plus the chat key, never `replaces`; the
2442    /// enrollment record stays, the chat key is bound.
2443    #[test]
2444    fn a_chat_key_repair_keeps_the_instance_and_sends_no_replaces() {
2445        let (answer, root) = fixture_answer();
2446        let (origin, seen) = one_answer_cloud(200, &answer);
2447        let (_dir, store, keys) = connected(&origin);
2448        let before = store.instance().unwrap().unwrap();
2449        let client = CloudClient::new(&origin).unwrap();
2450        let good = offer_for(&test_key(), &keys.public_key_b64());
2451        let outcome =
2452            repair_chat_key_at(&store, &client, &code(), &root, &|_| {}, &good, fixture_now)
2453                .unwrap();
2454        assert_eq!(outcome, ChatKeyRepair::Bound);
2455        assert_eq!(outcome.reason(), "bound");
2456        let sent = seen.lock().unwrap().clone();
2457        assert_eq!(sent.len(), 1);
2458        assert_eq!(sent[0]["device_code"], "hdc_repair");
2459        assert_eq!(sent[0]["instance_public_key"], keys.public_key_b64());
2460        assert_eq!(sent[0]["instance_label"], before.label.as_str());
2461        assert_eq!(sent[0]["chat_key"], good.request_member());
2462        assert!(sent[0].get("replaces").is_none(), "{}", sent[0]);
2463        let after = store.instance().unwrap().unwrap();
2464        assert_eq!(after.instance_id, before.instance_id);
2465        assert_eq!(after.enrolled_at, before.enrolled_at, "the record is kept");
2466        assert_eq!(
2467            InstanceKeys::load(&store).unwrap().public_key_b64(),
2468            keys.public_key_b64()
2469        );
2470        assert_eq!(
2471            crate::consent::chat_key::bound_chat_key(&store),
2472            Some(good.public())
2473        );
2474        // The same key again: unchanged.
2475        let again =
2476            repair_chat_key_at(&store, &client, &code(), &root, &|_| {}, &good, fixture_now)
2477                .unwrap();
2478        assert_eq!(again.reason(), "unchanged");
2479    }
2480
2481    #[test]
2482    fn each_chat_key_repair_refusal_maps_to_its_reason_and_text() {
2483        let (_, root) = fixture_answer();
2484        for (status, error, reason, text) in [
2485            (
2486                409,
2487                json!({"code": "invalid_state", "reason": "chat_key_bound", "message": "x"}),
2488                Some("chat_key_bound"),
2489                CHAT_KEY_BOUND,
2490            ),
2491            (
2492                409,
2493                json!({"code": "invalid_state", "reason": "chat_key_cleared", "message": "x"}),
2494                Some("chat_key_cleared"),
2495                CHAT_KEY_CLEARED,
2496            ),
2497            (
2498                400,
2499                json!({"code": "invalid_field", "field": "chat_key", "message": "x"}),
2500                None,
2501                CHAT_KEY_REFUSED,
2502            ),
2503            (
2504                400,
2505                json!({"code": "token_enrollment", "message": "x"}),
2506                None,
2507                CHAT_KEY_TOKEN_ENROLLMENT,
2508            ),
2509            // bd 40051: a Cloud that needs the keys announced (f3129).
2510            (
2511                400,
2512                json!({"code": "invalid_field", "field": "chat_key",
2513                    "reason": "app_key_not_announced", "message": "x"}),
2514                None,
2515                APP_KEY_PAIRING_FAILED,
2516            ),
2517        ] {
2518            let (origin, seen) = one_answer_cloud(status, &json!({ "error": error }));
2519            let (_dir, store, keys) = connected(&origin);
2520            let client = CloudClient::new(&origin).unwrap();
2521            let good = offer_for(&test_key(), &keys.public_key_b64());
2522            let refused =
2523                repair_chat_key_at(&store, &client, &code(), &root, &|_| {}, &good, fixture_now)
2524                    .expect_err("refused");
2525            assert_eq!(
2526                chat_key_repair_refusal(&refused),
2527                Some((reason, text)),
2528                "{status} {error}: {refused:?}"
2529            );
2530            if text == APP_KEY_PAIRING_FAILED {
2531                // The app's `connect --json` error event says which.
2532                assert_eq!(refused.event_code(), "app_key_not_announced");
2533            }
2534            assert_eq!(seen.lock().unwrap().len(), 1, "a final answer: no polling");
2535            assert!(store.instance().unwrap().is_some(), "still connected");
2536            assert_eq!(crate::consent::chat_key::bound_chat_key(&store), None);
2537        }
2538        assert_eq!(chat_key_repair_refusal(&CloudError::Unauthorized), None);
2539    }
2540
2541    /// bd 40051 S2: "the same instance" is the same id, team and Cloud; any
2542    /// other record, none, or an unreadable one is a new enrollment.
2543    #[test]
2544    fn a_rebind_is_the_same_instance_id_team_and_cloud() {
2545        let (_dir, session) = fixture_session_at("https://cloud.example.com");
2546        let store = session.store;
2547        let after = store.instance().unwrap().unwrap();
2548        let held = HeldInstance::read(&store).expect("held");
2549        assert_eq!(Pairing::of(Some(&held), &after), Pairing::Rebind);
2550        assert_eq!(Pairing::of(None, &after), Pairing::New);
2551        for other in [
2552            HeldInstance {
2553                instance_id: "inst_other".into(),
2554                ..held.clone()
2555            },
2556            HeldInstance {
2557                org_id: "org_other".into(),
2558                ..held.clone()
2559            },
2560            HeldInstance {
2561                url: "https://other.example.com".into(),
2562                ..held.clone()
2563            },
2564        ] {
2565            assert_eq!(Pairing::of(Some(&other), &after), Pairing::New, "{other:?}");
2566        }
2567        // Unreadable: none held, so a new enrollment (fail closed).
2568        std::fs::write(store.config_dir().join(INSTANCE_FILE), b"{ not json").unwrap();
2569        assert_eq!(HeldInstance::read(&store), None);
2570    }
2571
2572    /// bd 40051 S1: the device flow reads the held instance before the
2573    /// enrollment is accepted (which overwrites it). A rebind of the same
2574    /// instance offering only a task key keeps the bound chat key; a pairing
2575    /// that enrolls another instance forgets it.
2576    #[test]
2577    fn a_task_only_pairing_keeps_the_chat_key_of_the_same_instance_only() {
2578        use crate::consent::task_key::tests as task;
2579        let (answer, root) = fixture_answer();
2580        let (origin, seen) = one_answer_cloud(200, &answer);
2581        for same in [true, false] {
2582            let (_dir, store, keys) = connected(&origin);
2583            let chat = offer_for(&test_key(), &keys.public_key_b64());
2584            keep_chat_key(&store, Some(&chat), Pairing::New).unwrap();
2585            if !same {
2586                let mut record = store.instance().unwrap().unwrap();
2587                record.instance_id = "inst_held_before".into();
2588                store.write_config(INSTANCE_FILE, &record).unwrap();
2589            }
2590            let task_offer = task::offer(&task::test_key(), &keys.public_key_b64());
2591            let offers = AppKeyOffers {
2592                chat: None,
2593                task: Some(&task_offer),
2594                optin: None,
2595            };
2596            let client = CloudClient::new(&origin).unwrap();
2597            let (record, _) = poll_device_flow(
2598                &store,
2599                &client,
2600                &code(),
2601                "studio-mac",
2602                &root,
2603                &|_| {},
2604                offers,
2605                fixture_now,
2606            )
2607            .unwrap();
2608            assert_eq!(record.instance_id, "inst_01jb8z3k4m5n6p7q8r9s0t1v2w");
2609            assert_eq!(task_key::bound_task_key(&store), Some(task_offer.public()));
2610            let kept = crate::consent::chat_key::bound_chat_key(&store);
2611            if same {
2612                assert_eq!(kept, Some(chat.public()), "a rebind keeps the chat key");
2613            } else {
2614                assert_eq!(kept, None, "a new instance forgets the chat key");
2615            }
2616        }
2617        assert_eq!(seen.lock().unwrap().len(), 2);
2618    }
2619
2620    /// rc4-16 (bd 40254 S2): through the device flow against a Cloud, the
2621    /// opt-in key travels as `optin_key` in `POST /v1/device/token`; a 2xx
2622    /// keeps it accepted, a `409 optin_key_cleared` for that key puts it back
2623    /// to pending with the §46.4 text, and a `400 token_enrollment` gives the
2624    /// §46.2 text with its own code.
2625    #[test]
2626    fn an_optin_key_pairing_flow_sends_keeps_and_clears_the_optin_key() {
2627        use crate::consent::optin_key::test_key as optin;
2628        let (answer, root) = fixture_answer();
2629        let offered = |keys: &InstanceKeys| optin::offer(&optin::key(), &keys.public_key_b64());
2630
2631        // 2xx: sent as `optin_key`, kept accepted.
2632        let (origin, seen) = one_answer_cloud(200, &answer);
2633        let (_dir, store, keys) = connected(&origin);
2634        let good = offered(&keys);
2635        optin_key::store_pending(&store, &good).unwrap();
2636        let offers = AppKeyOffers {
2637            optin: Some(&good),
2638            ..AppKeyOffers::default()
2639        };
2640        offers.verify(&store).unwrap();
2641        let client = CloudClient::new(&origin).unwrap();
2642        finish_device_flow_at(
2643            &store,
2644            &client,
2645            &code(),
2646            "studio-mac",
2647            &root,
2648            &|_| {},
2649            offers,
2650            fixture_now,
2651        )
2652        .unwrap();
2653        let sent = seen.lock().unwrap().clone();
2654        assert_eq!(sent.len(), 1);
2655        assert_eq!(sent[0]["instance_public_key"], keys.public_key_b64());
2656        assert_eq!(sent[0]["optin_key"], good.request_member());
2657        let kept = optin_key::pending_optin_key(&store).unwrap();
2658        assert!(kept.accepted, "a 2xx keeps the key accepted");
2659        assert_eq!(kept.key_id, good.key_id);
2660
2661        // 409 optin_key_cleared for the same key: pending again, §46.4 text.
2662        let cleared = json!({"error": {"code": "optin_key_cleared", "message": "x"}});
2663        let (origin, seen) = one_answer_cloud(409, &cleared);
2664        let (_dir, store, keys) = connected(&origin);
2665        let good = offered(&keys);
2666        keep_optin_key(&store, Some(&good), Pairing::New).unwrap();
2667        assert!(optin_key::pending_optin_key(&store).unwrap().accepted);
2668        let offers = AppKeyOffers {
2669            optin: Some(&good),
2670            ..AppKeyOffers::default()
2671        };
2672        let client = CloudClient::new(&origin).unwrap();
2673        let refused = finish_device_flow_at(
2674            &store,
2675            &client,
2676            &code(),
2677            "studio-mac",
2678            &root,
2679            &|_| {},
2680            offers,
2681            fixture_now,
2682        )
2683        .expect_err("cleared");
2684        assert_eq!(seen.lock().unwrap()[0]["optin_key"], good.request_member());
2685        assert_eq!(refused.event_code(), "optin_key_cleared");
2686        assert!(
2687            matches!(&refused, CloudError::DeviceFlow(text) if text == OPTIN_KEY_WAS_REMOVED),
2688            "{refused:?}"
2689        );
2690        let pending = optin_key::pending_optin_key(&store).unwrap();
2691        assert!(!pending.accepted, "the cleared key is pending again");
2692        assert_eq!(pending.key_id, good.key_id);
2693
2694        // A computer enrolled with a token: §46.2 text, own code.
2695        let token = json!({"error": {"code": "token_enrollment", "message": "x"}});
2696        let (origin, _seen) = one_answer_cloud(400, &token);
2697        let (_dir, store, keys) = connected(&origin);
2698        let good = offered(&keys);
2699        let client = CloudClient::new(&origin).unwrap();
2700        let refused = finish_device_flow_at(
2701            &store,
2702            &client,
2703            &code(),
2704            "studio-mac",
2705            &root,
2706            &|_| {},
2707            AppKeyOffers {
2708                optin: Some(&good),
2709                ..AppKeyOffers::default()
2710            },
2711            fixture_now,
2712        )
2713        .expect_err("token enrollment");
2714        assert_eq!(refused.event_code(), "token_enrollment");
2715        assert!(
2716            matches!(&refused, CloudError::DeviceFlow(text) if text == OPTIN_KEY_TOKEN_ENROLLMENT),
2717            "{refused:?}"
2718        );
2719    }
2720
2721    /// bd 40254 S1: the offers are verified against this computer's instance
2722    /// key before the connect contacts the Cloud; nothing offered makes no
2723    /// key.
2724    #[test]
2725    fn app_key_offers_verify_before_the_cloud_is_contacted_for_optin_key() {
2726        use crate::consent::optin_key::test_key as optin;
2727        let dir = tempfile::tempdir().unwrap();
2728        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
2729        AppKeyOffers::default().verify(&store).unwrap();
2730        assert!(
2731            InstanceKeys::load(&store).is_err(),
2732            "nothing offered: no key made"
2733        );
2734        let keys = InstanceKeys::load_or_create(&store).unwrap();
2735        let foreign = optin::offer(&optin::key(), optin::INSTANCE_PUBLIC_KEY);
2736        let chat_foreign = offer(&test_key());
2737        for refused in [
2738            AppKeyOffers {
2739                optin: Some(&foreign),
2740                ..AppKeyOffers::default()
2741            },
2742            AppKeyOffers {
2743                chat: Some(&chat_foreign),
2744                ..AppKeyOffers::default()
2745            },
2746        ] {
2747            assert!(matches!(refused.verify(&store), Err(CloudError::Config(_))));
2748        }
2749        let good = optin::offer(&optin::key(), &keys.public_key_b64());
2750        AppKeyOffers {
2751            optin: Some(&good),
2752            ..AppKeyOffers::default()
2753        }
2754        .verify(&store)
2755        .unwrap();
2756    }
2757
2758    /// The device-code answer of a Cloud with or without `device_app_keys`.
2759    fn code_answer(app_keys: bool) -> Value {
2760        let mut answer = code();
2761        if !app_keys {
2762            answer.features.clear();
2763        }
2764        serde_json::to_value(answer).unwrap()
2765    }
2766
2767    /// f3129 S2: every offer is announced at `POST /v1/device/code` as
2768    /// `app_keys`, sorted chat < optin < task_propose; without offers the
2769    /// request carries no `app_keys` member and is the plain pairing's.
2770    #[test]
2771    fn f3129_app_keys_are_announced_sorted_at_the_device_code() {
2772        use crate::consent::optin_key::test_key as optin;
2773        use crate::consent::task_key::tests as task;
2774        let dir = tempfile::tempdir().unwrap();
2775        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
2776        let pk = InstanceKeys::load_or_create(&store)
2777            .unwrap()
2778            .public_key_b64();
2779        let chat = offer_for(&test_key(), &pk);
2780        let task_offer = task::offer(&task::test_key(), &pk);
2781        let optin_offer = optin::offer(&optin::key(), &pk);
2782        let offers = AppKeyOffers {
2783            chat: Some(&chat),
2784            task: Some(&task_offer),
2785            optin: Some(&optin_offer),
2786        };
2787        let (origin, seen) = one_answer_cloud(200, &code_answer(true));
2788        let client = CloudClient::new(&origin).unwrap();
2789        start_device_flow_with(&client, Some("studio-mac"), None, offers).unwrap();
2790        let announced = offers.announcements();
2791        assert_eq!(
2792            announced.iter().map(|a| a.kind).collect::<Vec<_>>(),
2793            [AppKeyKind::Chat, AppKeyKind::Optin, AppKeyKind::TaskPropose]
2794        );
2795        for (a, (public_key, key_id)) in announced.iter().zip([
2796            (&chat.public_key, &chat.key_id),
2797            (&optin_offer.public_key, &optin_offer.key_id),
2798            (&task_offer.public_key, &task_offer.key_id),
2799        ]) {
2800            assert_eq!(a.alg, "ed25519");
2801            assert_eq!((&a.public_key, &a.key_id), (public_key, key_id));
2802        }
2803        let sent = seen.lock().unwrap().clone();
2804        assert_eq!(sent.len(), 1);
2805        assert_eq!(
2806            sent[0]["app_keys"],
2807            serde_json::to_value(&announced).unwrap()
2808        );
2809        assert_eq!(sent[0]["app_keys"][0]["kind"], "chat");
2810        assert_eq!(sent[0]["app_keys"][2]["kind"], "task_propose");
2811
2812        // No offers: no `app_keys`, byte for byte the plain pairing.
2813        let (origin, seen) = one_answer_cloud(200, &code_answer(false));
2814        let client = CloudClient::new(&origin).unwrap();
2815        start_device_flow_with(&client, Some("studio-mac"), None, AppKeyOffers::default()).unwrap();
2816        start_device_flow_for(&client, Some("studio-mac"), None).unwrap();
2817        let sent = seen.lock().unwrap().clone();
2818        assert_eq!(sent.len(), 2);
2819        assert!(sent[0].get("app_keys").is_none(), "{}", sent[0]);
2820        assert_eq!(sent[0].to_string(), sent[1].to_string());
2821        let plain = DeviceCodeRequestV1::new(env!("CARGO_PKG_VERSION"), engine_os())
2822            .with_label(Some("studio-mac".into()));
2823        assert_eq!(sent[0], serde_json::to_value(plain).unwrap());
2824    }
2825
2826    /// f3129: a Cloud without `device_app_keys` (or one refusing `app_keys`
2827    /// as an unknown member) gets no offer: a clear `config` error before
2828    /// any polling; the pairing without offers is unaffected.
2829    #[test]
2830    fn f3129_app_keys_fail_closed_without_the_cloud_feature() {
2831        let dir = tempfile::tempdir().unwrap();
2832        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
2833        let keys = InstanceKeys::load_or_create(&store).unwrap();
2834        let chat = offer_for(&test_key(), &keys.public_key_b64());
2835        let offers = AppKeyOffers {
2836            chat: Some(&chat),
2837            ..AppKeyOffers::default()
2838        };
2839        let (origin, seen) = one_answer_cloud(200, &code_answer(false));
2840        let client = CloudClient::new(&origin).unwrap();
2841        let refused = start_device_flow_with(&client, None, None, offers).expect_err("no feature");
2842        assert!(
2843            matches!(&refused, CloudError::Config(text) if text == APP_KEYS_UNSUPPORTED),
2844            "{refused:?}"
2845        );
2846        assert_eq!(seen.lock().unwrap().len(), 1, "no polling");
2847        // Polling with offers on such a code is refused before it is sent.
2848        let (_, root) = fixture_answer();
2849        let mut old = code();
2850        old.features.clear();
2851        let refused = poll_device_flow(
2852            &store,
2853            &client,
2854            &old,
2855            "m",
2856            &root,
2857            &|_| {},
2858            offers,
2859            fixture_now,
2860        )
2861        .expect_err("no feature");
2862        assert!(matches!(&refused, CloudError::Config(_)), "{refused:?}");
2863        assert_eq!(seen.lock().unwrap().len(), 1, "nothing sent");
2864        start_device_flow_with(&client, None, None, AppKeyOffers::default()).unwrap();
2865        // An older Cloud's 400 on the unknown member reads the same.
2866        let old_cloud = json!({"error": {"code": "invalid_request", "message": "x"}});
2867        let (origin, _) = one_answer_cloud(400, &old_cloud);
2868        let client = CloudClient::new(&origin).unwrap();
2869        let refused = start_device_flow_with(&client, None, None, offers).expect_err("old");
2870        assert!(
2871            matches!(&refused, CloudError::Config(text) if text == APP_KEYS_UNSUPPORTED),
2872            "{refused:?}"
2873        );
2874    }
2875
2876    /// f3129 S3: the device-token request carries `app_keys_bind_signature`,
2877    /// the instance key's signature over the bind statement of the device
2878    /// code, the sent instance key and the announced set; none without
2879    /// offers.
2880    #[test]
2881    fn f3129_app_keys_bind_signature_verifies_with_the_instance_key() {
2882        use crate::consent::task_key::tests as task;
2883        use base64::Engine as _;
2884        use ed25519_dalek::Verifier as _;
2885        let (answer, root) = fixture_answer();
2886        let (origin, seen) = one_answer_cloud(200, &answer);
2887        let (_dir, store, keys) = connected(&origin);
2888        let pk = keys.public_key_b64();
2889        let chat = offer_for(&test_key(), &pk);
2890        let task_offer = task::offer(&task::test_key(), &pk);
2891        let offers = AppKeyOffers {
2892            chat: Some(&chat),
2893            task: Some(&task_offer),
2894            optin: None,
2895        };
2896        let client = CloudClient::new(&origin).unwrap();
2897        poll_device_flow(
2898            &store,
2899            &client,
2900            &code(),
2901            "m",
2902            &root,
2903            &|_| {},
2904            offers,
2905            fixture_now,
2906        )
2907        .unwrap();
2908        let sent = seen.lock().unwrap().clone();
2909        assert_eq!(sent.len(), 1);
2910        assert_eq!(sent[0]["instance_public_key"], pk);
2911        let signature = sent[0]["app_keys_bind_signature"].as_str().expect("signed");
2912        let raw = base64::engine::general_purpose::URL_SAFE_NO_PAD
2913            .decode(signature)
2914            .unwrap();
2915        let signature = ed25519_dalek::Signature::from_slice(&raw).unwrap();
2916        let verifying = keys.signing_key().verifying_key();
2917        let input = app_key_bind_signing_input("hdc_repair", &pk, &offers.announcements()).unwrap();
2918        verifying
2919            .verify(&input, &signature)
2920            .expect("the instance key signed the statement");
2921        // Another device code does not verify.
2922        let other = app_key_bind_signing_input("hdc_other", &pk, &offers.announcements()).unwrap();
2923        assert!(verifying.verify(&other, &signature).is_err());
2924        // No offers, no signature.
2925        let plain = device_token_request(&keys, "dc", "m", AppKeyOffers::default()).unwrap();
2926        assert!(plain.get("app_keys_bind_signature").is_none());
2927    }
2928
2929    /// f3129 §11: `400 invalid_field` with reason `app_key_not_announced` or
2930    /// `app_key_bind_invalid` reads "Pairing failed" with the app's code.
2931    #[test]
2932    fn f3129_app_keys_refusals_read_pairing_failed() {
2933        let (_, root) = fixture_answer();
2934        for reason in ["app_key_not_announced", "app_key_bind_invalid"] {
2935            let error = json!({"error": {"code": "invalid_field",
2936                "field": "app_keys_bind_signature", "reason": reason, "message": "x"}});
2937            let (origin, seen) = one_answer_cloud(400, &error);
2938            let (_dir, store, keys) = connected(&origin);
2939            let chat = offer_for(&test_key(), &keys.public_key_b64());
2940            let client = CloudClient::new(&origin).unwrap();
2941            let refused = finish_device_flow_at(
2942                &store,
2943                &client,
2944                &code(),
2945                "m",
2946                &root,
2947                &|_| {},
2948                AppKeyOffers {
2949                    chat: Some(&chat),
2950                    ..AppKeyOffers::default()
2951                },
2952                fixture_now,
2953            )
2954            .expect_err("refused");
2955            assert!(
2956                matches!(&refused, CloudError::DeviceFlow(text) if text == PAIRING_FAILED_TEXT),
2957                "{reason}: {refused:?}"
2958            );
2959            assert_eq!(refused.event_code(), "app_key_not_announced");
2960            assert_eq!(seen.lock().unwrap().len(), 1, "a final answer");
2961            assert_eq!(crate::consent::chat_key::bound_chat_key(&store), None);
2962        }
2963    }
2964
2965    /// f3129: a newer Cloud refusing the announcement itself at the device
2966    /// code (`400 invalid_field`, field `app_keys`) is a clear Config error
2967    /// that the re-pair names; without an announcement it stays as it was.
2968    #[test]
2969    fn f3129_app_keys_bad_announcement_is_a_clear_config_error() {
2970        let dir = tempfile::tempdir().unwrap();
2971        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
2972        let keys = InstanceKeys::load_or_create(&store).unwrap();
2973        let chat = offer_for(&test_key(), &keys.public_key_b64());
2974        let offers = AppKeyOffers {
2975            chat: Some(&chat),
2976            ..AppKeyOffers::default()
2977        };
2978        let refusal = json!({"error": {"code": "invalid_field", "field": "app_keys",
2979            "message": "x"}});
2980        let (origin, seen) = one_answer_cloud(400, &refusal);
2981        let client = CloudClient::new(&origin).unwrap();
2982        let refused = start_device_flow_with(&client, None, None, offers).expect_err("refused");
2983        assert!(
2984            matches!(&refused, CloudError::Config(text) if text == APP_KEY_PAIRING_FAILED),
2985            "{refused:?}"
2986        );
2987        assert_eq!(
2988            chat_key_repair_refusal(&refused),
2989            Some((None, APP_KEY_PAIRING_FAILED))
2990        );
2991        assert_eq!(
2992            seen.lock().unwrap().len(),
2993            1,
2994            "sent once, never without them"
2995        );
2996        // Without an announcement the same answer is not remapped.
2997        let (origin, _) = one_answer_cloud(400, &refusal);
2998        let client = CloudClient::new(&origin).unwrap();
2999        let plain = start_device_flow_with(&client, None, None, AppKeyOffers::default())
3000            .expect_err("refused");
3001        assert!(!matches!(&plain, CloudError::Config(_)), "{plain:?}");
3002    }
3003
3004    /// f3129: a re-pair against a code answer without `device_app_keys`
3005    /// sends nothing and binds nothing.
3006    #[test]
3007    fn f3129_chat_key_repair_fails_closed_without_the_cloud_feature() {
3008        let (answer, root) = fixture_answer();
3009        let (origin, seen) = one_answer_cloud(200, &answer);
3010        let (_dir, store, keys) = connected(&origin);
3011        let client = CloudClient::new(&origin).unwrap();
3012        let good = offer_for(&test_key(), &keys.public_key_b64());
3013        let mut old = code();
3014        old.features.clear();
3015        let refused = repair_chat_key_at(&store, &client, &old, &root, &|_| {}, &good, fixture_now)
3016            .expect_err("no feature");
3017        assert!(
3018            matches!(&refused, CloudError::Config(text) if text == APP_KEYS_UNSUPPORTED),
3019            "{refused:?}"
3020        );
3021        assert_eq!(
3022            chat_key_repair_refusal(&refused),
3023            Some((None, APP_KEYS_UNSUPPORTED))
3024        );
3025        assert!(seen.lock().unwrap().is_empty(), "nothing sent");
3026        assert_eq!(crate::consent::chat_key::bound_chat_key(&store), None);
3027    }
3028
3029    /// bd 40488: an older Cloud's 400 on a trial with keys names the trial.
3030    #[test]
3031    fn f3129_an_old_cloud_refusing_a_trial_with_keys_names_the_trial() {
3032        let dir = tempfile::tempdir().unwrap();
3033        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
3034        let keys = InstanceKeys::load_or_create(&store).unwrap();
3035        let chat = offer_for(&test_key(), &keys.public_key_b64());
3036        let offers = AppKeyOffers {
3037            chat: Some(&chat),
3038            ..AppKeyOffers::default()
3039        };
3040        let old_cloud = json!({"error": {"code": "invalid_request", "message": "x"}});
3041        let (origin, _) = one_answer_cloud(400, &old_cloud);
3042        let client = CloudClient::new(&origin).unwrap();
3043        let refused = start_device_flow_with(&client, None, Some(TrialPlan::Personal), offers)
3044            .expect_err("old");
3045        assert!(
3046            matches!(&refused, CloudError::TrialUnsupported { .. }),
3047            "{refused:?}"
3048        );
3049    }
3050
3051    /// f3129 S3: a token has no device code to sign over, so a chat key with
3052    /// a token is refused before anything is sent.
3053    #[test]
3054    fn f3129_app_keys_never_go_with_an_enrollment_token() {
3055        let (answer, root) = fixture_answer();
3056        let (origin, seen) = one_answer_cloud(200, &answer);
3057        let (_dir, store, keys) = connected(&origin);
3058        let chat = offer_for(&test_key(), &keys.public_key_b64());
3059        let client = CloudClient::new(&origin).unwrap();
3060        let token = EnrollmentToken::parse(
3061            "het_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
3062        )
3063        .unwrap();
3064        let refused = enroll_with_token_chat(&store, &client, &token, "m", &root, Some(&chat))
3065            .expect_err("refused");
3066        assert!(
3067            matches!(&refused, CloudError::Config(text) if text == CHAT_KEY_WITH_TOKEN),
3068            "{refused:?}"
3069        );
3070        assert!(seen.lock().unwrap().is_empty(), "nothing sent");
3071    }
3072}